text
stringlengths
54
60.6k
<commit_before>/*! * \file c_array.hpp * \brief file c_array.hpp * * Adapted from: c_array.hpp of WRATH: * * Copyright 2013 by Nomovok Ltd. * Contact: info@nomovok.com * 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/. * * \author Kevin Rogovin <kevin.rogovin@nomovok.com> * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <iterator> #include <fastuidraw/util/util.hpp> #include <fastuidraw/util/vecN.hpp> namespace fastuidraw { /*!\addtogroup Utility * @{ */ /*! * \brief * A c_array is a wrapper over a * C pointer with a size parameter * to facilitate bounds checking * and provide an STL-like iterator * interface. */ template<typename T> class c_array { public: /*! * \brief * STL compliant typedef */ typedef T* pointer; /*! * \brief * STL compliant typedef; notice that const_pointer * is type T* and not const T*. This is because * a c_array is just a HOLDER of a pointer and * a length and thus the contents of the value * behind the pointer are not part of the value * of a c_array. */ typedef T* const_pointer; /*! * \brief * STL compliant typedef */ typedef T& reference; /*! * \brief * STL compliant typedef; notice that const_pointer * is type T& and not const T&. This is because * a c_array is just a HOLDER of a pointer and * a length and thus the contents of the value * behind the pointer are not part of the value * of a c_array. */ typedef T& const_reference; /*! * \brief * STL compliant typedef */ typedef T value_type; /*! * \brief * STL compliant typedef */ typedef size_t size_type; /*! * \brief * STL compliant typedef */ typedef ptrdiff_t difference_type; /*! * \brief * iterator typedef to pointer */ typedef pointer iterator; /*! * \brief * iterator typedef to const_pointer */ typedef const_pointer const_iterator; /*! * \brief * iterator typedef using std::reverse_iterator. */ typedef std::reverse_iterator<const_iterator> const_reverse_iterator; /*! * \brief * iterator typedef using std::reverse_iterator. */ typedef std::reverse_iterator<iterator> reverse_iterator; /*! * Default ctor, initializing the pointer as nullptr * with size 0. */ c_array(void): m_size(0), m_ptr(nullptr) {} /*! * Ctor initializing the pointer and size * \param pptr pointer value * \param sz size, must be no more than the number of elements that pptr points to. */ template<typename U> c_array(U *pptr, size_type sz): m_size(sz), m_ptr(pptr) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from a vecN, size is the size of the fixed size array * \param pptr fixed size array that c_array references, must be * in scope as until c_array is changed */ template<typename U, size_type N> c_array(vecN<U, N> &pptr): m_size(N), m_ptr(pptr.c_ptr()) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from a vecN, size is the size of the fixed size array * \param pptr fixed size array that c_array references, must be * in scope as until c_array is changed */ template<typename U, size_type N> c_array(const vecN<U, N> &pptr): m_size(N), m_ptr(pptr.c_ptr()) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from another c_array object. * \tparam U type U* must be convertible to type T* AND * the size of U must be the same as the size * of T * \param obj value from which to copy */ template<typename U> c_array(const c_array<U> &obj): m_size(obj.m_size), m_ptr(obj.m_ptr) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from a range of pointers. * \param R R.m_begin will be the pointer and R.m_end - R.m_begin the size. */ c_array(range_type<iterator> R): m_size(R.m_end - R.m_begin), m_ptr((m_size > 0) ? &*R.m_begin : nullptr) {} /*! * Resets the \ref c_array<> object to be equivalent to * a nullptr, i.e. c_ptr() will return nullptr and size() * will return 0. */ void reset(void) { m_size = 0; m_ptr = nullptr; } /*! * Reinterpret style cast for c_array. It is required * that the sizeof(T)*size() evenly divides sizeof(S). * \tparam S type to which to be reinterpreted casted */ template<typename S> c_array<S> reinterpret_pointer(void) const { S *ptr; size_type num_bytes(size() * sizeof(T)); FASTUIDRAWassert(num_bytes % sizeof(S) == 0); ptr = reinterpret_cast<S*>(c_ptr()); return c_array<S>(ptr, num_bytes / sizeof(S)); } /*! * Const style cast for c_array. It is required * that the sizeof(T) is the same as sizeof(S). * \tparam S type to which to be const casted */ template<typename S> c_array<S> const_cast_pointer(void) const { S *ptr; FASTUIDRAWstatic_assert(sizeof(S) == sizeof(T)); ptr = const_cast<S*>(c_ptr()); return c_array<S>(ptr, m_size); } /*! * Pointer of the c_array. */ T* c_ptr(void) const { return m_ptr; } /*! * Pointer to the element one past * the last element of the c_array. */ T* end_c_ptr(void) const { return m_ptr + m_size; } /*! * Access named element of c_array, under * debug build also performs bounds checking. * \param j index */ reference operator[](size_type j) const { FASTUIDRAWassert(c_ptr() != nullptr); FASTUIDRAWassert(j < m_size); return c_ptr()[j]; } /*! * STL compliant function. */ bool empty(void) const { return m_size == 0; } /*! * STL compliant function. */ size_type size(void) const { return m_size; } /*! * STL compliant function. */ iterator begin(void) const { return iterator(c_ptr()); } /*! * STL compliant function. */ iterator end(void) const { return iterator(c_ptr() + static_cast<difference_type>(size())); } /*! * STL compliant function. */ reverse_iterator rbegin(void) const { return reverse_iterator(end()); } /*! * STL compliant function. */ reverse_iterator rend(void) const { return reverse_iterator(begin()); } /*! * Returns the range of the c_array as an * iterator range. */ range_type<iterator> range(void) const { return range_type<iterator>(begin(), end()); } /*! * Returns the range of the c_array as a * reverse_iterator range */ range_type<reverse_iterator> reverse_range(void) const { return range_type<reverse_iterator>(rbegin(), rend()); } /*! * Equivalent to * \code * operator[](size()-1-I) * \endcode * \param I index from the back to retrieve, I=0 * corrseponds to the back of the array. */ reference back(size_type I) const { FASTUIDRAWassert(I < size()); return (*this)[size() - 1 - I]; } /*! * STL compliant function. */ reference back(void) const { return (*this)[size() - 1]; } /*! * STL compliant function. */ reference front(void) const { return (*this)[0]; } /*! * Returns a sub-array * \param pos position of returned sub-array to start, * i.e. returned c_array's c_ptr() will return * this->c_ptr()+pos. It is an error if pos * is negative. * \param length length of sub array to return, note * that it is an error if length+pos>size() * or if length is negative. */ c_array sub_array(size_type pos, size_type length) const { FASTUIDRAWassert(pos + length <= m_size); return c_array(m_ptr + pos, length); } /*! * Returns a sub-array, equivalent to * \code * sub_array(pos, size() - pos) * \endcode * \param pos position of returned sub-array to start, * i.e. returned c_array's c_ptr() will return * this->c_ptr() + pos. It is an error is pos * is negative. */ c_array sub_array(size_type pos) const { FASTUIDRAWassert(pos <= m_size); return c_array(m_ptr + pos, m_size - pos); } /*! * Returns a sub-array, equivalent to * \code * sub_array(R.m_begin, R.m_end - R.m_begin) * \endcode * \tparam I type convertible to size_type * \param R range of returned sub-array */ template<typename I> c_array sub_array(range_type<I> R) const { return sub_array(R.m_begin, R.m_end - R.m_begin); } /*! * Provided as a conveniance, equivalent to * \code * *this = this->sub_array(0, size() - 1); * \endcode * It is an error to call this when size() is 0. */ void pop_back(void) { FASTUIDRAWassert(m_size > 0); --m_size; } /*! * Provided as a conveniance, equivalent to * \code * *this = this->sub_array(1, size() - 1); * \endcode * It is an error to call this when size() is 0. */ void pop_front(void) { FASTUIDRAWassert(m_size > 0); --m_size; ++m_ptr; } /*! * Returns true if and only if the passed * the c_array references exactly the same * data as this c_array. * \param rhs c_array to which to compare */ template<typename U> bool same_data(const c_array<U> &rhs) const { return m_ptr == rhs.m_ptr && m_size * sizeof(T) == rhs.m_size * sizeof(U); } private: template<typename> friend class c_array; size_type m_size; T *m_ptr; }; /*! @} */ } //namespace <commit_msg>util/c_array: doxytag fix<commit_after>/*! * \file c_array.hpp * \brief file c_array.hpp * * Adapted from: c_array.hpp of WRATH: * * Copyright 2013 by Nomovok Ltd. * Contact: info@nomovok.com * 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/. * * \author Kevin Rogovin <kevin.rogovin@nomovok.com> * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <iterator> #include <fastuidraw/util/util.hpp> #include <fastuidraw/util/vecN.hpp> namespace fastuidraw { /*!\addtogroup Utility * @{ */ /*! * \brief * A c_array is a wrapper over a * C pointer with a size parameter * to facilitate bounds checking * and provide an STL-like iterator * interface. */ template<typename T> class c_array { public: /*! * \brief * STL compliant typedef */ typedef T* pointer; /*! * \brief * STL compliant typedef; notice that const_pointer * is type T* and not const T*. This is because * a c_array is just a HOLDER of a pointer and * a length and thus the contents of the value * behind the pointer are not part of the value * of a c_array. */ typedef T* const_pointer; /*! * \brief * STL compliant typedef */ typedef T& reference; /*! * \brief * STL compliant typedef; notice that const_pointer * is type T& and not const T&. This is because * a c_array is just a HOLDER of a pointer and * a length and thus the contents of the value * behind the pointer are not part of the value * of a c_array. */ typedef T& const_reference; /*! * \brief * STL compliant typedef */ typedef T value_type; /*! * \brief * STL compliant typedef */ typedef size_t size_type; /*! * \brief * STL compliant typedef */ typedef ptrdiff_t difference_type; /*! * \brief * iterator typedef to pointer */ typedef pointer iterator; /*! * \brief * iterator typedef to const_pointer */ typedef const_pointer const_iterator; /*! * \brief * iterator typedef using std::reverse_iterator. */ typedef std::reverse_iterator<const_iterator> const_reverse_iterator; /*! * \brief * iterator typedef using std::reverse_iterator. */ typedef std::reverse_iterator<iterator> reverse_iterator; /*! * Default ctor, initializing the pointer as nullptr * with size 0. */ c_array(void): m_size(0), m_ptr(nullptr) {} /*! * Ctor initializing the pointer and size * \param pptr pointer value * \param sz size, must be no more than the number of elements that pptr points to. */ template<typename U> c_array(U *pptr, size_type sz): m_size(sz), m_ptr(pptr) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from a vecN, size is the size of the fixed size array * \param pptr fixed size array that c_array references, must be * in scope as until c_array is changed */ template<typename U, size_type N> c_array(vecN<U, N> &pptr): m_size(N), m_ptr(pptr.c_ptr()) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from a vecN, size is the size of the fixed size array * \param pptr fixed size array that c_array references, must be * in scope as until c_array is changed */ template<typename U, size_type N> c_array(const vecN<U, N> &pptr): m_size(N), m_ptr(pptr.c_ptr()) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from another c_array object. * \tparam U type U* must be convertible to type T* AND * the size of U must be the same as the size * of T * \param obj value from which to copy */ template<typename U> c_array(const c_array<U> &obj): m_size(obj.m_size), m_ptr(obj.m_ptr) { FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T)); } /*! * Ctor from a range of pointers. * \param R R.m_begin will be the pointer and R.m_end - R.m_begin the size. */ c_array(range_type<iterator> R): m_size(R.m_end - R.m_begin), m_ptr((m_size > 0) ? &*R.m_begin : nullptr) {} /*! * Resets the \ref c_array object to be equivalent to * a nullptr, i.e. c_ptr() will return nullptr and size() * will return 0. */ void reset(void) { m_size = 0; m_ptr = nullptr; } /*! * Reinterpret style cast for c_array. It is required * that the sizeof(T)*size() evenly divides sizeof(S). * \tparam S type to which to be reinterpreted casted */ template<typename S> c_array<S> reinterpret_pointer(void) const { S *ptr; size_type num_bytes(size() * sizeof(T)); FASTUIDRAWassert(num_bytes % sizeof(S) == 0); ptr = reinterpret_cast<S*>(c_ptr()); return c_array<S>(ptr, num_bytes / sizeof(S)); } /*! * Const style cast for c_array. It is required * that the sizeof(T) is the same as sizeof(S). * \tparam S type to which to be const casted */ template<typename S> c_array<S> const_cast_pointer(void) const { S *ptr; FASTUIDRAWstatic_assert(sizeof(S) == sizeof(T)); ptr = const_cast<S*>(c_ptr()); return c_array<S>(ptr, m_size); } /*! * Pointer of the c_array. */ T* c_ptr(void) const { return m_ptr; } /*! * Pointer to the element one past * the last element of the c_array. */ T* end_c_ptr(void) const { return m_ptr + m_size; } /*! * Access named element of c_array, under * debug build also performs bounds checking. * \param j index */ reference operator[](size_type j) const { FASTUIDRAWassert(c_ptr() != nullptr); FASTUIDRAWassert(j < m_size); return c_ptr()[j]; } /*! * STL compliant function. */ bool empty(void) const { return m_size == 0; } /*! * STL compliant function. */ size_type size(void) const { return m_size; } /*! * STL compliant function. */ iterator begin(void) const { return iterator(c_ptr()); } /*! * STL compliant function. */ iterator end(void) const { return iterator(c_ptr() + static_cast<difference_type>(size())); } /*! * STL compliant function. */ reverse_iterator rbegin(void) const { return reverse_iterator(end()); } /*! * STL compliant function. */ reverse_iterator rend(void) const { return reverse_iterator(begin()); } /*! * Returns the range of the c_array as an * iterator range. */ range_type<iterator> range(void) const { return range_type<iterator>(begin(), end()); } /*! * Returns the range of the c_array as a * reverse_iterator range */ range_type<reverse_iterator> reverse_range(void) const { return range_type<reverse_iterator>(rbegin(), rend()); } /*! * Equivalent to * \code * operator[](size()-1-I) * \endcode * \param I index from the back to retrieve, I=0 * corrseponds to the back of the array. */ reference back(size_type I) const { FASTUIDRAWassert(I < size()); return (*this)[size() - 1 - I]; } /*! * STL compliant function. */ reference back(void) const { return (*this)[size() - 1]; } /*! * STL compliant function. */ reference front(void) const { return (*this)[0]; } /*! * Returns a sub-array * \param pos position of returned sub-array to start, * i.e. returned c_array's c_ptr() will return * this->c_ptr()+pos. It is an error if pos * is negative. * \param length length of sub array to return, note * that it is an error if length+pos>size() * or if length is negative. */ c_array sub_array(size_type pos, size_type length) const { FASTUIDRAWassert(pos + length <= m_size); return c_array(m_ptr + pos, length); } /*! * Returns a sub-array, equivalent to * \code * sub_array(pos, size() - pos) * \endcode * \param pos position of returned sub-array to start, * i.e. returned c_array's c_ptr() will return * this->c_ptr() + pos. It is an error is pos * is negative. */ c_array sub_array(size_type pos) const { FASTUIDRAWassert(pos <= m_size); return c_array(m_ptr + pos, m_size - pos); } /*! * Returns a sub-array, equivalent to * \code * sub_array(R.m_begin, R.m_end - R.m_begin) * \endcode * \tparam I type convertible to size_type * \param R range of returned sub-array */ template<typename I> c_array sub_array(range_type<I> R) const { return sub_array(R.m_begin, R.m_end - R.m_begin); } /*! * Provided as a conveniance, equivalent to * \code * *this = this->sub_array(0, size() - 1); * \endcode * It is an error to call this when size() is 0. */ void pop_back(void) { FASTUIDRAWassert(m_size > 0); --m_size; } /*! * Provided as a conveniance, equivalent to * \code * *this = this->sub_array(1, size() - 1); * \endcode * It is an error to call this when size() is 0. */ void pop_front(void) { FASTUIDRAWassert(m_size > 0); --m_size; ++m_ptr; } /*! * Returns true if and only if the passed * the c_array references exactly the same * data as this c_array. * \param rhs c_array to which to compare */ template<typename U> bool same_data(const c_array<U> &rhs) const { return m_ptr == rhs.m_ptr && m_size * sizeof(T) == rhs.m_size * sizeof(U); } private: template<typename> friend class c_array; size_type m_size; T *m_ptr; }; /*! @} */ } //namespace <|endoftext|>
<commit_before>#ifndef ROCFFT_HPP_ #define ROCFFT_HPP_ #include "core/application.hpp" #include "core/timer_cuda.hpp" #include "core/fft.hpp" #include "core/types.hpp" #include "core/traits.hpp" #include "core/context.hpp" //#include "rocfft_helper.hpp" #include "hip/hip_runtime_api.h" #include "hip/hip_vector_types.h" #include "rocfft.h" #include <vector_types.h> #include <array> #include <regex> namespace gearshifft { namespace Rocfft { namespace traits{ template<typename T_Precision=float> struct Types { using ComplexType = std::complex<float32_t>; using RealType = float32_t; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; struct FFTExecuteForward{ void operator()(rocfft_plan plan, RealType* in, ComplexType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } void operator()(rocfftHandle plan, ComplexType* in, ComplexType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } }; struct FFTExecuteInverse{ void operator()(rocfftHandle plan, ComplexType* in, RealType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } void operator()(rocfftHandle plan, ComplexType* in, ComplexType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } }; }; template<> struct Types<double> { using ComplexType = std::complex<float64_t>; using RealType = float64_t; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; }; } // namespace traits /** * HIP context create() and destroy(). Time is benchmarked. */ struct RocfftContext : public ContextDefault<> { int device = 0; static const std::string title() { return "Rocfft"; } static std::string get_device_list() { return listHipDevices().str(); } std::string get_used_device_properties() { auto ss = getHIPDeviceInformations(device); return ss.str(); } void create() { const std::string options_devtype = options().getDevice(); device = atoi(options_devtype.c_str()); int nrdev=0; CHECK_HIP(hipGetDeviceCount(&nrdev)); assert(nrdev>0); if(device<0 || device>=nrdev) device = 0; CHECK_HIP(hipSetDevice(device)); } void destroy() { CHECK_HIP(hipDeviceReset()); } }; /** * Estimates memory required/reserved by rocfft plan to perform the transformation */ size_t estimateAllocSize(rocfft_plan& plan) { size_t s=0; CHECK_HIP( rocfft_plan_get_work_buffer_size(plan, &s) ); return s; } /** * Rocfft plan and execution class. * * This class handles: * - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}. */ template<typename TFFT, // see fft.hpp (FFT_Inplace_Real, ...) typename TPrecision, // double, float size_t NDim // 1..3 > struct RocfftImpl { using Extent = std::array<size_t,NDim>; using Types = typename traits::Types<TPrecision>; using ComplexType = typename Types::ComplexType; using RealType = typename Types::RealType; static constexpr bool IsInplace = TFFT::IsInplace; static constexpr bool IsComplex = TFFT::IsComplex; static constexpr bool IsHalf = std::is_same<TPrecision, float16>::value; static constexpr bool IsSingle = std::is_same<TPrecision, float32_t>::value; static constexpr bool IsInplaceReal = IsInplace && IsComplex==false; static constexpr rocfft_transform_type FFTForward = IsComplex ? Types::FFTComplexForward : Types::FFTRealForward; static constexpr rocfft_transform_type FFTInverse = IsComplex ? Types::FFTComplexInverse : Types::FFTRealInverse; static constexpr rocfft_precision FFTPrecision = IsSingle ? rocfft_precision_single : rocfft_precision_double; static constexpr rocfft_precision FFTPlacement = IsInplace ? rocfft_placement_inplace : rocfft_placement_notinplace; using value_type = typename std::conditional<IsComplex,ComplexType,RealType>::type; /// extents of the FFT input data Extent extents_ = {{0}}; /// extents of the FFT complex data (=FFT(input)) Extent extents_complex_ = {{0}}; /// product of corresponding extents size_t n_ = 0; /// product of corresponding extents size_t n_complex_ = 0; rocfft_plan plan_ = 0; rocfft_execution_info plan_info_= nullptr; void * work_buffer_ = nullptr; value_type* data_ = nullptr; ComplexType* data_complex_ = nullptr; /// size in bytes of FFT input data size_t data_size_ = 0; /// size in bytes of FFT(input) for out-of-place transforms size_t data_complex_size_ = 0; RocfftImpl(const Extent& cextents) { extents_ = interpret_as::column_major(cextents); extents_complex_ = extents_; n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<size_t>()); if(IsComplex==false){ extents_complex_.back() = (extents_.back()/2 + 1); } n_complex_ = std::accumulate(extents_complex_.begin(), extents_complex_.end(), 1, std::multiplies<size_t>()); data_size_ = (IsInplaceReal? 2*n_complex_ : n_) * sizeof(value_type); if(IsInplace==false) data_complex_size_ = n_complex_ * sizeof(ComplexType); } ~RocfftImpl() { destroy(); } /** * Returns allocated memory on device for FFT */ size_t get_allocation_size() { return data_size_ + data_complex_size_; } /** * Returns size in bytes of one data transfer. * * Upload and download have the same size due to round-trip FFT. * \return Size in bytes of FFT data to be transferred (to device or to host memory buffer). */ size_t get_transfer_size() { // when inplace-real then alloc'd data is bigger than data to be transferred return IsInplaceReal ? n_*sizeof(RealType) : data_size_; } /** * Returns estimated allocated memory on device for FFT plan */ size_t get_plan_size() { size_t size1 = 0; // size forward trafo size_t size2 = 0; // size inverse trafo size1 = estimateAllocSize(plan_); // CHECK_CUDA(rocfftDestroy(plan_)); // plan_=0; // if(IsHalf) // size2 = estimateAllocSizeHalf<ComplexType, value_type>(plan_, extents_); // else if(use64bit_) // size2 = estimateAllocSize64<FFTInverse>(plan_,extents_); // else{ // size2 = estimateAllocSize<FFTInverse>(plan_,extents_); // } // CHECK_CUDA(rocfftDestroy(plan_)); // plan_=0; // check available GPU memory size_t mem_free=0, mem_tot=0; CHECK_HIP( hipMemGetInfo(&mem_free, &mem_tot) ); size_t wanted = std::max(size1,size2) + data_size_ + data_complex_size_; if(mem_free<wanted) { std::stringstream ss; ss << mem_free << "<" << wanted << " (bytes)"; throw std::runtime_error("Not enough GPU memory available. "+ss.str()); } size_t total_mem = 95*getMemorySize()/100; // keep some memory available, otherwise an out-of-memory killer becomes more likely if(total_mem < 2*data_size_) { // includes host input buffers std::stringstream ss; ss << total_mem << "<" << 2*data_size_ << " (bytes)"; throw std::runtime_error("Host data exceeds physical memory. "+ss.str()); } return std::max(size1,size2); } // --- next methods are benchmarked --- /** * Allocate buffers on CUDA device */ void allocate() { CHECK_CUDA(cudaMalloc(&data_, data_size_)); if(IsInplace) { data_complex_ = reinterpret_cast<ComplexType*>(data_); }else{ CHECK_CUDA(cudaMalloc(&data_complex_, data_complex_size_)); } } // create FFT plan handle void init_forward() { rocfft_plan_create(&plan_, FFTPlacement, FFTForward, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr); if(data_size_ < 1024){ size_t workBufferSize = 0; rocfft_plan_get_work_buffer_size(plan_, &workBufferSize_fwd); rocfft_execution_info_create(&plan_info_); if(workBufferSize > 0) { CHECK_HIP(hipMalloc(&work_buffer, workBufferSize)); rocfft_execution_info_set_work_buffer(plan_info_, work_buffer, workBufferSize); } } } // recreates plan if needed void init_inverse() { rocfft_plan_create(&plan_, FFTPlacement, FFTInverse, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr); } void execute_forward() { rocfft_execute(plan_, (void**) &data_, (void**) &data_complex_, plan_info_); } void execute_inverse() { rocfft_execute(plan_, (void**) &data_complex_, (void**) &data_, plan_info_); } template<typename THostData> void upload(THostData* input) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(data_, pitch, input, w, w, h, hipMemcpyHostToDevice)); }else{ CHECK_HIP(hipMemcpy(data_, input, get_transfer_size(), hipMemcpyHostToDevice)); } } template<typename THostData> void download(THostData* output) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(output, w, data_, pitch, w, h, hipMemcpyDeviceToHost)); }else{ CHECK_HIP(hipMemcpy(output, data_, get_transfer_size(), hipMemcpyDeviceToHost)); } } void destroy() { CHECK_HIP( hipFree(data_) ); data_=nullptr; if(IsInplace==false && data_complex_) { CHECK_HIP( hipFree(data_complex_) ); data_complex_ = nullptr; } if(plan_) { CHECK_HIP( rocfftDestroy(plan_) ); plan_=0; } } }; using Inplace_Real = gearshifft::FFT<FFT_Inplace_Real, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; using Outplace_Real = gearshifft::FFT<FFT_Outplace_Real, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; using Inplace_Complex = gearshifft::FFT<FFT_Inplace_Complex, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; using Outplace_Complex = gearshifft::FFT<FFT_Outplace_Complex, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; } // namespace Rocfft } // namespace gearshifft #endif /* ROCFFT_HPP_ */ <commit_msg>added include of hipfied timer<commit_after>#ifndef ROCFFT_HPP_ #define ROCFFT_HPP_ #include "core/application.hpp" #include "core/timer_hip.hpp" #include "core/fft.hpp" #include "core/types.hpp" #include "core/traits.hpp" #include "core/context.hpp" //#include "rocfft_helper.hpp" #include "hip/hip_runtime_api.h" #include "hip/hip_vector_types.h" #include "rocfft.h" #include <vector_types.h> #include <array> #include <regex> namespace gearshifft { namespace Rocfft { namespace traits{ template<typename T_Precision=float> struct Types { using ComplexType = std::complex<float32_t>; using RealType = float32_t; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; struct FFTExecuteForward{ void operator()(rocfft_plan plan, RealType* in, ComplexType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } void operator()(rocfftHandle plan, ComplexType* in, ComplexType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } }; struct FFTExecuteInverse{ void operator()(rocfftHandle plan, ComplexType* in, RealType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } void operator()(rocfftHandle plan, ComplexType* in, ComplexType* out){ CHECK_HIP(rocfft_execute(plan, (void**) &in, out, nullptr)); } }; }; template<> struct Types<double> { using ComplexType = std::complex<float64_t>; using RealType = float64_t; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; }; } // namespace traits /** * HIP context create() and destroy(). Time is benchmarked. */ struct RocfftContext : public ContextDefault<> { int device = 0; static const std::string title() { return "Rocfft"; } static std::string get_device_list() { return listHipDevices().str(); } std::string get_used_device_properties() { auto ss = getHIPDeviceInformations(device); return ss.str(); } void create() { const std::string options_devtype = options().getDevice(); device = atoi(options_devtype.c_str()); int nrdev=0; CHECK_HIP(hipGetDeviceCount(&nrdev)); assert(nrdev>0); if(device<0 || device>=nrdev) device = 0; CHECK_HIP(hipSetDevice(device)); } void destroy() { CHECK_HIP(hipDeviceReset()); } }; /** * Estimates memory required/reserved by rocfft plan to perform the transformation */ size_t estimateAllocSize(rocfft_plan& plan) { size_t s=0; CHECK_HIP( rocfft_plan_get_work_buffer_size(plan, &s) ); return s; } /** * Rocfft plan and execution class. * * This class handles: * - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}. */ template<typename TFFT, // see fft.hpp (FFT_Inplace_Real, ...) typename TPrecision, // double, float size_t NDim // 1..3 > struct RocfftImpl { using Extent = std::array<size_t,NDim>; using Types = typename traits::Types<TPrecision>; using ComplexType = typename Types::ComplexType; using RealType = typename Types::RealType; static constexpr bool IsInplace = TFFT::IsInplace; static constexpr bool IsComplex = TFFT::IsComplex; static constexpr bool IsHalf = std::is_same<TPrecision, float16>::value; static constexpr bool IsSingle = std::is_same<TPrecision, float32_t>::value; static constexpr bool IsInplaceReal = IsInplace && IsComplex==false; static constexpr rocfft_transform_type FFTForward = IsComplex ? Types::FFTComplexForward : Types::FFTRealForward; static constexpr rocfft_transform_type FFTInverse = IsComplex ? Types::FFTComplexInverse : Types::FFTRealInverse; static constexpr rocfft_precision FFTPrecision = IsSingle ? rocfft_precision_single : rocfft_precision_double; static constexpr rocfft_precision FFTPlacement = IsInplace ? rocfft_placement_inplace : rocfft_placement_notinplace; using value_type = typename std::conditional<IsComplex,ComplexType,RealType>::type; /// extents of the FFT input data Extent extents_ = {{0}}; /// extents of the FFT complex data (=FFT(input)) Extent extents_complex_ = {{0}}; /// product of corresponding extents size_t n_ = 0; /// product of corresponding extents size_t n_complex_ = 0; rocfft_plan plan_ = 0; rocfft_execution_info plan_info_= nullptr; void * work_buffer_ = nullptr; value_type* data_ = nullptr; ComplexType* data_complex_ = nullptr; /// size in bytes of FFT input data size_t data_size_ = 0; /// size in bytes of FFT(input) for out-of-place transforms size_t data_complex_size_ = 0; RocfftImpl(const Extent& cextents) { extents_ = interpret_as::column_major(cextents); extents_complex_ = extents_; n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<size_t>()); if(IsComplex==false){ extents_complex_.back() = (extents_.back()/2 + 1); } n_complex_ = std::accumulate(extents_complex_.begin(), extents_complex_.end(), 1, std::multiplies<size_t>()); data_size_ = (IsInplaceReal? 2*n_complex_ : n_) * sizeof(value_type); if(IsInplace==false) data_complex_size_ = n_complex_ * sizeof(ComplexType); } ~RocfftImpl() { destroy(); } /** * Returns allocated memory on device for FFT */ size_t get_allocation_size() { return data_size_ + data_complex_size_; } /** * Returns size in bytes of one data transfer. * * Upload and download have the same size due to round-trip FFT. * \return Size in bytes of FFT data to be transferred (to device or to host memory buffer). */ size_t get_transfer_size() { // when inplace-real then alloc'd data is bigger than data to be transferred return IsInplaceReal ? n_*sizeof(RealType) : data_size_; } /** * Returns estimated allocated memory on device for FFT plan */ size_t get_plan_size() { size_t size1 = 0; // size forward trafo size_t size2 = 0; // size inverse trafo size1 = estimateAllocSize(plan_); // CHECK_CUDA(rocfftDestroy(plan_)); // plan_=0; // if(IsHalf) // size2 = estimateAllocSizeHalf<ComplexType, value_type>(plan_, extents_); // else if(use64bit_) // size2 = estimateAllocSize64<FFTInverse>(plan_,extents_); // else{ // size2 = estimateAllocSize<FFTInverse>(plan_,extents_); // } // CHECK_CUDA(rocfftDestroy(plan_)); // plan_=0; // check available GPU memory size_t mem_free=0, mem_tot=0; CHECK_HIP( hipMemGetInfo(&mem_free, &mem_tot) ); size_t wanted = std::max(size1,size2) + data_size_ + data_complex_size_; if(mem_free<wanted) { std::stringstream ss; ss << mem_free << "<" << wanted << " (bytes)"; throw std::runtime_error("Not enough GPU memory available. "+ss.str()); } size_t total_mem = 95*getMemorySize()/100; // keep some memory available, otherwise an out-of-memory killer becomes more likely if(total_mem < 2*data_size_) { // includes host input buffers std::stringstream ss; ss << total_mem << "<" << 2*data_size_ << " (bytes)"; throw std::runtime_error("Host data exceeds physical memory. "+ss.str()); } return std::max(size1,size2); } // --- next methods are benchmarked --- /** * Allocate buffers on CUDA device */ void allocate() { CHECK_CUDA(cudaMalloc(&data_, data_size_)); if(IsInplace) { data_complex_ = reinterpret_cast<ComplexType*>(data_); }else{ CHECK_CUDA(cudaMalloc(&data_complex_, data_complex_size_)); } } // create FFT plan handle void init_forward() { rocfft_plan_create(&plan_, FFTPlacement, FFTForward, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr); if(data_size_ < 1024){ size_t workBufferSize = 0; rocfft_plan_get_work_buffer_size(plan_, &workBufferSize_fwd); rocfft_execution_info_create(&plan_info_); if(workBufferSize > 0) { CHECK_HIP(hipMalloc(&work_buffer, workBufferSize)); rocfft_execution_info_set_work_buffer(plan_info_, work_buffer, workBufferSize); } } } // recreates plan if needed void init_inverse() { rocfft_plan_create(&plan_, FFTPlacement, FFTInverse, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr); } void execute_forward() { rocfft_execute(plan_, (void**) &data_, (void**) &data_complex_, plan_info_); } void execute_inverse() { rocfft_execute(plan_, (void**) &data_complex_, (void**) &data_, plan_info_); } template<typename THostData> void upload(THostData* input) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(data_, pitch, input, w, w, h, hipMemcpyHostToDevice)); }else{ CHECK_HIP(hipMemcpy(data_, input, get_transfer_size(), hipMemcpyHostToDevice)); } } template<typename THostData> void download(THostData* output) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(output, w, data_, pitch, w, h, hipMemcpyDeviceToHost)); }else{ CHECK_HIP(hipMemcpy(output, data_, get_transfer_size(), hipMemcpyDeviceToHost)); } } void destroy() { CHECK_HIP( hipFree(data_) ); data_=nullptr; if(IsInplace==false && data_complex_) { CHECK_HIP( hipFree(data_complex_) ); data_complex_ = nullptr; } if(plan_) { CHECK_HIP( rocfftDestroy(plan_) ); plan_=0; } } }; using Inplace_Real = gearshifft::FFT<FFT_Inplace_Real, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; using Outplace_Real = gearshifft::FFT<FFT_Outplace_Real, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; using Inplace_Complex = gearshifft::FFT<FFT_Inplace_Complex, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; using Outplace_Complex = gearshifft::FFT<FFT_Outplace_Complex, FFT_Plan_Reusable, RocfftImpl, TimerGPU >; } // namespace Rocfft } // namespace gearshifft #endif /* ROCFFT_HPP_ */ <|endoftext|>
<commit_before>// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { #if defined(OS_CHROMEOS) // Chromeos disallows extensions with NPAPI plug-ins, so it's count is one // less num_expected_extensions_ = 2; #else num_expected_extensions_ = 3; #endif } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.empty()) { command_line->AppendSwitchPath(switches::kLoadExtension, load_extension_); command_line->AppendSwitch(switches::kDisableExtensionsFileAccessCheck); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); // Count the number of non-component extensions. int found_extensions = 0; for (size_t i = 0; i < service->extensions()->size(); i++) if (service->extensions()->at(i)->location() != Extension::COMPONENT) found_extensions++; ASSERT_EQ(static_cast<uint32>(num_expected_extensions), static_cast<uint32>(found_extensions)); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result)); EXPECT_EQ(expect_css, result); result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result)); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; int num_expected_extensions_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(num_expected_extensions_, true); TestInjection(true, true); } // Sometimes times out on Mac. http://crbug.com/48151 #if defined(OS_MACOSX) #define MAYBE_NoFileAccess DISABLED_NoFileAccess #else #define MAYBE_NoFileAccess NoFileAccess #endif // Tests that disallowing file access on an extension prevents it from injecting // script into a page with a file URL. IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_NoFileAccess) { WaitForServicesToStart(num_expected_extensions_, true); ExtensionsService* service = browser()->profile()->GetExtensionsService(); for (size_t i = 0; i < service->extensions()->size(); ++i) { if (service->extensions()->at(i)->location() == Extension::COMPONENT) continue; if (service->AllowFileAccess(service->extensions()->at(i))) { service->SetAllowFileAccess(service->extensions()->at(i), false); ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } } TestInjection(false, false); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; // Flaky (times out) on Mac/Windows. http://crbug.com/46301. #if defined(OS_MACOSX) || defined(OS_WIN) #define MAYBE_Test FLAKY_Test #else #define MAYBE_Test Test #endif IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) { WaitForServicesToStart(1, false); TestInjection(true, true); } <commit_msg>Unmark ExtensionsLoadTest.Test as flaky. It doesn't appear to flake anymore on windows or linux. For some reason it doesn't show up in the flakiness dashboard at all for mac, but a spot check of recent builds show similar rock-solidness.<commit_after>// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { #if defined(OS_CHROMEOS) // Chromeos disallows extensions with NPAPI plug-ins, so it's count is one // less num_expected_extensions_ = 2; #else num_expected_extensions_ = 3; #endif } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.empty()) { command_line->AppendSwitchPath(switches::kLoadExtension, load_extension_); command_line->AppendSwitch(switches::kDisableExtensionsFileAccessCheck); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); // Count the number of non-component extensions. int found_extensions = 0; for (size_t i = 0; i < service->extensions()->size(); i++) if (service->extensions()->at(i)->location() != Extension::COMPONENT) found_extensions++; ASSERT_EQ(static_cast<uint32>(num_expected_extensions), static_cast<uint32>(found_extensions)); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result)); EXPECT_EQ(expect_css, result); result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result)); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; int num_expected_extensions_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(num_expected_extensions_, true); TestInjection(true, true); } // Sometimes times out on Mac. http://crbug.com/48151 #if defined(OS_MACOSX) #define MAYBE_NoFileAccess DISABLED_NoFileAccess #else #define MAYBE_NoFileAccess NoFileAccess #endif // Tests that disallowing file access on an extension prevents it from injecting // script into a page with a file URL. IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_NoFileAccess) { WaitForServicesToStart(num_expected_extensions_, true); ExtensionsService* service = browser()->profile()->GetExtensionsService(); for (size_t i = 0; i < service->extensions()->size(); ++i) { if (service->extensions()->at(i)->location() == Extension::COMPONENT) continue; if (service->AllowFileAccess(service->extensions()->at(i))) { service->SetAllowFileAccess(service->extensions()->at(i), false); ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } } TestInjection(false, false); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) { WaitForServicesToStart(1, false); TestInjection(true, true); } <|endoftext|>
<commit_before>#ifndef KEYBOARD_HPP #define KEYBOARD_HPP /// /// \brief The Keyboard class provides support to read the keyboard. /// class Keyboard { public: /// /// \brief Contains all supported keys. /// enum Key { Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, A, AC_BACK, AC_BOOKMARKS, AC_FORWARD, AC_HOME, AC_REFRESH, AC_SEARCH, AC_STOP, Again, AltErase, Quote, Application, AudioMute, AudioNext, AudioPlay, AudioPrev, AuidoStop, B, Backslash, Backspace, BrightnessDown, BrightnessUp, C, Calculator, Cancel, Capslock, Clear, ClearAgain, Comma, Computer, Copy, CrSel, CurrencySubUnit, CurrencyUnit, Cut, D, DecimalSeparator, Delete, DisplaySwitch, Down, E, Eject, End, Equals, Escape, Execute, Exsel, F, F1, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F2, F20, F21, F22, F23, F24, F3, F4, F5, F6, F7, F8, F9, Find, G, BackQuote, H, Help, Home, I, Insert, J, K, KBDIllumDown, KBDIllumToggle, KBDIllumUp, Keypad0, Keypad00, Keypad000, Keypad1, Keypad2, Keypad3, Keypad4, Keypad5, Keypad6, Keypad7, Keypad8, Keypad9, KeypadA, KeypadAmpersand, KeypadAt, KeypadB, KeypadBackspace, KeypadBinary, KeypadC, KeypadClear, KeypadClearEntry, KeypadColon, KeypadComma, KeypadD, KeypadDoubleAmpersand, KeypadDoubleVerticalBar, KeypadDecimal, KeypadDivide, KeypadE, KeypadEnter, KeypadEquals, KeypadEqualsAS400, KeypadExclamation, KeypadF, KeypadGreater, KeypadHash, KeypadHexadecimal, KeypadLBrace, KeypadLParenthesis, KeypadLess, KeypadMemAdd, KeypadMemClear, KeypadMemDivide, KeypadMemMultiply, KeypadMemRecall, KeypadMemStore, KeypadMemSubstract, KeypadMinus, KeypadMultiply, KeypadOctal, KeypadPercent, KeypadPeriod, KeypadPlus, KeypadPlusMinus, KeypadPower, KeypadRBrace, KeypadRParenthesis, KeypadSpace, KeypadTab, KeypadVerticalBar, KeypadXor, L, LAlt, LControl, Left, LBracket, LGUI, LShift, M, Mail, MediaSelect, Menu, Minus, Mode, Mute, N, NumLockClear, O, Oper, Out, P, PageDown, PageUp, Paste, Pause, Period, Power, PrintScren, Prior, Q, R, RAlt, RControl, Return, Return2, RGUI, Right, RBracket, RShift, S, ScrollLock, Select, Semicolont, Separator, Slash, Sleep, Space, Stop, Sysreq, T, Tab, ThousandsSeparator, U, Undo, Unknown, UP, V, VolumeDown, VolumeUp, W, WWW, X, Y, Z, Ampersand, Asterisk, At, Caret, Colon, Dollar, Exclamation, Greater, Hash, LParenthesis, Less, Percent, Plus, Question, DoubleQuote, RParenthesis, Underscore, KeyCount }; /// /// \brief Tells whether the given key is pressed (held down) /// static bool pressed(Key k); /// /// \brief Tells whether the given key has just been pressed (It was not pressed on the last frame and now it is.) /// static bool justPressed(Key k); /// /// \brief Tells whether the given key has just been released (It was pressed on the last frame and it's now released.) /// static bool justReleased(Key k); private: static void init(); static void update(); static bool oldKeyPresses[Keyboard::KeyCount]; friend class Window; }; /// /// \class Keyboard Keyboard.hpp <VBE/system/Keyboard.hpp> /// \ingroup System /// /// You can use this class within an init Environment to access the current /// keyboard device's state. Not all keys are supported in all devices and will /// never be marked as pressed. The state of this device will be updated to /// match recieved events whenever Environment::update() is called. /// /// A Key will be 'just pressed' for only one frame (one update()) call. Then held for /// an indefinite number of frames and released right after. For Example, if the /// user pressed the A Key on frame 1 and released it on frame 4, this would /// register (updating the environment every frame of course): /// /// - Frame 1 /// + Key Keyboard::A is just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 2 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is held /// + Key Keyboard::A is not just released /// - Frame 3 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is held /// + Key Keyboard::A is not just released /// - Frame 4 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is not held /// + Key Keyboard::A is just released /// #endif // KEYBOARD_HPP <commit_msg>Update Keyboard.hpp<commit_after>#ifndef KEYBOARD_HPP #define KEYBOARD_HPP /// /// \brief The Keyboard class provides support to read the keyboard. /// class Keyboard { public: /// /// \brief Contains all supported keys. /// enum Key { Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, A, AC_BACK, AC_BOOKMARKS, AC_FORWARD, AC_HOME, AC_REFRESH, AC_SEARCH, AC_STOP, Again, AltErase, Quote, Application, AudioMute, AudioNext, AudioPlay, AudioPrev, AuidoStop, B, Backslash, Backspace, BrightnessDown, BrightnessUp, C, Calculator, Cancel, Capslock, Clear, ClearAgain, Comma, Computer, Copy, CrSel, CurrencySubUnit, CurrencyUnit, Cut, D, DecimalSeparator, Delete, DisplaySwitch, Down, E, Eject, End, Equals, Escape, Execute, Exsel, F, F1, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F2, F20, F21, F22, F23, F24, F3, F4, F5, F6, F7, F8, F9, Find, G, BackQuote, H, Help, Home, I, Insert, J, K, KBDIllumDown, KBDIllumToggle, KBDIllumUp, Keypad0, Keypad00, Keypad000, Keypad1, Keypad2, Keypad3, Keypad4, Keypad5, Keypad6, Keypad7, Keypad8, Keypad9, KeypadA, KeypadAmpersand, KeypadAt, KeypadB, KeypadBackspace, KeypadBinary, KeypadC, KeypadClear, KeypadClearEntry, KeypadColon, KeypadComma, KeypadD, KeypadDoubleAmpersand, KeypadDoubleVerticalBar, KeypadDecimal, KeypadDivide, KeypadE, KeypadEnter, KeypadEquals, KeypadEqualsAS400, KeypadExclamation, KeypadF, KeypadGreater, KeypadHash, KeypadHexadecimal, KeypadLBrace, KeypadLParenthesis, KeypadLess, KeypadMemAdd, KeypadMemClear, KeypadMemDivide, KeypadMemMultiply, KeypadMemRecall, KeypadMemStore, KeypadMemSubstract, KeypadMinus, KeypadMultiply, KeypadOctal, KeypadPercent, KeypadPeriod, KeypadPlus, KeypadPlusMinus, KeypadPower, KeypadRBrace, KeypadRParenthesis, KeypadSpace, KeypadTab, KeypadVerticalBar, KeypadXor, L, LAlt, LControl, Left, LBracket, LGUI, LShift, M, Mail, MediaSelect, Menu, Minus, Mode, Mute, N, NumLockClear, O, Oper, Out, P, PageDown, PageUp, Paste, Pause, Period, Power, PrintScren, Prior, Q, R, RAlt, RControl, Return, Return2, RGUI, Right, RBracket, RShift, S, ScrollLock, Select, Semicolont, Separator, Slash, Sleep, Space, Stop, Sysreq, T, Tab, ThousandsSeparator, U, Undo, Unknown, UP, V, VolumeDown, VolumeUp, W, WWW, X, Y, Z, Ampersand, Asterisk, At, Caret, Colon, Dollar, Exclamation, Greater, Hash, LParenthesis, Less, Percent, Plus, Question, DoubleQuote, RParenthesis, Underscore, KeyCount }; /// /// \brief Tells whether the given key is pressed (held down) /// static bool pressed(Key k); /// /// \brief Tells whether the given key has just been pressed (It was not pressed on the last frame and now it is.) /// static bool justPressed(Key k); /// /// \brief Tells whether the given key has just been released (It was pressed on the last frame and it's now released.) /// static bool justReleased(Key k); private: static void init(); static void update(); static bool oldKeyPresses[Keyboard::KeyCount]; friend class Window; }; /// /// \class Keyboard Keyboard.hpp <VBE/system/Keyboard.hpp> /// \ingroup System /// /// You can use this class within an init Environment to access the current /// keyboard device's state. Not all keys are supported in all devices and will /// never be marked as pressed. The state of this device will be updated to /// match recieved events whenever Environment::update() is called. /// /// A Key will be 'just pressed' for only one frame (one update()) call. Then held for /// an indefinite number of frames and released right after. For Example, if the /// user pressed the A Key on frame 1 and released it on frame 4, this would /// register (updating the environment every frame of course): /// /// - Frame 1 /// + Key Keyboard::A is just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 2 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 3 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is pressed /// + Key Keyboard::A is not just released /// - Frame 4 /// + Key Keyboard::A is not just pressed /// + Key Keyboard::A is not pressed /// + Key Keyboard::A is just released /// #endif // KEYBOARD_HPP <|endoftext|>
<commit_before>#ifndef ELEKTRA_KDBTHREAD_HPP #define ELEKTRA_KDBTHREAD_HPP #include <kdbcontext.hpp> #include <kdb.hpp> #include <mutex> #include <thread> #include <vector> #include <cassert> #include <algorithm> #include <functional> #include <unordered_map> namespace kdb { /// Subject from Observer pattern for ThreadContext class ThreadSubject { public: virtual void notify(KeySet &ks) = 0; virtual void syncLayers() = 0; }; /// A vector of layers typedef std::vector<std::shared_ptr<Layer>> LayerVector; typedef std::unordered_map<std::string, std::vector<std::function<void()>>> FunctionMap; /// A data structure that is stored by context inside the Coordinator struct PerContext { KeySet toUpdate; LayerVector toActivate; LayerVector toDeactivate; }; class ThreadNoContext { public: /** * @brief attach a new value * * NoContext will never update anything */ void attachByName(ELEKTRA_UNUSED std::string const & key_name,ELEKTRA_UNUSED ValueObserver & ValueObserver) {} /** * @brief The evaluated equals the non-evaluated name! * * @return NoContext always returns the same string */ std::string evaluate(std::string const & key_name) const { return key_name; } /** * @brief (Re)attaches a ValueSubject to a thread or simply * execute code in a locked section. * * NoContext just executes the function but does so in a * thread-safe way * * @param c the command to apply */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); c(); } private: std::mutex m_mutex; }; /** * @brief Thread safe coordination of ThreadContext per Threads. */ class Coordinator { public: template <typename T> void onLayerActivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onActivate[layer->id()].push_back(f); } template <typename T> void onLayerDeactivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onDeactivate[layer->id()].push_back(f); } void onLayerActivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].push_back(f); } void onLayerDeactivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].push_back(f); } void clearOnLayerActivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].clear(); } void clearOnLayerDeactivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].clear(); } std::unique_lock<std::mutex> requireLock() { std::unique_lock<std::mutex> lock(m_mutex); return std::move(lock); } private: friend class ThreadContext; void attach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.insert(std::make_pair(c, PerContext())); } void detach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.erase(c); } /** * @brief Update the given ThreadContext with newly assigned * values. */ void updateNewlyAssignedValues(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); KeySet & toUpdate = m_updates[c].toUpdate; if (toUpdate.size() == 0) return; c->notify(toUpdate); toUpdate.clear(); } /** * @brief Receive a function to be executed and remember * which keys need a update in the other ThreadContexts. */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); Command::Pair ret = c(); c.oldKey = ret.first; c.newKey = ret.second; // potentially an assignment took place, notify others for (auto & i: m_updates) { i.second.toUpdate.append(Key(c.newKey, KEY_CASCADING_NAME, KEY_END)); } } void runOnActivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); for (auto && f: m_onActivate[layer->id()]) { f(); } } /** * @brief Request that some layer needs to be globally * activated. * * @param cc requests it and already has it updated itself * @param layer to activate for all threads */ void globalActivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnActivate(layer); cc->syncLayers(); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already activated if (cc == c.first) continue; c.second.toActivate.push_back(layer); } } void runOnDeactivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); for (auto && f: m_onDeactivate[layer->id()]) { f(); } } void globalDeactivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnDeactivate(layer); cc->syncLayers(); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already deactivated if (cc == c.first) continue; c.second.toDeactivate.push_back(layer); } } /** * @param cc requester of its updates * * @see globalActivate * @return all layers for that subject */ LayerVector fetchGlobalActivation(ThreadSubject *cc) { std::lock_guard<std::mutex> lock (m_mutex); LayerVector ret; ret.swap(m_updates[cc].toActivate); return std::move(ret); } LayerVector fetchGlobalDeactivation(ThreadSubject *cc) { std::lock_guard<std::mutex> lock (m_mutex); LayerVector ret; ret.swap(m_updates[cc].toDeactivate); return std::move(ret); } /// stores per context updates not yet delievered std::unordered_map<ThreadSubject *, PerContext> m_updates; /// mutex protecting m_updates std::mutex m_mutex; FunctionMap m_onActivate; std::mutex m_mutexOnActivate; FunctionMap m_onDeactivate; std::mutex m_mutexOnDeactivate; }; class ThreadContext : public ThreadSubject, public Context { public: typedef std::reference_wrapper<ValueSubject> ValueRef ; explicit ThreadContext(Coordinator & gc) : m_gc(gc) { m_gc.attach(this); } ~ThreadContext() { m_gc.detach(this); } Coordinator & global() { return m_gc; } Coordinator & g() { return m_gc; } template <typename T, typename... Args> std::shared_ptr<Layer> activate(Args&&... args) { std::shared_ptr<Layer>layer = Context::activate<T>(std::forward<Args>(args)...); m_gc.globalActivate(this, layer); return layer; } template <typename T, typename... Args> std::shared_ptr<Layer> deactivate(Args&&... args) { std::shared_ptr<Layer>layer = Context::deactivate<T>(std::forward<Args>(args)...); m_gc.globalDeactivate(this, layer); return layer; } void syncLayers() { // now activate/deactive layers Events e; for(auto const & l: m_gc.fetchGlobalActivation(this)) { lazyActivateLayer(l); e.push_back(l->id()); } for(auto const & l: m_gc.fetchGlobalDeactivation(this)) { lazyDeactivateLayer(l); e.push_back(l->id()); } notifyByEvents(e); // pull in assignments from other threads m_gc.updateNewlyAssignedValues(this); } /** * @brief Command dispatching * * @param c the command to execute */ void execute(Command & c) { m_gc.execute(c); if (c.oldKey != c.newKey) { if (!c.oldKey.empty()) { m_keys.erase(c.oldKey); } if (!c.newKey.empty()) { m_keys.insert(std::make_pair(c.newKey, ValueRef(c.v))); } } } /** * @brief notify all keys * * Locked during execution, safe to use ks * * @param ks */ void notify(KeySet & ks) { for(auto const & k: ks) { auto const& f = m_keys.find(k.getName()); if (f == m_keys.end()) continue; // key already had context change f->second.get().notifyInThread(); } } private: Coordinator & m_gc; /** * @brief A map of values this ThreadContext is responsible for. */ std::unordered_map<std::string, ValueRef> m_keys; }; template<typename T, typename PolicySetter1 = DefaultPolicyArgs, typename PolicySetter2 = DefaultPolicyArgs, typename PolicySetter3 = DefaultPolicyArgs, typename PolicySetter4 = DefaultPolicyArgs, typename PolicySetter5 = DefaultPolicyArgs > using ThreadValue = Value <T, ContextPolicyIs<ThreadContext>, PolicySetter1, PolicySetter2, PolicySetter3, PolicySetter4, PolicySetter5 >; typedef ThreadValue<uint32_t>ThreadInteger; typedef ThreadValue<bool>ThreadBoolean; typedef ThreadValue<std::string>ThreadString; } #endif <commit_msg>add debug for left-over objects<commit_after>#ifndef ELEKTRA_KDBTHREAD_HPP #define ELEKTRA_KDBTHREAD_HPP #include <kdbcontext.hpp> #include <kdb.hpp> #include <mutex> #include <thread> #include <vector> #include <cassert> #include <algorithm> #include <functional> #include <unordered_map> namespace kdb { /// Subject from Observer pattern for ThreadContext class ThreadSubject { public: virtual void notify(KeySet &ks) = 0; virtual void syncLayers() = 0; }; /// A vector of layers typedef std::vector<std::shared_ptr<Layer>> LayerVector; typedef std::unordered_map<std::string, std::vector<std::function<void()>>> FunctionMap; /// A data structure that is stored by context inside the Coordinator struct PerContext { KeySet toUpdate; LayerVector toActivate; LayerVector toDeactivate; }; class ThreadNoContext { public: /** * @brief attach a new value * * NoContext will never update anything */ void attachByName(ELEKTRA_UNUSED std::string const & key_name,ELEKTRA_UNUSED ValueObserver & ValueObserver) {} /** * @brief The evaluated equals the non-evaluated name! * * @return NoContext always returns the same string */ std::string evaluate(std::string const & key_name) const { return key_name; } /** * @brief (Re)attaches a ValueSubject to a thread or simply * execute code in a locked section. * * NoContext just executes the function but does so in a * thread-safe way * * @param c the command to apply */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); c(); } private: std::mutex m_mutex; }; /** * @brief Thread safe coordination of ThreadContext per Threads. */ class Coordinator { public: template <typename T> void onLayerActivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onActivate[layer->id()].push_back(f); } template <typename T> void onLayerDeactivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onDeactivate[layer->id()].push_back(f); } void onLayerActivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].push_back(f); } void onLayerDeactivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].push_back(f); } void clearOnLayerActivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].clear(); } void clearOnLayerDeactivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].clear(); } std::unique_lock<std::mutex> requireLock() { std::unique_lock<std::mutex> lock(m_mutex); return std::move(lock); } ~Coordinator() { #if DEBUG for (auto & i: m_updates) { std::cout << "coordinator " << this << "left over : " << i.first << " with updates: " << i.second.toUpdate.size() << " activations: " << i.second.toActivate.size() << " deactivations: " << i.second.toDeactivate.size() << std::endl; } #endif } private: friend class ThreadContext; void attach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.insert(std::make_pair(c, PerContext())); } void detach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.erase(c); } /** * @brief Update the given ThreadContext with newly assigned * values. */ void updateNewlyAssignedValues(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); KeySet & toUpdate = m_updates[c].toUpdate; if (toUpdate.size() == 0) return; c->notify(toUpdate); toUpdate.clear(); } /** * @brief Receive a function to be executed and remember * which keys need a update in the other ThreadContexts. */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); Command::Pair ret = c(); c.oldKey = ret.first; c.newKey = ret.second; // potentially an assignment took place, notify others for (auto & i: m_updates) { i.second.toUpdate.append(Key(c.newKey, KEY_CASCADING_NAME, KEY_END)); } } void runOnActivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); for (auto && f: m_onActivate[layer->id()]) { f(); } } /** * @brief Request that some layer needs to be globally * activated. * * @param cc requests it and already has it updated itself * @param layer to activate for all threads */ void globalActivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnActivate(layer); cc->syncLayers(); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already activated if (cc == c.first) continue; c.second.toActivate.push_back(layer); } } void runOnDeactivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); for (auto && f: m_onDeactivate[layer->id()]) { f(); } } void globalDeactivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnDeactivate(layer); cc->syncLayers(); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already deactivated if (cc == c.first) continue; c.second.toDeactivate.push_back(layer); } } /** * @param cc requester of its updates * * @see globalActivate * @return all layers for that subject */ LayerVector fetchGlobalActivation(ThreadSubject *cc) { std::lock_guard<std::mutex> lock (m_mutex); LayerVector ret; ret.swap(m_updates[cc].toActivate); return std::move(ret); } LayerVector fetchGlobalDeactivation(ThreadSubject *cc) { std::lock_guard<std::mutex> lock (m_mutex); LayerVector ret; ret.swap(m_updates[cc].toDeactivate); return std::move(ret); } /// stores per context updates not yet delievered std::unordered_map<ThreadSubject *, PerContext> m_updates; /// mutex protecting m_updates std::mutex m_mutex; FunctionMap m_onActivate; std::mutex m_mutexOnActivate; FunctionMap m_onDeactivate; std::mutex m_mutexOnDeactivate; }; class ThreadContext : public ThreadSubject, public Context { public: typedef std::reference_wrapper<ValueSubject> ValueRef ; explicit ThreadContext(Coordinator & gc) : m_gc(gc) { m_gc.attach(this); } ~ThreadContext() { m_gc.detach(this); #if DEBUG for (auto & i: m_keys) { std::cout << "threadcontext " << this << " left over: " << i.first << std::endl; } #endif } Coordinator & global() { return m_gc; } Coordinator & g() { return m_gc; } template <typename T, typename... Args> std::shared_ptr<Layer> activate(Args&&... args) { std::shared_ptr<Layer>layer = Context::activate<T>(std::forward<Args>(args)...); m_gc.globalActivate(this, layer); return layer; } template <typename T, typename... Args> std::shared_ptr<Layer> deactivate(Args&&... args) { std::shared_ptr<Layer>layer = Context::deactivate<T>(std::forward<Args>(args)...); m_gc.globalDeactivate(this, layer); return layer; } void syncLayers() { // now activate/deactive layers Events e; for(auto const & l: m_gc.fetchGlobalActivation(this)) { lazyActivateLayer(l); e.push_back(l->id()); } for(auto const & l: m_gc.fetchGlobalDeactivation(this)) { lazyDeactivateLayer(l); e.push_back(l->id()); } notifyByEvents(e); // pull in assignments from other threads m_gc.updateNewlyAssignedValues(this); } /** * @brief Command dispatching * * @param c the command to execute */ void execute(Command & c) { m_gc.execute(c); if (c.oldKey != c.newKey) { if (!c.oldKey.empty()) { m_keys.erase(c.oldKey); } if (!c.newKey.empty()) { m_keys.insert(std::make_pair(c.newKey, ValueRef(c.v))); } } } /** * @brief notify all keys * * Locked during execution, safe to use ks * * @param ks */ void notify(KeySet & ks) { for(auto const & k: ks) { auto const& f = m_keys.find(k.getName()); if (f == m_keys.end()) continue; // key already had context change f->second.get().notifyInThread(); } } private: Coordinator & m_gc; /** * @brief A map of values this ThreadContext is responsible for. */ std::unordered_map<std::string, ValueRef> m_keys; }; template<typename T, typename PolicySetter1 = DefaultPolicyArgs, typename PolicySetter2 = DefaultPolicyArgs, typename PolicySetter3 = DefaultPolicyArgs, typename PolicySetter4 = DefaultPolicyArgs, typename PolicySetter5 = DefaultPolicyArgs > using ThreadValue = Value <T, ContextPolicyIs<ThreadContext>, PolicySetter1, PolicySetter2, PolicySetter3, PolicySetter4, PolicySetter5 >; typedef ThreadValue<uint32_t>ThreadInteger; typedef ThreadValue<bool>ThreadBoolean; typedef ThreadValue<std::string>ThreadString; } #endif <|endoftext|>
<commit_before>#ifndef ALEPH_GEOMETRY_FLANN_HH__ #define ALEPH_GEOMETRY_FLANN_HH__ #include <aleph/config/FLANN.hh> #include <aleph/geometry/NearestNeighbours.hh> #include <aleph/geometry/distances/Traits.hh> #ifdef ALEPH_WITH_FLANN #include <flann/flann.hpp> #endif #include <algorithm> #include <vector> namespace aleph { namespace geometry { template <class Container, class DistanceFunctor> class FLANN : public NearestNeighbours< FLANN<Container, DistanceFunctor>, std::size_t, typename Container::ElementType > { public: using IndexType = std::size_t; using ElementType = typename Container::ElementType; using Traits = aleph::distances::Traits<DistanceFunctor>; explicit FLANN( const Container& container ) : _container( container ) { #ifdef ALEPH_WITH_FLANN _matrix = flann::Matrix<ElementType>( container.data(), container.size(), container.dimension() ); flann::IndexParams indexParameters = flann::KDTreeSingleIndexParams(); _index = new flann::Index<DistanceFunctor>( _matrix, indexParameters ); _index->buildIndex(); #endif } ~FLANN() { #ifdef ALEPH_WITH_FLANN delete _index; #endif } #ifdef ALEPH_WITH_FLANN void radiusSearch( ElementType radius, std::vector< std::vector<IndexType> >& indices, std::vector< std::vector<ElementType> >& distances ) const { flann::SearchParams searchParameters = flann::SearchParams(); searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED; using ResultType = typename DistanceFunctor::ResultType; std::vector< std::vector<int> > internalIndices; std::vector< std::vector<ResultType> > internalDistances; _index->radiusSearch( _matrix, internalIndices, internalDistances, static_cast<float>( _traits.to( radius ) ), searchParameters ); // Perform transformation of indices ------------------------------- indices.clear(); indices.resize( _matrix.rows ); for( std::size_t i = 0; i < internalIndices.size(); i++ ) { indices[i] = std::vector<IndexType>( internalIndices[i].size() ); std::transform( internalIndices[i].begin(), internalIndices[i].end(), indices[i].begin(), [] ( int j ) { return static_cast<IndexType>( j ); } ); } // Perform transformation of distances ----------------------------- if( internalDistances.empty() ) return; distances.clear(); distances.resize( internalDistances.size(), std::vector<ElementType>( internalDistances.front().size() ) ); { using size_type = typename std::vector< std::vector<ElementType> >::size_type; for( size_type row = 0; row < distances.size(); row++ ) for( size_type col = 0; col < distances[row].size(); col++ ) distances[row][col] = static_cast<ElementType>( internalDistances[row][col] ); } for( auto&& D : distances ) { std::transform( D.begin(), D.end(), D.begin(), [this] ( ElementType x ) { return _traits.from( x ); } ); } } #else void radiusSearch( ElementType /* radius */, std::vector< std::vector<IndexType> >& /* indices */, std::vector< std::vector<ElementType> >& /* distances */ ) const { } #endif #ifdef ALEPH_WITH_FLANN void neighbourSearch( unsigned k, std::vector< std::vector<IndexType> >& indices, std::vector< std::vector<ElementType> >& distances ) const { // FLANN does *not* like being queries for no neighbours at all, so // let's play nice. if( k == 0 ) { indices.clear(); distances.clear(); indices.resize( _matrix.rows ); distances.resize( _matrix.rows ); return; } flann::SearchParams searchParameters = flann::SearchParams(); searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED; using ResultType = typename DistanceFunctor::ResultType; std::vector< std::vector<int> > internalIndices; std::vector< std::vector<ResultType> > internalDistances; _index->knnSearch( _matrix, internalIndices, internalDistances, k, searchParameters ); // Perform transformation of indices ------------------------------- indices.clear(); indices.resize( _matrix.rows ); for( std::size_t i = 0; i < internalIndices.size(); i++ ) { indices[i] = std::vector<IndexType>( internalIndices[i].size() ); std::transform( internalIndices[i].begin(), internalIndices[i].end(), indices[i].begin(), [] ( int j ) { return static_cast<IndexType>( j ); } ); } // Perform transformation of distances ----------------------------- if( internalDistances.empty() ) return; distances.clear(); distances.resize( internalDistances.size(), std::vector<ElementType>( internalDistances.front().size() ) ); { using size_type = typename std::vector< std::vector<ElementType> >::size_type; for( size_type row = 0; row < distances.size(); row++ ) for( size_type col = 0; col < distances[row].size(); col++ ) distances[row][col] = static_cast<ElementType>( internalDistances[row][col] ); } for( auto&& D : distances ) { std::transform( D.begin(), D.end(), D.begin(), [this] ( ElementType x ) { return _traits.from( x ); } ); } } #else void neighbourSearch( unsigned /* k */, std::vector< std::vector<IndexType> >& /* indices */, std::vector< std::vector<ElementType> >& /* distances */ ) const { } #endif std::size_t size() const noexcept { return _container.size(); } // The wrapper must not be copied. Else, clients will run afoul of memory // management issues. FLANN( const FLANN& other ) = delete; FLANN& operator=( const FLANN& other ) = delete; private: const Container& _container; #ifdef ALEPH_WITH_FLANN /** Copy of container data. This makes interfacing with FLANN easier, at the expense of having large storage costs. */ flann::Matrix<ElementType> _matrix; /** Index structure for queries. */ flann::Index<DistanceFunctor>* _index = nullptr; #endif /** Required for optional distance functor conversions */ Traits _traits; }; } // namespace geometry } // namespace aleph #endif <commit_msg>Forcing FLANN results to be sorted<commit_after>#ifndef ALEPH_GEOMETRY_FLANN_HH__ #define ALEPH_GEOMETRY_FLANN_HH__ #include <aleph/config/FLANN.hh> #include <aleph/geometry/NearestNeighbours.hh> #include <aleph/geometry/distances/Traits.hh> #ifdef ALEPH_WITH_FLANN #include <flann/flann.hpp> #endif #include <algorithm> #include <vector> namespace aleph { namespace geometry { template <class Container, class DistanceFunctor> class FLANN : public NearestNeighbours< FLANN<Container, DistanceFunctor>, std::size_t, typename Container::ElementType > { public: using IndexType = std::size_t; using ElementType = typename Container::ElementType; using Traits = aleph::distances::Traits<DistanceFunctor>; explicit FLANN( const Container& container ) : _container( container ) { #ifdef ALEPH_WITH_FLANN _matrix = flann::Matrix<ElementType>( container.data(), container.size(), container.dimension() ); flann::IndexParams indexParameters = flann::KDTreeSingleIndexParams(); _index = new flann::Index<DistanceFunctor>( _matrix, indexParameters ); _index->buildIndex(); #endif } ~FLANN() { #ifdef ALEPH_WITH_FLANN delete _index; #endif } #ifdef ALEPH_WITH_FLANN void radiusSearch( ElementType radius, std::vector< std::vector<IndexType> >& indices, std::vector< std::vector<ElementType> >& distances ) const { flann::SearchParams searchParameters = flann::SearchParams(); searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED; searchParameters.sorted = true; using ResultType = typename DistanceFunctor::ResultType; std::vector< std::vector<int> > internalIndices; std::vector< std::vector<ResultType> > internalDistances; _index->radiusSearch( _matrix, internalIndices, internalDistances, static_cast<float>( _traits.to( radius ) ), searchParameters ); // Perform transformation of indices ------------------------------- indices.clear(); indices.resize( _matrix.rows ); for( std::size_t i = 0; i < internalIndices.size(); i++ ) { indices[i] = std::vector<IndexType>( internalIndices[i].size() ); std::transform( internalIndices[i].begin(), internalIndices[i].end(), indices[i].begin(), [] ( int j ) { return static_cast<IndexType>( j ); } ); } // Perform transformation of distances ----------------------------- if( internalDistances.empty() ) return; distances.clear(); distances.resize( internalDistances.size(), std::vector<ElementType>( internalDistances.front().size() ) ); { using size_type = typename std::vector< std::vector<ElementType> >::size_type; for( size_type row = 0; row < distances.size(); row++ ) for( size_type col = 0; col < distances[row].size(); col++ ) distances[row][col] = static_cast<ElementType>( internalDistances[row][col] ); } for( auto&& D : distances ) { std::transform( D.begin(), D.end(), D.begin(), [this] ( ElementType x ) { return _traits.from( x ); } ); } } #else void radiusSearch( ElementType /* radius */, std::vector< std::vector<IndexType> >& /* indices */, std::vector< std::vector<ElementType> >& /* distances */ ) const { } #endif #ifdef ALEPH_WITH_FLANN void neighbourSearch( unsigned k, std::vector< std::vector<IndexType> >& indices, std::vector< std::vector<ElementType> >& distances ) const { // FLANN does *not* like being queries for no neighbours at all, so // let's play nice. if( k == 0 ) { indices.clear(); distances.clear(); indices.resize( _matrix.rows ); distances.resize( _matrix.rows ); return; } flann::SearchParams searchParameters = flann::SearchParams(); searchParameters.checks = flann::FLANN_CHECKS_UNLIMITED; using ResultType = typename DistanceFunctor::ResultType; std::vector< std::vector<int> > internalIndices; std::vector< std::vector<ResultType> > internalDistances; _index->knnSearch( _matrix, internalIndices, internalDistances, k, searchParameters ); // Perform transformation of indices ------------------------------- indices.clear(); indices.resize( _matrix.rows ); for( std::size_t i = 0; i < internalIndices.size(); i++ ) { indices[i] = std::vector<IndexType>( internalIndices[i].size() ); std::transform( internalIndices[i].begin(), internalIndices[i].end(), indices[i].begin(), [] ( int j ) { return static_cast<IndexType>( j ); } ); } // Perform transformation of distances ----------------------------- if( internalDistances.empty() ) return; distances.clear(); distances.resize( internalDistances.size(), std::vector<ElementType>( internalDistances.front().size() ) ); { using size_type = typename std::vector< std::vector<ElementType> >::size_type; for( size_type row = 0; row < distances.size(); row++ ) for( size_type col = 0; col < distances[row].size(); col++ ) distances[row][col] = static_cast<ElementType>( internalDistances[row][col] ); } for( auto&& D : distances ) { std::transform( D.begin(), D.end(), D.begin(), [this] ( ElementType x ) { return _traits.from( x ); } ); } } #else void neighbourSearch( unsigned /* k */, std::vector< std::vector<IndexType> >& /* indices */, std::vector< std::vector<ElementType> >& /* distances */ ) const { } #endif std::size_t size() const noexcept { return _container.size(); } // The wrapper must not be copied. Else, clients will run afoul of memory // management issues. FLANN( const FLANN& other ) = delete; FLANN& operator=( const FLANN& other ) = delete; private: const Container& _container; #ifdef ALEPH_WITH_FLANN /** Copy of container data. This makes interfacing with FLANN easier, at the expense of having large storage costs. */ flann::Matrix<ElementType> _matrix; /** Index structure for queries. */ flann::Index<DistanceFunctor>* _index = nullptr; #endif /** Required for optional distance functor conversions */ Traits _traits; }; } // namespace geometry } // namespace aleph #endif <|endoftext|>
<commit_before>/** * @file postings_data.tcc * @author Sean Massung */ #include <algorithm> #include "index/postings_data.h" namespace meta { namespace index { template <class PrimaryKey, class SecondaryKey> postings_data<PrimaryKey, SecondaryKey>::postings_data(PrimaryKey p_id): _p_id{p_id} { /* nothing */ } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::merge_with( postings_data & other) { auto searcher = [](const pair_t & p, const SecondaryKey & s) { return p.first < s; }; // O(n log n) now, could be O(n) // if the primary_key doesn't exist, add onto back uint64_t orig_length = _counts.size(); for(auto & p: other._counts) { auto it = std::lower_bound(_counts.begin(), _counts.begin() + orig_length, p.first, searcher); if(it == _counts.end() || it->first != p.first) _counts.emplace_back(std::move(p)); else it->second += p.second; } // sort _counts again to fix new elements added onto back if (_counts.size() > orig_length) { std::sort(_counts.begin(), _counts.end(), [](const pair_t & a, const pair_t & b) { return a.first < b.first; } ); } } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::increase_count( SecondaryKey s_id, double amount) { auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id, [](const pair_t & p, const SecondaryKey & s) { return p.first < s; } ); if(it == _counts.end()) _counts.emplace_back(s_id, amount); else if(it->first != s_id) _counts.emplace(it, s_id, amount); else it->second += amount; } template <class PrimaryKey, class SecondaryKey> double postings_data<PrimaryKey, SecondaryKey>::count(SecondaryKey s_id) const { auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id, [](const pair_t & p, const SecondaryKey & s) { return p.first < s; } ); if(it == _counts.end() || it->first != s_id) return 0.0; return it->second; } template <class PrimaryKey, class SecondaryKey> const std::vector<std::pair<SecondaryKey, double>> & postings_data<PrimaryKey, SecondaryKey>::counts() const { return _counts; } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::set_counts(const count_t & counts) { _counts = counts; std::sort(_counts.begin(), _counts.end(), [](const pair_t & a, const pair_t & b) { return a.first < b.first; } ); } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::set_primary_key(PrimaryKey new_key) { _p_id = new_key; } template <class PrimaryKey, class SecondaryKey> bool postings_data<PrimaryKey, SecondaryKey>::operator<(const postings_data & other) const { return primary_key() < other.primary_key(); } template <class PrimaryKey, class SecondaryKey> bool operator==(const postings_data<PrimaryKey, SecondaryKey> & lhs, const postings_data<PrimaryKey, SecondaryKey> & rhs) { return lhs.primary_key() == rhs.primary_key(); } template <class PrimaryKey, class SecondaryKey> PrimaryKey postings_data<PrimaryKey, SecondaryKey>::primary_key() const { return _p_id; } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::write_compressed( io::compressed_file_writer & writer) const { count_t mutable_counts{_counts}; writer.write(mutable_counts[0].first); if(std::is_same<PrimaryKey, term_id>::value || std::is_same<PrimaryKey, std::string>::value) writer.write(static_cast<uint64_t>(mutable_counts[0].second)); else writer.write(*reinterpret_cast<uint64_t*>(&mutable_counts[0].second)); // use gap encoding on the SecondaryKeys (we know they are integral types) uint64_t cur_id = mutable_counts[0].first; for(size_t i = 1; i < mutable_counts.size(); ++i) { uint64_t temp_id = mutable_counts[i].first; mutable_counts[i].first = mutable_counts[i].first - cur_id; cur_id = temp_id; writer.write(mutable_counts[i].first); if(std::is_same<PrimaryKey, term_id>::value || std::is_same<PrimaryKey, std::string>::value) writer.write(static_cast<uint64_t>(mutable_counts[i].second)); else writer.write(*reinterpret_cast<uint64_t*>(&mutable_counts[i].second)); } // mark end of postings_data writer.write(_delimiter); } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::read_compressed( io::compressed_file_reader & reader) { _counts.clear(); uint64_t last_id = 0; while(true) { uint64_t this_id = reader.next(); // have we reached a delimiter? if(this_id == _delimiter) break; // we're using gap encoding last_id += this_id; SecondaryKey key{last_id}; uint64_t next = reader.next(); double count; if(std::is_same<PrimaryKey, term_id>::value) count = static_cast<double>(next); else count = *reinterpret_cast<double*>(&next); _counts.emplace_back(key, count); } // compress vector to conserve memory (it shouldn't be modified again after // this) _counts.shrink_to_fit(); } namespace { template <class T> uint64_t length(const T & elem, typename std::enable_if< std::is_same<T, std::string>::value >::type * = nullptr) { return elem.size(); } template <class T> uint64_t length(const T & elem, typename std::enable_if< !std::is_same<T, std::string>::value >::type * = nullptr) { return sizeof(elem); } } template <class PrimaryKey, class SecondaryKey> uint64_t postings_data<PrimaryKey, SecondaryKey>::bytes_used() const { return sizeof(pair_t) * _counts.size() + length(_p_id); } } } <commit_msg>Eliminate strict-aliasing violations.<commit_after>/** * @file postings_data.tcc * @author Sean Massung */ #include <algorithm> #include <cstring> #include "index/postings_data.h" namespace meta { namespace index { template <class PrimaryKey, class SecondaryKey> postings_data<PrimaryKey, SecondaryKey>::postings_data(PrimaryKey p_id): _p_id{p_id} { /* nothing */ } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::merge_with( postings_data & other) { auto searcher = [](const pair_t & p, const SecondaryKey & s) { return p.first < s; }; // O(n log n) now, could be O(n) // if the primary_key doesn't exist, add onto back uint64_t orig_length = _counts.size(); for(auto & p: other._counts) { auto it = std::lower_bound(_counts.begin(), _counts.begin() + orig_length, p.first, searcher); if(it == _counts.end() || it->first != p.first) _counts.emplace_back(std::move(p)); else it->second += p.second; } // sort _counts again to fix new elements added onto back if (_counts.size() > orig_length) { std::sort(_counts.begin(), _counts.end(), [](const pair_t & a, const pair_t & b) { return a.first < b.first; } ); } } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::increase_count( SecondaryKey s_id, double amount) { auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id, [](const pair_t & p, const SecondaryKey & s) { return p.first < s; } ); if(it == _counts.end()) _counts.emplace_back(s_id, amount); else if(it->first != s_id) _counts.emplace(it, s_id, amount); else it->second += amount; } template <class PrimaryKey, class SecondaryKey> double postings_data<PrimaryKey, SecondaryKey>::count(SecondaryKey s_id) const { auto it = std::lower_bound(_counts.begin(), _counts.end(), s_id, [](const pair_t & p, const SecondaryKey & s) { return p.first < s; } ); if(it == _counts.end() || it->first != s_id) return 0.0; return it->second; } template <class PrimaryKey, class SecondaryKey> const std::vector<std::pair<SecondaryKey, double>> & postings_data<PrimaryKey, SecondaryKey>::counts() const { return _counts; } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::set_counts(const count_t & counts) { _counts = counts; std::sort(_counts.begin(), _counts.end(), [](const pair_t & a, const pair_t & b) { return a.first < b.first; } ); } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::set_primary_key(PrimaryKey new_key) { _p_id = new_key; } template <class PrimaryKey, class SecondaryKey> bool postings_data<PrimaryKey, SecondaryKey>::operator<(const postings_data & other) const { return primary_key() < other.primary_key(); } template <class PrimaryKey, class SecondaryKey> bool operator==(const postings_data<PrimaryKey, SecondaryKey> & lhs, const postings_data<PrimaryKey, SecondaryKey> & rhs) { return lhs.primary_key() == rhs.primary_key(); } template <class PrimaryKey, class SecondaryKey> PrimaryKey postings_data<PrimaryKey, SecondaryKey>::primary_key() const { return _p_id; } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::write_compressed( io::compressed_file_writer & writer) const { count_t mutable_counts{_counts}; writer.write(mutable_counts[0].first); if(std::is_same<PrimaryKey, term_id>::value || std::is_same<PrimaryKey, std::string>::value) writer.write(static_cast<uint64_t>(mutable_counts[0].second)); else { uint64_t to_write; std::memcpy(&to_write, &mutable_counts[0].second, sizeof(mutable_counts[0].second)); writer.write(to_write); } // use gap encoding on the SecondaryKeys (we know they are integral types) uint64_t cur_id = mutable_counts[0].first; for(size_t i = 1; i < mutable_counts.size(); ++i) { uint64_t temp_id = mutable_counts[i].first; mutable_counts[i].first = mutable_counts[i].first - cur_id; cur_id = temp_id; writer.write(mutable_counts[i].first); if(std::is_same<PrimaryKey, term_id>::value || std::is_same<PrimaryKey, std::string>::value) writer.write(static_cast<uint64_t>(mutable_counts[i].second)); else { uint64_t to_write; std::memcpy(&to_write, &mutable_counts[i].second, sizeof(mutable_counts[i].second)); writer.write(to_write); } } // mark end of postings_data writer.write(_delimiter); } template <class PrimaryKey, class SecondaryKey> void postings_data<PrimaryKey, SecondaryKey>::read_compressed( io::compressed_file_reader & reader) { _counts.clear(); uint64_t last_id = 0; while(true) { uint64_t this_id = reader.next(); // have we reached a delimiter? if(this_id == _delimiter) break; // we're using gap encoding last_id += this_id; SecondaryKey key{last_id}; uint64_t next = reader.next(); double count; if(std::is_same<PrimaryKey, term_id>::value) count = static_cast<double>(next); else std::memcpy(&count, &next, sizeof(next)); _counts.emplace_back(key, count); } // compress vector to conserve memory (it shouldn't be modified again after // this) _counts.shrink_to_fit(); } namespace { template <class T> uint64_t length(const T & elem, typename std::enable_if< std::is_same<T, std::string>::value >::type * = nullptr) { return elem.size(); } template <class T> uint64_t length(const T & elem, typename std::enable_if< !std::is_same<T, std::string>::value >::type * = nullptr) { return sizeof(elem); } } template <class PrimaryKey, class SecondaryKey> uint64_t postings_data<PrimaryKey, SecondaryKey>::bytes_used() const { return sizeof(pair_t) * _counts.size() + length(_p_id); } } } <|endoftext|>
<commit_before>/*********************************************************************** FONCTION : ---------- file OpenGl_togl_redraw.c : REMARQUES: ---------- HISTORIQUE DES MODIFICATIONS : -------------------------------- xx-xx-xx : CAL ; Creation. 23-01-97 : CAL : Ajout pour mettre des traces facilement apres lancement de Designer 05-02-97 : FMN ; Suppression de OpenGl_tgl_vis.h 03-03-97 : FMN ; (PRO4063) Ajout displaylist pour le mode transient 07-10-97 : FMN ; Simplification WNT 08-08-98 : FMN ; ajout PRINT debug 18-11-98 : CAL ; S4062. Ajout des layers. 15-11-99 : GG ; Add call_togl_redraw_area() 15-11-99 : VKH ; G004 redrawing view to a large pixmap 02.01.100 : JR : = 0 for Integer and = NULL for pointers 02.02.100 " #include <GL/glu.h> for declaration of gluErrorString 07-03-00 : GG : G004 use the already created pixmap. Enable two side lighting before redrawing in pixmap. ************************************************************************/ #define G004 /* VKH 15-11-99 redrawing view to a large pixmap */ #define RIC120302 /* GG Enable to use the application display callback at end of traversal Modified P. Dolbey 09/06/07 to call back before redrawing the overlayer */ /*----------------------------------------------------------------------*/ /* * Includes */ #ifdef G004 #ifndef WNT #define CALL_DEF_STRING_LENGTH 132 #else #include <OpenGl_AVIWriter.hxx> #endif # include <OpenGl_tgl_all.hxx> GLboolean g_fBitmap; #endif /*G004*/ #include <OpenGl_tgl.hxx> #include <OpenGl_tsm_ws.hxx> #include <OpenGl_tgl_tox.hxx> #include <OpenGl_txgl.hxx> #include <OpenGl_tgl_funcs.hxx> #include <OpenGl_tgl_subrvis.hxx> #include <OpenGl_FrameBuffer.hxx> #include <InterfaceGraphic_Graphic3d.hxx> #include <InterfaceGraphic_Visual3d.hxx> #if defined(WNT) && defined(__MINGW32__) # include <GL/glext.h> #endif void EXPORT call_togl_redraw ( CALL_DEF_VIEW * aview, CALL_DEF_LAYER * anunderlayer, CALL_DEF_LAYER * anoverlayer ) { CMN_KEY_DATA data; Tint swap = 1; /* swap buffers ? yes */ if ( TsmGetWSAttri (aview->WsId, WSWindow, &data) != TSuccess ) return; WINDOW aWin = (WINDOW )data.ldata; if (TxglWinset (call_thedisplay, aWin) == TSuccess) { OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )aview->ptrFBO; GLint aViewPortBack[4]; glGetIntegerv (GL_VIEWPORT, aViewPortBack); if (aFrameBuffer != NULL) { aFrameBuffer->SetupViewport(); aFrameBuffer->BindBuffer(); swap = 0; // no need to swap buffers } call_func_redraw_all_structs_begin (aview->WsId); if (anunderlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anunderlayer); } call_func_redraw_all_structs_proc (aview->WsId); if (anoverlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anoverlayer); } call_subr_displayCB (aview, OCC_REDRAW_WINDOW); call_func_redraw_all_structs_end (aview->WsId, swap); call_togl_redraw_immediat_mode (aview); if (aFrameBuffer != NULL) { aFrameBuffer->UnbindBuffer(); // move back original viewport glViewport (aViewPortBack[0], aViewPortBack[1], aViewPortBack[2], aViewPortBack[3]); } } #ifdef WNT if (OpenGl_AVIWriter_AllowWriting (aview->DefWindow.XWindow)) { GLint params[4]; glGetIntegerv (GL_VIEWPORT, params); int nWidth = params[2] & ~0x7; int nHeight = params[3] & ~0x7; const int nBitsPerPixel = 24; GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8]; glPixelStorei (GL_PACK_ALIGNMENT, 1); glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData); OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel); delete[] aDumpData; } #endif return; } void EXPORT call_togl_redraw_area ( CALL_DEF_VIEW * aview, CALL_DEF_LAYER * anunderlayer, CALL_DEF_LAYER * anoverlayer, int x, int y, int width, int height ) { CMN_KEY_DATA data; /* When the exposure area size is > window size / 2 do a full redraw. */ if( width*height > (int)(aview->DefWindow.dx*aview->DefWindow.dy)/2 ) { call_togl_redraw(aview,anunderlayer,anoverlayer); return; } /* Or redraw only the area in the front buffer */ TsmGetWSAttri (aview->WsId, WSWindow, &data); if (TxglWinset (call_thedisplay, (WINDOW) data.ldata) == TSuccess) { GLint buffer; glGetIntegerv (GL_DRAW_BUFFER, &buffer); if (buffer != GL_FRONT) glDrawBuffer (GL_FRONT); glEnable (GL_SCISSOR_TEST); glScissor ((GLint )x, (GLint )((int )aview->DefWindow.dy - (y + height)), (GLsizei )width, (GLsizei )height); call_func_redraw_all_structs_begin (aview->WsId); if (anunderlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anunderlayer); } call_func_redraw_all_structs_proc (aview->WsId); if (anoverlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anoverlayer); } call_subr_displayCB(aview,OCC_REDRAW_WINDOWAREA); call_func_redraw_all_structs_end (aview->WsId, 0); call_togl_redraw_immediat_mode (aview); glFlush(); glDisable (GL_SCISSOR_TEST); if (buffer != GL_FRONT) glDrawBuffer (buffer); } } <commit_msg>Slightly change again glext.h conditional include<commit_after>/*********************************************************************** FONCTION : ---------- file OpenGl_togl_redraw.c : REMARQUES: ---------- HISTORIQUE DES MODIFICATIONS : -------------------------------- xx-xx-xx : CAL ; Creation. 23-01-97 : CAL : Ajout pour mettre des traces facilement apres lancement de Designer 05-02-97 : FMN ; Suppression de OpenGl_tgl_vis.h 03-03-97 : FMN ; (PRO4063) Ajout displaylist pour le mode transient 07-10-97 : FMN ; Simplification WNT 08-08-98 : FMN ; ajout PRINT debug 18-11-98 : CAL ; S4062. Ajout des layers. 15-11-99 : GG ; Add call_togl_redraw_area() 15-11-99 : VKH ; G004 redrawing view to a large pixmap 02.01.100 : JR : = 0 for Integer and = NULL for pointers 02.02.100 " #include <GL/glu.h> for declaration of gluErrorString 07-03-00 : GG : G004 use the already created pixmap. Enable two side lighting before redrawing in pixmap. ************************************************************************/ #define G004 /* VKH 15-11-99 redrawing view to a large pixmap */ #define RIC120302 /* GG Enable to use the application display callback at end of traversal Modified P. Dolbey 09/06/07 to call back before redrawing the overlayer */ /*----------------------------------------------------------------------*/ /* * Includes */ #ifdef G004 #ifndef WNT #define CALL_DEF_STRING_LENGTH 132 #else #include <OpenGl_AVIWriter.hxx> #endif # include <OpenGl_tgl_all.hxx> GLboolean g_fBitmap; #endif /*G004*/ #include <OpenGl_tgl.hxx> #include <OpenGl_tsm_ws.hxx> #include <OpenGl_tgl_tox.hxx> #include <OpenGl_txgl.hxx> #include <OpenGl_tgl_funcs.hxx> #include <OpenGl_tgl_subrvis.hxx> #include <OpenGl_FrameBuffer.hxx> #include <InterfaceGraphic_Graphic3d.hxx> #include <InterfaceGraphic_Visual3d.hxx> #if defined(__MINGW32__) # include <GL/glext.h> #endif void EXPORT call_togl_redraw ( CALL_DEF_VIEW * aview, CALL_DEF_LAYER * anunderlayer, CALL_DEF_LAYER * anoverlayer ) { CMN_KEY_DATA data; Tint swap = 1; /* swap buffers ? yes */ if ( TsmGetWSAttri (aview->WsId, WSWindow, &data) != TSuccess ) return; WINDOW aWin = (WINDOW )data.ldata; if (TxglWinset (call_thedisplay, aWin) == TSuccess) { OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )aview->ptrFBO; GLint aViewPortBack[4]; glGetIntegerv (GL_VIEWPORT, aViewPortBack); if (aFrameBuffer != NULL) { aFrameBuffer->SetupViewport(); aFrameBuffer->BindBuffer(); swap = 0; // no need to swap buffers } call_func_redraw_all_structs_begin (aview->WsId); if (anunderlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anunderlayer); } call_func_redraw_all_structs_proc (aview->WsId); if (anoverlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anoverlayer); } call_subr_displayCB (aview, OCC_REDRAW_WINDOW); call_func_redraw_all_structs_end (aview->WsId, swap); call_togl_redraw_immediat_mode (aview); if (aFrameBuffer != NULL) { aFrameBuffer->UnbindBuffer(); // move back original viewport glViewport (aViewPortBack[0], aViewPortBack[1], aViewPortBack[2], aViewPortBack[3]); } } #ifdef WNT if (OpenGl_AVIWriter_AllowWriting (aview->DefWindow.XWindow)) { GLint params[4]; glGetIntegerv (GL_VIEWPORT, params); int nWidth = params[2] & ~0x7; int nHeight = params[3] & ~0x7; const int nBitsPerPixel = 24; GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8]; glPixelStorei (GL_PACK_ALIGNMENT, 1); glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData); OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel); delete[] aDumpData; } #endif return; } void EXPORT call_togl_redraw_area ( CALL_DEF_VIEW * aview, CALL_DEF_LAYER * anunderlayer, CALL_DEF_LAYER * anoverlayer, int x, int y, int width, int height ) { CMN_KEY_DATA data; /* When the exposure area size is > window size / 2 do a full redraw. */ if( width*height > (int)(aview->DefWindow.dx*aview->DefWindow.dy)/2 ) { call_togl_redraw(aview,anunderlayer,anoverlayer); return; } /* Or redraw only the area in the front buffer */ TsmGetWSAttri (aview->WsId, WSWindow, &data); if (TxglWinset (call_thedisplay, (WINDOW) data.ldata) == TSuccess) { GLint buffer; glGetIntegerv (GL_DRAW_BUFFER, &buffer); if (buffer != GL_FRONT) glDrawBuffer (GL_FRONT); glEnable (GL_SCISSOR_TEST); glScissor ((GLint )x, (GLint )((int )aview->DefWindow.dy - (y + height)), (GLsizei )width, (GLsizei )height); call_func_redraw_all_structs_begin (aview->WsId); if (anunderlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anunderlayer); } call_func_redraw_all_structs_proc (aview->WsId); if (anoverlayer->ptrLayer) { call_togl_redraw_layer2d (aview, anoverlayer); } call_subr_displayCB(aview,OCC_REDRAW_WINDOWAREA); call_func_redraw_all_structs_end (aview->WsId, 0); call_togl_redraw_immediat_mode (aview); glFlush(); glDisable (GL_SCISSOR_TEST); if (buffer != GL_FRONT) glDrawBuffer (buffer); } } <|endoftext|>
<commit_before>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ /** \file Tools/Utils/HeapT.hh A generic heap class **/ /** Martin, 26.12.2004: 1) replaced resize(size()-1) with pop_back(), since the later is more efficient 2) replaced interface_.set_heap_position(entry(0), -1); with reset_heap_position() 3) added const modifier to various functions TODO: in the moment the heap does not conform to the HeapInterface specification, i.e., copies are passed instead of references. This is especially important for set_heap_position(), where the reference argument is non-const. The specification should be changed to reflect that the heap actually (only?) works when the heap entry is nothing more but a handle. TODO: change the specification of HeapInterface to make less(), greater() and get_heap_position() const. Needs changing DecimaterT. Might break someone's code. */ //============================================================================= // // CLASS HeapT // //============================================================================= #ifndef OPENMESH_UTILS_HEAPT_HH #define OPENMESH_UTILS_HEAPT_HH //== INCLUDES ================================================================= #include "Config.hh" #include <vector> #include <OpenMesh/Core/System/omstream.hh> //== NAMESPACE ================================================================ namespace OpenMesh { // BEGIN_NS_OPENMESH namespace Utils { // BEGIN_NS_UTILS //== CLASS DEFINITION ========================================================= /** This class demonstrates the HeapInterface's interface. If you * want to build your customized heap you will have to specify a heap * interface class and use this class as a template parameter for the * class HeapT. This class defines the interface that this heap * interface has to implement. * * \see HeapT */ template <class HeapEntry> struct HeapInterfaceT { /// Comparison of two HeapEntry's: strict less bool less(const HeapEntry& _e1, const HeapEntry& _e2); /// Comparison of two HeapEntry's: strict greater bool greater(const HeapEntry& _e1, const HeapEntry& _e2); /// Get the heap position of HeapEntry _e int get_heap_position(const HeapEntry& _e); /// Set the heap position of HeapEntry _e void set_heap_position(HeapEntry& _e, int _i); }; /** \class HeapT HeapT.hh <OSG/Utils/HeapT.hh> * * An efficient, highly customizable heap. * * The main difference (and performance boost) of this heap compared * to e.g. the heap of the STL is that here the positions of the * heap's elements are accessible from the elements themself. * Therefore if one changes the priority of an element one does not * have to remove and re-insert this element, but can just call the * update(HeapEntry) method. * * This heap class is parameterized by two template arguments: * \li the class \c HeapEntry, that will be stored in the heap * \li the HeapInterface telling the heap how to compare heap entries and * how to store the heap positions in the heap entries. * * As an example how to use the class see declaration of class * Decimater::DecimaterT. * * \see HeapInterfaceT */ template <class HeapEntry, class HeapInterface=HeapEntry> class HeapT : private std::vector<HeapEntry> { private: typedef std::vector<HeapEntry> Base; public: /// Constructor HeapT() : HeapVector() {} /// Construct with a given \c HeapIterface. HeapT(const HeapInterface& _interface) : HeapVector(), interface_(_interface) {} /// Destructor. ~HeapT(){}; /// clear the heap void clear() { HeapVector::clear(); } /// is heap empty? bool empty() const { return HeapVector::empty(); } /// returns the size of heap size_t size() const { return HeapVector::size(); } /// reserve space for _n entries void reserve(size_t _n) { HeapVector::reserve(_n); } /// reset heap position to -1 (not in heap) void reset_heap_position(HeapEntry _h) { interface_.set_heap_position(_h, -1); } /// is an entry in the heap? bool is_stored(HeapEntry _h) { return interface_.get_heap_position(_h) != -1; } /// insert the entry _h void insert(HeapEntry _h) { this->push_back(_h); upheap(size()-1); } /// get the first entry HeapEntry front() const { assert(!empty()); return entry(0); } /// delete the first entry void pop_front() { assert(!empty()); reset_heap_position(entry(0)); if (size() > 1) { entry(0, entry(size()-1)); Base::pop_back(); downheap(0); } else { Base::pop_back(); } } /// remove an entry void remove(HeapEntry _h) { int pos = interface_.get_heap_position(_h); reset_heap_position(_h); assert(pos != -1); assert((unsigned int) pos < size()); // last item ? if ((unsigned int) pos == size()-1) { Base::pop_back(); } else { entry(pos, entry(size()-1)); // move last elem to pos Base::pop_back(); downheap(pos); upheap(pos); } } /** update an entry: change the key and update the position to reestablish the heap property. */ void update(HeapEntry _h) { int pos = interface_.get_heap_position(_h); assert(pos != -1); assert((unsigned int)pos < size()); downheap(pos); upheap(pos); } /// check heap condition bool check() { bool ok(true); unsigned int i, j; for (i=0; i<size(); ++i) { if (((j=left(i))<size()) && interface_.greater(entry(i), entry(j))) { omerr() << "Heap condition violated\n"; ok=false; } if (((j=right(i))<size()) && interface_.greater(entry(i), entry(j))) { omerr() << "Heap condition violated\n"; ok=false; } } return ok; } protected: /// Instance of HeapInterface HeapInterface interface_; private: // typedef typedef std::vector<HeapEntry> HeapVector; /// Upheap. Establish heap property. void upheap(unsigned int _idx); /// Downheap. Establish heap property. void downheap(unsigned int _idx); /// Get the entry at index _idx inline HeapEntry entry(size_t _idx) const { assert(_idx < size()); return (Base::operator[](_idx)); } /// Set entry _h to index _idx and update _h's heap position. inline void entry(size_t _idx, HeapEntry _h) { assert(_idx < size()); Base::operator[](_idx) = _h; interface_.set_heap_position(_h, _idx); } /// Get parent's index inline unsigned int parent(unsigned int _i) { return (_i-1)>>1; } /// Get left child's index inline unsigned int left(unsigned int _i) { return (_i<<1)+1; } /// Get right child's index inline unsigned int right(unsigned int _i) { return (_i<<1)+2; } }; //== IMPLEMENTATION ========================================================== template <class HeapEntry, class HeapInterface> void HeapT<HeapEntry, HeapInterface>:: upheap(unsigned int _idx) { HeapEntry h = entry(_idx); size_t parentIdx; while ((_idx>0) && interface_.less(h, entry(parentIdx=parent(_idx)))) { entry(_idx, entry(parentIdx)); _idx = parentIdx; } entry(_idx, h); } //----------------------------------------------------------------------------- template <class HeapEntry, class HeapInterface> void HeapT<HeapEntry, HeapInterface>:: downheap(unsigned int _idx) { HeapEntry h = entry(_idx); unsigned int childIdx; unsigned int s = size(); while(_idx < s) { childIdx = left(_idx); if (childIdx >= s) break; if ((childIdx + 1 < s) && (interface_.less(entry(childIdx + 1), entry(childIdx)))) ++childIdx; if (interface_.less(h, entry(childIdx))) break; entry(_idx, entry(childIdx)); _idx = childIdx; } entry(_idx, h); } //============================================================================= } // END_NS_UTILS } // END_NS_OPENMESH //============================================================================= #endif // OSG_HEAP_HH defined //============================================================================= <commit_msg>Fixed more size_t in Heap<commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ /** \file Tools/Utils/HeapT.hh A generic heap class **/ /** Martin, 26.12.2004: 1) replaced resize(size()-1) with pop_back(), since the later is more efficient 2) replaced interface_.set_heap_position(entry(0), -1); with reset_heap_position() 3) added const modifier to various functions TODO: in the moment the heap does not conform to the HeapInterface specification, i.e., copies are passed instead of references. This is especially important for set_heap_position(), where the reference argument is non-const. The specification should be changed to reflect that the heap actually (only?) works when the heap entry is nothing more but a handle. TODO: change the specification of HeapInterface to make less(), greater() and get_heap_position() const. Needs changing DecimaterT. Might break someone's code. */ //============================================================================= // // CLASS HeapT // //============================================================================= #ifndef OPENMESH_UTILS_HEAPT_HH #define OPENMESH_UTILS_HEAPT_HH //== INCLUDES ================================================================= #include "Config.hh" #include <vector> #include <OpenMesh/Core/System/omstream.hh> //== NAMESPACE ================================================================ namespace OpenMesh { // BEGIN_NS_OPENMESH namespace Utils { // BEGIN_NS_UTILS //== CLASS DEFINITION ========================================================= /** This class demonstrates the HeapInterface's interface. If you * want to build your customized heap you will have to specify a heap * interface class and use this class as a template parameter for the * class HeapT. This class defines the interface that this heap * interface has to implement. * * \see HeapT */ template <class HeapEntry> struct HeapInterfaceT { /// Comparison of two HeapEntry's: strict less bool less(const HeapEntry& _e1, const HeapEntry& _e2); /// Comparison of two HeapEntry's: strict greater bool greater(const HeapEntry& _e1, const HeapEntry& _e2); /// Get the heap position of HeapEntry _e int get_heap_position(const HeapEntry& _e); /// Set the heap position of HeapEntry _e void set_heap_position(HeapEntry& _e, int _i); }; /** \class HeapT HeapT.hh <OSG/Utils/HeapT.hh> * * An efficient, highly customizable heap. * * The main difference (and performance boost) of this heap compared * to e.g. the heap of the STL is that here the positions of the * heap's elements are accessible from the elements themself. * Therefore if one changes the priority of an element one does not * have to remove and re-insert this element, but can just call the * update(HeapEntry) method. * * This heap class is parameterized by two template arguments: * \li the class \c HeapEntry, that will be stored in the heap * \li the HeapInterface telling the heap how to compare heap entries and * how to store the heap positions in the heap entries. * * As an example how to use the class see declaration of class * Decimater::DecimaterT. * * \see HeapInterfaceT */ template <class HeapEntry, class HeapInterface=HeapEntry> class HeapT : private std::vector<HeapEntry> { private: typedef std::vector<HeapEntry> Base; public: /// Constructor HeapT() : HeapVector() {} /// Construct with a given \c HeapIterface. HeapT(const HeapInterface& _interface) : HeapVector(), interface_(_interface) {} /// Destructor. ~HeapT(){}; /// clear the heap void clear() { HeapVector::clear(); } /// is heap empty? bool empty() const { return HeapVector::empty(); } /// returns the size of heap size_t size() const { return HeapVector::size(); } /// reserve space for _n entries void reserve(size_t _n) { HeapVector::reserve(_n); } /// reset heap position to -1 (not in heap) void reset_heap_position(HeapEntry _h) { interface_.set_heap_position(_h, -1); } /// is an entry in the heap? bool is_stored(HeapEntry _h) { return interface_.get_heap_position(_h) != -1; } /// insert the entry _h void insert(HeapEntry _h) { this->push_back(_h); upheap(size()-1); } /// get the first entry HeapEntry front() const { assert(!empty()); return entry(0); } /// delete the first entry void pop_front() { assert(!empty()); reset_heap_position(entry(0)); if (size() > 1) { entry(0, entry(size()-1)); Base::pop_back(); downheap(0); } else { Base::pop_back(); } } /// remove an entry void remove(HeapEntry _h) { int pos = interface_.get_heap_position(_h); reset_heap_position(_h); assert(pos != -1); assert((unsigned int) pos < size()); // last item ? if ((unsigned int) pos == size()-1) { Base::pop_back(); } else { entry(pos, entry(size()-1)); // move last elem to pos Base::pop_back(); downheap(pos); upheap(pos); } } /** update an entry: change the key and update the position to reestablish the heap property. */ void update(HeapEntry _h) { int pos = interface_.get_heap_position(_h); assert(pos != -1); assert((unsigned int)pos < size()); downheap(pos); upheap(pos); } /// check heap condition bool check() { bool ok(true); unsigned int i, j; for (i=0; i<size(); ++i) { if (((j=left(i))<size()) && interface_.greater(entry(i), entry(j))) { omerr() << "Heap condition violated\n"; ok=false; } if (((j=right(i))<size()) && interface_.greater(entry(i), entry(j))) { omerr() << "Heap condition violated\n"; ok=false; } } return ok; } protected: /// Instance of HeapInterface HeapInterface interface_; private: // typedef typedef std::vector<HeapEntry> HeapVector; /// Upheap. Establish heap property. void upheap(size_t _idx); /// Downheap. Establish heap property. void downheap(size_t _idx); /// Get the entry at index _idx inline HeapEntry entry(size_t _idx) const { assert(_idx < size()); return (Base::operator[](_idx)); } /// Set entry _h to index _idx and update _h's heap position. inline void entry(size_t _idx, HeapEntry _h) { assert(_idx < size()); Base::operator[](_idx) = _h; interface_.set_heap_position(_h, _idx); } /// Get parent's index inline unsigned int parent(unsigned int _i) { return (_i-1)>>1; } /// Get left child's index inline unsigned int left(unsigned int _i) { return (_i<<1)+1; } /// Get right child's index inline unsigned int right(unsigned int _i) { return (_i<<1)+2; } }; //== IMPLEMENTATION ========================================================== template <class HeapEntry, class HeapInterface> void HeapT<HeapEntry, HeapInterface>:: upheap(size_t _idx) { HeapEntry h = entry(_idx); size_t parentIdx; while ((_idx>0) && interface_.less(h, entry(parentIdx=parent(_idx)))) { entry(_idx, entry(parentIdx)); _idx = parentIdx; } entry(_idx, h); } //----------------------------------------------------------------------------- template <class HeapEntry, class HeapInterface> void HeapT<HeapEntry, HeapInterface>:: downheap(size_t _idx) { HeapEntry h = entry(_idx); size_t childIdx; size_t s = size(); while(_idx < s) { childIdx = left(_idx); if (childIdx >= s) break; if ((childIdx + 1 < s) && (interface_.less(entry(childIdx + 1), entry(childIdx)))) ++childIdx; if (interface_.less(h, entry(childIdx))) break; entry(_idx, entry(childIdx)); _idx = childIdx; } entry(_idx, h); } //============================================================================= } // END_NS_UTILS } // END_NS_OPENMESH //============================================================================= #endif // OSG_HEAP_HH defined //============================================================================= <|endoftext|>
<commit_before>/** * @file */ #pragma once #include "bi/lib/Heap.hpp" #include "bi/lib/FiberState.hpp" namespace bi { /** * Fiber. * * @ingroup library * * @tparam Type Yield type. */ template<class Type> class Fiber { public: /** * Constructor. */ Fiber(const bool closed = false) : heap(closed ? new Heap(*fiberHeap) : nullptr) { // } /** * Copy constructor. */ Fiber(const Fiber<Type>& o) { if (o.heap) { heap = new Heap(*o.heap); } else { heap = nullptr; } state = o.state; } /** * Move constructor. */ Fiber(Fiber<Type> && o) : heap(o.heap), state(o.state) { o.heap = nullptr; o.state = nullptr; } /** * Destructor. */ virtual ~Fiber() { if (heap) { delete heap; } } /** * Copy assignment. */ Fiber<Type>& operator=(const Fiber<Type>& o) { if (heap) { if (o.heap) { *heap = *o.heap; } else { delete heap; heap = nullptr; } } else if (o.heap) { heap = new Heap(*o.heap); } state = o.state; return *this; } /** * Move assignment. */ Fiber<Type>& operator=(Fiber<Type> && o) { std::swap(heap, o.heap); std::swap(state, o.state); return *this; } /** * Run to next yield point. * * @return Was a value yielded? */ bool query() { if (!state.isNull()) { swap(); bool result = state->query(); swap(); return result; } else { return false; } } /** * Get the last yield value. */ Type& get() { assert(!state.isNull()); swap(); Type& result = state->get(); swap(); return result; } const Type& get() const { assert(!state.isNull()); swap(); const Type& result = state->get(); swap(); return result; } /** * Swap in/out the fiber-local heap. */ void swap() { if (heap) { std::swap(heap, fiberHeap); } } /** * Fiber state. */ Pointer<FiberState<Type>> state; /** * Fiber-local heap, nullptr if shared with the parent fiber. */ Heap* heap; }; } <commit_msg>Change the initialization order of the heap and the state in the fiber class.<commit_after>/** * @file */ #pragma once #include "bi/lib/Heap.hpp" #include "bi/lib/FiberState.hpp" namespace bi { /** * Fiber. * * @ingroup library * * @tparam Type Yield type. */ template<class Type> class Fiber { public: /** * Constructor. */ Fiber(const bool closed = false) : heap(closed ? new Heap(*fiberHeap) : nullptr) { // } /** * Copy constructor. */ Fiber(const Fiber<Type>& o) { if (o.heap) { heap = new Heap(*o.heap); } else { heap = nullptr; } state = o.state; } /** * Move constructor. */ Fiber(Fiber<Type> && o) : state(o.state), heap(o.heap) { o.heap = nullptr; o.state = nullptr; } /** * Destructor. */ virtual ~Fiber() { if (heap) { delete heap; } } /** * Copy assignment. */ Fiber<Type>& operator=(const Fiber<Type>& o) { if (heap) { if (o.heap) { *heap = *o.heap; } else { delete heap; heap = nullptr; } } else if (o.heap) { heap = new Heap(*o.heap); } state = o.state; return *this; } /** * Move assignment. */ Fiber<Type>& operator=(Fiber<Type> && o) { std::swap(heap, o.heap); std::swap(state, o.state); return *this; } /** * Run to next yield point. * * @return Was a value yielded? */ bool query() { if (!state.isNull()) { swap(); bool result = state->query(); swap(); return result; } else { return false; } } /** * Get the last yield value. */ Type& get() { assert(!state.isNull()); swap(); Type& result = state->get(); swap(); return result; } const Type& get() const { assert(!state.isNull()); swap(); const Type& result = state->get(); swap(); return result; } /** * Swap in/out the fiber-local heap. */ void swap() { if (heap) { std::swap(heap, fiberHeap); } } /** * Fiber state. */ Pointer<FiberState<Type>> state; /** * Fiber-local heap, nullptr if shared with the parent fiber. */ Heap* heap; }; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, 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_BITFIELD_HPP_INCLUDED #define TORRENT_BITFIELD_HPP_INCLUDED #include "libtorrent/assert.hpp" #include "libtorrent/config.hpp" namespace libtorrent { struct TORRENT_EXPORT bitfield { bitfield(): m_bytes(0), m_size(0), m_own(false) {} bitfield(int bits): m_bytes(0), m_size(0) { resize(bits); } bitfield(int bits, bool val): m_bytes(0), m_size(0) { resize(bits, val); } bitfield(char const* bytes, int bits): m_bytes(0), m_size(0) { assign(bytes, bits); } bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false) { assign(rhs.bytes(), rhs.size()); } void borrow_bytes(char* bytes, int bits) { dealloc(); m_bytes = (unsigned char*)bytes; m_size = bits; m_own = false; } ~bitfield() { dealloc(); } void assign(char const* bytes, int bits) { resize(bits); std::memcpy(m_bytes, bytes, (bits + 7) / 8); clear_trailing_bits(); } bool operator[](int index) const { return get_bit(index); } bool get_bit(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); return m_bytes[index / 8] & (0x80 >> (index & 7)); } void clear_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] &= ~(0x80 >> (index & 7)); } void set_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] |= (0x80 >> (index & 7)); } std::size_t size() const { return m_size; } bool empty() const { return m_size == 0; } char const* bytes() const { return (char*)m_bytes; } bitfield& operator=(bitfield const& rhs) { assign(rhs.bytes(), rhs.size()); return *this; } int count() const { // 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, // 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 const static char num_bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int ret = 0; const int num_bytes = m_size / 8; for (int i = 0; i < num_bytes; ++i) { ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4]; } int rest = m_size - num_bytes * 8; for (int i = 0; i < rest; ++i) { ret += (m_bytes[num_bytes] >> (7-i)) & 1; } TORRENT_ASSERT(ret <= m_size); TORRENT_ASSERT(ret >= 0); return ret; } struct const_iterator { friend struct bitfield; typedef bool value_type; typedef ptrdiff_t difference_type; typedef bool const* pointer; typedef bool& reference; typedef std::forward_iterator_tag iterator_category; bool operator*() { return *byte & bit; } const_iterator& operator++() { inc(); return *this; } const_iterator operator++(int) { const_iterator ret(*this); inc(); return ret; } const_iterator& operator--() { dec(); return *this; } const_iterator operator--(int) { const_iterator ret(*this); dec(); return ret; } const_iterator(): byte(0), bit(0x80) {} bool operator==(const_iterator const& rhs) const { return byte == rhs.byte && bit == rhs.bit; } bool operator!=(const_iterator const& rhs) const { return byte != rhs.byte || bit != rhs.bit; } private: void inc() { TORRENT_ASSERT(byte); if (bit == 0x01) { bit = 0x80; ++byte; } else { bit >>= 1; } } void dec() { TORRENT_ASSERT(byte); if (bit == 0x80) { bit = 0x01; --byte; } else { bit <<= 1; } } const_iterator(unsigned char const* ptr, int offset) : byte(ptr), bit(0x80 >> offset) {} unsigned char const* byte; int bit; }; const_iterator begin() const { return const_iterator(m_bytes, 0); } const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); } void resize(int bits, bool val) { int s = m_size; int b = m_size & 7; resize(bits); if (s >= m_size) return; int old_size_bytes = (s + 7) / 8; int new_size_bytes = (m_size + 7) / 8; if (val) { if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); clear_trailing_bits(); } else { if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes); } } void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); clear_trailing_bits(); } void clear_all() { std::memset(m_bytes, 0x00, (m_size + 7) / 8); } void resize(int bits) { const int bytes = (bits + 7) / 8; if (m_bytes) { if (m_own) { m_bytes = (unsigned char*)std::realloc(m_bytes, bytes); m_own = true; } else if (bits > m_size) { unsigned char* tmp = (unsigned char*)std::malloc(bytes); std::memcpy(tmp, m_bytes, (std::min)((m_size + 7)/ 8, bytes)); m_bytes = tmp; m_own = true; } } else { m_bytes = (unsigned char*)std::malloc(bytes); m_own = true; } m_size = bits; clear_trailing_bits(); } void free() { dealloc(); m_size = 0; } private: void clear_trailing_bits() { // clear the tail bits in the last byte if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); } void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits bool m_own:1; }; } #endif // TORRENT_BITFIELD_HPP_INCLUDED <commit_msg>memcpy/memset build issue in bitfield.hpp<commit_after>/* Copyright (c) 2008, 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_BITFIELD_HPP_INCLUDED #define TORRENT_BITFIELD_HPP_INCLUDED #include "libtorrent/assert.hpp" #include "libtorrent/config.hpp" #include <cstring> // for memset and memcpy namespace libtorrent { struct TORRENT_EXPORT bitfield { bitfield(): m_bytes(0), m_size(0), m_own(false) {} bitfield(int bits): m_bytes(0), m_size(0) { resize(bits); } bitfield(int bits, bool val): m_bytes(0), m_size(0) { resize(bits, val); } bitfield(char const* bytes, int bits): m_bytes(0), m_size(0) { assign(bytes, bits); } bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false) { assign(rhs.bytes(), rhs.size()); } void borrow_bytes(char* bytes, int bits) { dealloc(); m_bytes = (unsigned char*)bytes; m_size = bits; m_own = false; } ~bitfield() { dealloc(); } void assign(char const* bytes, int bits) { resize(bits); std::memcpy(m_bytes, bytes, (bits + 7) / 8); clear_trailing_bits(); } bool operator[](int index) const { return get_bit(index); } bool get_bit(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); return m_bytes[index / 8] & (0x80 >> (index & 7)); } void clear_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] &= ~(0x80 >> (index & 7)); } void set_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] |= (0x80 >> (index & 7)); } std::size_t size() const { return m_size; } bool empty() const { return m_size == 0; } char const* bytes() const { return (char*)m_bytes; } bitfield& operator=(bitfield const& rhs) { assign(rhs.bytes(), rhs.size()); return *this; } int count() const { // 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, // 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 const static char num_bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int ret = 0; const int num_bytes = m_size / 8; for (int i = 0; i < num_bytes; ++i) { ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4]; } int rest = m_size - num_bytes * 8; for (int i = 0; i < rest; ++i) { ret += (m_bytes[num_bytes] >> (7-i)) & 1; } TORRENT_ASSERT(ret <= m_size); TORRENT_ASSERT(ret >= 0); return ret; } struct const_iterator { friend struct bitfield; typedef bool value_type; typedef ptrdiff_t difference_type; typedef bool const* pointer; typedef bool& reference; typedef std::forward_iterator_tag iterator_category; bool operator*() { return *byte & bit; } const_iterator& operator++() { inc(); return *this; } const_iterator operator++(int) { const_iterator ret(*this); inc(); return ret; } const_iterator& operator--() { dec(); return *this; } const_iterator operator--(int) { const_iterator ret(*this); dec(); return ret; } const_iterator(): byte(0), bit(0x80) {} bool operator==(const_iterator const& rhs) const { return byte == rhs.byte && bit == rhs.bit; } bool operator!=(const_iterator const& rhs) const { return byte != rhs.byte || bit != rhs.bit; } private: void inc() { TORRENT_ASSERT(byte); if (bit == 0x01) { bit = 0x80; ++byte; } else { bit >>= 1; } } void dec() { TORRENT_ASSERT(byte); if (bit == 0x80) { bit = 0x01; --byte; } else { bit <<= 1; } } const_iterator(unsigned char const* ptr, int offset) : byte(ptr), bit(0x80 >> offset) {} unsigned char const* byte; int bit; }; const_iterator begin() const { return const_iterator(m_bytes, 0); } const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); } void resize(int bits, bool val) { int s = m_size; int b = m_size & 7; resize(bits); if (s >= m_size) return; int old_size_bytes = (s + 7) / 8; int new_size_bytes = (m_size + 7) / 8; if (val) { if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); clear_trailing_bits(); } else { if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes); } } void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); clear_trailing_bits(); } void clear_all() { std::memset(m_bytes, 0x00, (m_size + 7) / 8); } void resize(int bits) { const int bytes = (bits + 7) / 8; if (m_bytes) { if (m_own) { m_bytes = (unsigned char*)std::realloc(m_bytes, bytes); m_own = true; } else if (bits > m_size) { unsigned char* tmp = (unsigned char*)std::malloc(bytes); std::memcpy(tmp, m_bytes, (std::min)((m_size + 7)/ 8, bytes)); m_bytes = tmp; m_own = true; } } else { m_bytes = (unsigned char*)std::malloc(bytes); m_own = true; } m_size = bits; clear_trailing_bits(); } void free() { dealloc(); m_size = 0; } private: void clear_trailing_bits() { // clear the tail bits in the last byte if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); } void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits bool m_own:1; }; } #endif // TORRENT_BITFIELD_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_VERTEX_CACHE_HPP #define MAPNIK_VERTEX_CACHE_HPP // mapnik #include <mapnik/pixel_position.hpp> #include <mapnik/debug.hpp> #include <mapnik/config.hpp> #include <mapnik/util/noncopyable.hpp> // agg #include "agg_basics.h" // stl #include <vector> #include <memory> #include <map> namespace mapnik { class vertex_cache; using vertex_cache_ptr = std::unique_ptr<vertex_cache>; // Caches all path points and their lengths. Allows easy moving in both directions. class MAPNIK_DECL vertex_cache : util::noncopyable { struct segment { segment(double x, double y, double length) : pos(x, y), length(length) {} pixel_position pos; //Last point of this segment, first point is implicitly defined by the previous segement in this vector double length; }; // The first segment always has the length 0 and just defines the starting point. struct segment_vector { segment_vector() : vector(), length(0.) {} void add_segment(double x, double y, double len) { if (len == 0. && !vector.empty()) return; //Don't add zero length segments vector.emplace_back(x, y, len); length += len; } using iterator = std::vector<segment>::iterator; std::vector<segment> vector; double length; }; public: // This class has no public members to avoid acciedential modification. // It should only be used with save_state/restore_state. class state { segment_vector::iterator current_segment; double position_in_segment; pixel_position current_position; pixel_position segment_starting_point; double position_; friend class vertex_cache; public: pixel_position const& position() const { return current_position; } }; class scoped_state : util::noncopyable { public: scoped_state(vertex_cache &pp) : pp_(pp), state_(pp.save_state()), restored_(false) {} void restore() { pp_.restore_state(state_); restored_ = true; } ~scoped_state() { if (!restored_) pp_.restore_state(state_); } state const& get_state() const { return state_; } private: vertex_cache &pp_; state state_; bool restored_; }; /////////////////////////////////////////////////////////////////////// template <typename T> vertex_cache(T &path); vertex_cache(vertex_cache && rhs); double length() const { return current_subpath_->length; } pixel_position const& current_position() const { return current_position_; } double angle(double width=0.); double current_segment_angle(); double linear_position() const { return position_; } // Returns a parallel line in the specified distance. vertex_cache & get_offseted(double offset, double region_width); // Skip a certain amount of space. // This functions automatically calculate new points if the position is not exactly // on a point on the path. bool forward(double length); // Go backwards. bool backward(double length); // Move in any direction (based on sign of length). Returns false if it reaches either end of the path. bool move(double length); // Move to given distance. bool move_to_distance(double distance); // Work on next subpath. Returns false if the is no next subpath. bool next_subpath(); // Compatibility with standard path interface void rewind(unsigned); unsigned vertex(double *x, double *y); // State state save_state() const; void restore_state(state const& s); // Go back to initial state. void reset(); // position on this line closest to the target position double position_closest_to(pixel_position const &target_pos); private: void rewind_subpath(); bool next_segment(); bool previous_segment(); void find_line_circle_intersection( double cx, double cy, double radius, double x1, double y1, double x2, double y2, double & ix, double & iy) const; // Position as calculated by last move/forward/next call. pixel_position current_position_; // First pixel of current segment. pixel_position segment_starting_point_; // List of all subpaths. std::vector<segment_vector> subpaths_; // Currently active subpath. std::vector<segment_vector>::iterator current_subpath_; // Current segment for normal operation (move()). segment_vector::iterator current_segment_; // Current segment in compatibility mode (vertex(), rewind()). segment_vector::iterator vertex_segment_; // Currently active subpath in compatibility mode. std::vector<segment_vector>::iterator vertex_subpath_; // State is initialized (after first call to next_subpath()). bool initialized_; // Position from start of segment. double position_in_segment_; // Angle for current segment. mutable double angle_; // Is the value in angle_ valid? // Used to avoid unnecessary calculations. mutable bool angle_valid_; using offseted_lines_map = std::map<double, vertex_cache_ptr>; // Cache of all offseted lines already computed. offseted_lines_map offseted_lines_; // Linear position, i.e distance from start of line. double position_; }; template <typename T> vertex_cache::vertex_cache(T & path) : current_position_(), segment_starting_point_(), subpaths_(), current_subpath_(), current_segment_(), vertex_segment_(), vertex_subpath_(), initialized_(false), position_in_segment_(0.), angle_(0.), angle_valid_(false), offseted_lines_(), position_(0.) { path.rewind(0); unsigned cmd; double new_x = 0., new_y = 0., old_x = 0., old_y = 0.; bool first = true; //current_subpath_ uninitalized while (!agg::is_stop(cmd = path.vertex(&new_x, &new_y))) { if (agg::is_move_to(cmd)) { //Create new sub path subpaths_.emplace_back(); current_subpath_ = subpaths_.end()-1; current_subpath_->add_segment(new_x, new_y, 0); first = false; } if (agg::is_line_to(cmd)) { if (first) { MAPNIK_LOG_ERROR(vertex_cache) << "No starting point in path!\n"; continue; } double dx = old_x - new_x; double dy = old_y - new_y; double segment_length = std::sqrt(dx*dx + dy*dy); current_subpath_->add_segment(new_x, new_y, segment_length); } if (agg::is_closed(cmd) && !current_subpath_->vector.empty()) { segment const & first_segment = current_subpath_->vector[0]; double dx = old_x - first_segment.pos.x; double dy = old_y - first_segment.pos.y; double segment_length = std::sqrt(dx*dx + dy*dy); current_subpath_->add_segment(first_segment.pos.x, first_segment.pos.y, segment_length); } old_x = new_x; old_y = new_y; } } } #endif <commit_msg>use else if<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_VERTEX_CACHE_HPP #define MAPNIK_VERTEX_CACHE_HPP // mapnik #include <mapnik/pixel_position.hpp> #include <mapnik/debug.hpp> #include <mapnik/config.hpp> #include <mapnik/util/noncopyable.hpp> // agg #include "agg_basics.h" // stl #include <vector> #include <memory> #include <map> namespace mapnik { class vertex_cache; using vertex_cache_ptr = std::unique_ptr<vertex_cache>; // Caches all path points and their lengths. Allows easy moving in both directions. class MAPNIK_DECL vertex_cache : util::noncopyable { struct segment { segment(double x, double y, double length) : pos(x, y), length(length) {} pixel_position pos; //Last point of this segment, first point is implicitly defined by the previous segement in this vector double length; }; // The first segment always has the length 0 and just defines the starting point. struct segment_vector { segment_vector() : vector(), length(0.) {} void add_segment(double x, double y, double len) { if (len == 0. && !vector.empty()) return; //Don't add zero length segments vector.emplace_back(x, y, len); length += len; } using iterator = std::vector<segment>::iterator; std::vector<segment> vector; double length; }; public: // This class has no public members to avoid acciedential modification. // It should only be used with save_state/restore_state. class state { segment_vector::iterator current_segment; double position_in_segment; pixel_position current_position; pixel_position segment_starting_point; double position_; friend class vertex_cache; public: pixel_position const& position() const { return current_position; } }; class scoped_state : util::noncopyable { public: scoped_state(vertex_cache &pp) : pp_(pp), state_(pp.save_state()), restored_(false) {} void restore() { pp_.restore_state(state_); restored_ = true; } ~scoped_state() { if (!restored_) pp_.restore_state(state_); } state const& get_state() const { return state_; } private: vertex_cache &pp_; state state_; bool restored_; }; /////////////////////////////////////////////////////////////////////// template <typename T> vertex_cache(T &path); vertex_cache(vertex_cache && rhs); double length() const { return current_subpath_->length; } pixel_position const& current_position() const { return current_position_; } double angle(double width=0.); double current_segment_angle(); double linear_position() const { return position_; } // Returns a parallel line in the specified distance. vertex_cache & get_offseted(double offset, double region_width); // Skip a certain amount of space. // This functions automatically calculate new points if the position is not exactly // on a point on the path. bool forward(double length); // Go backwards. bool backward(double length); // Move in any direction (based on sign of length). Returns false if it reaches either end of the path. bool move(double length); // Move to given distance. bool move_to_distance(double distance); // Work on next subpath. Returns false if the is no next subpath. bool next_subpath(); // Compatibility with standard path interface void rewind(unsigned); unsigned vertex(double *x, double *y); // State state save_state() const; void restore_state(state const& s); // Go back to initial state. void reset(); // position on this line closest to the target position double position_closest_to(pixel_position const &target_pos); private: void rewind_subpath(); bool next_segment(); bool previous_segment(); void find_line_circle_intersection( double cx, double cy, double radius, double x1, double y1, double x2, double y2, double & ix, double & iy) const; // Position as calculated by last move/forward/next call. pixel_position current_position_; // First pixel of current segment. pixel_position segment_starting_point_; // List of all subpaths. std::vector<segment_vector> subpaths_; // Currently active subpath. std::vector<segment_vector>::iterator current_subpath_; // Current segment for normal operation (move()). segment_vector::iterator current_segment_; // Current segment in compatibility mode (vertex(), rewind()). segment_vector::iterator vertex_segment_; // Currently active subpath in compatibility mode. std::vector<segment_vector>::iterator vertex_subpath_; // State is initialized (after first call to next_subpath()). bool initialized_; // Position from start of segment. double position_in_segment_; // Angle for current segment. mutable double angle_; // Is the value in angle_ valid? // Used to avoid unnecessary calculations. mutable bool angle_valid_; using offseted_lines_map = std::map<double, vertex_cache_ptr>; // Cache of all offseted lines already computed. offseted_lines_map offseted_lines_; // Linear position, i.e distance from start of line. double position_; }; template <typename T> vertex_cache::vertex_cache(T & path) : current_position_(), segment_starting_point_(), subpaths_(), current_subpath_(), current_segment_(), vertex_segment_(), vertex_subpath_(), initialized_(false), position_in_segment_(0.), angle_(0.), angle_valid_(false), offseted_lines_(), position_(0.) { path.rewind(0); unsigned cmd; double new_x = 0., new_y = 0., old_x = 0., old_y = 0.; bool first = true; //current_subpath_ uninitalized while (!agg::is_stop(cmd = path.vertex(&new_x, &new_y))) { if (agg::is_move_to(cmd)) { //Create new sub path subpaths_.emplace_back(); current_subpath_ = subpaths_.end()-1; current_subpath_->add_segment(new_x, new_y, 0); first = false; } else if (agg::is_line_to(cmd)) { if (first) { MAPNIK_LOG_ERROR(vertex_cache) << "No starting point in path!\n"; continue; } double dx = old_x - new_x; double dy = old_y - new_y; double segment_length = std::sqrt(dx*dx + dy*dy); current_subpath_->add_segment(new_x, new_y, segment_length); } else if (agg::is_closed(cmd) && !current_subpath_->vector.empty()) { segment const & first_segment = current_subpath_->vector[0]; double dx = old_x - first_segment.pos.x; double dy = old_y - first_segment.pos.y; double segment_length = std::sqrt(dx*dx + dy*dy); current_subpath_->add_segment(first_segment.pos.x, first_segment.pos.y, segment_length); } old_x = new_x; old_y = new_y; } } } #endif <|endoftext|>
<commit_before>#pragma once #include <Windows.h> #include <malloc.h> #include <vector> #include <string> #include <iterator> #include <algorithm> #include <cstdint> #include <quote/tmp/on_exit.hpp> namespace quote{ namespace win32{ template <class Window> // return: tuple<files, index of filter> inline std::tuple<std::vector<std::wstring>, std::uint32_t> get_open_file(const Window &parent, const std::vector<std::pair<std::wstring, std::vector<std::wstring>>> &filter = {}, std::uint32_t index = 1) { std::vector<wchar_t> f; auto inserter = std::back_inserter(f); if(filter.size() != 0){ for(auto &p: filter){ auto &label = std::get<0>(p); auto &ext = std::get<1>(p); auto add_extension = [&inserter, &ext](){ for(auto &e: ext){ *inserter = L'*'; std::copy(e.begin(), e.end(), inserter); *inserter = L';'; } }; if(ext.size() == 0) continue; std::copy(label.begin(), label.end(), inserter); *inserter = L' '; *inserter = L'('; add_extension(); f.back() = L')'; *inserter = L'\0'; add_extension(); f.back() = L'\0'; } }else{ const wchar_t *s = L"All Files (*.*)\0*.*\0"; f = std::vector<wchar_t>(s, s + 20); } *inserter = L'\0'; std::vector<std::wstring> result; DWORD length = ::GetCurrentDirectoryW(0, nullptr); auto currentdir = reinterpret_cast<wchar_t*>(_malloca(sizeof(wchar_t) * length)); ::GetCurrentDirectoryW(length, currentdir); auto buffer = reinterpret_cast<wchar_t*>(_malloca(sizeof(wchar_t) * _MAX_PATH * 10000)); buffer[0] = 0; QUOTE_ON_EXIT{ _freea(currentdir); _freea(buffer); }; OPENFILENAMEW ofn = {}; ofn.lStructSize = sizeof ofn; ofn.hwndOwner = parent.get_hwnd(); ofn.hInstance = ::GetModuleHandleW(nullptr); ofn.lpstrFilter = &f[0]; ofn.lpstrCustomFilter = nullptr; ofn.nMaxCustFilter = 1; ofn.nFilterIndex = index; ofn.lpstrFile = buffer; ofn.nMaxFile = _MAX_PATH * 10000; ofn.lpstrFileTitle = nullptr; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = currentdir; ofn.lpstrTitle = nullptr; ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ALLOWMULTISELECT; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = L"png"; ofn.lCustData = NULL; ofn.lpfnHook = NULL; if(filter.size() != 0){ if(std::get<1>(filter[0]).size() != 0){ ofn.lpstrDefExt = &std::get<1>(filter[0])[0][1]; } } if(::GetOpenFileNameW(&ofn)){ wchar_t *iter = std::wcschr(buffer, L'\0'); if(*++iter == L'\0'){ result.emplace_back(buffer); }else{ do{ result.emplace_back(buffer); result.back() += L'\\'; result.back() += iter; iter = ::wcschr(iter, L'\0') + 1; }while(*iter != L'\0'); } } return std::make_tuple(result, ofn.nFilterIndex); } inline std::wstring get_save_file() { } } } <commit_msg>Add win32::open_directory_dialog<commit_after>#pragma once #include <Windows.h> #include <malloc.h> #include <ShObjIdl.h> #include <vector> #include <string> #include <iterator> #include <algorithm> #include <cstdint> #include <quote/tmp/on_exit.hpp> namespace quote{ namespace win32{ template <class Window> // return: tuple<files, index of filter> inline std::tuple<std::vector<std::wstring>, std::uint32_t> get_open_file(const Window &parent, const std::vector<std::pair<std::wstring, std::vector<std::wstring>>> &filter = {}, std::uint32_t index = 1) { std::vector<wchar_t> f; auto inserter = std::back_inserter(f); if(filter.size() != 0){ for(auto &p: filter){ auto &label = std::get<0>(p); auto &ext = std::get<1>(p); auto add_extension = [&inserter, &ext](){ for(auto &e: ext){ *inserter = L'*'; std::copy(e.begin(), e.end(), inserter); *inserter = L';'; } }; if(ext.size() == 0) continue; std::copy(label.begin(), label.end(), inserter); *inserter = L' '; *inserter = L'('; add_extension(); f.back() = L')'; *inserter = L'\0'; add_extension(); f.back() = L'\0'; } }else{ const wchar_t *s = L"All Files (*.*)\0*.*\0"; f = std::vector<wchar_t>(s, s + 20); } *inserter = L'\0'; std::vector<std::wstring> result; DWORD length = ::GetCurrentDirectoryW(0, nullptr); auto currentdir = reinterpret_cast<wchar_t*>(_malloca(sizeof(wchar_t) * length)); ::GetCurrentDirectoryW(length, currentdir); auto buffer = reinterpret_cast<wchar_t*>(_malloca(sizeof(wchar_t) * _MAX_PATH * 10000)); buffer[0] = 0; QUOTE_ON_EXIT{ _freea(currentdir); _freea(buffer); }; OPENFILENAMEW ofn = {}; ofn.lStructSize = sizeof ofn; ofn.hwndOwner = parent.get_hwnd(); ofn.hInstance = ::GetModuleHandleW(nullptr); ofn.lpstrFilter = &f[0]; ofn.lpstrCustomFilter = nullptr; ofn.nMaxCustFilter = 1; ofn.nFilterIndex = index; ofn.lpstrFile = buffer; ofn.nMaxFile = _MAX_PATH * 10000; ofn.lpstrFileTitle = nullptr; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = currentdir; ofn.lpstrTitle = nullptr; ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ALLOWMULTISELECT; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = L"png"; ofn.lCustData = nullptr; ofn.lpfnHook = nullptr; if(filter.size() != 0){ if(std::get<1>(filter[0]).size() != 0){ ofn.lpstrDefExt = &std::get<1>(filter[0])[0][1]; } } if(::GetOpenFileNameW(&ofn)){ wchar_t *iter = std::wcschr(buffer, L'\0'); if(*++iter == L'\0'){ result.emplace_back(buffer); }else{ do{ result.emplace_back(buffer); result.back() += L'\\'; result.back() += iter; iter = ::wcschr(iter, L'\0') + 1; }while(*iter != L'\0'); } } return std::make_tuple(result, ofn.nFilterIndex); } inline std::wstring get_save_file() { } template <typename Window> inline std::wstring open_directory_dialog(const Window &parent, const wchar_t *root = nullptr, const wchar_t *title = L"Select directory") { IFileOpenDialog *fod; if (FAILED(::CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&fod)))) { return L""; } std::wstring result; HRESULT hr; DWORD options; hr = fod->SetTitle(title); if (SUCCEEDED(hr)) { hr = fod->GetOptions(&options); } if (SUCCEEDED(hr)) { hr = fod->SetOptions(options | FOS_PICKFOLDERS); } if (root != nullptr) { IShellItem *psi; HRESULT hr = ::SHCreateItemFromParsingName(root, nullptr, IID_PPV_ARGS(&psi)); if (SUCCEEDED(hr)) { fod->SetFolder(psi); psi->Release(); } } if (SUCCEEDED(hr)) { hr = fod->Show(parent.get_hwnd()); } if (SUCCEEDED(hr)) { LPWSTR path; IShellItem *psi; hr = fod->GetResult(&psi); if (SUCCEEDED(hr)) { psi->GetDisplayName(SIGDN_FILESYSPATH, &path); result = path; ::CoTaskMemFree(path); psi->Release(); } } fod->Release(); return result; } } } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2005 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "Models/Glm/WeightedRegressionModel.hpp" #include "distributions.hpp" #include <cmath> #include "Models/PosteriorSamplers/PosteriorSampler.hpp" #include "Models/SufstatAbstractCombineImpl.hpp" #include "cpputil/math_utils.hpp" namespace BOOM { typedef WeightedRegressionData WRD; //============================================================ typedef WeightedRegSuf WRS; WRS::WeightedRegSuf(int p) : xtwx_(p, 0.0), xtwy_(p, 0.0), n_(0.0), yt_w_y_(0.0), sym_(false) {} WRS::WeightedRegSuf(const Matrix &X, const Vector &y, const Vector &w) { Matrix tmpx = add_intercept(X); uint p = tmpx.nrow(); setup_mat(p); if (w.empty()) { recompute(tmpx, y, Vector(y.size()d, 1.0)); } else { recompute(tmpx, y, w); } } WRS::WeightedRegSuf(const Matrix &X, const Vector &y) { Matrix tmpx = add_intercept(X); uint p = tmpx.nrow(); setup_mat(p); Vector w(y.size(), 1.0); recompute(tmpx, y, w); } WRS::WeightedRegSuf(const dsetPtr &dat) { uint p = dat->front()->xdim(); setup_mat(p); recompute(dat); } WRS::WeightedRegSuf(const WeightedRegSuf &rhs) : Sufstat(rhs), SufstatDetails<DataType>(rhs), xtwx_(rhs.xtwx_), xtwy_(rhs.xtwy_), n_(rhs.n_), yt_w_y_(rhs.yt_w_y_), sym_(rhs.sym_) {} WRS *WRS::clone() const { return new WRS(*this); } std::ostream &WRS::print(std::ostream &out) const { out << "xtwx_ = " << endl << xtx() << endl << "xtwy_ = " << xtwy_ << endl << "n_ = " << n_ << endl << "yt_w_y_ = " << yt_w_y_ << endl << "sumlogw_= " << sumlogw_ << endl; return out; } void WRS::combine(const Ptr<WRS> &s) { xtwx_ += s->xtwx_; xtwy_ += s->xtwy_; n_ += s->n_; yt_w_y_ += s->yt_w_y_; sumlogw_ += s->sumlogw_; sym_ = sym_ && s->sym_; } void WRS::combine(const WRS &s) { xtwx_ += s.xtwx_; xtwy_ += s.xtwy_; n_ += s.n_; yt_w_y_ += s.yt_w_y_; sumlogw_ += s.sumlogw_; sym_ = sym_ && s.sym_; } WeightedRegSuf *WRS::abstract_combine(Sufstat *s) { return abstract_combine_impl(this, s); } Vector WRS::vectorize(bool minimal) const { Vector ans = xtwx_.vectorize(minimal); ans.concat(xtwy_); ans.push_back(n_); ans.push_back(yt_w_y_); ans.push_back(sumlogw_); return ans; } Vector::const_iterator WRS::unvectorize(Vector::const_iterator &v, bool) { xtwx_.unvectorize(v); uint dim = xtwy_.size(); xtwy_.assign(v, v + dim); v += dim; n_ = *v; ++v; yt_w_y_ = *v; ++v; sumlogw_ = *v; ++v; return v; } Vector::const_iterator WRS::unvectorize(const Vector &v, bool minimal) { Vector::const_iterator it = v.begin(); return unvectorize(it, minimal); } //------------------------------------------------------------ void WRS::setup_mat(uint p) { xtwx_ = SpdMatrix(p, 0.0); xtwy_ = Vector(p, 0.0); sym_ = false; } void WRS::recompute(const Matrix &X, const Vector &y, const Vector &w) { uint n = w.size(); assert(y.size() == n && X.nrow() == n); clear(); for (uint i = 0; i < n; ++i) add_data(X.row(i), y[i], w[i]); } void WRS::recompute(const dsetPtr &dp) { clear(); for (uint i = 0; i < dp->size(); ++i) update((*dp)[i]); } //------------------------------------------------------------ void WRS::set_xtwx(const SpdMatrix &xtwx) { xtwx_ = xtwx; } void WRS::set_xtwy(const Vector &xtwy) { xtwy_ = xtwy; } void WRS::reset(const SpdMatrix &xtwx, const Vector &xtwy, double ytwy, double sample_size, double sum_weights, double sum_log_weights) { xtwx_ = xtwx; xtwy_ = xtwy; n_ = sample_size; yt_w_y_ = ytwy; sumlogw_ = sum_log_weights; sym_ = true; } //------------------------------------------------------------ void WRS::add_data(const Vector &x, double y, double w) { ++n_; yt_w_y_ += w * y * y; sumlogw_ += log(w); xtwx_.add_outer(x, w, false); xtwy_.axpy(x, w * y); sym_ = false; } void WRS::clear() { xtwx_ = 0.0; xtwy_ = 0.0; yt_w_y_ = n_ = sumlogw_ = 0.0; sym_ = false; } void WRS::Update(const WRD &d) { add_data(d.x(), d.y(), d.weight()); } //------------------------------------------------------------ uint WRS::size() const { return xtwx_.nrow(); } double WRS::yty() const { return yt_w_y_; } Vector WRS::xty() const { return xtwy_; } SpdMatrix WRS::xtx() const { if (!sym_) make_symmetric(); return xtwx_; } void WRS::make_symmetric() const { xtwx_.reflect(); sym_ = true; } Vector WRS::xty(const Selector &inc) const { return inc.select(xtwy_); } SpdMatrix WRS::xtx(const Selector &inc) const { return inc.select(xtx()); } Vector WRS::beta_hat() const { return xtx().solve(xtwy_); } double WRS::weighted_sum_of_squared_errors(const Vector &beta) const { return xtx().Mdist(beta) - 2 * beta.dot(xty()) + yty(); } double WRS::SSE() const { SpdMatrix ivar = xtx().inv(); return yty() - ivar.Mdist(xty()); } double WRS::SST() const { return yty() / sumw() - pow(ybar(), 2); } double WRS::n() const { return n_; } double WRS::sumw() const { return xtwx_(0, 0); } double WRS::sumlogw() const { return sumlogw_; } double WRS::ybar() const { return xtwy_[0] / sumw(); } //---------------------------------------------------------------------- typedef WeightedRegressionModel WRM; WRM::WeightedRegressionModel(uint p) : ParamPolicy(new GlmCoefs(p), new UnivParams(1.0)), DataPolicy(new WRS(p)) {} WRM::WeightedRegressionModel(const Vector &b, double Sigma) : ParamPolicy(new GlmCoefs(b), new UnivParams(pow(Sigma, 2))), DataPolicy(new WRS(b.size())) {} namespace { std::vector<Ptr<WRD> > make_data(const Matrix &X, const Vector &y, const Vector &w) { std::vector<Ptr<WRD> > ans; for (uint i = 0; i < X.nrow(); ++i) { ans.push_back(new WeightedRegressionData(y[i], X.row(i), w[i])); } return ans; } } // namespace WRM::WeightedRegressionModel(const Matrix &X, const Vector &y) : ParamPolicy(new GlmCoefs(X.ncol()), new UnivParams(1.0)), DataPolicy(new WRS(X.ncol()), make_data(X, y, Vector(y.size(), 1.0))) { mle(); } WRM::WeightedRegressionModel(const Matrix &X, const Vector &y, const Vector &w) : ParamPolicy(new GlmCoefs(X.ncol()), new UnivParams(1.0)), DataPolicy(new WRS(X.ncol()), make_data(X, y, w)) { mle(); } WRM::WeightedRegressionModel(const DatasetType &d, bool all) : ParamPolicy(new GlmCoefs(d[0]->xdim(), all), new UnivParams(1.0)), DataPolicy(new WRS(d[0]->xdim()), d) { mle(); } WRM::WeightedRegressionModel(const WeightedRegressionModel &rhs) : Model(rhs), ParamPolicy(rhs), DataPolicy(rhs), PriorPolicy(rhs), GlmModel(rhs), NumOptModel(rhs) {} WeightedRegressionModel *WRM::clone() const { return new WRM(*this); } double WRM::pdf(const Ptr<Data> &dp, bool logscale) const { Ptr<DataType> d = dp.dcast<DataType>(); return pdf(d, logscale); } double WRM::pdf(const Ptr<WeightedRegressionData> &dp, bool logscale) const { double mu = predict(dp->x()); double sigsq = this->sigsq(); double w = dp->weight(); return dnorm(dp->y(), mu, sqrt(sigsq / w), logscale); } GlmCoefs &WRM::coef() { return ParamPolicy::prm1_ref(); } const GlmCoefs &WRM::coef() const { return ParamPolicy::prm1_ref(); } Ptr<GlmCoefs> WRM::coef_prm() { return ParamPolicy::prm1(); } const Ptr<GlmCoefs> WRM::coef_prm() const { return ParamPolicy::prm1(); } void WRM::set_sigsq(double s2) { ParamPolicy::prm2_ref().set(s2); } Ptr<UnivParams> WRM::Sigsq_prm() { return ParamPolicy::prm2(); } const Ptr<UnivParams> WRM::Sigsq_prm() const { return ParamPolicy::prm2(); } const double &WRM::sigsq() const { return ParamPolicy::prm2_ref().value(); } double WRM::sigma() const { return sqrt(sigsq()); } void WRM::mle() { SpdMatrix xtx(suf()->xtx(coef().inc())); Vector xty(suf()->xty(coef().inc())); Vector b = xtx.solve(xty); set_included_coefficients(b); double SSE = suf()->yty() - 2 * b.dot(xty) + xtx.Mdist(b); double n = suf()->n(); set_sigsq(SSE / n); } double WRM::Loglike(const Vector &beta_sigsq, Vector &g, Matrix &h, uint nd) const { const double log2pi = 1.8378770664093453; const Selector &inclusion_indicators(coef().inc()); const int beta_dim(inclusion_indicators.nvars()); const Vector beta(ConstVectorView(beta_sigsq, 0, beta_dim)); const double sigsq = beta_sigsq.back(); if (sigsq <= 0) { g = 0; g.back() = -sigsq; h = h.Id(); return BOOM::negative_infinity(); } SpdMatrix xtwx(suf()->xtx(inclusion_indicators)); Vector xtwy(suf()->xty(inclusion_indicators)); double ytwy = suf()->yty(); double n = suf()->n(); double sumlogw = suf()->sumlogw(); double SS = xtwx.Mdist(beta) - 2 * beta.dot(xtwy) + ytwy; double ans = -.5 * (n * log2pi + n * log(sigsq) - sumlogw + SS / sigsq); if (nd > 0) { double siginv = 1.0 / sigsq; Vector gb = xtwx * beta; gb -= xtwy; gb *= -siginv; double isig4 = siginv * siginv; double gs2 = -n / 2 * siginv + SS / 2 * isig4; g = concat(gb, gs2); if (nd > 1) { Matrix hb = -siginv * xtwx; double hs2 = n / 2 * isig4 - SS * isig4 * siginv; h = block_diagonal(hb, Matrix(1, 1, hs2)); } } return ans; } } // namespace BOOM <commit_msg>Submitted last one too soon! Fix tests broken by renaming.<commit_after>// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2005 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "Models/Glm/WeightedRegressionModel.hpp" #include "distributions.hpp" #include <cmath> #include "Models/PosteriorSamplers/PosteriorSampler.hpp" #include "Models/SufstatAbstractCombineImpl.hpp" #include "cpputil/math_utils.hpp" namespace BOOM { typedef WeightedRegressionData WRD; //============================================================ typedef WeightedRegSuf WRS; WRS::WeightedRegSuf(int p) : xtwx_(p, 0.0), xtwy_(p, 0.0), n_(0.0), yt_w_y_(0.0), sym_(false) {} WRS::WeightedRegSuf(const Matrix &X, const Vector &y, const Vector &w) { Matrix tmpx = add_intercept(X); uint p = tmpx.nrow(); setup_mat(p); if (w.empty()) { recompute(tmpx, y, Vector(y.size(), 1.0)); } else { recompute(tmpx, y, w); } } WRS::WeightedRegSuf(const std::vector<Ptr<WeightedRegressionData>> &data) { uint xdim = data.front()->xdim(); setup_mat(xdim); recompute(data); } WRS::WeightedRegSuf(const WeightedRegSuf &rhs) : Sufstat(rhs), SufstatDetails<DataType>(rhs), xtwx_(rhs.xtwx_), xtwy_(rhs.xtwy_), n_(rhs.n_), yt_w_y_(rhs.yt_w_y_), sym_(rhs.sym_) {} WRS *WRS::clone() const { return new WRS(*this); } std::ostream &WRS::print(std::ostream &out) const { out << "xtwx_ = " << endl << xtx() << endl << "xtwy_ = " << xtwy_ << endl << "n_ = " << n_ << endl << "yt_w_y_ = " << yt_w_y_ << endl << "sumlogw_= " << sumlogw_ << endl; return out; } void WRS::combine(const Ptr<WRS> &s) { xtwx_ += s->xtwx_; xtwy_ += s->xtwy_; n_ += s->n_; yt_w_y_ += s->yt_w_y_; sumlogw_ += s->sumlogw_; sym_ = sym_ && s->sym_; } void WRS::combine(const WRS &s) { xtwx_ += s.xtwx_; xtwy_ += s.xtwy_; n_ += s.n_; yt_w_y_ += s.yt_w_y_; sumlogw_ += s.sumlogw_; sym_ = sym_ && s.sym_; } WeightedRegSuf *WRS::abstract_combine(Sufstat *s) { return abstract_combine_impl(this, s); } Vector WRS::vectorize(bool minimal) const { Vector ans = xtwx_.vectorize(minimal); ans.concat(xtwy_); ans.push_back(n_); ans.push_back(yt_w_y_); ans.push_back(sumlogw_); return ans; } Vector::const_iterator WRS::unvectorize(Vector::const_iterator &v, bool) { xtwx_.unvectorize(v); uint dim = xtwy_.size(); xtwy_.assign(v, v + dim); v += dim; n_ = *v; ++v; yt_w_y_ = *v; ++v; sumlogw_ = *v; ++v; return v; } Vector::const_iterator WRS::unvectorize(const Vector &v, bool minimal) { Vector::const_iterator it = v.begin(); return unvectorize(it, minimal); } //------------------------------------------------------------ void WRS::setup_mat(uint p) { xtwx_ = SpdMatrix(p, 0.0); xtwy_ = Vector(p, 0.0); sym_ = false; } void WRS::recompute(const Matrix &X, const Vector &y, const Vector &w) { uint n = w.size(); assert(y.size() == n && X.nrow() == n); clear(); for (uint i = 0; i < n; ++i) add_data(X.row(i), y[i], w[i]); } void WRS::recompute(const std::vector<Ptr<WeightedRegressionData>> &data) { clear(); for (uint i = 0; i < data.size(); ++i) update(data[i]); } //------------------------------------------------------------ void WRS::set_xtwx(const SpdMatrix &xtwx) { xtwx_ = xtwx; } void WRS::set_xtwy(const Vector &xtwy) { xtwy_ = xtwy; } void WRS::reset(const SpdMatrix &xtwx, const Vector &xtwy, double ytwy, double sample_size, double sum_weights, double sum_log_weights) { xtwx_ = xtwx; xtwy_ = xtwy; n_ = sample_size; yt_w_y_ = ytwy; sumlogw_ = sum_log_weights; sym_ = true; } //------------------------------------------------------------ void WRS::add_data(const Vector &x, double y, double w) { ++n_; yt_w_y_ += w * y * y; sumlogw_ += log(w); xtwx_.add_outer(x, w, false); xtwy_.axpy(x, w * y); sym_ = false; } void WRS::clear() { xtwx_ = 0.0; xtwy_ = 0.0; yt_w_y_ = n_ = sumlogw_ = 0.0; sym_ = false; } void WRS::Update(const WRD &d) { add_data(d.x(), d.y(), d.weight()); } //------------------------------------------------------------ uint WRS::size() const { return xtwx_.nrow(); } double WRS::yty() const { return yt_w_y_; } Vector WRS::xty() const { return xtwy_; } SpdMatrix WRS::xtx() const { if (!sym_) make_symmetric(); return xtwx_; } void WRS::make_symmetric() const { xtwx_.reflect(); sym_ = true; } Vector WRS::xty(const Selector &inc) const { return inc.select(xtwy_); } SpdMatrix WRS::xtx(const Selector &inc) const { return inc.select(xtx()); } Vector WRS::beta_hat() const { return xtx().solve(xtwy_); } double WRS::weighted_sum_of_squared_errors(const Vector &beta) const { return xtx().Mdist(beta) - 2 * beta.dot(xty()) + yty(); } double WRS::SSE() const { SpdMatrix ivar = xtx().inv(); return yty() - ivar.Mdist(xty()); } double WRS::SST() const { return yty() / sumw() - pow(ybar(), 2); } double WRS::n() const { return n_; } double WRS::sumw() const { return xtwx_(0, 0); } double WRS::sumlogw() const { return sumlogw_; } double WRS::ybar() const { return xtwy_[0] / sumw(); } //---------------------------------------------------------------------- typedef WeightedRegressionModel WRM; WRM::WeightedRegressionModel(uint p) : ParamPolicy(new GlmCoefs(p), new UnivParams(1.0)), DataPolicy(new WRS(p)) {} WRM::WeightedRegressionModel(const Vector &b, double Sigma) : ParamPolicy(new GlmCoefs(b), new UnivParams(pow(Sigma, 2))), DataPolicy(new WRS(b.size())) {} namespace { std::vector<Ptr<WRD> > make_data(const Matrix &X, const Vector &y, const Vector &w) { std::vector<Ptr<WRD> > ans; for (uint i = 0; i < X.nrow(); ++i) { ans.push_back(new WeightedRegressionData(y[i], X.row(i), w[i])); } return ans; } } // namespace WRM::WeightedRegressionModel(const Matrix &X, const Vector &y) : ParamPolicy(new GlmCoefs(X.ncol()), new UnivParams(1.0)), DataPolicy(new WRS(X.ncol()), make_data(X, y, Vector(y.size(), 1.0))) { mle(); } WRM::WeightedRegressionModel(const Matrix &X, const Vector &y, const Vector &w) : ParamPolicy(new GlmCoefs(X.ncol()), new UnivParams(1.0)), DataPolicy(new WRS(X.ncol()), make_data(X, y, w)) { mle(); } WRM::WeightedRegressionModel(const DatasetType &d, bool all) : ParamPolicy(new GlmCoefs(d[0]->xdim(), all), new UnivParams(1.0)), DataPolicy(new WRS(d[0]->xdim()), d) { mle(); } WRM::WeightedRegressionModel(const WeightedRegressionModel &rhs) : Model(rhs), ParamPolicy(rhs), DataPolicy(rhs), PriorPolicy(rhs), GlmModel(rhs), NumOptModel(rhs) {} WeightedRegressionModel *WRM::clone() const { return new WRM(*this); } double WRM::pdf(const Ptr<Data> &dp, bool logscale) const { Ptr<DataType> d = dp.dcast<DataType>(); return pdf(d, logscale); } double WRM::pdf(const Ptr<WeightedRegressionData> &dp, bool logscale) const { double mu = predict(dp->x()); double sigsq = this->sigsq(); double w = dp->weight(); return dnorm(dp->y(), mu, sqrt(sigsq / w), logscale); } GlmCoefs &WRM::coef() { return ParamPolicy::prm1_ref(); } const GlmCoefs &WRM::coef() const { return ParamPolicy::prm1_ref(); } Ptr<GlmCoefs> WRM::coef_prm() { return ParamPolicy::prm1(); } const Ptr<GlmCoefs> WRM::coef_prm() const { return ParamPolicy::prm1(); } void WRM::set_sigsq(double s2) { ParamPolicy::prm2_ref().set(s2); } Ptr<UnivParams> WRM::Sigsq_prm() { return ParamPolicy::prm2(); } const Ptr<UnivParams> WRM::Sigsq_prm() const { return ParamPolicy::prm2(); } const double &WRM::sigsq() const { return ParamPolicy::prm2_ref().value(); } double WRM::sigma() const { return sqrt(sigsq()); } void WRM::mle() { SpdMatrix xtx(suf()->xtx(coef().inc())); Vector xty(suf()->xty(coef().inc())); Vector b = xtx.solve(xty); set_included_coefficients(b); double SSE = suf()->yty() - 2 * b.dot(xty) + xtx.Mdist(b); double n = suf()->n(); set_sigsq(SSE / n); } double WRM::Loglike(const Vector &beta_sigsq, Vector &g, Matrix &h, uint nd) const { const double log2pi = 1.8378770664093453; const Selector &inclusion_indicators(coef().inc()); const int beta_dim(inclusion_indicators.nvars()); const Vector beta(ConstVectorView(beta_sigsq, 0, beta_dim)); const double sigsq = beta_sigsq.back(); if (sigsq <= 0) { g = 0; g.back() = -sigsq; h = h.Id(); return BOOM::negative_infinity(); } SpdMatrix xtwx(suf()->xtx(inclusion_indicators)); Vector xtwy(suf()->xty(inclusion_indicators)); double ytwy = suf()->yty(); double n = suf()->n(); double sumlogw = suf()->sumlogw(); double SS = xtwx.Mdist(beta) - 2 * beta.dot(xtwy) + ytwy; double ans = -.5 * (n * log2pi + n * log(sigsq) - sumlogw + SS / sigsq); if (nd > 0) { double siginv = 1.0 / sigsq; Vector gb = xtwx * beta; gb -= xtwy; gb *= -siginv; double isig4 = siginv * siginv; double gs2 = -n / 2 * siginv + SS / 2 * isig4; g = concat(gb, gs2); if (nd > 1) { Matrix hb = -siginv * xtwx; double hs2 = n / 2 * isig4 - SS * isig4 * siginv; h = block_diagonal(hb, Matrix(1, 1, hs2)); } } return ans; } } // namespace BOOM <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkTestFixture.h" #include <mitkPointSet.h> #include <mitkNumericTypes.h> #include <mitkPointOperation.h> #include <mitkInteractionConst.h> #include <fstream> /** * TestSuite for PointSet stuff not only operating on an empty PointSet */ class mitkPointSetTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetTestSuite); MITK_TEST(TestIsNotEmpty); MITK_TEST(TestSetSelectInfo); MITK_TEST(TestGetNumberOfSelected); MITK_TEST(TestSearchSelectedPoint); MITK_TEST(TestGetPointIfExists); MITK_TEST(TestSwapPointPositionUpwards); MITK_TEST(TestSwapPointPositionUpwardsNotPossible); MITK_TEST(TestSwapPointPositionDownwards); MITK_TEST(TestSwapPointPositionDownwardsNotPossible); MITK_TEST(TestCreateHoleInThePointIDs); MITK_TEST(TestInsertPointWithPointSpecification); CPPUNIT_TEST_SUITE_END(); private: mitk::PointSet::Pointer pointSet; static const mitk::PointSet::PointIdentifier selectedPointId = 2; public: void setUp() override { //Create PointSet pointSet = mitk::PointSet::New(); // add some points mitk::Point3D point2, point3, point4; point2.Fill(3); point3.Fill(4); point4.Fill(5); pointSet->InsertPoint(2,point2); pointSet->InsertPoint(3,point3); pointSet->InsertPoint(4,point4); mitk::Point3D point1; mitk::FillVector3D(point1, 1.0, 2.0, 3.0); pointSet->InsertPoint(1, point1); mitk::Point3D point0; point0.Fill(1); pointSet->InsertPoint(0, point0); // select point with id 2 pointSet->SetSelectInfo(2, true); } void tearDown() override { pointSet = nullptr; } void TestIsNotEmpty() { //PointSet can not be empty! CPPUNIT_ASSERT_EQUAL_MESSAGE( "check if the PointSet is not empty ", true, !pointSet->IsEmptyTimeStep(0) ); /* std::cout << "check if the PointSet is not empty "; if (pointSet->IsEmpty(0)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSetSelectInfo() { //check SetSelectInfo pointSet->SetSelectInfo(4, true); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SetSelectInfo", true, pointSet->GetSelectInfo(4)); /* if (!pointSet->GetSelectInfo(2)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } delete doOp; std::cout<<"[PASSED]"<<std::endl; */ } void TestSearchSelectedPoint() { // check SearchSelectedPoint CPPUNIT_ASSERT_EQUAL_MESSAGE("check SearchSelectedPoint ", true, pointSet->SearchSelectedPoint() == (int) selectedPointId); /* if( pointSet->SearchSelectedPoint() != 4) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestGetNumberOfSelected() { // check GetNumeberOfSelected CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetNumeberOfSelected ", true, pointSet->GetNumberOfSelected() == 1); /* if(pointSet->GetNumberOfSelected() != 1) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestGetPointIfExists() { //check GetPointIfExists mitk::Point3D point4; mitk::Point3D tempPoint; point4.Fill(5); mitk::PointSet::PointType tmpPoint; pointSet->GetPointIfExists(4, &tmpPoint); CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetPointIfExists: ", true, tmpPoint == point4); /* if (tmpPoint != point5) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionUpwards() { //Check SwapPointPosition upwards mitk::Point3D point; mitk::Point3D tempPoint; point = pointSet->GetPoint(1); pointSet->SwapPointPosition(1, true); tempPoint = pointSet->GetPoint(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition upwards", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionUpwardsNotPossible() { //Check SwapPointPosition upwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition upwards not possible", false, pointSet->SwapPointPosition(0, true)); /* if(pointSet->SwapPointPosition(0, true)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionDownwards() { //Check SwapPointPosition downwards mitk::Point3D point; mitk::Point3D tempPoint; point = pointSet->GetPoint(0); pointSet->SwapPointPosition(0, false); tempPoint = pointSet->GetPoint(1); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition down", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionDownwardsNotPossible() { mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New(); int id = 0; mitk::Point3D point; point.Fill(1); pointSet2->SetPoint(id, point); //Check SwapPointPosition downwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition downwards not possible", false, pointSet2->SwapPointPosition(id, false)); /* if(pointSet->SwapPointPosition(1, false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestCreateHoleInThePointIDs() { // create a hole in the point IDs mitk::Point3D point(0.); mitk::PointSet::PointType p10, p11, p12; p10.Fill(10.0); p11.Fill(11.0); p12.Fill(12.0); pointSet->InsertPoint(10, p10); pointSet->InsertPoint(11, p11); pointSet->InsertPoint(12, p12); CPPUNIT_ASSERT_EQUAL_MESSAGE("add points with id 10, 11, 12: ", true, (pointSet->IndexExists(10) == true) || (pointSet->IndexExists(11) == true) || (pointSet->IndexExists(12) == true)); //check OpREMOVE ExecuteOperation int id = 11; auto doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id); pointSet->ExecuteOperation(doOp); CPPUNIT_ASSERT_EQUAL_MESSAGE( "remove point id 11: ", false, pointSet->IndexExists(id)); /* if(pointSet->IndexExists(id)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } delete doOp; std::cout<<"[PASSED]"<<std::endl; */ //mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); //pointSet->ExecuteOperation(doOp); delete doOp; //check OpMOVEPOINTUP ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); pointSet->ExecuteOperation(doOp); delete doOp; mitk::PointSet::PointType newP10 = pointSet->GetPoint(10); mitk::PointSet::PointType newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE("check PointOperation OpMOVEPOINTUP for point id 12:", true, ((newP10 == p12) && (newP12 == p10))); //check OpMOVEPOINTDOWN ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, p10, 10); pointSet->ExecuteOperation(doOp); delete doOp; newP10 = pointSet->GetPoint(10); newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE("check PointOperation OpMOVEPOINTDOWN for point id 10: ", true, ((newP10 == p10) && (newP12 == p12))); } void TestInsertPointWithPointSpecification() { //check InsertPoint with PointSpecification mitk::Point3D point5; mitk::Point3D tempPoint; point5.Fill(7); pointSet->SetPoint(5, point5, mitk::PTEDGE ); tempPoint = pointSet->GetPoint(5); CPPUNIT_ASSERT_EQUAL_MESSAGE("check InsertPoint with PointSpecification" , true, tempPoint == point5); /* if (tempPoint != point5) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } }; MITK_TEST_SUITE_REGISTRATION(mitkPointSet) <commit_msg>Point removal testing cases added to mitkPointSetTestSuite.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkTestFixture.h" #include <mitkPointSet.h> #include <mitkNumericTypes.h> #include <mitkPointOperation.h> #include <mitkInteractionConst.h> #include <fstream> /** * TestSuite for PointSet stuff not only operating on an empty PointSet */ class mitkPointSetTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetTestSuite); MITK_TEST(TestIsNotEmpty); MITK_TEST(TestSetSelectInfo); MITK_TEST(TestGetNumberOfSelected); MITK_TEST(TestSearchSelectedPoint); MITK_TEST(TestGetPointIfExists); MITK_TEST(TestSwapPointPositionUpwards); MITK_TEST(TestSwapPointPositionUpwardsNotPossible); MITK_TEST(TestSwapPointPositionDownwards); MITK_TEST(TestSwapPointPositionDownwardsNotPossible); MITK_TEST(TestCreateHoleInThePointIDs); MITK_TEST(TestInsertPointWithPointSpecification); MITK_TEST(TestRemovePointInterface); CPPUNIT_TEST_SUITE_END(); private: mitk::PointSet::Pointer pointSet; static const mitk::PointSet::PointIdentifier selectedPointId = 2; public: void setUp() override { //Create PointSet pointSet = mitk::PointSet::New(); // add some points mitk::Point3D point2, point3, point4; point2.Fill(3); point3.Fill(4); point4.Fill(5); pointSet->InsertPoint(2,point2); pointSet->InsertPoint(3,point3); pointSet->InsertPoint(4,point4); mitk::Point3D point1; mitk::FillVector3D(point1, 1.0, 2.0, 3.0); pointSet->InsertPoint(1, point1); mitk::Point3D point0; point0.Fill(1); pointSet->InsertPoint(0, point0); // select point with id 2 pointSet->SetSelectInfo(2, true); } void tearDown() override { pointSet = nullptr; } void TestIsNotEmpty() { //PointSet can not be empty! CPPUNIT_ASSERT_EQUAL_MESSAGE( "check if the PointSet is not empty ", true, !pointSet->IsEmptyTimeStep(0) ); /* std::cout << "check if the PointSet is not empty "; if (pointSet->IsEmpty(0)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSetSelectInfo() { //check SetSelectInfo pointSet->SetSelectInfo(4, true); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SetSelectInfo", true, pointSet->GetSelectInfo(4)); /* if (!pointSet->GetSelectInfo(2)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } delete doOp; std::cout<<"[PASSED]"<<std::endl; */ } void TestSearchSelectedPoint() { // check SearchSelectedPoint CPPUNIT_ASSERT_EQUAL_MESSAGE("check SearchSelectedPoint ", true, pointSet->SearchSelectedPoint() == (int) selectedPointId); /* if( pointSet->SearchSelectedPoint() != 4) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestGetNumberOfSelected() { // check GetNumeberOfSelected CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetNumeberOfSelected ", true, pointSet->GetNumberOfSelected() == 1); /* if(pointSet->GetNumberOfSelected() != 1) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestGetPointIfExists() { //check GetPointIfExists mitk::Point3D point4; mitk::Point3D tempPoint; point4.Fill(5); mitk::PointSet::PointType tmpPoint; pointSet->GetPointIfExists(4, &tmpPoint); CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetPointIfExists: ", true, tmpPoint == point4); /* if (tmpPoint != point5) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionUpwards() { //Check SwapPointPosition upwards mitk::Point3D point; mitk::Point3D tempPoint; point = pointSet->GetPoint(1); pointSet->SwapPointPosition(1, true); tempPoint = pointSet->GetPoint(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition upwards", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionUpwardsNotPossible() { //Check SwapPointPosition upwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition upwards not possible", false, pointSet->SwapPointPosition(0, true)); /* if(pointSet->SwapPointPosition(0, true)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionDownwards() { //Check SwapPointPosition downwards mitk::Point3D point; mitk::Point3D tempPoint; point = pointSet->GetPoint(0); pointSet->SwapPointPosition(0, false); tempPoint = pointSet->GetPoint(1); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition down", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionDownwardsNotPossible() { mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New(); int id = 0; mitk::Point3D point; point.Fill(1); pointSet2->SetPoint(id, point); //Check SwapPointPosition downwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition downwards not possible", false, pointSet2->SwapPointPosition(id, false)); /* if(pointSet->SwapPointPosition(1, false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestCreateHoleInThePointIDs() { // create a hole in the point IDs mitk::Point3D point(0.); mitk::PointSet::PointType p10, p11, p12; p10.Fill(10.0); p11.Fill(11.0); p12.Fill(12.0); pointSet->InsertPoint(10, p10); pointSet->InsertPoint(11, p11); pointSet->InsertPoint(12, p12); CPPUNIT_ASSERT_EQUAL_MESSAGE("add points with id 10, 11, 12: ", true, (pointSet->IndexExists(10) == true) || (pointSet->IndexExists(11) == true) || (pointSet->IndexExists(12) == true)); //check OpREMOVE ExecuteOperation int id = 11; auto doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id); pointSet->ExecuteOperation(doOp); CPPUNIT_ASSERT_EQUAL_MESSAGE( "remove point id 11: ", false, pointSet->IndexExists(id)); /* if(pointSet->IndexExists(id)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } delete doOp; std::cout<<"[PASSED]"<<std::endl; */ //mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); //pointSet->ExecuteOperation(doOp); delete doOp; //check OpMOVEPOINTUP ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); pointSet->ExecuteOperation(doOp); delete doOp; mitk::PointSet::PointType newP10 = pointSet->GetPoint(10); mitk::PointSet::PointType newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE("check PointOperation OpMOVEPOINTUP for point id 12:", true, ((newP10 == p12) && (newP12 == p10))); //check OpMOVEPOINTDOWN ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, p10, 10); pointSet->ExecuteOperation(doOp); delete doOp; newP10 = pointSet->GetPoint(10); newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE("check PointOperation OpMOVEPOINTDOWN for point id 10: ", true, ((newP10 == p10) && (newP12 == p12))); } void TestInsertPointWithPointSpecification() { //check InsertPoint with PointSpecification mitk::Point3D point5; mitk::Point3D tempPoint; point5.Fill(7); pointSet->SetPoint(5, point5, mitk::PTEDGE ); tempPoint = pointSet->GetPoint(5); CPPUNIT_ASSERT_EQUAL_MESSAGE("check InsertPoint with PointSpecification" , true, tempPoint == point5); /* if (tempPoint != point5) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestRemovePointInterface() { mitk::PointSet::Pointer psClone = pointSet->Clone(); mitk::PointSet::Pointer refPsLastRemoved = mitk::PointSet::New(); mitk::Point3D point0, point1, point2, point3, point4; point0.Fill(1); refPsLastRemoved->InsertPoint(0, point0); mitk::FillVector3D(point1, 1.0, 2.0, 3.0); refPsLastRemoved->InsertPoint(1, point1); point2.Fill(3); point3.Fill(4); refPsLastRemoved->InsertPoint(2,point2); refPsLastRemoved->InsertPoint(3,point3); mitk::PointSet::Pointer refPsMiddleRemoved = mitk::PointSet::New(); refPsMiddleRemoved->InsertPoint(0, point0); refPsMiddleRemoved->InsertPoint(1, point1); refPsMiddleRemoved->InsertPoint(3, point3); //remove non-existent point bool removed = pointSet->RemovePointIfExists( 5, 0 ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove non-existent point", false, removed ); MITK_ASSERT_EQUAL( pointSet, psClone, "No changes made" ); //remove point from non-existent time-step removed = pointSet->RemovePointIfExists( 1, 1 ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove non-existent point", false, removed ); MITK_ASSERT_EQUAL( pointSet, psClone, "No changes made" ); //remove max id from non-existent time-step mitk::PointSet::PointsIterator maxIt = pointSet->RemovePointAtEnd( 2 ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove max id point from non-existent time step", true, maxIt == pointSet->End( 2 ) ); MITK_ASSERT_EQUAL( pointSet, psClone, "No changes made" ); //remove max id from empty point set mitk::PointSet::Pointer emptyPS = mitk::PointSet::New(); maxIt = emptyPS->RemovePointAtEnd( 0 ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove max id point from non-existent time step", true, maxIt == emptyPS->End( 0 ) ); int size = emptyPS->GetSize( 0 ); unsigned int pointSetSeriesSize = emptyPS->GetPointSetSeriesSize(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Nothing added", true, size == 0 && pointSetSeriesSize == 1); //remove max id point maxIt = pointSet->RemovePointAtEnd( 0 ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Point id 4 removed", false, pointSet->IndexExists(4) ); MITK_ASSERT_EQUAL( pointSet, refPsLastRemoved, "No changes made" ); mitk::PointSet::PointIdentifier id = maxIt.Index(); mitk::PointSet::PointType refPt; refPt[0] = 4.0; refPt[1] = 4.0; refPt[2] = 4.0; mitk::PointSet::PointType pt = maxIt.Value(); bool equal = mitk::Equal( refPt, pt ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Returned iterator pointing at max id", true, id == 3 && equal ); //remove middle point removed = pointSet->RemovePointIfExists( 2, 0 ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove point id 2", true, removed ); MITK_ASSERT_EQUAL( pointSet, refPsMiddleRemoved, "Point removed" ); } }; MITK_TEST_SUITE_REGISTRATION(mitkPointSet) <|endoftext|>
<commit_before><commit_msg>Adding code to turn off anti-aliasing for certain older ATI drivers<commit_after><|endoftext|>
<commit_before>#ifndef ORG_EEROS_CONTROL_GAIN_HPP_ #define ORG_EEROS_CONTROL_GAIN_HPP_ #include <eeros/control/Block1i1o.hpp> #include <type_traits> namespace eeros { namespace control { /** * A gain block is used to amplify an input signal. This is basically done by * multiplying the gain with the input signal value. * The following term represents the operation performed in this block. * * output = gain * input * * Gain is a class template with two type and one non-type template arguments. * The two type template arguments specify the types which are used for the * output type and the gain type when the class template is instanciated. * The non-type template argument specifies if the multiplication will be done * element wise in case the gain is used with matrices. * * @tparam Tout - output type (double - default type) * @tparam Tgain - gain type (double - default type) * @tparam elementWise - amplify element wise (false - default value) * * @since v0.6 */ template <typename Tout = double, typename Tgain = double, bool elementWise = false> class Gain : public Block1i1o<Tout> { public: /** * Constructs a default gain instance with a gain of 1.\n * Calls Gain(Tgain c). * * @see Gain(Tgain c) */ Gain() : Gain(1.0) {} /** * Constructs a gain instance with a gain of the value of the parameter c.\n * Calls Gain(Tgain c, Tgain maxGain, Tgain minGain).\n * * @see Gain(Tgain c, Tgain maxGain, Tgain minGain) * * @param c - initial gain value */ Gain(Tgain c) : Gain(c, 1.0, -1.0) { // 1.0 and -1.0 are temp values only. resetMinMaxGain<Tgain>(); // set limits to smallest/largest value. } /** * Constructs a gain instance with a gain of the value of the parameter c, * a maximum gain of maxGain and a minimum gain of minGain.\n * Sets the target gain to the value of the parameter c.\n * Sets the gain diff to 0. * * @param c - initial gain value * @param maxGain - initial maximum gain value * @param minGain - initial minimum gain value */ Gain(Tgain c, Tgain maxGain, Tgain minGain) { gain = c; this->maxGain = maxGain; this->minGain = minGain; targetGain = gain; gainDiff = 0; } /** * Runs the amplification algorithm. * * Performs the smooth change if smooth change is enabled with enableSmoothChange(bool). * A smooth change of the gain is performed by adding or subtracting a gain differential * specifiable by setGainDiff(Tgain). * * Checks if gain is in the band in between minGain and maxGain or correct it otherwise. * The correction is done by setting the maxGain or minGain to gain. * * Sets the output signal value to the amplified value calculated by multiplying gain * input if * the gain instance is enabled by enable(). * * @see enableSmoothChange(bool) * @see setGainDiff(Tgain) * @see enable() * @see disable() */ virtual void run() { if(smoothChange) { if(gain < targetGain) { gain += gainDiff; if(gain > targetGain) { // overshoot case. gain = targetGain; } } if(gain > targetGain) { gain -= gainDiff; if(gain < targetGain) { gain = targetGain; } } } if(gain > maxGain) { // if diff will cause gain to be too large. gain = maxGain; } if(gain < minGain) { gain = minGain; } if(enabled) { this->out.getSignal().setValue(calculateResults<Tout>(this->in.getSignal().getValue())); } else { this->out.getSignal().setValue(this->in.getSignal().getValue()); } this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp()); } /** * Enables the gain. * * If enabled, run() will set the output signal to the amplified value calculated by multiplying gain * input. * * Does not enable smooth change. This is done by calling enableSmoothChange(bool). * * @see run() * @see enableSmoothChange(bool) */ virtual void enable() { enabled = true; } /** * Disables the gain. * * If disabled, run() will set the output signal to the input signal. * * Does not disable smooth change. This is done by calling enableSmoothChange(bool). * * @see run() * @see enableSmoothChange(bool) */ virtual void disable() { enabled = false; } /** * Enables or disables a smooth change of the gain. * * If enabled, run() will perform a smooth change of the gain value. * * Does not enable or disable the gain. This is done by calling enable() and disable() respectively. * * @param enable - enables or disables a smooth change of the gain * * @see run() * @see enable() * @see disable() */ virtual void enableSmoothChange(bool enable) { smoothChange = enable; } /** * Sets the gain value if smooth change is disabled and c is in the band in between minGain and maxGain. * * Sets the target gain value if smooth change is enabled and c is in the band in between minGain and maxGain. * * Does not change gain or target gain value otherwise. * * @param c - gain value */ virtual void setGain(Tgain c) { if(c <= maxGain && c >= minGain) { if(smoothChange) { targetGain = c; }else { gain = c; } } } /** * Sets the maximum allowed gain. * * @param maxGain - maximum allowed gain value */ virtual void setMaxGain(Tgain maxGain) { this->maxGain = maxGain; } /** * Sets the minimum allowed gain. * * @param minGain - minimum allowed gain value */ virtual void setMinGain(Tgain minGain) { this->minGain = minGain; } /** * Sets the gain differential needed by run() to perform a smooth gain change. * * @param gainDiff - gain differential */ virtual void setGainDiff(Tgain gainDiff) { this->gainDiff = gainDiff; } /* * Friend operator overload to give the operator overload outside * the class access to the private fields. */ template <typename Xout, typename Xgain> friend std::ostream& operator<<(std::ostream& os, Gain<Xout,Xgain>& gain); protected: Tgain gain; Tgain maxGain; Tgain minGain; Tgain targetGain; Tgain gainDiff; bool enabled{true}; bool smoothChange{false}; private: template <typename S> typename std::enable_if<!elementWise,S>::type calculateResults(S value) { return gain * value; } template <typename S> typename std::enable_if<elementWise,S>::type calculateResults(S value) { return value.multiplyElementWise(gain); } template <typename S> typename std::enable_if<std::is_integral<S>::value>::type resetMinMaxGain() { minGain = std::numeric_limits<int32_t>::min(); maxGain = std::numeric_limits<int32_t>::max(); } template <typename S> typename std::enable_if<std::is_floating_point<S>::value>::type resetMinMaxGain() { minGain = std::numeric_limits<double>::lowest(); maxGain = std::numeric_limits<double>::max(); } template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value && std::is_integral<typename S::value_type>::value>::type resetMinMaxGain() { minGain.fill(std::numeric_limits<int32_t>::min()); maxGain.fill(std::numeric_limits<int32_t>::max()); } template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value && std::is_floating_point<typename S::value_type>::value>::type resetMinMaxGain() { minGain.fill(std::numeric_limits<double>::lowest()); maxGain.fill(std::numeric_limits<double>::max()); } }; /** * Operator overload (<<) to enable an easy way to print the state of a * Gain instance to an output stream.\n * Does not print a newline control character. */ template <typename Tout, typename Tgain> std::ostream& operator<<(std::ostream& os, Gain<Tout,Tgain>& gain) { os << "Block Gain: '" << gain.getName() << "' is enabled=" << gain.enabled << ", gain=" << gain.gain << ", "; os << "smoothChange=" << gain.smoothChange << ", minGain=" << gain.minGain << ", maxGain=" << gain.maxGain << ", "; os << "targetGain=" << gain.targetGain << ", gainDiff=" << gain.gainDiff; } }; }; #endif /* ORG_EEROS_CONTROL_GAIN_HPP_ */ <commit_msg>Make Gain block thread safe<commit_after>#ifndef ORG_EEROS_CONTROL_GAIN_HPP_ #define ORG_EEROS_CONTROL_GAIN_HPP_ #include <eeros/control/Block1i1o.hpp> #include <type_traits> #include <memory> #include <mutex> namespace eeros { namespace control { /** * A gain block is used to amplify an input signal. This is basically done by * multiplying the gain with the input signal value. * The following term represents the operation performed in this block. * * output = gain * input * * Gain is a class template with two type and one non-type template arguments. * The two type template arguments specify the types which are used for the * output type and the gain type when the class template is instanciated. * The non-type template argument specifies if the multiplication will be done * element wise in case the gain is used with matrices. * * A gain block is suitable for use with multiple threads. However, * enabling/disabling of the gain and the smooth change feature * is not synchronized. * * @tparam Tout - output type (double - default type) * @tparam Tgain - gain type (double - default type) * @tparam elementWise - amplify element wise (false - default value) * * @since v0.6 */ template <typename Tout = double, typename Tgain = double, bool elementWise = false> class Gain : public Block1i1o<Tout> { public: /** * Constructs a default gain instance with a gain of 1.\n * Calls Gain(Tgain c). * * @see Gain(Tgain c) */ Gain() : Gain(1.0) {} /** * Constructs a gain instance with a gain of the value of the parameter c.\n * Calls Gain(Tgain c, Tgain maxGain, Tgain minGain).\n * * @see Gain(Tgain c, Tgain maxGain, Tgain minGain) * * @param c - initial gain value */ Gain(Tgain c) : Gain(c, 1.0, -1.0) { // 1.0 and -1.0 are temp values only. resetMinMaxGain<Tgain>(); // set limits to smallest/largest value. } /** * Constructs a gain instance with a gain of the value of the parameter c, * a maximum gain of maxGain and a minimum gain of minGain.\n * Sets the target gain to the value of the parameter c.\n * Sets the gain diff to 0. * * @param c - initial gain value * @param maxGain - initial maximum gain value * @param minGain - initial minimum gain value */ Gain(Tgain c, Tgain maxGain, Tgain minGain) { gain = c; this->maxGain = maxGain; this->minGain = minGain; targetGain = gain; gainDiff = 0; } /** * Runs the amplification algorithm. * * Performs the smooth change if smooth change is enabled with enableSmoothChange(bool). * A smooth change of the gain is performed by adding or subtracting a gain differential * specifiable by setGainDiff(Tgain). * * Checks if gain is in the band in between minGain and maxGain or correct it otherwise. * The correction is done by setting the maxGain or minGain to gain. * * Sets the output signal value to the amplified value calculated by multiplying gain * input if * the gain instance is enabled by enable(). * * @see enableSmoothChange(bool) * @see setGainDiff(Tgain) * @see enable() * @see disable() */ virtual void run() { std::lock_guard<std::mutex> lock(mtx); if(smoothChange) { if(gain < targetGain) { gain += gainDiff; if(gain > targetGain) { // overshoot case. gain = targetGain; } } if(gain > targetGain) { gain -= gainDiff; if(gain < targetGain) { gain = targetGain; } } } if(gain > maxGain) { // if diff will cause gain to be too large. gain = maxGain; } if(gain < minGain) { gain = minGain; } if(enabled) { this->out.getSignal().setValue(calculateResults<Tout>(this->in.getSignal().getValue())); } else { this->out.getSignal().setValue(this->in.getSignal().getValue()); } this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp()); } /** * Enables the gain. * * If enabled, run() will set the output signal to the amplified value calculated by multiplying gain * input. * * Does not enable smooth change. This is done by calling enableSmoothChange(bool). * * @see run() * @see enableSmoothChange(bool) */ virtual void enable() { enabled = true; } /** * Disables the gain. * * If disabled, run() will set the output signal to the input signal. * * Does not disable smooth change. This is done by calling enableSmoothChange(bool). * * @see run() * @see enableSmoothChange(bool) */ virtual void disable() { enabled = false; } /** * Enables or disables a smooth change of the gain. * * If enabled, run() will perform a smooth change of the gain value. * * Does not enable or disable the gain. This is done by calling enable() and disable() respectively. * * @param enable - enables or disables a smooth change of the gain * * @see run() * @see enable() * @see disable() */ virtual void enableSmoothChange(bool enable) { smoothChange = enable; } /** * Sets the gain value if smooth change is disabled and c is in the band in between minGain and maxGain. * * Sets the target gain value if smooth change is enabled and c is in the band in between minGain and maxGain. * * Does not change gain or target gain value otherwise. * * @param c - gain value */ virtual void setGain(Tgain c) { std::lock_guard<std::mutex> lock(mtx); if(c <= maxGain && c >= minGain) { if(smoothChange) { targetGain = c; }else { gain = c; } } } /** * Sets the maximum allowed gain. * * @param maxGain - maximum allowed gain value */ virtual void setMaxGain(Tgain maxGain) { std::lock_guard<std::mutex> lock(mtx); this->maxGain = maxGain; } /** * Sets the minimum allowed gain. * * @param minGain - minimum allowed gain value */ virtual void setMinGain(Tgain minGain) { std::lock_guard<std::mutex> lock(mtx); this->minGain = minGain; } /** * Sets the gain differential needed by run() to perform a smooth gain change. * * @param gainDiff - gain differential */ virtual void setGainDiff(Tgain gainDiff) { std::lock_guard<std::mutex> lock(mtx); this->gainDiff = gainDiff; } /* * Friend operator overload to give the operator overload outside * the class access to the private fields. */ template <typename Xout, typename Xgain> friend std::ostream& operator<<(std::ostream& os, Gain<Xout,Xgain>& gain); protected: Tgain gain; Tgain maxGain; Tgain minGain; Tgain targetGain; Tgain gainDiff; bool enabled{true}; bool smoothChange{false}; std::mutex mtx; private: template <typename S> typename std::enable_if<!elementWise,S>::type calculateResults(S value) { return gain * value; } template <typename S> typename std::enable_if<elementWise,S>::type calculateResults(S value) { return value.multiplyElementWise(gain); } template <typename S> typename std::enable_if<std::is_integral<S>::value>::type resetMinMaxGain() { minGain = std::numeric_limits<int32_t>::min(); maxGain = std::numeric_limits<int32_t>::max(); } template <typename S> typename std::enable_if<std::is_floating_point<S>::value>::type resetMinMaxGain() { minGain = std::numeric_limits<double>::lowest(); maxGain = std::numeric_limits<double>::max(); } template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value && std::is_integral<typename S::value_type>::value>::type resetMinMaxGain() { minGain.fill(std::numeric_limits<int32_t>::min()); maxGain.fill(std::numeric_limits<int32_t>::max()); } template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value && std::is_floating_point<typename S::value_type>::value>::type resetMinMaxGain() { minGain.fill(std::numeric_limits<double>::lowest()); maxGain.fill(std::numeric_limits<double>::max()); } }; /** * Operator overload (<<) to enable an easy way to print the state of a * Gain instance to an output stream.\n * Does not print a newline control character. */ template <typename Tout, typename Tgain> std::ostream& operator<<(std::ostream& os, Gain<Tout,Tgain>& gain) { os << "Block Gain: '" << gain.getName() << "' is enabled=" << gain.enabled << ", gain=" << gain.gain << ", "; os << "smoothChange=" << gain.smoothChange << ", minGain=" << gain.minGain << ", maxGain=" << gain.maxGain << ", "; os << "targetGain=" << gain.targetGain << ", gainDiff=" << gain.gainDiff; } }; }; #endif /* ORG_EEROS_CONTROL_GAIN_HPP_ */ <|endoftext|>
<commit_before>#include "mapDisplay.hpp" mapDisplay::mapDisplay(GPSState reference, cvImage startImage) { lastImage=(IplImage)startImage; referencePoint=reference; cvNamedWindow("Field Map",CV_WINDOW_AUTOSIZE); cvMoveWindow("Field Map",X_COORD_ON_SCREEN ,Y_COORD_ON_SCREEN); cvResizeWindow("Field Map",WIDTH,HEIGHT); } mapDisplay::draw(cvImage newImage) { lastImage=(IplImage)startImage; CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX,1.0,1.0,1,CV_AA); for(int i=0;i<GPSPoints.size();i++) Circle(lastImage,GPSPoints[i],1,CvScalar(0,255,0)); for(int i=0;i<additionalPoints.size();i++) Circle(lastImage,dditionalPoints[i],1,CvScalar(0,0,255)); cvShowImage("Field Map",&lastImage); } mapDisplay::addPointToDraw(GPSState newPoint) { double xGPS; double yGPS; lambert_distance_xy(newPoint,referencePoint,&xGPS,&yGPS); cvPoint toAdd((int)(xGPS/meters_per_pixel),(int)(yGPS/meters_per_pixel)); additionalPoints.push_end(toAdd); } mapDisplay::addGPSPointToDraw(GPSState newGPSPoint) { double xGPS; double yGPS; lambert_distance_xy(newGPSPoint,referencePoint,&xGPS,&yGPS); cvPoint toAdd((int)(xGPS/meters_per_pixel),(int)(yGPS/meters_per_pixel)); GPSPoints.push_end(toAdd); } mapDisplay::addPointToDraw(double lat, double lon) { GPSState newPoint; givenStates.lon=lon; givenStates.lat=lat; double xGPS; double yGPS; lambert_distance_xy(newPoint,referencePoint,&xGPS,&yGPS); cvPoint toAdd((int)(xGPS/meters_per_pixel),(int)(yGPS/meters_per_pixel)); additionalPoints.push_end(toAdd); } mapDisplay::addGPSPointToDraw(double lat, double lon) { GPSState newPoint; givenStates.lon=lon; givenStates.lat=lat; double xGPS; double yGPS; lambert_distance_xy(newPoint,referencePoint,&xGPS,&yGPS); cvPoint toAdd((int)(xGPS/meters_per_pixel),(int)(yGPS/meters_per_pixel)); GPSPoints.push_end(toAdd); } <commit_msg>Remove dead file "maDisplay" bc "mapDisplay" is used. minor update to docs<commit_after><|endoftext|>
<commit_before>/** * File : C.cpp * Author : Kazune Takahashi * Created : 9/22/2018, 9:12:06 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll MOD = 1000000007; int N, K; ll A[100]; ll cnt[100]; ll DP[50][5010][2]; int main() { cin >> N >> K; for (auto i = 1; i <= N; i++) { cin >> A[i]; } for (auto i = 1; i <= N; i++) { cnt[i] = 0; while (A[i] > 0) { A[i] /= 2; cnt[i]++; } } fill(&DP[0][0][0], &DP[0][0][0] + 50 * 5010 * 2, 0); DP[0][0][0] = 1; K = min(K, 5000); for (auto i = 1; i <= N; i++) { ll C = cnt[i]; for (auto j = 0; j <= K; j++) { /* DP[i][j][0] = 0; int ind = j - 1; if (ind >= 0) { DP[i][j][0] += DP[i][ind][0]; DP[i][j][0] %= MOD; DP[i][j][0] += MOD - DP[i - 1][ind][0]; DP[i][j][0] %= MOD; } ind = j - 1 + C; if (0 <= ind && ind <= K) { DP[i][j][0] += DP[i][ind][0]; DP[i][j][0] %= MOD; } DP[i][j][1] = 0; ind = j - 1; if (ind >= 0) { DP[i][j][1] += DP[i][ind][1]; DP[i][j][1] %= MOD; DP[i][j][1] += MOD - DP[i - 1][ind][1]; DP[i][j][1] %= MOD; } ind = j + C; if (0 <= ind && ind <= K) { DP[i][j][1] += DP[i][ind][1]; DP[i][j][1] %= MOD; } ind = j - C; if (0 <= ind && ind <= K) { DP[i][j][1] += DP[i][ind][0]; DP[i][j][1] %= MOD; } */ DP[i][j][0] = 0; for (auto k = 0; k <= C - 1; k++) { if (0 <= j - k && j - k <= K) { DP[i][j][0] += DP[i - 1][j - k][0]; DP[i][j][0] %= MOD; } } DP[i][j][1] = 0; for (auto k = 0; k <= C; k++) { if (0 <= j - k && j - k <= K) { DP[i][j][1] += DP[i - 1][j - k][1]; DP[i][j][1] %= MOD; } } if (j - C >= 0) { DP[i][j][1] += DP[i - 1][j - C][0]; DP[i][j][1] %= MOD; } } } ll ans = DP[N][K][0]; for (auto i = 0; i <= K; i++) { ans += DP[N][i][1]; ans %= MOD; } cout << ans << endl; } <commit_msg>submit C.cpp to 'C - 半分' (code-festival-2018-quala) [C++14 (GCC 5.4.1)]<commit_after>/** * File : C.cpp * Author : Kazune Takahashi * Created : 9/22/2018, 9:12:06 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll MOD = 1000000007; int N, K; ll A[100]; ll cnt[100]; ll DP[60][5010][2]; int main() { cin >> N >> K; for (auto i = 1; i <= N; i++) { cin >> A[i]; } for (auto i = 1; i <= N; i++) { cnt[i] = 0; while (A[i] > 0) { A[i] /= 2; cnt[i]++; } } fill(&DP[0][0][0], &DP[0][0][0] + 60 * 5010 * 2, 0); DP[0][0][0] = 1; K = min(K, 5000); for (auto i = 1; i <= N; i++) { ll C = cnt[i]; for (auto j = 0; j <= K; j++) { /* DP[i][j][0] = 0; int ind = j - 1; if (ind >= 0) { DP[i][j][0] += DP[i][ind][0]; DP[i][j][0] %= MOD; DP[i][j][0] += MOD - DP[i - 1][ind][0]; DP[i][j][0] %= MOD; } ind = j - 1 + C; if (0 <= ind && ind <= K) { DP[i][j][0] += DP[i][ind][0]; DP[i][j][0] %= MOD; } DP[i][j][1] = 0; ind = j - 1; if (ind >= 0) { DP[i][j][1] += DP[i][ind][1]; DP[i][j][1] %= MOD; DP[i][j][1] += MOD - DP[i - 1][ind][1]; DP[i][j][1] %= MOD; } ind = j + C; if (0 <= ind && ind <= K) { DP[i][j][1] += DP[i][ind][1]; DP[i][j][1] %= MOD; } ind = j - C; if (0 <= ind && ind <= K) { DP[i][j][1] += DP[i][ind][0]; DP[i][j][1] %= MOD; } */ DP[i][j][0] = 0; for (auto k = 0; k <= C - 1; k++) { if (0 <= j - k && j - k <= K) { DP[i][j][0] += DP[i - 1][j - k][0]; DP[i][j][0] %= MOD; } } DP[i][j][1] = 0; for (auto k = 0; k <= C; k++) { if (0 <= j - k && j - k <= K) { DP[i][j][1] += DP[i - 1][j - k][1]; DP[i][j][1] %= MOD; } } if (j - C >= 0) { DP[i][j][1] += DP[i - 1][j - C][0]; DP[i][j][1] %= MOD; } } } ll ans = DP[N][K][0]; for (auto i = 0; i <= K; i++) { ans += DP[N][i][1]; ans %= MOD; } cout << ans << endl; } <|endoftext|>
<commit_before>/* Simple DirectMedia Layer Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "xinputcheck.h" #include <string.h> #include <stdlib.h> // XInputCheck is an XInput check abstracted away from SDL. // // If you need to update this file, please arrange the code such that // it is possible to copy/paste directly from SDL. This makes code // sharing easier! Right now, the SDL_IsXInputDevice is directly // copied from SDL. // // Below, we have a few preprocessor defines, that allow the SDL functions // we use, to run in our environment. // // After that, there is an implementation of the SDL_XINPUT_Enabled // that always returns true. // // Then comes the implementation of SDL_IsXInputDevice, which is copied // directly from SDL. // // At the bottom of the file, you'll find our wrapper interfaces -- // the public API for the XInputCheck library. // // Again, if you ever need to change anything in the SDL functions, well. // Think again! If you find a bug, feel free to fix it, but report it // upstream as well. // If at all possible, try to use wrapper functions to implement "new" // functionality (such as XInputCheck_ClearDeviceCache, for clearing // the internal cache). // Preprocessor helpers for running SDL code as-is. #define SDL_bool bool #define SDL_TRUE true #define SDL_FALSE false #define SDL_free free #define SDL_malloc malloc #define SDL_OutOfMemory abort #define SDL_strstr strstr #define SDL_memcmp memcmp #define SDL_arraysize(array) (sizeof(array)/sizeof(array[0])) static SDL_bool SDL_XINPUT_Enabled() { return SDL_TRUE; } static PRAWINPUTDEVICELIST SDL_RawDevList = NULL; static UINT SDL_RawDevListCount = 0; static SDL_bool SDL_IsXInputDevice(const GUID* pGuidProductFromDirectInput) { static GUID IID_ValveStreamingGamepad = { MAKELONG(0x28DE, 0x11FF), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_X360WiredGamepad = { MAKELONG(0x045E, 0x02A1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_X360WirelessGamepad = { MAKELONG(0x045E, 0x028E), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static const GUID *s_XInputProductGUID[] = { &IID_ValveStreamingGamepad, &IID_X360WiredGamepad, /* Microsoft's wired X360 controller for Windows. */ &IID_X360WirelessGamepad /* Microsoft's wireless X360 controller for Windows. */ }; size_t iDevice; UINT i; if (!SDL_XINPUT_Enabled()) { return SDL_FALSE; } /* Check for well known XInput device GUIDs */ /* This lets us skip RAWINPUT for popular devices. Also, we need to do this for the Valve Streaming Gamepad because it's virtualized and doesn't show up in the device list. */ for (iDevice = 0; iDevice < SDL_arraysize(s_XInputProductGUID); ++iDevice) { if (SDL_memcmp(pGuidProductFromDirectInput, s_XInputProductGUID[iDevice], sizeof(GUID)) == 0) { return SDL_TRUE; } } /* Go through RAWINPUT (WinXP and later) to find HID devices. */ /* Cache this if we end up using it. */ if (SDL_RawDevList == NULL) { if ((GetRawInputDeviceList(NULL, &SDL_RawDevListCount, sizeof(RAWINPUTDEVICELIST)) == -1) || (!SDL_RawDevListCount)) { return SDL_FALSE; /* oh well. */ } SDL_RawDevList = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * SDL_RawDevListCount); if (SDL_RawDevList == NULL) { SDL_OutOfMemory(); return SDL_FALSE; } if (GetRawInputDeviceList(SDL_RawDevList, &SDL_RawDevListCount, sizeof(RAWINPUTDEVICELIST)) == -1) { SDL_free(SDL_RawDevList); SDL_RawDevList = NULL; return SDL_FALSE; /* oh well. */ } } for (i = 0; i < SDL_RawDevListCount; i++) { RID_DEVICE_INFO rdi; char devName[128]; UINT rdiSize = sizeof(rdi); UINT nameSize = SDL_arraysize(devName); rdi.cbSize = sizeof(rdi); if ((SDL_RawDevList[i].dwType == RIM_TYPEHID) && (GetRawInputDeviceInfoA(SDL_RawDevList[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != ((UINT)-1)) && (MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == ((LONG)pGuidProductFromDirectInput->Data1)) && (GetRawInputDeviceInfoA(SDL_RawDevList[i].hDevice, RIDI_DEVICENAME, devName, &nameSize) != ((UINT)-1)) && (SDL_strstr(devName, "IG_") != NULL)) { return SDL_TRUE; } } return SDL_FALSE; } bool XInputCheck_IsGuidProductXInputDevice(const GUID *pGuidProductFromDirectInput) { return SDL_IsXInputDevice(pGuidProductFromDirectInput); } void XInputCheck_ClearDeviceCache() { SDL_free(SDL_RawDevList); SDL_RawDevList = NULL; SDL_RawDevListCount = 0; } <commit_msg>3rdparty/xinputcheck-src: add Xbox One controller GUIDs to avoid device list querying for Xbox One controllers.<commit_after>/* Simple DirectMedia Layer Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "xinputcheck.h" #include <string.h> #include <stdlib.h> // XInputCheck is an XInput check abstracted away from SDL. // // If you need to update this file, please arrange the code such that // it is possible to copy/paste directly from SDL. This makes code // sharing easier! Right now, the SDL_IsXInputDevice is directly // copied from SDL. // // Below, we have a few preprocessor defines, that allow the SDL functions // we use, to run in our environment. // // After that, there is an implementation of the SDL_XINPUT_Enabled // that always returns true. // // Then comes the implementation of SDL_IsXInputDevice, which is copied // directly from SDL. // // At the bottom of the file, you'll find our wrapper interfaces -- // the public API for the XInputCheck library. // // Again, if you ever need to change anything in the SDL functions, well. // Think again! If you find a bug, feel free to fix it, but report it // upstream as well. // If at all possible, try to use wrapper functions to implement "new" // functionality (such as XInputCheck_ClearDeviceCache, for clearing // the internal cache). // Preprocessor helpers for running SDL code as-is. #define SDL_bool bool #define SDL_TRUE true #define SDL_FALSE false #define SDL_free free #define SDL_malloc malloc #define SDL_OutOfMemory abort #define SDL_strstr strstr #define SDL_memcmp memcmp #define SDL_arraysize(array) (sizeof(array)/sizeof(array[0])) static SDL_bool SDL_XINPUT_Enabled() { return SDL_TRUE; } static PRAWINPUTDEVICELIST SDL_RawDevList = NULL; static UINT SDL_RawDevListCount = 0; static SDL_bool SDL_IsXInputDevice(const GUID* pGuidProductFromDirectInput) { static GUID IID_ValveStreamingGamepad = { MAKELONG(0x28DE, 0x11FF), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_X360WiredGamepad = { MAKELONG(0x045E, 0x02A1), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_X360WirelessGamepad = { MAKELONG(0x045E, 0x028E), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_XOneWiredGamepad = { MAKELONG(0x045E, 0x02FF), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_XOneWirelessGamepad = { MAKELONG(0x045E, 0x02DD), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static GUID IID_XOneBluetoothGamepad = { MAKELONG(0x045E, 0x02E0), 0x0000, 0x0000, { 0x00, 0x00, 0x50, 0x49, 0x44, 0x56, 0x49, 0x44 } }; static const GUID *s_XInputProductGUID[] = { &IID_ValveStreamingGamepad, &IID_X360WiredGamepad, /* Microsoft's wired X360 controller for Windows. */ &IID_X360WirelessGamepad, /* Microsoft's wireless X360 controller for Windows. */ &IID_XOneWiredGamepad, /* Microsoft's wired Xbox One controller for Windows. */ &IID_XOneWirelessGamepad, /* Microsoft's wireless Xbox One controller for Windows. */ &IID_XOneBluetoothGamepad /* Microsoft's Bluetooth Xbox One controller for Windows. */ }; size_t iDevice; UINT i; if (!SDL_XINPUT_Enabled()) { return SDL_FALSE; } /* Check for well known XInput device GUIDs */ /* This lets us skip RAWINPUT for popular devices. Also, we need to do this for the Valve Streaming Gamepad because it's virtualized and doesn't show up in the device list. */ for (iDevice = 0; iDevice < SDL_arraysize(s_XInputProductGUID); ++iDevice) { if (SDL_memcmp(pGuidProductFromDirectInput, s_XInputProductGUID[iDevice], sizeof(GUID)) == 0) { return SDL_TRUE; } } /* Go through RAWINPUT (WinXP and later) to find HID devices. */ /* Cache this if we end up using it. */ if (SDL_RawDevList == NULL) { if ((GetRawInputDeviceList(NULL, &SDL_RawDevListCount, sizeof(RAWINPUTDEVICELIST)) == -1) || (!SDL_RawDevListCount)) { return SDL_FALSE; /* oh well. */ } SDL_RawDevList = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * SDL_RawDevListCount); if (SDL_RawDevList == NULL) { SDL_OutOfMemory(); return SDL_FALSE; } if (GetRawInputDeviceList(SDL_RawDevList, &SDL_RawDevListCount, sizeof(RAWINPUTDEVICELIST)) == -1) { SDL_free(SDL_RawDevList); SDL_RawDevList = NULL; return SDL_FALSE; /* oh well. */ } } for (i = 0; i < SDL_RawDevListCount; i++) { RID_DEVICE_INFO rdi; char devName[128]; UINT rdiSize = sizeof(rdi); UINT nameSize = SDL_arraysize(devName); rdi.cbSize = sizeof(rdi); if ((SDL_RawDevList[i].dwType == RIM_TYPEHID) && (GetRawInputDeviceInfoA(SDL_RawDevList[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != ((UINT)-1)) && (MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == ((LONG)pGuidProductFromDirectInput->Data1)) && (GetRawInputDeviceInfoA(SDL_RawDevList[i].hDevice, RIDI_DEVICENAME, devName, &nameSize) != ((UINT)-1)) && (SDL_strstr(devName, "IG_") != NULL)) { return SDL_TRUE; } } return SDL_FALSE; } bool XInputCheck_IsGuidProductXInputDevice(const GUID *pGuidProductFromDirectInput) { return SDL_IsXInputDevice(pGuidProductFromDirectInput); } void XInputCheck_ClearDeviceCache() { SDL_free(SDL_RawDevList); SDL_RawDevList = NULL; SDL_RawDevListCount = 0; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertymap.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_HELPER_PROPERTYMAP_HXX #define OOX_HELPER_PROPERTYMAP_HXX #include <map> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/uno/Sequence.hxx> namespace oox { typedef std::map< ::rtl::OUString, com::sun::star::uno::Any > PropertyMapBase; class PropertyMap : public PropertyMapBase { public: bool hasProperty( const ::rtl::OUString& rName ) const; const com::sun::star::uno::Any* getPropertyValue( const ::rtl::OUString& rName ) const; void makeSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rSequence ) const; void makeSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rSequence ) const; void makeSequence( ::com::sun::star::uno::Sequence< ::rtl::OUString >& rNames, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rValues ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > makePropertySet() const; void dump_debug(const char *pMessage = NULL); }; } // namespace oox #endif <commit_msg>INTEGRATION: CWS xmlfilter06 (1.3.8); FILE MERGED 2008/06/27 09:18:00 dr 1.3.8.2: fill properties cleanup, resolve line gradients to solid color 2008/06/26 14:15:56 dr 1.3.8.1: handle drawing object tables separated for chart import, extended line formatting with own property name sets<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertymap.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_HELPER_PROPERTYMAP_HXX #define OOX_HELPER_PROPERTYMAP_HXX #include <map> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/uno/Sequence.hxx> #include "oox/helper/helper.hxx" namespace oox { typedef std::map< ::rtl::OUString, com::sun::star::uno::Any > PropertyMapBase; class PropertyMap : public PropertyMapBase { public: bool hasProperty( const ::rtl::OUString& rName ) const; const com::sun::star::uno::Any* getPropertyValue( const ::rtl::OUString& rName ) const; template< typename Type > inline void setProperty( const ::rtl::OUString& rName, const Type& rValue ) { if( rName.getLength() > 0 ) (*this)[ rName ] <<= rValue; } void makeSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rSequence ) const; void makeSequence( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rSequence ) const; void makeSequence( ::com::sun::star::uno::Sequence< ::rtl::OUString >& rNames, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rValues ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > makePropertySet() const; void dump_debug(const char *pMessage = NULL); }; } // namespace oox #endif <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/algorithms/corr_dist.h" #include <memory> #include "open_spiel/abseil-cpp/absl/algorithm/container.h" #include "open_spiel/abseil-cpp/absl/strings/numbers.h" #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/abseil-cpp/absl/strings/str_format.h" #include "open_spiel/abseil-cpp/absl/strings/str_join.h" #include "open_spiel/abseil-cpp/absl/strings/str_split.h" #include "open_spiel/algorithms/best_response.h" #include "open_spiel/algorithms/corr_dist/efcce.h" #include "open_spiel/algorithms/corr_dist/efce.h" #include "open_spiel/algorithms/expected_returns.h" #include "open_spiel/game_transforms/turn_based_simultaneous_game.h" #include "open_spiel/policy.h" #include "open_spiel/spiel.h" namespace open_spiel { namespace algorithms { namespace { // A few helper functions local to this file. void CheckCorrelationDeviceProbDist(const CorrelationDevice& mu) { double prob_sum = 0.0; for (const std::pair<double, TabularPolicy>& item : mu) { SPIEL_CHECK_PROB(item.first); prob_sum += item.first; } SPIEL_CHECK_FLOAT_EQ(prob_sum, 1.0); } ActionsAndProbs CreateDeterministicPolicy(Action chosen_action, int num_actions) { ActionsAndProbs actions_and_probs; actions_and_probs.reserve(num_actions); int num_ones = 0; int num_zeros = 0; for (Action action = 0; action < num_actions; ++action) { if (action == chosen_action) { num_ones++; actions_and_probs.push_back({action, 1.0}); } else { num_zeros++; actions_and_probs.push_back({action, 0.0}); } } SPIEL_CHECK_EQ(num_ones, 1); SPIEL_CHECK_EQ(num_ones + num_zeros, num_actions); return actions_and_probs; } CorrelationDevice ConvertCorrelationDevice( const Game& turn_based_nfg, const NormalFormCorrelationDevice& mu) { // First get all the infostate strings. std::unique_ptr<State> state = turn_based_nfg.NewInitialState(); std::vector<std::string> infostate_strings; infostate_strings.reserve(turn_based_nfg.NumPlayers()); for (Player p = 0; p < turn_based_nfg.NumPlayers(); ++p) { infostate_strings.push_back(state->InformationStateString()); state->ApplyAction(0); } SPIEL_CHECK_TRUE(state->IsTerminal()); int num_actions = turn_based_nfg.NumDistinctActions(); CorrelationDevice new_mu; new_mu.reserve(mu.size()); // Next, convert to tabular policies. for (const NormalFormJointPolicyWithProb& jpp : mu) { TabularPolicy policy; SPIEL_CHECK_EQ(jpp.actions.size(), turn_based_nfg.NumPlayers()); for (Player p = 0; p < turn_based_nfg.NumPlayers(); p++) { policy.SetStatePolicy( infostate_strings[p], CreateDeterministicPolicy(jpp.actions[p], num_actions)); } new_mu.push_back({jpp.probability, policy}); } return new_mu; } // This is essentially the same as NashConv, but we need to add a max(0, di) to // the incentive to deviate, di, because the best response can be negative if // the pi_{-i} is correlated (there may not be any single action / strategy to // switch to for this player that gets higher value than playing the correlated // joint policy). double CustomNashConv(const Game& game, const Policy& policy, bool use_state_get_policy) { GameType game_type = game.GetType(); if (game_type.dynamics != GameType::Dynamics::kSequential) { SpielFatalError("The game must be turn-based."); } std::unique_ptr<State> root = game.NewInitialState(); std::vector<double> best_response_values(game.NumPlayers()); for (auto p = Player{0}; p < game.NumPlayers(); ++p) { TabularBestResponse best_response(game, p, &policy); best_response_values[p] = best_response.Value(root->ToString()); } std::vector<double> on_policy_values = ExpectedReturns(*root, policy, -1, !use_state_get_policy); SPIEL_CHECK_EQ(best_response_values.size(), on_policy_values.size()); double nash_conv = 0; for (auto p = Player{0}; p < game.NumPlayers(); ++p) { nash_conv += std::max(0.0, best_response_values[p] - on_policy_values[p]); } return nash_conv; } } // namespace // Return a string representation of the correlation device. std::string ToString(const CorrelationDevice& corr_dev) { std::string corr_dev_str; for (const auto& prob_and_policy : corr_dev) { absl::StrAppend(&corr_dev_str, "Prob: ", prob_and_policy.first, "\n"); absl::StrAppend(&corr_dev_str, prob_and_policy.second.ToStringSorted(), "\n"); } return corr_dev_str; } std::vector<double> ExpectedValues(const Game& game, const CorrelationDevice& mu) { CheckCorrelationDeviceProbDist(mu); std::vector<double> values(game.NumPlayers(), 0); for (const std::pair<double, TabularPolicy>& item : mu) { std::vector<double> item_values = ExpectedReturns(*game.NewInitialState(), item.second, -1, false); for (Player p = 0; p < game.NumPlayers(); ++p) { values[p] += item.first * item_values[p]; } } return values; } std::vector<double> ExpectedValues(const Game& game, const NormalFormCorrelationDevice& mu) { if (game.GetType().information == GameType::Information::kOneShot) { std::shared_ptr<const Game> actual_game = ConvertToTurnBased(game); CorrelationDevice converted_mu = ConvertCorrelationDevice(*actual_game, mu); return ExpectedValues(*actual_game, converted_mu); } else { SPIEL_CHECK_EQ(game.GetType().dynamics, GameType::Dynamics::kSequential); CorrelationDevice converted_mu = ConvertCorrelationDevice(game, mu); return ExpectedValues(game, converted_mu); } } double EFCEDist(const Game& game, CorrDistConfig config, const CorrelationDevice& mu) { // Check that the config matches what is supported. SPIEL_CHECK_TRUE(config.deterministic); SPIEL_CHECK_FALSE(config.convert_policy); // Check for proper probability distribution. CheckCorrelationDeviceProbDist(mu); std::shared_ptr<const Game> efce_game(new EFCEGame(game.Clone(), config, mu)); // Note that the policies are already inside the game via the correlation // device, mu. So this is a simple wrapper policy that simply follows the // recommendations. EFCETabularPolicy policy(config); return CustomNashConv(*efce_game, policy, true); } double EFCCEDist(const Game& game, CorrDistConfig config, const CorrelationDevice& mu) { // Check that the config matches what is supported. SPIEL_CHECK_TRUE(config.deterministic); SPIEL_CHECK_FALSE(config.convert_policy); // Check for proper probability distribution. CheckCorrelationDeviceProbDist(mu); std::shared_ptr<const EFCCEGame> efcce_game( new EFCCEGame(game.Clone(), config, mu)); // Note that the policies are already inside the game via the correlation // device, mu. So this is a simple wrapper policy that simply follows the // recommendations. EFCCETabularPolicy policy(efcce_game->FollowAction(), efcce_game->DefectAction()); return CustomNashConv(*efcce_game, policy, true); } double CEDist(const Game& game, const NormalFormCorrelationDevice& mu) { if (game.GetType().information == GameType::Information::kOneShot) { std::shared_ptr<const Game> actual_game = ConvertToTurnBased(game); CorrelationDevice converted_mu = ConvertCorrelationDevice(*actual_game, mu); CorrDistConfig config; return EFCEDist(*actual_game, config, converted_mu); } else { SPIEL_CHECK_EQ(game.GetType().dynamics, GameType::Dynamics::kSequential); CorrelationDevice converted_mu = ConvertCorrelationDevice(game, mu); CorrDistConfig config; return EFCEDist(game, config, converted_mu); } } double CCEDist(const Game& game, const NormalFormCorrelationDevice& mu) { if (game.GetType().information == GameType::Information::kOneShot) { std::shared_ptr<const Game> actual_game = ConvertToTurnBased(game); CorrelationDevice converted_mu = ConvertCorrelationDevice(*actual_game, mu); CorrDistConfig config; return EFCCEDist(*actual_game, config, converted_mu); } else { SPIEL_CHECK_EQ(game.GetType().dynamics, GameType::Dynamics::kSequential); CorrelationDevice converted_mu = ConvertCorrelationDevice(game, mu); CorrDistConfig config; return EFCCEDist(game, config, converted_mu); } } } // namespace algorithms } // namespace open_spiel <commit_msg>CorrDist cleanup: remove CustomNashConv as max(0, d_i) is not needed since the follow action is always included in these gadget games, ensuring the per-player incentive deviation is always >= 0.<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/algorithms/corr_dist.h" #include <memory> #include "open_spiel/abseil-cpp/absl/algorithm/container.h" #include "open_spiel/abseil-cpp/absl/strings/numbers.h" #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/abseil-cpp/absl/strings/str_format.h" #include "open_spiel/abseil-cpp/absl/strings/str_join.h" #include "open_spiel/abseil-cpp/absl/strings/str_split.h" #include "open_spiel/algorithms/best_response.h" #include "open_spiel/algorithms/corr_dist/efcce.h" #include "open_spiel/algorithms/corr_dist/efce.h" #include "open_spiel/algorithms/expected_returns.h" #include "open_spiel/algorithms/tabular_exploitability.h" #include "open_spiel/game_transforms/turn_based_simultaneous_game.h" #include "open_spiel/policy.h" #include "open_spiel/spiel.h" namespace open_spiel { namespace algorithms { namespace { // A few helper functions local to this file. void CheckCorrelationDeviceProbDist(const CorrelationDevice& mu) { double prob_sum = 0.0; for (const std::pair<double, TabularPolicy>& item : mu) { SPIEL_CHECK_PROB(item.first); prob_sum += item.first; } SPIEL_CHECK_FLOAT_EQ(prob_sum, 1.0); } ActionsAndProbs CreateDeterministicPolicy(Action chosen_action, int num_actions) { ActionsAndProbs actions_and_probs; actions_and_probs.reserve(num_actions); int num_ones = 0; int num_zeros = 0; for (Action action = 0; action < num_actions; ++action) { if (action == chosen_action) { num_ones++; actions_and_probs.push_back({action, 1.0}); } else { num_zeros++; actions_and_probs.push_back({action, 0.0}); } } SPIEL_CHECK_EQ(num_ones, 1); SPIEL_CHECK_EQ(num_ones + num_zeros, num_actions); return actions_and_probs; } CorrelationDevice ConvertCorrelationDevice( const Game& turn_based_nfg, const NormalFormCorrelationDevice& mu) { // First get all the infostate strings. std::unique_ptr<State> state = turn_based_nfg.NewInitialState(); std::vector<std::string> infostate_strings; infostate_strings.reserve(turn_based_nfg.NumPlayers()); for (Player p = 0; p < turn_based_nfg.NumPlayers(); ++p) { infostate_strings.push_back(state->InformationStateString()); state->ApplyAction(0); } SPIEL_CHECK_TRUE(state->IsTerminal()); int num_actions = turn_based_nfg.NumDistinctActions(); CorrelationDevice new_mu; new_mu.reserve(mu.size()); // Next, convert to tabular policies. for (const NormalFormJointPolicyWithProb& jpp : mu) { TabularPolicy policy; SPIEL_CHECK_EQ(jpp.actions.size(), turn_based_nfg.NumPlayers()); for (Player p = 0; p < turn_based_nfg.NumPlayers(); p++) { policy.SetStatePolicy( infostate_strings[p], CreateDeterministicPolicy(jpp.actions[p], num_actions)); } new_mu.push_back({jpp.probability, policy}); } return new_mu; } } // namespace // Return a string representation of the correlation device. std::string ToString(const CorrelationDevice& corr_dev) { std::string corr_dev_str; for (const auto& prob_and_policy : corr_dev) { absl::StrAppend(&corr_dev_str, "Prob: ", prob_and_policy.first, "\n"); absl::StrAppend(&corr_dev_str, prob_and_policy.second.ToStringSorted(), "\n"); } return corr_dev_str; } std::vector<double> ExpectedValues(const Game& game, const CorrelationDevice& mu) { CheckCorrelationDeviceProbDist(mu); std::vector<double> values(game.NumPlayers(), 0); for (const std::pair<double, TabularPolicy>& item : mu) { std::vector<double> item_values = ExpectedReturns(*game.NewInitialState(), item.second, -1, false); for (Player p = 0; p < game.NumPlayers(); ++p) { values[p] += item.first * item_values[p]; } } return values; } std::vector<double> ExpectedValues(const Game& game, const NormalFormCorrelationDevice& mu) { if (game.GetType().information == GameType::Information::kOneShot) { std::shared_ptr<const Game> actual_game = ConvertToTurnBased(game); CorrelationDevice converted_mu = ConvertCorrelationDevice(*actual_game, mu); return ExpectedValues(*actual_game, converted_mu); } else { SPIEL_CHECK_EQ(game.GetType().dynamics, GameType::Dynamics::kSequential); CorrelationDevice converted_mu = ConvertCorrelationDevice(game, mu); return ExpectedValues(game, converted_mu); } } double EFCEDist(const Game& game, CorrDistConfig config, const CorrelationDevice& mu) { // Check that the config matches what is supported. SPIEL_CHECK_TRUE(config.deterministic); SPIEL_CHECK_FALSE(config.convert_policy); // Check for proper probability distribution. CheckCorrelationDeviceProbDist(mu); std::shared_ptr<const Game> efce_game(new EFCEGame(game.Clone(), config, mu)); // Note that the policies are already inside the game via the correlation // device, mu. So this is a simple wrapper policy that simply follows the // recommendations. EFCETabularPolicy policy(config); return NashConv(*efce_game, policy, true); } double EFCCEDist(const Game& game, CorrDistConfig config, const CorrelationDevice& mu) { // Check that the config matches what is supported. SPIEL_CHECK_TRUE(config.deterministic); SPIEL_CHECK_FALSE(config.convert_policy); // Check for proper probability distribution. CheckCorrelationDeviceProbDist(mu); std::shared_ptr<const EFCCEGame> efcce_game( new EFCCEGame(game.Clone(), config, mu)); // Note that the policies are already inside the game via the correlation // device, mu. So this is a simple wrapper policy that simply follows the // recommendations. EFCCETabularPolicy policy(efcce_game->FollowAction(), efcce_game->DefectAction()); return NashConv(*efcce_game, policy, true); } double CEDist(const Game& game, const NormalFormCorrelationDevice& mu) { if (game.GetType().information == GameType::Information::kOneShot) { std::shared_ptr<const Game> actual_game = ConvertToTurnBased(game); CorrelationDevice converted_mu = ConvertCorrelationDevice(*actual_game, mu); CorrDistConfig config; return EFCEDist(*actual_game, config, converted_mu); } else { SPIEL_CHECK_EQ(game.GetType().dynamics, GameType::Dynamics::kSequential); CorrelationDevice converted_mu = ConvertCorrelationDevice(game, mu); CorrDistConfig config; return EFCEDist(game, config, converted_mu); } } double CCEDist(const Game& game, const NormalFormCorrelationDevice& mu) { if (game.GetType().information == GameType::Information::kOneShot) { std::shared_ptr<const Game> actual_game = ConvertToTurnBased(game); CorrelationDevice converted_mu = ConvertCorrelationDevice(*actual_game, mu); CorrDistConfig config; return EFCCEDist(*actual_game, config, converted_mu); } else { SPIEL_CHECK_EQ(game.GetType().dynamics, GameType::Dynamics::kSequential); CorrelationDevice converted_mu = ConvertCorrelationDevice(game, mu); CorrDistConfig config; return EFCCEDist(game, config, converted_mu); } } } // namespace algorithms } // namespace open_spiel <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : A.cpp * Author : Kazune Takahashi * Created : 2020/6/28 20:51:38 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } void TLE() { sleep(10); } void RE() { assert(false); } std::random_device seed_gen; std::mt19937 engine(seed_gen()); // ----- Solve ----- #if DEBUG == 1 constexpr int D = 5; #else constexpr int D = 365; #endif constexpr int C = 26; constexpr int K = 1; constexpr int M = 5000; class Solve { vector<ll> c; vector<vector<ll>> s; vector<int> t; vector<set<int>> contestDays; ll totalScore; public: Solve() : c(C), s(D, vector<ll>(C, 0)), t(D), contestDays(C), totalScore{0} { for (auto i{0}; i < C; ++i) { cin >> c[i]; } for (auto i{0}; i < D; ++i) { for (auto j{0}; j < C; ++j) { cin >> s[i][j]; } } for (auto i{0}; i < C; ++i) { contestDays[i].insert(0); contestDays[i].insert(D + 1); } } void flush() { for (auto i{0}; i < D; ++i) { t[i] = engine() % C; } calc_score(); for (auto i{0}; i < M; ++i) { auto pScore{totalScore}; vector<int> d(K), q(K), p(K); for (auto j{0}; j < K; ++j) { d[j] = engine() % D; q[j] = engine() % C; p[j] = t[d[j] - 1]; change_score(d[j] + 1, q[j]); #if DEBUG == 1 cerr << "d" << d[j] << ", q = " << q[j] << ", p = " << p[j] << endl; #endif } auto qScore{totalScore}; #if DEBUG == 1 cerr << "pScore = " << pScore << ", qScore = " << qScore << endl; #endif if (pScore > qScore) { for (auto j{K - 1}; j >= 0; --j) { #if DEBUG == 1 cerr << "q = " << t[d[j] - 1] << endl; #endif change_score(d[j] + 1, p[j]); } #if DEBUG == 1 cerr << "score = " << totalScore << endl; #endif } } for (auto e : t) { cout << e + 1 << endl; } } private: ll change_score(int d, int q) { int p{t[d - 1]}; if (p == q) { return totalScore; } ll newScore{totalScore}; t[d - 1] = q; newScore -= s[d - 1][p]; newScore += s[d - 1][q]; { auto it{contestDays[p].find(d)}; --it; auto x{*it}; ++it; ++it; auto y{*it}; auto dif{(y - d) * (d - x)}; newScore -= c[p] * dif; --it; contestDays[p].erase(it); } { contestDays[q].insert(d); auto it{contestDays[q].find(d)}; --it; auto x{*it}; ++it; ++it; auto y{*it}; auto dif{(y - d) * (d - x)}; newScore += c[q] * dif; } return totalScore = newScore; } vector<ll> calc_score() { vector<ll> ans(D); vector<vector<int>> last(D + 1, vector<int>(C, 0)); ll now{0}; for (auto d{0}; d < D; ++d) { now += s[d][t[d]]; contestDays[t[d]].insert(d + 1); last[d + 1] = last[d]; last[d + 1][t[d]] = d + 1; ll penalty{0}; for (auto i{0}; i < C; ++i) { penalty += c[i] * (d + 1 - last[d + 1][i]); } now -= penalty; ans[d] = now; } totalScore = now; return ans; } }; // ----- main() ----- int main() { ll d; cin >> d; Solve solve; solve.flush(); } <commit_msg>tried A.cpp to 'A'<commit_after>#define DEBUG 1 /** * File : A.cpp * Author : Kazune Takahashi * Created : 2020/6/28 20:51:38 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/integer/common_factor_rt.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::integer::gcd; // for C++14 or for cpp_int using boost::integer::lcm; // for C++14 or for cpp_int using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> bool ch_max(T &left, T right) { if (left < right) { left = right; return true; } return false; } template <typename T> bool ch_min(T &left, T right) { if (left > right) { left = right; return true; } return false; } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; // ----- for C++17 ----- template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr> size_t popcount(T x) { return bitset<64>(x).count(); } size_t popcount(string const &S) { return bitset<200010>{S}.count(); } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } void TLE() { sleep(10); } void RE() { assert(false); } std::random_device seed_gen; std::mt19937 engine(seed_gen()); // ----- Solve ----- #if DEBUG == 1 constexpr int D = 5; #else constexpr int D = 365; #endif constexpr int C = 26; constexpr int K = 1; constexpr int M = 5000; class Solve { vector<ll> c; vector<vector<ll>> s; vector<int> t; vector<set<int>> contestDays; ll totalScore; public: Solve() : c(C), s(D, vector<ll>(C, 0)), t(D), contestDays(C), totalScore{0} { for (auto i{0}; i < C; ++i) { cin >> c[i]; } for (auto i{0}; i < D; ++i) { for (auto j{0}; j < C; ++j) { cin >> s[i][j]; } } for (auto i{0}; i < C; ++i) { contestDays[i].insert(0); contestDays[i].insert(D + 1); } } void flush() { for (auto i{0}; i < D; ++i) { t[i] = engine() % C; } calc_score(); for (auto i{0}; i < M; ++i) { auto pScore{totalScore}; vector<int> d(K), q(K), p(K); for (auto j{0}; j < K; ++j) { d[j] = engine() % D; q[j] = engine() % C; p[j] = t[d[j] - 1]; change_score(d[j] + 1, q[j]); #if DEBUG == 1 cerr << "d = " << d[j] << ", q = " << q[j] << ", p = " << p[j] << endl; #endif } auto qScore{totalScore}; #if DEBUG == 1 cerr << "pScore = " << pScore << ", qScore = " << qScore << endl; #endif if (pScore > qScore) { for (auto j{K - 1}; j >= 0; --j) { #if DEBUG == 1 cerr << "q = " << t[d[j] - 1] << endl; #endif change_score(d[j] + 1, p[j]); } #if DEBUG == 1 cerr << "score = " << totalScore << endl; #endif } } for (auto e : t) { cout << e + 1 << endl; } } private: ll change_score(int d, int q) { int p{t[d - 1]}; if (p == q) { return totalScore; } ll newScore{totalScore}; t[d - 1] = q; newScore -= s[d - 1][p]; newScore += s[d - 1][q]; { auto it{contestDays[p].find(d)}; --it; auto x{*it}; ++it; ++it; auto y{*it}; auto dif{(y - d) * (d - x)}; newScore -= c[p] * dif; --it; contestDays[p].erase(it); } { contestDays[q].insert(d); auto it{contestDays[q].find(d)}; --it; auto x{*it}; ++it; ++it; auto y{*it}; auto dif{(y - d) * (d - x)}; newScore += c[q] * dif; } return totalScore = newScore; } vector<ll> calc_score() { vector<ll> ans(D); vector<vector<int>> last(D + 1, vector<int>(C, 0)); ll now{0}; for (auto d{0}; d < D; ++d) { now += s[d][t[d]]; contestDays[t[d]].insert(d + 1); last[d + 1] = last[d]; last[d + 1][t[d]] = d + 1; ll penalty{0}; for (auto i{0}; i < C; ++i) { penalty += c[i] * (d + 1 - last[d + 1][i]); } now -= penalty; ans[d] = now; } totalScore = now; return ans; } }; // ----- main() ----- int main() { ll d; cin >> d; Solve solve; solve.flush(); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------- // $Id$ // // Copyright (C) 2000, 2001, 2003, 2004, 2007, 2008, 2009, 2010, 2012, 2013 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------------- // Test whether the various assember classes put the right data in the // right place. // This test is a modification of the test with the same name in ../integrators #include "../tests.h" #include <deal.II/meshworker/assembler.h> #include <deal.II/meshworker/loop.h> #include <deal.II/base/std_cxx1x/function.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/trilinos_sparse_matrix.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/filtered_iterator.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/mapping_q1.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_dgp.h> #include <deal.II/fe/fe_system.h> #include <fstream> #include <iomanip> using namespace dealii; // Define a class that fills all available entries in the info objects // with recognizable numbers. template <int dim> class Local : public Subscriptor { public: typedef MeshWorker::IntegrationInfo<dim> CellInfo; void cell(MeshWorker::DoFInfo<dim>& dinfo, CellInfo& info) const; void bdry(MeshWorker::DoFInfo<dim>& dinfo, CellInfo& info) const; void face(MeshWorker::DoFInfo<dim>& dinfo1, MeshWorker::DoFInfo<dim>& dinfo2, CellInfo& info1, CellInfo& info2) const; bool cells; bool faces; }; template <int dim> void Local<dim>::cell(MeshWorker::DoFInfo<dim>& info, CellInfo&) const { if (!cells) return; for (unsigned int k=0;k<info.n_matrices();++k) { const unsigned int block_row = info.matrix(k).row; const unsigned int block_col = info.matrix(k).column; FullMatrix<double>& M1 = info.matrix(k).matrix; if (block_row == block_col) for (unsigned int i=0;i<M1.m();++i) for (unsigned int j=0;j<M1.n();++j) { M1(i,j) = 10.; } } } template <int dim> void Local<dim>::bdry(MeshWorker::DoFInfo<dim>& info, CellInfo&) const { if (!faces) return; for (unsigned int k=0;k<info.n_matrices();++k) { const unsigned int block_row = info.matrix(k).row; const unsigned int block_col = info.matrix(k).column; FullMatrix<double>& M1 = info.matrix(k).matrix; if (block_row == block_col) for (unsigned int i=0;i<M1.m();++i) for (unsigned int j=0;j<M1.n();++j) { M1(i,j) = 1.; } } } template <int dim> void Local<dim>::face(MeshWorker::DoFInfo<dim>& info1, MeshWorker::DoFInfo<dim>& info2, CellInfo&, CellInfo&) const { if (!faces) return; for (unsigned int k=0;k<info1.n_matrices();++k) { const unsigned int block_row = info1.matrix(k).row; const unsigned int block_col = info1.matrix(k).column; FullMatrix<double>& M1 = info1.matrix(k).matrix; if (block_row == block_col) for (unsigned int i=0;i<M1.m();++i) for (unsigned int j=0;j<M1.n();++j) { info1.matrix(k,false).matrix(i,j) = 1.; info2.matrix(k,false).matrix(i,j) = 1.; info1.matrix(k,true).matrix(i,j) = -1.; info2.matrix(k,true).matrix(i,j) = -1.; } } } template <int dim> void test_simple(DoFHandler<dim>& dofs, bool faces) { TrilinosWrappers::SparsityPattern pattern; TrilinosWrappers::SparseMatrix matrix; const FiniteElement<dim>& fe = dofs.get_fe(); pattern.reinit (dofs.n_dofs(), dofs.n_dofs(), (GeometryInfo<dim>::faces_per_cell *GeometryInfo<dim>::max_children_per_face+1)*fe.dofs_per_cell); DoFTools::make_flux_sparsity_pattern (dofs, pattern); pattern.compress(); matrix.reinit (pattern); Local<dim> local; local.cells = true; local.faces = faces; MappingQ1<dim> mapping; MeshWorker::IntegrationInfoBox<dim> info_box; info_box.initialize_gauss_quadrature(1, 1, 1); info_box.initialize_update_flags(); info_box.initialize(fe, mapping); MeshWorker::DoFInfo<dim> dof_info(dofs.block_info()); MeshWorker::Assembler::MatrixSimple<TrilinosWrappers::SparseMatrix> assembler; assembler.initialize(matrix); FilteredIterator<typename DoFHandler<dim>::active_cell_iterator> cell(IteratorFilters::LocallyOwnedCell(), dofs.begin_active()); FilteredIterator<typename DoFHandler<dim>::active_cell_iterator> end(IteratorFilters::LocallyOwnedCell(), dofs.end()); MeshWorker::loop<dim, dim, MeshWorker::DoFInfo<dim>, MeshWorker::IntegrationInfoBox<dim> > (cell, end, dof_info, info_box, std_cxx1x::bind (&Local<dim>::cell, local, std_cxx1x::_1, std_cxx1x::_2), std_cxx1x::bind (&Local<dim>::bdry, local, std_cxx1x::_1, std_cxx1x::_2), std_cxx1x::bind (&Local<dim>::face, local, std_cxx1x::_1, std_cxx1x::_2, std_cxx1x::_3, std_cxx1x::_4), assembler, true); matrix.compress(VectorOperation::add); matrix.print(deallog.get_file_stream()); } template<int dim> void test(const FiniteElement<dim>& fe) { parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD, Triangulation<dim>::none/*, parallel::distributed::Triangulation<dim>::construct_multigrid_hierarchy*/); GridGenerator::hyper_cube(tr); tr.refine_global(2); //tr.begin_active()->set_refine_flag(); //tr.execute_coarsening_and_refinement(); deallog << "Triangulation levels"; for (unsigned int l=0;l<tr.n_levels();++l) deallog << ' ' << l << ':' << tr.n_cells(l); deallog << std::endl; unsigned int cn = 0; for (typename Triangulation<dim>::cell_iterator cell = tr.begin(); cell != tr.end(); ++cell, ++cn) cell->set_user_index(cn); DoFHandler<dim> dofs(tr); dofs.distribute_dofs(fe); dofs.initialize_local_block_info(); deallog << "DoFHandler " << dofs.n_dofs() << std::endl; test_simple(dofs, false); deallog << "now with jump terms" << std::endl; test_simple(dofs, true); } int main (int argc, char** argv) { Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv); MPILogInitAll i(__FILE__); FE_DGP<2> p0(0); FE_Q<2> q1(1); FESystem<2,2> sys1(p0,1,q1,1); std::vector<FiniteElement<2>*> fe2; fe2.push_back(&p0); fe2.push_back(&q1); fe2.push_back(&sys1); for (unsigned int i=0;i<fe2.size();++i) test(*fe2[i]); } <commit_msg>improve test<commit_after>//---------------------------------------------------------------------- // $Id$ // // Copyright (C) 2000, 2001, 2003, 2004, 2007, 2008, 2009, 2010, 2012, 2013 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------------- // Test whether the various assember classes put the right data in the // right place. // This test is a modification of the test with the same name in ../integrators #include "../tests.h" #include <deal.II/meshworker/assembler.h> #include <deal.II/meshworker/loop.h> #include <deal.II/base/std_cxx1x/function.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/trilinos_sparse_matrix.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/filtered_iterator.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/mapping_q1.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_dgp.h> #include <deal.II/fe/fe_system.h> #include <fstream> #include <iomanip> using namespace dealii; // Define a class that fills all available entries in the info objects // with recognizable numbers. template <int dim> class Local : public Subscriptor { public: typedef MeshWorker::IntegrationInfo<dim> CellInfo; void cell(MeshWorker::DoFInfo<dim>& dinfo, CellInfo& info) const; void bdry(MeshWorker::DoFInfo<dim>& dinfo, CellInfo& info) const; void face(MeshWorker::DoFInfo<dim>& dinfo1, MeshWorker::DoFInfo<dim>& dinfo2, CellInfo& info1, CellInfo& info2) const; bool cells; bool faces; }; template <int dim> void Local<dim>::cell(MeshWorker::DoFInfo<dim>& info, CellInfo&) const { if (!cells) return; for (unsigned int k=0;k<info.n_matrices();++k) { const unsigned int block_row = info.matrix(k).row; const unsigned int block_col = info.matrix(k).column; FullMatrix<double>& M1 = info.matrix(k).matrix; if (block_row == block_col) for (unsigned int i=0;i<M1.m();++i) for (unsigned int j=0;j<M1.n();++j) { M1(i,j) = 10.; } } } template <int dim> void Local<dim>::bdry(MeshWorker::DoFInfo<dim>& info, CellInfo&) const { if (!faces) return; for (unsigned int k=0;k<info.n_matrices();++k) { const unsigned int block_row = info.matrix(k).row; const unsigned int block_col = info.matrix(k).column; FullMatrix<double>& M1 = info.matrix(k).matrix; if (block_row == block_col) for (unsigned int i=0;i<M1.m();++i) for (unsigned int j=0;j<M1.n();++j) { M1(i,j) = 1.; } } } template <int dim> void Local<dim>::face(MeshWorker::DoFInfo<dim>& info1, MeshWorker::DoFInfo<dim>& info2, CellInfo&, CellInfo&) const { if (!faces) return; for (unsigned int k=0;k<info1.n_matrices();++k) { const unsigned int block_row = info1.matrix(k).row; const unsigned int block_col = info1.matrix(k).column; FullMatrix<double>& M1 = info1.matrix(k).matrix; if (block_row == block_col) for (unsigned int i=0;i<M1.m();++i) for (unsigned int j=0;j<M1.n();++j) { info1.matrix(k,false).matrix(i,j) = 1.; info2.matrix(k,false).matrix(i,j) = 1.; info1.matrix(k,true).matrix(i,j) = -1.; info2.matrix(k,true).matrix(i,j) = -1.; } } } template <int dim> void test_simple(DoFHandler<dim>& dofs, bool faces) { TrilinosWrappers::SparseMatrix matrix; const FiniteElement<dim>& fe = dofs.get_fe(); CompressedSimpleSparsityPattern csp(dofs.n_dofs(), dofs.n_dofs()); DoFTools::make_flux_sparsity_pattern (dofs, csp); matrix.reinit (dofs.locally_owned_dofs(), csp, MPI_COMM_WORLD, true); Local<dim> local; local.cells = true; local.faces = faces; MappingQ1<dim> mapping; MeshWorker::IntegrationInfoBox<dim> info_box; info_box.initialize_gauss_quadrature(1, 1, 1); info_box.initialize_update_flags(); info_box.initialize(fe, mapping); MeshWorker::DoFInfo<dim> dof_info(dofs.block_info()); MeshWorker::Assembler::MatrixSimple<TrilinosWrappers::SparseMatrix> assembler; assembler.initialize(matrix); FilteredIterator<typename DoFHandler<dim>::active_cell_iterator> cell(IteratorFilters::LocallyOwnedCell(), dofs.begin_active()); FilteredIterator<typename DoFHandler<dim>::active_cell_iterator> end(IteratorFilters::LocallyOwnedCell(), dofs.end()); MeshWorker::loop<dim, dim, MeshWorker::DoFInfo<dim>, MeshWorker::IntegrationInfoBox<dim> > (cell, end, dof_info, info_box, std_cxx1x::bind (&Local<dim>::cell, local, std_cxx1x::_1, std_cxx1x::_2), std_cxx1x::bind (&Local<dim>::bdry, local, std_cxx1x::_1, std_cxx1x::_2), std_cxx1x::bind (&Local<dim>::face, local, std_cxx1x::_1, std_cxx1x::_2, std_cxx1x::_3, std_cxx1x::_4), assembler, true); matrix.compress(VectorOperation::add); matrix.print(deallog.get_file_stream()); } template<int dim> void test(const FiniteElement<dim>& fe) { parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD, Triangulation<dim>::none/*, parallel::distributed::Triangulation<dim>::construct_multigrid_hierarchy*/); GridGenerator::hyper_cube(tr); tr.refine_global(2); //tr.begin_active()->set_refine_flag(); //tr.execute_coarsening_and_refinement(); deallog << "Triangulation levels"; for (unsigned int l=0;l<tr.n_levels();++l) deallog << ' ' << l << ':' << tr.n_cells(l); deallog << std::endl; unsigned int cn = 0; for (typename Triangulation<dim>::cell_iterator cell = tr.begin(); cell != tr.end(); ++cell, ++cn) cell->set_user_index(cn); DoFHandler<dim> dofs(tr); dofs.distribute_dofs(fe); dofs.initialize_local_block_info(); deallog << "DoFHandler " << dofs.n_dofs() << std::endl; test_simple(dofs, false); deallog << "now with jump terms" << std::endl; test_simple(dofs, true); } int main (int argc, char** argv) { Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv); MPILogInitAll i(__FILE__); FE_DGP<2> p0(0); FE_Q<2> q1(1); FESystem<2,2> sys1(p0,1,q1,1); std::vector<FiniteElement<2>*> fe2; fe2.push_back(&p0); fe2.push_back(&q1); fe2.push_back(&sys1); for (unsigned int i=0;i<fe2.size();++i) test(*fe2[i]); } <|endoftext|>
<commit_before>// // ArrayBuilder.cpp // Clock Signal // // Created by Thomas Harte on 17/11/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #include "ArrayBuilder.hpp" using namespace Outputs::CRT; ArrayBuilder::ArrayBuilder(size_t input_size, size_t output_size) : output_(output_size, nullptr), input_(input_size, nullptr) {} ArrayBuilder::ArrayBuilder(size_t input_size, size_t output_size, std::function<void(bool is_input, uint8_t *, size_t)> submission_function) : output_(output_size, submission_function), input_(input_size, submission_function) {} bool ArrayBuilder::is_full() { bool was_full; was_full = is_full_; return was_full; } uint8_t *ArrayBuilder::get_input_storage(size_t size) { return get_storage(size, input_); } uint8_t *ArrayBuilder::get_output_storage(size_t size) { return get_storage(size, output_); } void ArrayBuilder::flush(const std::function<void(uint8_t *input, size_t input_size, uint8_t *output, size_t output_size)> &function) { if(!is_full_) { size_t input_size, output_size; uint8_t *input = input_.get_unflushed(input_size); uint8_t *output = output_.get_unflushed(output_size); function(input, input_size, output, output_size); input_.flush(); output_.flush(); } } void ArrayBuilder::bind_input() { input_.bind(); } void ArrayBuilder::bind_output() { output_.bind(); } ArrayBuilder::Submission ArrayBuilder::submit() { ArrayBuilder::Submission submission; submission.input_size = input_.submit(true); submission.output_size = output_.submit(false); if(is_full_) { is_full_ = false; input_.reset(); output_.reset(); } return submission; } ArrayBuilder::Buffer::Buffer(size_t size, std::function<void(bool is_input, uint8_t *, size_t)> submission_function) : is_full(false), submission_function_(submission_function), allocated_data(0), flushed_data(0), submitted_data(0) { if(!submission_function_) { glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)size, NULL, GL_STREAM_DRAW); } data.resize(size); } ArrayBuilder::Buffer::~Buffer() { if(!submission_function_) glDeleteBuffers(1, &buffer); } uint8_t *ArrayBuilder::get_storage(size_t size, Buffer &buffer) { uint8_t *pointer = buffer.get_storage(size); if(!pointer) is_full_ = true; return pointer; } uint8_t *ArrayBuilder::Buffer::get_storage(size_t size) { if(is_full || allocated_data + size > data.size()) { is_full = true; return nullptr; } uint8_t *pointer = &data[allocated_data]; allocated_data += size; return pointer; } uint8_t *ArrayBuilder::Buffer::get_unflushed(size_t &size) { if(is_full) { return nullptr; } size = allocated_data - flushed_data; return &data[flushed_data]; } void ArrayBuilder::Buffer::flush() { if(submitted_data) { memmove(data.data(), &data[submitted_data], allocated_data - submitted_data); allocated_data -= submitted_data; flushed_data -= submitted_data; submitted_data = 0; } flushed_data = allocated_data; } size_t ArrayBuilder::Buffer::submit(bool is_input) { size_t length = flushed_data; if(submission_function_) submission_function_(is_input, data.data(), length); else { glBindBuffer(GL_ARRAY_BUFFER, buffer); uint8_t *destination = (uint8_t *)glMapBufferRange(GL_ARRAY_BUFFER, 0, (GLsizeiptr)length, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT | GL_MAP_FLUSH_EXPLICIT_BIT); memcpy(destination, data.data(), length); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, (GLsizeiptr)length); glUnmapBuffer(GL_ARRAY_BUFFER); } submitted_data = flushed_data; return length; } void ArrayBuilder::Buffer::bind() { glBindBuffer(GL_ARRAY_BUFFER, buffer); } void ArrayBuilder::Buffer::reset() { is_full = false; allocated_data = 0; flushed_data = 0; submitted_data = 0; } <commit_msg>Resolved spurious static analyser complaint: input_size and output_size aren't supposed to have defined values if input or output is null. But whatever.<commit_after>// // ArrayBuilder.cpp // Clock Signal // // Created by Thomas Harte on 17/11/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #include "ArrayBuilder.hpp" using namespace Outputs::CRT; ArrayBuilder::ArrayBuilder(size_t input_size, size_t output_size) : output_(output_size, nullptr), input_(input_size, nullptr) {} ArrayBuilder::ArrayBuilder(size_t input_size, size_t output_size, std::function<void(bool is_input, uint8_t *, size_t)> submission_function) : output_(output_size, submission_function), input_(input_size, submission_function) {} bool ArrayBuilder::is_full() { bool was_full; was_full = is_full_; return was_full; } uint8_t *ArrayBuilder::get_input_storage(size_t size) { return get_storage(size, input_); } uint8_t *ArrayBuilder::get_output_storage(size_t size) { return get_storage(size, output_); } void ArrayBuilder::flush(const std::function<void(uint8_t *input, size_t input_size, uint8_t *output, size_t output_size)> &function) { if(!is_full_) { size_t input_size = 0, output_size = 0; uint8_t *input = input_.get_unflushed(input_size); uint8_t *output = output_.get_unflushed(output_size); function(input, input_size, output, output_size); input_.flush(); output_.flush(); } } void ArrayBuilder::bind_input() { input_.bind(); } void ArrayBuilder::bind_output() { output_.bind(); } ArrayBuilder::Submission ArrayBuilder::submit() { ArrayBuilder::Submission submission; submission.input_size = input_.submit(true); submission.output_size = output_.submit(false); if(is_full_) { is_full_ = false; input_.reset(); output_.reset(); } return submission; } ArrayBuilder::Buffer::Buffer(size_t size, std::function<void(bool is_input, uint8_t *, size_t)> submission_function) : is_full(false), submission_function_(submission_function), allocated_data(0), flushed_data(0), submitted_data(0) { if(!submission_function_) { glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)size, NULL, GL_STREAM_DRAW); } data.resize(size); } ArrayBuilder::Buffer::~Buffer() { if(!submission_function_) glDeleteBuffers(1, &buffer); } uint8_t *ArrayBuilder::get_storage(size_t size, Buffer &buffer) { uint8_t *pointer = buffer.get_storage(size); if(!pointer) is_full_ = true; return pointer; } uint8_t *ArrayBuilder::Buffer::get_storage(size_t size) { if(is_full || allocated_data + size > data.size()) { is_full = true; return nullptr; } uint8_t *pointer = &data[allocated_data]; allocated_data += size; return pointer; } uint8_t *ArrayBuilder::Buffer::get_unflushed(size_t &size) { if(is_full) { return nullptr; } size = allocated_data - flushed_data; return &data[flushed_data]; } void ArrayBuilder::Buffer::flush() { if(submitted_data) { memmove(data.data(), &data[submitted_data], allocated_data - submitted_data); allocated_data -= submitted_data; flushed_data -= submitted_data; submitted_data = 0; } flushed_data = allocated_data; } size_t ArrayBuilder::Buffer::submit(bool is_input) { size_t length = flushed_data; if(submission_function_) submission_function_(is_input, data.data(), length); else { glBindBuffer(GL_ARRAY_BUFFER, buffer); uint8_t *destination = (uint8_t *)glMapBufferRange(GL_ARRAY_BUFFER, 0, (GLsizeiptr)length, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT | GL_MAP_FLUSH_EXPLICIT_BIT); memcpy(destination, data.data(), length); glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, (GLsizeiptr)length); glUnmapBuffer(GL_ARRAY_BUFFER); } submitted_data = flushed_data; return length; } void ArrayBuilder::Buffer::bind() { glBindBuffer(GL_ARRAY_BUFFER, buffer); } void ArrayBuilder::Buffer::reset() { is_full = false; allocated_data = 0; flushed_data = 0; submitted_data = 0; } <|endoftext|>
<commit_before>#ifndef __CINT__ #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliAnalysisTaskHMTFMCMultEst.h" #endif AliAnalysisTaskHMTFMCMultEst *AddTaskHMTFMCMultEst(Int_t globalTrigger) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskHMTFMCMultEst", "No analysis manager to connect to."); return NULL; } TString sumsName; if (globalTrigger == 0) sumsName = TString("SumsInel"); else if (globalTrigger == 1) sumsName = TString("SumsInelGt0"); else if (globalTrigger == 2) sumsName = TString("SumsV0AND"); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(sumsName, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:MultEstimators", mgr->GetCommonFileName())); AliAnalysisTaskHMTFMCMultEst *multEstTask = new AliAnalysisTaskHMTFMCMultEst("TaskHMTFMCMultEst"); multEstTask->SetGlobalTrigger(globalTrigger); if (!multEstTask) { Error("CreateTasks", "Failed to add task!"); return NULL; } mgr->AddTask(multEstTask); AliAnalysisDataContainer *inputContainer = mgr->GetCommonInputContainer(); if(!inputContainer) { Error("CreateTasks", "No input container available. Failed to add task!"); return NULL; } mgr->ConnectInput(multEstTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(multEstTask, 1, coutput1); return multEstTask; } <commit_msg>Allow for subwagon configuration<commit_after>#ifndef __CINT__ #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliAnalysisTaskHMTFMCMultEst.h" #endif AliAnalysisTaskHMTFMCMultEst *AddTaskHMTFMCMultEst(Int_t globalTrigger, const std::string &name = "") { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskHMTFMCMultEst", "No analysis manager to connect to."); return NULL; } TString sumsName; if (name.size() != 0) sumsName = name; else if (globalTrigger == 0) sumsName = TString("SumsInel"); else if (globalTrigger == 1) sumsName = TString("SumsInelGt0"); else if (globalTrigger == 2) sumsName = TString("SumsV0AND"); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(sumsName, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:MultEstimators", mgr->GetCommonFileName())); AliAnalysisTaskHMTFMCMultEst *multEstTask = new AliAnalysisTaskHMTFMCMultEst("TaskHMTFMCMultEst"); multEstTask->SetGlobalTrigger(globalTrigger); if (!multEstTask) { Error("CreateTasks", "Failed to add task!"); return NULL; } mgr->AddTask(multEstTask); AliAnalysisDataContainer *inputContainer = mgr->GetCommonInputContainer(); if(!inputContainer) { Error("CreateTasks", "No input container available. Failed to add task!"); return NULL; } mgr->ConnectInput(multEstTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(multEstTask, 1, coutput1); return multEstTask; } <|endoftext|>
<commit_before>#include "tidyup_actions/actionExecutorDetectObjects.h" #include <pluginlib/class_list_macros.h> #include <tidyup_msgs/RequestObjectsGraspability.h> #include "tidyup_utils/planning_scene_interface.h" PLUGINLIB_DECLARE_CLASS(tidyup_actions, action_executor_detect_objects, tidyup_actions::ActionExecutorDetectObjects, continual_planning_executive::ActionExecutorInterface) namespace tidyup_actions { void ActionExecutorDetectObjects::initialize(const std::deque<std::string> & arguments) { ActionExecutorService<tidyup_msgs::DetectGraspableObjects>::initialize(arguments); requestGraspability = false; string graspabilityServiceName = "/learned_grasping/request_objects_graspability"; tidyLocationName = "table1"; if (arguments.size() >= 3) { if (arguments[2] == "NULL") { requestGraspability = false; } else { graspabilityServiceName = arguments[2]; } } if (arguments.size() >= 4) { tidyLocationName = arguments[3]; } ROS_ASSERT(_nh); if(requestGraspability) { serviceClientGraspability = _nh->serviceClient<tidyup_msgs::RequestObjectsGraspability>( graspabilityServiceName); if(!serviceClientGraspability) { ROS_FATAL("Could not initialize service for RequestObjectsGraspability."); } } } bool ActionExecutorDetectObjects::fillGoal(tidyup_msgs::DetectGraspableObjects::Request & goal, const DurativeAction & a, const SymbolicState & current) { if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways? ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__); ROS_ASSERT(a.parameters.size() == 1); goal.static_object = findStaticObjectForLocation(a.parameters[0], current); return true; } void ActionExecutorDetectObjects::updateState(bool success, tidyup_msgs::DetectGraspableObjects::Response & response, const DurativeAction & a, SymbolicState & current) { ROS_INFO("DetectObjects returned result"); if(success) { ROS_INFO("DetectObjects succeeded."); ROS_ASSERT(a.parameters.size() == 1); std::string location = a.parameters[0]; current.setBooleanPredicate("searched", location, true); current.setBooleanPredicate("recent-detected-objects", location, true); std::vector<tidyup_msgs::GraspableObject>& objects = response.objects; if(requestGraspability && false) { ROS_INFO("Requesting graspability."); tidyup_msgs::RequestObjectsGraspability request; request.request.objects = objects; if(!serviceClientGraspability.call(request)) { ROS_ERROR("Failed to call RequestObjectsGraspability service."); } else { objects = request.response.objects; } } // find correct static object and set the "on" predicate string static_object = findStaticObjectForLocation(location, current); ROS_ASSERT(static_object != ""); // remove objects form state, which were previously detected from this location Predicate p; p.name = "object-detected-from"; p.parameters.push_back("object"); pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange = current.getTypedObjects().equal_range("movable_object"); for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first; objectIterator != objectRange.second; objectIterator++) { string object = objectIterator->second; p.parameters[0] = object; string detection_location; if (current.hasObjectFluent(p, &detection_location)) { if (location == detection_location) { current.removeObject(object, true); } } } for(std::vector<tidyup_msgs::GraspableObject>::iterator it = objects.begin(); it != objects.end(); it++) { tidyup_msgs::GraspableObject & object = *it; current.addObject(object.name, "movable_object"); if(object.pose.header.frame_id.empty()) { ROS_ERROR("DetectGraspableObjects returned empty frame_id for object: %s", object.name.c_str()); object.pose.header.frame_id = "INVALID_FRAME_ID"; } current.addObject(object.pose.header.frame_id, "frameid"); current.addObject(object.name, "pose"); current.setObjectFluent("frame-id", object.name, object.pose.header.frame_id); current.setNumericalFluent("x", object.name, object.pose.pose.position.x); current.setNumericalFluent("y", object.name, object.pose.pose.position.y); current.setNumericalFluent("z", object.name, object.pose.pose.position.z); current.setNumericalFluent("qx", object.name, object.pose.pose.orientation.x); current.setNumericalFluent("qy", object.name, object.pose.pose.orientation.y); current.setNumericalFluent("qz", object.name, object.pose.pose.orientation.z); current.setNumericalFluent("qw", object.name, object.pose.pose.orientation.w); current.setNumericalFluent("timestamp", object.name, object.pose.header.stamp.toSec()); current.setBooleanPredicate("on", object.name + " " + static_object, true); current.setObjectFluent("object-detected-from", object.name, location); // tidy-location: (tidy-location ?o ?s) current.setBooleanPredicate("tidy-location", object.name + " " + tidyLocationName, true); // add graspable predicates from current location if(requestGraspability || true) { current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm", object.reachable_left_arm); current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm", object.reachable_right_arm); } else { current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm", true); current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm", true); } } } } std::string ActionExecutorDetectObjects::findStaticObjectForLocation(const std::string& location, const SymbolicState & current) const { Predicate p; string static_object; p.name = "static-object-at-location"; p.parameters.push_back("object"); p.parameters.push_back(location); pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange = current.getTypedObjects().equal_range("static_object"); for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first; objectIterator != objectRange.second; objectIterator++) { string object = objectIterator->second; p.parameters[0] = object; bool value = false; if (current.hasBooleanPredicate(p, &value)) { if (value) { static_object = object; break; } } } return static_object; } }; <commit_msg>detect object does planning scene reset when done<commit_after>#include "tidyup_actions/actionExecutorDetectObjects.h" #include <pluginlib/class_list_macros.h> #include <tidyup_msgs/RequestObjectsGraspability.h> #include "tidyup_utils/planning_scene_interface.h" PLUGINLIB_DECLARE_CLASS(tidyup_actions, action_executor_detect_objects, tidyup_actions::ActionExecutorDetectObjects, continual_planning_executive::ActionExecutorInterface) namespace tidyup_actions { void ActionExecutorDetectObjects::initialize(const std::deque<std::string> & arguments) { ActionExecutorService<tidyup_msgs::DetectGraspableObjects>::initialize(arguments); requestGraspability = false; string graspabilityServiceName = "/learned_grasping/request_objects_graspability"; tidyLocationName = "table1"; if (arguments.size() >= 3) { if (arguments[2] == "NULL") { requestGraspability = false; } else { graspabilityServiceName = arguments[2]; } } if (arguments.size() >= 4) { tidyLocationName = arguments[3]; } ROS_ASSERT(_nh); if(requestGraspability) { serviceClientGraspability = _nh->serviceClient<tidyup_msgs::RequestObjectsGraspability>( graspabilityServiceName); if(!serviceClientGraspability) { ROS_FATAL("Could not initialize service for RequestObjectsGraspability."); } } } bool ActionExecutorDetectObjects::fillGoal(tidyup_msgs::DetectGraspableObjects::Request & goal, const DurativeAction & a, const SymbolicState & current) { if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways? ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__); ROS_ASSERT(a.parameters.size() == 1); goal.static_object = findStaticObjectForLocation(a.parameters[0], current); return true; } void ActionExecutorDetectObjects::updateState(bool success, tidyup_msgs::DetectGraspableObjects::Response & response, const DurativeAction & a, SymbolicState & current) { ROS_INFO("DetectObjects returned result"); if(success) { ROS_INFO("DetectObjects succeeded."); ROS_ASSERT(a.parameters.size() == 1); std::string location = a.parameters[0]; current.setBooleanPredicate("searched", location, true); current.setBooleanPredicate("recent-detected-objects", location, true); std::vector<tidyup_msgs::GraspableObject>& objects = response.objects; if(requestGraspability && false) { ROS_INFO("Requesting graspability."); tidyup_msgs::RequestObjectsGraspability request; request.request.objects = objects; if(!serviceClientGraspability.call(request)) { ROS_ERROR("Failed to call RequestObjectsGraspability service."); } else { objects = request.response.objects; } } // find correct static object and set the "on" predicate string static_object = findStaticObjectForLocation(location, current); ROS_ASSERT(static_object != ""); // remove objects form state, which were previously detected from this location Predicate p; p.name = "object-detected-from"; p.parameters.push_back("object"); pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange = current.getTypedObjects().equal_range("movable_object"); for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first; objectIterator != objectRange.second; objectIterator++) { string object = objectIterator->second; p.parameters[0] = object; string detection_location; if (current.hasObjectFluent(p, &detection_location)) { if (location == detection_location) { current.removeObject(object, true); } } } for(std::vector<tidyup_msgs::GraspableObject>::iterator it = objects.begin(); it != objects.end(); it++) { tidyup_msgs::GraspableObject & object = *it; current.addObject(object.name, "movable_object"); if(object.pose.header.frame_id.empty()) { ROS_ERROR("DetectGraspableObjects returned empty frame_id for object: %s", object.name.c_str()); object.pose.header.frame_id = "INVALID_FRAME_ID"; } current.addObject(object.pose.header.frame_id, "frameid"); current.addObject(object.name, "pose"); current.setObjectFluent("frame-id", object.name, object.pose.header.frame_id); current.setNumericalFluent("x", object.name, object.pose.pose.position.x); current.setNumericalFluent("y", object.name, object.pose.pose.position.y); current.setNumericalFluent("z", object.name, object.pose.pose.position.z); current.setNumericalFluent("qx", object.name, object.pose.pose.orientation.x); current.setNumericalFluent("qy", object.name, object.pose.pose.orientation.y); current.setNumericalFluent("qz", object.name, object.pose.pose.orientation.z); current.setNumericalFluent("qw", object.name, object.pose.pose.orientation.w); current.setNumericalFluent("timestamp", object.name, object.pose.header.stamp.toSec()); current.setBooleanPredicate("on", object.name + " " + static_object, true); current.setObjectFluent("object-detected-from", object.name, location); // tidy-location: (tidy-location ?o ?s) current.setBooleanPredicate("tidy-location", object.name + " " + tidyLocationName, true); // add graspable predicates from current location if(requestGraspability || true) { current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm", object.reachable_left_arm); current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm", object.reachable_right_arm); } else { current.setBooleanPredicate("graspable-from", object.name + " " + location + " left_arm", true); current.setBooleanPredicate("graspable-from", object.name + " " + location + " right_arm", true); } } if(!PlanningSceneInterface::instance()->resetPlanningScene()) // FIXME try anyways? ROS_ERROR("%s: PlanningScene reset failed.", __PRETTY_FUNCTION__); } } std::string ActionExecutorDetectObjects::findStaticObjectForLocation(const std::string& location, const SymbolicState & current) const { Predicate p; string static_object; p.name = "static-object-at-location"; p.parameters.push_back("object"); p.parameters.push_back(location); pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> objectRange = current.getTypedObjects().equal_range("static_object"); for (SymbolicState::TypedObjectConstIterator objectIterator = objectRange.first; objectIterator != objectRange.second; objectIterator++) { string object = objectIterator->second; p.parameters[0] = object; bool value = false; if (current.hasBooleanPredicate(p, &value)) { if (value) { static_object = object; break; } } } return static_object; } }; <|endoftext|>
<commit_before>#include "pch.h" #include "taskqueue_service.h" #include "service_manager.h" #include <atomic> class TaskQueue : Noncopyable { public: TaskQueue(const char * name, TaskQueueService * taskService); virtual ~TaskQueue(); void start(); void stop(); int addWorkItem(const std::function<void()>& func); void removeWorkItem(int itemHandle); int getWorkItemsCount() const { return static_cast<int>(_queue.size()); } private: static void threadProc(void * cookie); std::unique_ptr<std::thread> _workThread; bool _workThreadIsActive; std::string _name; TaskQueueService * _service; std::mutex _queueMutex; std::mutex _queueItemRemoveMutex; // needed to prevent work item deletion after it started processing std::condition_variable _queueIsNotEmpty; std::deque<std::pair<int, std::function<void()> > > _queue; static std::atomic_int _itemCounter; }; std::atomic_int TaskQueueService::_itemCounter; TaskQueueService::TaskQueueService(const ServiceManager * manager) : Service(manager) { } TaskQueueService::~TaskQueueService() { } bool TaskQueueService::onInit() { return true; } bool TaskQueueService::onTick() { PROFILE("TaskQueueService::onTick", "Application"); if (!_queue.empty()) { _queueMutex.lock(); if (!_queue.empty()) { // copy functor std::unique_lock<std::recursive_mutex> itemRemovelock(_queueItemRemoveMutex); auto fn = _queue.front().second; _queue.pop_front(); _queueMutex.unlock(); // make sure functor is executed while mutex is not acquired fn(); } else { _queueMutex.unlock(); } } return false; } bool TaskQueueService::onShutdown() { // first release all queues since they can invoke events on main thread _queues.clear(); // now process all events on main thread if (!_queue.empty()) { std::unique_lock<std::mutex> lock(_queueMutex); std::unique_lock<std::recursive_mutex> itemRemovelock(_queueItemRemoveMutex); while(!_queue.empty()) { _queue.front().second(); _queue.pop_front(); } } return true; } void TaskQueueService::createQueue(const char * name) { if (_queues.find(name) != _queues.end()) return; _queues.insert(std::make_pair(std::string(name), std::shared_ptr<TaskQueue>(new TaskQueue(name, this)))); } void TaskQueueService::removeQueue(const char * name) { _queues.erase(name); } int TaskQueueService::addWorkItem(const char * queue, const std::function<void()>& func) { if (!queue) return runOnMainThread(func); #if defined(__EMSCRIPTEN__) // emscripten does not fully support multithreading and conditional variables runOnMainThread(func); return -1; #else auto it = _queues.find(queue); if (it == _queues.end()) return -1; return (*it).second->addWorkItem(func); #endif } void TaskQueueService::removeWorkItem(const char * queue, int itemHandle) { if (queue) { auto it = _queues.find(queue); if (it == _queues.end()) return; (*it).second->removeWorkItem(itemHandle); return; } // remove item from main thread queue std::unique_lock<std::mutex> lock(_queueMutex); std::unique_lock<std::recursive_mutex> itemRemoveLock(_queueItemRemoveMutex); auto it = std::find_if(_queue.begin(), _queue.end(), [&itemHandle](const std::pair<int, std::function<void()> >& a) {return a.first == itemHandle; }); if (it == _queue.end()) return; _queue.erase(it); } int TaskQueueService::runOnMainThread(const std::function<void()>& func) { std::unique_lock<std::mutex> lock(_queueMutex); _itemCounter++; _queue.push_back(std::make_pair(_itemCounter.load(), func)); return _itemCounter; } int TaskQueueService::getWorkItemsCount(const char * queue) const { // no need to make synchronization here // result may be not accurate by design if (queue) { auto it = _queues.find(queue); if (it == _queues.end()) return 0; return (*it).second->getWorkItemsCount(); } return static_cast<int>(_queue.size()); } // // TaskQueue // std::atomic_int TaskQueue::_itemCounter; TaskQueue::TaskQueue(const char * name, TaskQueueService * taskService) : _workThreadIsActive(true) , _name(name) , _service(taskService) { start(); } TaskQueue::~TaskQueue() { stop(); } void TaskQueue::start() { GP_ASSERT(_workThread.get() == nullptr); _workThreadIsActive = true; _workThread.reset(new std::thread(&TaskQueue::threadProc, this)); } void TaskQueue::stop() { { std::unique_lock<std::mutex> lock(_queueMutex); _workThreadIsActive = false; _queueIsNotEmpty.notify_one(); } if (_workThread && _workThread->joinable()) _workThread->join(); _workThread.reset(); } int TaskQueue::addWorkItem(const std::function<void()>& func) { std::unique_lock<std::mutex> lock(_queueMutex); _itemCounter++; _queue.push_back(std::make_pair(_itemCounter.load(), func)); _queueIsNotEmpty.notify_one(); return _itemCounter; } void TaskQueue::removeWorkItem(int itemHandle) { std::unique_lock<std::mutex> lock(_queueMutex); std::unique_lock<std::mutex> itemRemoveLock(_queueItemRemoveMutex); auto it = std::find_if(_queue.begin(), _queue.end(), [&itemHandle](const std::pair<int, std::function<void()> >& a){return a.first == itemHandle; }); if (it == _queue.end()) return; _queue.erase(it); } void TaskQueue::threadProc(void * cookie) { TaskQueue * _this = reinterpret_cast<TaskQueue *>(cookie); _this->_service->runOnMainThread([_this](){ ServiceManager::getInstance()->signals.taskQueueStartedEvent(_this->_name.c_str()); }); while (_this->_workThreadIsActive) { std::pair<int, std::function<void()> > item; { std::unique_lock<std::mutex> lock(_this->_queueMutex); while (_this->_queue.empty() && _this->_workThreadIsActive) _this->_queueIsNotEmpty.wait(lock); if (!_this->_workThreadIsActive) break; _this->_queueItemRemoveMutex.lock(); item = _this->_queue.front(); _this->_queue.pop_front(); } _this->_service->runOnMainThread([&item, _this]() { ServiceManager::getInstance()->signals.taskQueueWorkItemLoadedEvent(_this->_name.c_str(), item.first); }); item.second(); _this->_queueItemRemoveMutex.unlock(); _this->_service->runOnMainThread([&item, _this](){ ServiceManager::getInstance()->signals.taskQueueWorkItemProcessedEvent(_this->_name.c_str(), item.first); }); } _this->_service->runOnMainThread([_this](){ ServiceManager::getInstance()->signals.taskQueueStoppedEvent(_this->_name.c_str()); }); }<commit_msg>disabled thread creation on emscripten<commit_after>#include "pch.h" #include "taskqueue_service.h" #include "service_manager.h" #include <atomic> class TaskQueue : Noncopyable { public: TaskQueue(const char * name, TaskQueueService * taskService); virtual ~TaskQueue(); void start(); void stop(); int addWorkItem(const std::function<void()>& func); void removeWorkItem(int itemHandle); int getWorkItemsCount() const { return static_cast<int>(_queue.size()); } private: static void threadProc(void * cookie); std::unique_ptr<std::thread> _workThread; bool _workThreadIsActive; std::string _name; TaskQueueService * _service; std::mutex _queueMutex; std::mutex _queueItemRemoveMutex; // needed to prevent work item deletion after it started processing std::condition_variable _queueIsNotEmpty; std::deque<std::pair<int, std::function<void()> > > _queue; static std::atomic_int _itemCounter; }; std::atomic_int TaskQueueService::_itemCounter; TaskQueueService::TaskQueueService(const ServiceManager * manager) : Service(manager) { } TaskQueueService::~TaskQueueService() { } bool TaskQueueService::onInit() { return true; } bool TaskQueueService::onTick() { PROFILE("TaskQueueService::onTick", "Application"); if (!_queue.empty()) { _queueMutex.lock(); if (!_queue.empty()) { // copy functor std::unique_lock<std::recursive_mutex> itemRemovelock(_queueItemRemoveMutex); auto fn = _queue.front().second; _queue.pop_front(); _queueMutex.unlock(); // make sure functor is executed while mutex is not acquired fn(); } else { _queueMutex.unlock(); } } return false; } bool TaskQueueService::onShutdown() { // first release all queues since they can invoke events on main thread _queues.clear(); // now process all events on main thread if (!_queue.empty()) { std::unique_lock<std::mutex> lock(_queueMutex); std::unique_lock<std::recursive_mutex> itemRemovelock(_queueItemRemoveMutex); while(!_queue.empty()) { _queue.front().second(); _queue.pop_front(); } } return true; } void TaskQueueService::createQueue(const char * name) { #if !defined(__EMSCRIPTEN__) if (_queues.find(name) != _queues.end()) return; _queues.insert(std::make_pair(std::string(name), std::shared_ptr<TaskQueue>(new TaskQueue(name, this)))); #endif } void TaskQueueService::removeQueue(const char * name) { _queues.erase(name); } int TaskQueueService::addWorkItem(const char * queue, const std::function<void()>& func) { if (!queue) return runOnMainThread(func); #if defined(__EMSCRIPTEN__) // emscripten does not fully support multithreading and conditional variables runOnMainThread(func); return -1; #else auto it = _queues.find(queue); if (it == _queues.end()) return -1; return (*it).second->addWorkItem(func); #endif } void TaskQueueService::removeWorkItem(const char * queue, int itemHandle) { if (queue) { auto it = _queues.find(queue); if (it == _queues.end()) return; (*it).second->removeWorkItem(itemHandle); return; } // remove item from main thread queue std::unique_lock<std::mutex> lock(_queueMutex); std::unique_lock<std::recursive_mutex> itemRemoveLock(_queueItemRemoveMutex); auto it = std::find_if(_queue.begin(), _queue.end(), [&itemHandle](const std::pair<int, std::function<void()> >& a) {return a.first == itemHandle; }); if (it == _queue.end()) return; _queue.erase(it); } int TaskQueueService::runOnMainThread(const std::function<void()>& func) { std::unique_lock<std::mutex> lock(_queueMutex); _itemCounter++; _queue.push_back(std::make_pair(_itemCounter.load(), func)); return _itemCounter; } int TaskQueueService::getWorkItemsCount(const char * queue) const { // no need to make synchronization here // result may be not accurate by design if (queue) { auto it = _queues.find(queue); if (it == _queues.end()) return 0; return (*it).second->getWorkItemsCount(); } return static_cast<int>(_queue.size()); } // // TaskQueue // std::atomic_int TaskQueue::_itemCounter; TaskQueue::TaskQueue(const char * name, TaskQueueService * taskService) : _workThreadIsActive(true) , _name(name) , _service(taskService) { start(); } TaskQueue::~TaskQueue() { stop(); } void TaskQueue::start() { GP_ASSERT(_workThread.get() == nullptr); _workThreadIsActive = true; _workThread.reset(new std::thread(&TaskQueue::threadProc, this)); } void TaskQueue::stop() { { std::unique_lock<std::mutex> lock(_queueMutex); _workThreadIsActive = false; _queueIsNotEmpty.notify_one(); } if (_workThread && _workThread->joinable()) _workThread->join(); _workThread.reset(); } int TaskQueue::addWorkItem(const std::function<void()>& func) { std::unique_lock<std::mutex> lock(_queueMutex); _itemCounter++; _queue.push_back(std::make_pair(_itemCounter.load(), func)); _queueIsNotEmpty.notify_one(); return _itemCounter; } void TaskQueue::removeWorkItem(int itemHandle) { std::unique_lock<std::mutex> lock(_queueMutex); std::unique_lock<std::mutex> itemRemoveLock(_queueItemRemoveMutex); auto it = std::find_if(_queue.begin(), _queue.end(), [&itemHandle](const std::pair<int, std::function<void()> >& a){return a.first == itemHandle; }); if (it == _queue.end()) return; _queue.erase(it); } void TaskQueue::threadProc(void * cookie) { TaskQueue * _this = reinterpret_cast<TaskQueue *>(cookie); _this->_service->runOnMainThread([_this](){ ServiceManager::getInstance()->signals.taskQueueStartedEvent(_this->_name.c_str()); }); while (_this->_workThreadIsActive) { std::pair<int, std::function<void()> > item; { std::unique_lock<std::mutex> lock(_this->_queueMutex); while (_this->_queue.empty() && _this->_workThreadIsActive) _this->_queueIsNotEmpty.wait(lock); if (!_this->_workThreadIsActive) break; _this->_queueItemRemoveMutex.lock(); item = _this->_queue.front(); _this->_queue.pop_front(); } _this->_service->runOnMainThread([&item, _this]() { ServiceManager::getInstance()->signals.taskQueueWorkItemLoadedEvent(_this->_name.c_str(), item.first); }); item.second(); _this->_queueItemRemoveMutex.unlock(); _this->_service->runOnMainThread([&item, _this](){ ServiceManager::getInstance()->signals.taskQueueWorkItemProcessedEvent(_this->_name.c_str(), item.first); }); } _this->_service->runOnMainThread([_this](){ ServiceManager::getInstance()->signals.taskQueueStoppedEvent(_this->_name.c_str()); }); }<|endoftext|>
<commit_before> #include <windows.h> #include <string> #include <vector> #include <map> #include <sstream> #include "../Network/network.h" #pragma comment( lib, "winmm.lib" ) using namespace std; const int WINSIZE_X = 300; //ʱ ũ const int WINSIZE_Y = 300; //ʱ ũ const int WINPOS_X = 0; //ʱ ġ X const int WINPOS_Y = 0; //ʱ ġ Y struct sClient { string name; string ip; SOCKET sock; }; SOCKET g_svrSock; map<SOCKET, sClient> g_clients; HWND g_hWnd; // ݹ ν Լ Ÿ LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ); void MainLoop(int timeDelta); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { wchar_t className[32] = L"Server"; wchar_t windowName[32] = L"Server"; // Ŭ // ̷ ڴ WNDCLASS WndClass; WndClass.cbClsExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.cbWndExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // WndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); // Ŀ WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION ); //ܸ WndClass.hInstance = hInstance; //α׷νϽڵ WndClass.lpfnWndProc = (WNDPROC)WndProc; // ν Լ WndClass.lpszMenuName = NULL; //޴̸ NULL WndClass.lpszClassName = className; // ۼϰ ִ Ŭ ̸ WndClass.style = CS_HREDRAW | CS_VREDRAW; // ׸ (  ɶ ȭ鰻 CS_HREDRAW | CS_VREDRAW ) // ۼ Ŭ RegisterClass( &WndClass ); // // ڵ g_hWnd ޴´. HWND hWnd = CreateWindow( className, //Ǵ Ŭ̸ windowName, // ŸƲٿ µǴ ̸ WS_OVERLAPPEDWINDOW, // Ÿ WS_OVERLAPPEDWINDOW WINPOS_X, // ġ X WINPOS_Y, // ġ Y WINSIZE_X, // ũ ( ۾ ũⰡ ƴ ) WINSIZE_Y, // ũ ( ۾ ũⰡ ƴ ) GetDesktopWindow(), //θ ڵ ( α׷ ֻ NULL Ǵ GetDesktopWindow() ) NULL, //޴ ID ( ڽ Ʈ ü ΰ Ʈ ID hInstance, // 찡 α׷ νϽ ڵ NULL //߰ NULL ( Ű ) ); //츦 Ȯ ۾ ũ RECT rcClient = { 0, 0, WINSIZE_X, WINSIZE_Y }; AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE ); //rcClient ũ⸦ ۾ ũ⸦ rcClient ԵǾ ´. // ũ ġ ٲپش. SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER | SWP_NOMOVE ); ShowWindow( hWnd, nCmdShow ); g_hWnd = hWnd; if (!network::LaunchServer(10000, g_svrSock)) { return 0; } OutputDebugStringA( "Server Launched \n"); //޽ ü MSG msg; ZeroMemory( &msg, sizeof( MSG ) ); int oldT = GetTickCount(); while (msg.message != WM_QUIT) { //PeekMessage ޽ ť ޽  α׷ ߱ ʰ ȴ. //̶ ޽ť ޽ false ϵǰ ޽ true ̵ȴ. if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage( &msg ); // Ű ڸ Ͽ WM_CHAR ޽ ߻Ų. DispatchMessage( &msg ); //޾ƿ ޽ ν Լ Ų. } else { const int curT = timeGetTime(); const int elapseT = curT - oldT; oldT = curT; MainLoop(elapseT); } } return 0; } // // ν Լ ( ޽ ť ޾ƿ ޽ óѴ ) // LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch (msg) { case WM_KEYDOWN: if (wParam == VK_ESCAPE) ::DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; } return DefWindowProc( hWnd, msg, wParam, lParam ); } void AcceptClient() { const timeval t = {0, 10}; // 10 millisecond fd_set readSockets; FD_ZERO(&readSockets); FD_SET(g_svrSock, &readSockets); const int ret = select( readSockets.fd_count, &readSockets, NULL, NULL, &t ); if (ret != 0 && ret != SOCKET_ERROR) { for (u_int i=0; i < readSockets.fd_count; ++i) { // accept(û , Ŭ̾Ʈ ּ) SOCKET remoteSocket = accept(readSockets.fd_array[ i], NULL, NULL); if (remoteSocket == INVALID_SOCKET) { return; } if (g_clients.end() == g_clients.find(remoteSocket)) { // get ip address sockaddr_in addr; int len = sizeof(addr); memset(&addr,0,sizeof(addr)); getpeername( remoteSocket, (sockaddr*)&addr, &len ); string ip = inet_ntoa(addr.sin_addr); sClient client; client.ip = ip; client.sock = remoteSocket; g_clients[ remoteSocket] = client; } } } } void DisplayClient() { HDC hdc = GetDC(g_hWnd); Rectangle(hdc, 0, 0, 500, 500); std::stringstream ss; ss << "client count = " << g_clients.size(); const string str = ss.str(); TextOutA(hdc, 10, 10, str.c_str(), str.length()); int y = 25; auto it = g_clients.begin(); while (g_clients.end() != it) { std::stringstream ss; ss << "ip = " << it->second.ip; const string str = ss.str(); TextOutA(hdc, 10, y, str.c_str(), str.length()); ++it; y += 20; } ReleaseDC(g_hWnd, hdc); } void MakeSessionFdset( OUT fd_set &set) { FD_ZERO(&set); auto it = g_clients.begin(); while (g_clients.end() != it) { FD_SET(it->second.sock, &set); ++it; } } void SendAll(char buff[128]) { auto it = g_clients.begin(); while (g_clients.end() != it) { send(it->second.sock, buff, 128, 0); ++it; } } // . void MainLoop(int timeDelta) { DisplayClient(); AcceptClient(); const timeval t = {0, 10}; // 10 millisecond fd_set readSockets; MakeSessionFdset(readSockets); const fd_set sockets = readSockets; const int ret = select( readSockets.fd_count, &readSockets, NULL, NULL, &t ); if (ret != 0 && ret != SOCKET_ERROR) { for (u_int i=0; i < sockets.fd_count; ++i) { if (!FD_ISSET(sockets.fd_array[ i], &readSockets)) continue; char buff[ 128]; const int result = recv(sockets.fd_array[ i], buff, sizeof(buff), 0); if (result == SOCKET_ERROR || result == 0) // Ŷ 0̸ ٴ ǹ̴. { g_clients.erase(sockets.fd_array[ i]); } else { SendAll(buff); } } } } <commit_msg>update chat<commit_after> #include <windows.h> #include <string> #include <vector> #include <map> #include <sstream> #include "../Network/network.h" #pragma comment( lib, "winmm.lib" ) using namespace std; const int WINSIZE_X = 300; //ʱ ũ const int WINSIZE_Y = 300; //ʱ ũ const int WINPOS_X = 0; //ʱ ġ X const int WINPOS_Y = 0; //ʱ ġ Y struct sClient { string name; string ip; SOCKET sock; }; SOCKET g_svrSock; map<SOCKET, sClient> g_clients; HWND g_hWnd; // ݹ ν Լ Ÿ LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ); void MainLoop(int timeDelta); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { wchar_t className[32] = L"Server"; wchar_t windowName[32] = L"Server"; // Ŭ // ̷ ڴ WNDCLASS WndClass; WndClass.cbClsExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.cbWndExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // WndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); // Ŀ WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION ); //ܸ WndClass.hInstance = hInstance; //α׷νϽڵ WndClass.lpfnWndProc = (WNDPROC)WndProc; // ν Լ WndClass.lpszMenuName = NULL; //޴̸ NULL WndClass.lpszClassName = className; // ۼϰ ִ Ŭ ̸ WndClass.style = CS_HREDRAW | CS_VREDRAW; // ׸ (  ɶ ȭ鰻 CS_HREDRAW | CS_VREDRAW ) // ۼ Ŭ RegisterClass( &WndClass ); // // ڵ g_hWnd ޴´. HWND hWnd = CreateWindow( className, //Ǵ Ŭ̸ windowName, // ŸƲٿ µǴ ̸ WS_OVERLAPPEDWINDOW, // Ÿ WS_OVERLAPPEDWINDOW WINPOS_X, // ġ X WINPOS_Y, // ġ Y WINSIZE_X, // ũ ( ۾ ũⰡ ƴ ) WINSIZE_Y, // ũ ( ۾ ũⰡ ƴ ) GetDesktopWindow(), //θ ڵ ( α׷ ֻ NULL Ǵ GetDesktopWindow() ) NULL, //޴ ID ( ڽ Ʈ ü ΰ Ʈ ID hInstance, // 찡 α׷ νϽ ڵ NULL //߰ NULL ( Ű ) ); //츦 Ȯ ۾ ũ RECT rcClient = { 0, 0, WINSIZE_X, WINSIZE_Y }; AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE ); //rcClient ũ⸦ ۾ ũ⸦ rcClient ԵǾ ´. // ũ ġ ٲپش. SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER | SWP_NOMOVE ); ShowWindow( hWnd, nCmdShow ); g_hWnd = hWnd; if (!network::LaunchServer(10000, g_svrSock)) { return 0; } OutputDebugStringA( "Server Launched \n"); //޽ ü MSG msg; ZeroMemory( &msg, sizeof( MSG ) ); int oldT = GetTickCount(); while (msg.message != WM_QUIT) { //PeekMessage ޽ ť ޽  α׷ ߱ ʰ ȴ. //̶ ޽ť ޽ false ϵǰ ޽ true ̵ȴ. if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage( &msg ); // Ű ڸ Ͽ WM_CHAR ޽ ߻Ų. DispatchMessage( &msg ); //޾ƿ ޽ ν Լ Ų. } else { const int curT = timeGetTime(); const int elapseT = curT - oldT; oldT = curT; MainLoop(elapseT); } } return 0; } // // ν Լ ( ޽ ť ޾ƿ ޽ óѴ ) // LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch (msg) { case WM_KEYDOWN: if (wParam == VK_ESCAPE) ::DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; } return DefWindowProc( hWnd, msg, wParam, lParam ); } void AcceptClient() { const timeval t = {0, 10}; // 10 millisecond fd_set readSockets; FD_ZERO(&readSockets); FD_SET(g_svrSock, &readSockets); const int ret = select( readSockets.fd_count, &readSockets, NULL, NULL, &t ); if (ret != 0 && ret != SOCKET_ERROR) { for (u_int i=0; i < readSockets.fd_count; ++i) { // accept(û , Ŭ̾Ʈ ּ) SOCKET remoteSocket = accept(readSockets.fd_array[ i], NULL, NULL); if (remoteSocket == INVALID_SOCKET) { return; } if (g_clients.end() == g_clients.find(remoteSocket)) { // get ip address sockaddr_in addr; int len = sizeof(addr); memset(&addr,0,sizeof(addr)); getpeername( remoteSocket, (sockaddr*)&addr, &len ); string ip = inet_ntoa(addr.sin_addr); sClient client; client.ip = ip; client.sock = remoteSocket; g_clients[ remoteSocket] = client; } } } } void DisplayClient() { HDC hdc = GetDC(g_hWnd); Rectangle(hdc, 0, 0, 500, 500); std::stringstream ss; ss << "client count = " << g_clients.size(); const string str = ss.str(); TextOutA(hdc, 10, 10, str.c_str(), str.length()); int y = 25; auto it = g_clients.begin(); while (g_clients.end() != it) { std::stringstream ss; ss << "ip = " << it->second.ip; const string str = ss.str(); TextOutA(hdc, 10, y, str.c_str(), str.length()); ++it; y += 20; } ReleaseDC(g_hWnd, hdc); } void MakeSessionFdset( OUT fd_set &set) { FD_ZERO(&set); auto it = g_clients.begin(); while (g_clients.end() != it) { FD_SET(it->second.sock, &set); ++it; } } void SendAll(char buff[128]) { auto it = g_clients.begin(); while (g_clients.end() != it) { send(it->second.sock, buff, 128, 0); ++it; } } // . void MainLoop(int timeDelta) { DisplayClient(); AcceptClient(); const timeval t = {0, 10}; // 10 millisecond fd_set readSockets; MakeSessionFdset(readSockets); const int ret = select( readSockets.fd_count, &readSockets, NULL, NULL, &t ); if (ret != 0 && ret != SOCKET_ERROR) { for (u_int i=0; i < readSockets.fd_count; ++i) { char buff[ 128]; const int result = recv(readSockets.fd_array[ i], buff, sizeof(buff), 0); if (result == SOCKET_ERROR || result == 0) // Ŷ 0̸ ٴ ǹ̴. { g_clients.erase(readSockets.fd_array[ i]); } else { SendAll(buff); } } } } <|endoftext|>
<commit_before>#include <malloc.h> #include <stdlib.h> #include <dos.h> #include <conio.h> #include <memory.h> typedef unsigned long int UInt32; typedef signed long int SInt32; typedef unsigned short int UInt16; typedef signed short int SInt16; typedef unsigned char UInt8; typedef signed char SInt8; static const UInt16 width = 80; static const UInt16 height = 200; static const UInt16 pointCount = 16193; static const UInt16 particleCount = 948; static const UInt16 particleSize = 15; static const UInt16 headerSize = 15; static const UInt16 footerSize = 5; static const UInt8 particleCode[] = { 0xbf, 0x00, 0x00, // mov di,0000 0xaa, // stosb 0xd1, 0xe7, // shl di,1 0x8b, 0x3d, // mov di,[di] 0x26, 0x88, 0x25, // es: mov [di],ah 0x89, 0x3e, 0x00, 0x00, // mov [0000],di }; static const UInt8 headerCode[] = { // 0xcc, // int 3 0x06, // push es 0x1e, // push ds 0x57, // push di 0x9c, // pushf 0xfc, // cld 0xb8, 0x00, 0xb8, // mov ax,0b800 0x8e, 0xc0, // mov es,ax 0x0e, // push cs 0x1f, // pop ds 0xb8, 0x00, 0xff // mov ax,0ff00 }; static const UInt8 footerCode[] = { 0x9d, // popf 0x5f, // pop di 0x1f, // pop ds 0x07, // pop es 0xcb // retf }; // These arrays form a set of doubly-linked lists. At each location in the // array is the point number of the next/previous point in the chain. // The top bit of pointsNext is a flag meaning "on free list". UInt16 far* pointsNext; UInt16 far* pointsPrev; // The following are either: // 0xffff: The corresponding list is empty. // anything else: A point in the list. UInt16 freeList; // List of points which haven't been placed in their final locations yet. UInt16 gapList; // List of points which are not on screen and should be ignored. UInt16 usedList; // List of points which are finalized. UInt16 next(UInt16 point) { return pointsNext[point] & 0x7fff; } UInt16 prev(UInt16 point) { return pointsPrev[point]; } // Moves a point to its own list. void remove(UInt16 point) { UInt16 oldPrev = prev(point); UInt16 oldNext = next(point); pointsNext[oldPrev] = oldNext; // TODO: Need to preserve free flag here. pointsPrev[oldNext] = oldPrev; pointsNext[point] = point; pointsPrev[point] = point; } // Moves a point to (the end of) list. void place(UInt16* list, UInt16 point) { if (*list == 0xffff) { remove(point); *list = point; } else { remove(point); pointsNext[point] = *list; } } bool isFree(UInt16 point) { return (pointsNext[point] & 0x8000) != 0; } void freeAll() { for (UInt16 point = 0; point < pointCount - 1; ++point) pointsNext[i] |= 0x8000; // TODO: Put all points on free list. } int main() { UInt8 far* program = (UInt8 far*)(_fmalloc(pointCount*2 + particleCount*particleSize + headerSize + footerSize)); UInt32 address = ((UInt32)(FP_SEG(program))) << 4; address += (UInt32)(FP_OFF(program)); UInt16 segment = (UInt16)((address + 0xf) >> 4); UInt16 far* points = (UInt16 far*)MK_FP(segment, 0); pointsPrev = (UInt16 far*)(_fmalloc(pointCount*2)); _fmemset(points, 0, pointCount*2); // Initialize the code block UInt8 far* particles = (UInt8 far*)MK_FP(segment, pointCount*2); _fmemcpy(particles, headerCode, headerSize); particles += headerSize; for (UInt16 particle = 0; particle < particleCount; ++particle) { // Copy the code _fmemcpy(particles, particleCode, particleSize); // Find an unused random point. TODO: Don't use gap points. UInt16 r; do { r = rand() % (pointCount - 1); } while (points[r] != 0); points[r] = 1; // Fill in the operands UInt8 far* p = &particles[1]; *(UInt16 far*)(p) = r; *(UInt16 far*)(&particles[13]) = FP_OFF(p); particles += particleSize; } _fmemcpy(particles, footerCode, footerSize); pointsNext = points + 1; // Initialize the points with a pattern. TODO: Make a more interesting pattern for (UInt16 point = 0; point < pointCount - 1; ++point) { UInt16 next = (point + 1) % pointCount; pointsNext[point] = next; pointsPrev[next] = point; } freeAll(); // Set screen mode to 4 (CGA 320x200 2bpp) union REGS regs; regs.x.ax = 0x04; int86(0x10, &regs, &regs); // Call code repeatedly. TODO: jmp instead of retf in the code and use interrupt for keyboard void (far* code)() = (void (far*)())MK_FP(segment, pointCount*2); int k = 0; do { code(); if (kbhit()) k = getch(); } while (k != 27); regs.x.ax = 0x03; int86(0x10, &regs, &regs); hfree(program); return 0; } <commit_msg>Particles: isVisible<commit_after>#include <malloc.h> #include <stdlib.h> #include <dos.h> #include <conio.h> #include <memory.h> typedef unsigned long int UInt32; typedef signed long int SInt32; typedef unsigned short int UInt16; typedef signed short int SInt16; typedef unsigned char UInt8; typedef signed char SInt8; static const UInt16 width = 80; static const UInt16 height = 200; static const UInt16 pointCount = 16193; static const UInt16 particleCount = 948; static const UInt16 particleSize = 15; static const UInt16 headerSize = 15; static const UInt16 footerSize = 5; static const UInt8 particleCode[] = { 0xbf, 0x00, 0x00, // mov di,0000 0xaa, // stosb 0xd1, 0xe7, // shl di,1 0x8b, 0x3d, // mov di,[di] 0x26, 0x88, 0x25, // es: mov [di],ah 0x89, 0x3e, 0x00, 0x00, // mov [0000],di }; static const UInt8 headerCode[] = { // 0xcc, // int 3 0x06, // push es 0x1e, // push ds 0x57, // push di 0x9c, // pushf 0xfc, // cld 0xb8, 0x00, 0xb8, // mov ax,0b800 0x8e, 0xc0, // mov es,ax 0x0e, // push cs 0x1f, // pop ds 0xb8, 0x00, 0xff // mov ax,0ff00 }; static const UInt8 footerCode[] = { 0x9d, // popf 0x5f, // pop di 0x1f, // pop ds 0x07, // pop es 0xcb // retf }; // These arrays form a set of doubly-linked lists. At each location in the // array is the point number of the next/previous point in the chain. // The top bit of pointsNext is a flag meaning "on free list". UInt16 far* pointsNext; UInt16 far* pointsPrev; // The following are either: // 0xffff: The corresponding list is empty. // anything else: A point in the list. UInt16 freeList; // List of points which haven't been placed in their final locations yet. UInt16 gapList; // List of points which are not on screen and should be ignored. UInt16 usedList; // List of points which are finalized. UInt16 next(UInt16 point) { return pointsNext[point] & 0x7fff; } UInt16 prev(UInt16 point) { return pointsPrev[point]; } // Moves a point to its own list. void remove(UInt16 point) { UInt16 oldPrev = prev(point); UInt16 oldNext = next(point); pointsNext[oldPrev] = oldNext; // TODO: Need to preserve free flag here. pointsPrev[oldNext] = oldPrev; pointsNext[point] = point; pointsPrev[point] = point; } // Moves a point to (the end of) list. void place(UInt16* list, UInt16 point) { if (*list == 0xffff) { remove(point); *list = point; } else { remove(point); pointsNext[point] = *list; } } bool isFree(UInt16 point) { return (pointsNext[point] & 0x8000) != 0; } void freeAll() { for (UInt16 point = 0; point < pointCount - 1; ++point) pointsNext[i] |= 0x8000; // TODO: Put all points on free list. } bool isVisible(UInt16 point) { return (point & 1fff) < 80*100; } void shuffle() { // TODO: Fill pointsPrev with the list of visible points // TODO: Shuffle pointsPrev // TODO: Go through pointsPrev and use it to set up singly linked list in pointsNext // TODO: Make the list doubly linked } int main() { UInt8 far* program = (UInt8 far*)(_fmalloc(pointCount*2 + particleCount*particleSize + headerSize + footerSize)); UInt32 address = ((UInt32)(FP_SEG(program))) << 4; address += (UInt32)(FP_OFF(program)); UInt16 segment = (UInt16)((address + 0xf) >> 4); UInt16 far* points = (UInt16 far*)MK_FP(segment, 0); pointsPrev = (UInt16 far*)(_fmalloc(pointCount*2)); _fmemset(points, 0, pointCount*2); // Initialize the code block UInt8 far* particles = (UInt8 far*)MK_FP(segment, pointCount*2); _fmemcpy(particles, headerCode, headerSize); particles += headerSize; for (UInt16 particle = 0; particle < particleCount; ++particle) { // Copy the code _fmemcpy(particles, particleCode, particleSize); // Find an unused random point. TODO: Don't use gap points. UInt16 r; do { r = rand() % (pointCount - 1); } while (points[r] != 0); points[r] = 1; // Fill in the operands UInt8 far* p = &particles[1]; *(UInt16 far*)(p) = r; *(UInt16 far*)(&particles[13]) = FP_OFF(p); particles += particleSize; } _fmemcpy(particles, footerCode, footerSize); pointsNext = points + 1; // Initialize the points with a pattern. TODO: Make a more interesting pattern for (UInt16 point = 0; point < pointCount - 1; ++point) { UInt16 next = (point + 1) % pointCount; pointsNext[point] = next; pointsPrev[next] = point; } freeAll(); // Set screen mode to 4 (CGA 320x200 2bpp) union REGS regs; regs.x.ax = 0x04; int86(0x10, &regs, &regs); // Call code repeatedly. TODO: jmp instead of retf in the code and use interrupt for keyboard void (far* code)() = (void (far*)())MK_FP(segment, pointCount*2); int k = 0; do { code(); if (kbhit()) k = getch(); } while (k != 27); regs.x.ax = 0x03; int86(0x10, &regs, &regs); hfree(program); return 0; } <|endoftext|>
<commit_before>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/IOConfig.h" #include "mirtk/GenericImage.h" #include "mirtk/Transformation.h" #include "mirtk/AffineTransformation.h" #include "mirtk/FreeFormTransformation.h" using namespace mirtk; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << "\n"; cout << "Usage: " << name << " [<dof>...] [options]" << endl; cout << "\n"; cout << "Description:" << endl; cout << " Calculates registration transformation quality measures such as the voxel-wise\n"; cout << " cumulative or mean inverse-consistency error (CICE/MICE) for pairs of forward\n"; cout << " transformation from target to source and backward transformation from source\n"; cout << " to target image. Another voxel-wise measure that can be computed using this\n"; cout << " program are the cumulative or mean transitivity error (CTE/MTE) given three\n"; cout << " transformations, from target (A) to B, from B to C, and from C to A again.\n"; cout << "\n"; cout << " This tool can further be used to evaluate the deviation of N affine transformations\n"; cout << " which map a template to each one of N images from the barycenter corresponding\n"; cout << " to the identity transformation. A larger deviation indicates a stronger bias of\n"; cout << " the template towards a subset of the images and/or unbalanced registration errors.\n"; cout << "\n"; cout << "Arguments:\n"; cout << " <dof> File path of input transformation. Depending on the evaluation measure,\n"; cout << " multiple consecutive transformations are processed in tuples of fixed\n"; cout << " size and an error measure is computed for each such tuple of transformations.\n"; cout << " In the default case of 1-tuples, each transformation is evaluated separately.\n"; cout << " For other evaluation measures which are based on more than just one transformation\n"; cout << " see the list of optional arguments below.\n"; cout << "\n"; cout << "Optional arguments:\n"; cout << " -dofs <file>\n"; cout << " Text file with (additional) input transformation paths. (default: none)\n"; cout << " -output <file>\n"; cout << " Name of voxel-wise output error map. (default: none)\n"; cout << " -target <file>\n"; cout << " Target image. (default: FFD lattice)\n"; cout << " -mask <file>\n"; cout << " Target region-of-interest mask. (default: none)\n"; cout << " -padding <value>\n"; cout << " Target background value, unused if -mask specified. (default: none)\n"; cout << " -cumulative\n"; cout << " Whether to compute the cumulative error. (default: mean)\n"; cout << " -inverse-consistency\n"; cout << " Request evaluation of inverse-consistency error for each\n"; cout << " pair of input transformations when applied in the given order.\n"; cout << " -transitivity\n"; cout << " Request evaluation of transitivity error for each triple\n"; cout << " of input transformations when applied in the given order.\n"; cout << " -barycentricity\n"; cout << " Evaluate norm of the average log map of all input transformations.\n"; cout << " When the transformations map each image to the common barycenter,\n"; cout << " the reported value should be (close to) zero.\n"; PrintStandardOptions(cout); cout << endl; } // ============================================================================= // Types // ============================================================================= // ----------------------------------------------------------------------------- /// Enumeration of implemented evaluation metrics enum Metric { None, InverseConsistency, Transitivity, Barycentricity }; // ============================================================================= // Auxiliary functions // ============================================================================= // ----------------------------------------------------------------------------- /// Read input file names from text file int read_list_file(const char *list_name, Array<string>& paths) { string base_dir = Directory(list_name); // Base directory containing files ifstream iff(list_name); // List input file stream string line; // Input line int l = 0; // Line number size_t pos; // Read base directory for relative file paths if (!getline(iff, line)) { cerr << "Error: Cannot parse list file " << list_name << endl; return 0; } if (!base_dir.empty() && line[0] != PATHSEP) { if (line != ".") base_dir += PATHSEP + line; } else { base_dir = line; } l++; while (getline(iff, line)) { l++; // Trim line string pos = line.find_first_not_of(" \t"); if (pos != string::npos) line = line.substr(pos); pos = line.find_last_not_of(" \t"); if (pos != string::npos) line = line.substr(0, pos + 1); // Ignore blank lines and comment lines starting with # character if (line.empty() || line[0] == '#') continue; // Make relative file paths absolute if (!base_dir.empty() && line[0] != PATHSEP) line = base_dir + PATHSEP + line; paths.push_back(line); } return static_cast<int>(paths.size()); } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- int main(int argc, char **argv) { // Positional arguments REQUIRES_POSARGS(0); Array<string> dofin_name; for (ALL_POSARGS) dofin_name.push_back(ARGUMENT); // Optional arguments const char *list_name = NULL; const char *output_name = NULL; const char *target_name = NULL; const char *mask_name = NULL; double padding_value = -numeric_limits<double>::infinity(); bool cumulative = false; bool squared = false; Metric metric = None; for (ALL_OPTIONS) { if (OPTION("-output")) output_name = ARGUMENT; else if (OPTION("-dofs")) list_name = ARGUMENT; else if (OPTION("-target")) target_name = ARGUMENT; else if (OPTION("-mask")) mask_name = ARGUMENT; else if (OPTION("-padding")) { const char *arg = ARGUMENT; if (!FromString(arg, padding_value)) { cerr << "Invalid -padding value" << endl; exit(1); } } else if (OPTION("-cumulative")) cumulative = true; else if (OPTION("-squared")) squared = true; else if (OPTION("-inverse-consistency") || OPTION("-ice") || OPTION("-ic")) { metric = InverseConsistency; } else if (OPTION("-transitivity") || OPTION("-te")) metric = Transitivity; else if (OPTION("-mice")) { metric = InverseConsistency; cumulative = false; } else if (OPTION("-cice")) { metric = InverseConsistency; cumulative = true; } else if (OPTION("-mte")) { metric = Transitivity; cumulative = false; } else if (OPTION("-cte")) { metric = Transitivity; cumulative = true; } else if (OPTION("-barycentricity")) metric = Barycentricity; else HANDLE_COMMON_OR_UNKNOWN_OPTION(); } if (list_name) { read_list_file(list_name, dofin_name); } if (dofin_name.empty()) { PrintHelp(EXECNAME); exit(1); } if (metric == None) { metric = Barycentricity; } if (metric == Barycentricity) { Matrix residual(4, 4); AffineTransformation dof; for (auto fname : dofin_name) { dof.Read(fname.c_str()); residual += dof.GetMatrix().Log(); } residual /= static_cast<double>(dofin_name.size()); cout << residual.Norm() << endl; } else { // Shared pointers for input tuples Array<SharedPtr<Transformation> > dofs; if (metric == InverseConsistency) dofs.resize(2); else if (metric == Transitivity) dofs.resize(3); else dofs.resize(1); if (dofin_name.size() % dofs.size() != 0) { cerr << "Invalid number of input transformations. Require " << dofs.size() << "-tuples for the evaluation!" << endl; exit(1); } // Read first transformation SharedPtr<Transformation> dof(Transformation::New(dofin_name[0].c_str())); // Read target, foreground mask, and/or determine attributes for voxel-wise metrics GreyImage target; BinaryImage mask; ImageAttributes attr; WorldCoordsImage i2w; if (mask_name) { InitializeIOLibrary(); mask.Read(mask_name); attr = mask.Attributes(); } if (target_name) { InitializeIOLibrary(); target.Read(target_name); if (!IsInf(padding_value)) target.PutBackgroundValueAsDouble(padding_value, true); attr = target.Attributes(); } if (!attr) { FreeFormTransformation *ffd = dynamic_cast<FreeFormTransformation *>(dof.get()); if (!ffd) { cerr << "First input transformation is no 3D FFD. Either -target or -mask image is required!" << endl; exit(1); } attr = ffd->Attributes(); } if (!mask.IsEmpty() && !mask.Attributes().EqualInSpace(attr)) { cerr << "Mask and target image must have identical spatial attributs!" << endl; exit(1); } // Pre-compute world coordinates of reference voxels if (verbose) cout << "Pre-computing world coordinates of input points" << endl; i2w.Initialize(attr, 3); double *x = i2w.Data(0, 0, 0, 0); double *y = i2w.Data(0, 0, 0, 1); double *z = i2w.Data(0, 0, 0, 2); for (int k = 0; k < attr._z; ++k) for (int j = 0; j < attr._y; ++j) for (int i = 0; i < attr._x; ++i) { *x = i, *y = j, *z = k; i2w.ImageToWorld(*x, *y, *z); ++x, ++y, ++z; } // Compute inverse-consistency error for each pair of transformations GenericImage<float> output(attr); const int nvox = output.NumberOfVoxels(); int ntuple = 0; int ntotal = static_cast<int>(dofin_name.size() / dofs.size()); size_t i, j; double x2, y2, z2, d; for (i = 0; i < dofin_name.size(); i += dofs.size()) { ++ntuple; if (verbose) { const char *suffix = "th"; if (ntuple == 1) suffix = "st"; else if (ntuple == 2) suffix = "nd"; else if (ntuple == 3) suffix = "rd"; cout << "Performing evaluation of " << ntuple << suffix << " " << dofs.size() << "-tuple" << " out of " << ntotal << endl; } for (j = 0; j < dofs.size(); ++j) { if (i == 0 && j == 0) dofs[j] = dof; else dofs[j].reset(Transformation::New(dofin_name[i + j].c_str())); } const double *x1 = i2w.Data(0, 0, 0, 0); const double *y1 = i2w.Data(0, 0, 0, 1); const double *z1 = i2w.Data(0, 0, 0, 2); float *err = output.Data(); for (int n = 0; n < nvox; ++n) { if ((target.IsEmpty() || target.IsForeground(n)) && (mask.IsEmpty() || mask.Get(n))) { x2 = x1[n], y2 = y1[n], z2 = z1[n]; for (j = 0; j < dofs.size(); ++j) dofs[j]->Transform(x2, y2, z2); x2 -= x1[n], y2 -= y1[n], z2 -= z1[n]; d = x2 * x2 + y2 * y2 + z2 * z2; err[n] += static_cast<float>(squared ? d : sqrt(d)); } } } // Calculate mean inverse-consistency error if (!cumulative && ntuple > 0) output /= ntuple; // Write voxel-wise error map if (output_name) { InitializeIOLibrary(); output.Write(output_name); } } return 0; } <commit_msg>enh: evaluate-dof -ss option for SVFFD [Applications]<commit_after>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2017 Imperial College London * Copyright 2013-2017 Andreas Schuh * * 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 "mirtk/Common.h" #include "mirtk/Options.h" #include "mirtk/IOConfig.h" #include "mirtk/GenericImage.h" #include "mirtk/Transformation.h" #include "mirtk/AffineTransformation.h" #include "mirtk/FreeFormTransformation.h" #include "mirtk/MultiLevelFreeFormTransformation.h" #include "mirtk/LinearFreeFormTransformation3D.h" using namespace mirtk; // ============================================================================= // Help // ============================================================================= // ----------------------------------------------------------------------------- void PrintHelp(const char *name) { cout << "\n"; cout << "Usage: " << name << " [<dof>...] [options]" << endl; cout << "\n"; cout << "Description:" << endl; cout << " Calculates registration transformation quality measures such as the voxel-wise\n"; cout << " cumulative or mean inverse-consistency error (CICE/MICE) for pairs of forward\n"; cout << " transformation from target to source and backward transformation from source\n"; cout << " to target image. Another voxel-wise measure that can be computed using this\n"; cout << " program are the cumulative or mean transitivity error (CTE/MTE) given three\n"; cout << " transformations, from target (A) to B, from B to C, and from C to A again.\n"; cout << "\n"; cout << " This tool can further be used to evaluate the deviation of N affine transformations\n"; cout << " which map a template to each one of N images from the barycenter corresponding\n"; cout << " to the identity transformation. A larger deviation indicates a stronger bias of\n"; cout << " the template towards a subset of the images and/or unbalanced registration errors.\n"; cout << "\n"; cout << "Arguments:\n"; cout << " <dof> File path of input transformation. Depending on the evaluation measure,\n"; cout << " multiple consecutive transformations are processed in tuples of fixed\n"; cout << " size and an error measure is computed for each such tuple of transformations.\n"; cout << " In the default case of 1-tuples, each transformation is evaluated separately.\n"; cout << " For other evaluation measures which are based on more than just one transformation\n"; cout << " see the list of optional arguments below.\n"; cout << "\n"; cout << "Optional arguments:\n"; cout << " -dofs <file>\n"; cout << " Text file with (additional) input transformation paths. (default: none)\n"; cout << " -output <file>\n"; cout << " Name of voxel-wise output error map. (default: none)\n"; cout << " -target <file>\n"; cout << " Target image. (default: FFD lattice)\n"; cout << " -mask <file>\n"; cout << " Target region-of-interest mask. (default: none)\n"; cout << " -padding <value>\n"; cout << " Target background value, unused if -mask specified. (default: none)\n"; cout << " -cumulative\n"; cout << " Whether to compute the cumulative error. (default: mean)\n"; cout << " -inverse-consistency\n"; cout << " Request evaluation of inverse-consistency error for each\n"; cout << " pair of input transformations when applied in the given order.\n"; cout << " -transitivity\n"; cout << " Request evaluation of transitivity error for each triple\n"; cout << " of input transformations when applied in the given order.\n"; cout << " -barycentricity\n"; cout << " Evaluate norm of the average log map of all input transformations.\n"; cout << " When the transformations map each image to the common barycenter,\n"; cout << " the reported value should be (close to) zero.\n"; PrintStandardOptions(cout); cout << endl; } // ============================================================================= // Types // ============================================================================= // ----------------------------------------------------------------------------- /// Enumeration of implemented evaluation metrics enum Metric { None, InverseConsistency, Transitivity, Barycentricity }; // ============================================================================= // Auxiliary functions // ============================================================================= // ----------------------------------------------------------------------------- /// Read input file names from text file int read_list_file(const char *list_name, Array<string>& paths) { string base_dir = Directory(list_name); // Base directory containing files ifstream iff(list_name); // List input file stream string line; // Input line int l = 0; // Line number size_t pos; // Read base directory for relative file paths if (!getline(iff, line)) { cerr << "Error: Cannot parse list file " << list_name << endl; return 0; } if (!base_dir.empty() && line[0] != PATHSEP) { if (line != ".") base_dir += PATHSEP + line; } else { base_dir = line; } l++; while (getline(iff, line)) { l++; // Trim line string pos = line.find_first_not_of(" \t"); if (pos != string::npos) line = line.substr(pos); pos = line.find_last_not_of(" \t"); if (pos != string::npos) line = line.substr(0, pos + 1); // Ignore blank lines and comment lines starting with # character if (line.empty() || line[0] == '#') continue; // Make relative file paths absolute if (!base_dir.empty() && line[0] != PATHSEP) line = base_dir + PATHSEP + line; paths.push_back(line); } return static_cast<int>(paths.size()); } // ============================================================================= // Main // ============================================================================= // ----------------------------------------------------------------------------- int main(int argc, char **argv) { // Positional arguments REQUIRES_POSARGS(0); Array<string> dofin_name; for (ALL_POSARGS) dofin_name.push_back(ARGUMENT); // Optional arguments const char *list_name = nullptr; const char *output_name = nullptr; const char *target_name = nullptr; const char *mask_name = nullptr; double padding_value = -inf; bool cache_disp = false; bool cumulative = false; bool squared = false; Metric metric = None; for (ALL_OPTIONS) { if (OPTION("-output")) output_name = ARGUMENT; else if (OPTION("-dofs")) list_name = ARGUMENT; else if (OPTION("-target")) target_name = ARGUMENT; else if (OPTION("-mask")) mask_name = ARGUMENT; else if (OPTION("-padding")) { const char *arg = ARGUMENT; if (!FromString(arg, padding_value)) { cerr << "Invalid -padding value" << endl; exit(1); } } else if (OPTION("-cumulative")) cumulative = true; else if (OPTION("-squared")) squared = true; else if (OPTION("-inverse-consistency") || OPTION("-ice") || OPTION("-ic")) { metric = InverseConsistency; } else if (OPTION("-transitivity") || OPTION("-te")) metric = Transitivity; else if (OPTION("-mice")) { metric = InverseConsistency; cumulative = false; } else if (OPTION("-cice")) { metric = InverseConsistency; cumulative = true; } else if (OPTION("-mte")) { metric = Transitivity; cumulative = false; } else if (OPTION("-cte")) { metric = Transitivity; cumulative = true; } else if (OPTION("-barycentricity")) metric = Barycentricity; else if (OPTION("-allow-caching-of-displacements") || OPTION("-ss")) { cache_disp = true; if (HAS_ARGUMENT) PARSE_ARGUMENT(cache_disp); } else HANDLE_COMMON_OR_UNKNOWN_OPTION(); } if (list_name) { read_list_file(list_name, dofin_name); } if (dofin_name.empty()) { PrintHelp(EXECNAME); exit(1); } if (metric == None) { metric = Barycentricity; } if (metric == Barycentricity) { Matrix residual(4, 4); AffineTransformation dof; for (auto fname : dofin_name) { dof.Read(fname.c_str()); residual += dof.GetMatrix().Log(); } residual /= static_cast<double>(dofin_name.size()); cout << residual.Norm() << endl; } else { // Shared pointers for input tuples Array<SharedPtr<Transformation> > dofs; if (metric == InverseConsistency) dofs.resize(2); else if (metric == Transitivity) dofs.resize(3); else dofs.resize(1); if (dofin_name.size() % dofs.size() != 0) { cerr << "Invalid number of input transformations. Require " << dofs.size() << "-tuples for the evaluation!" << endl; exit(1); } // Read first transformation SharedPtr<Transformation> dof(Transformation::New(dofin_name[0].c_str())); // Read target, foreground mask, and/or determine attributes for voxel-wise metrics GreyImage target; BinaryImage mask; ImageAttributes attr; WorldCoordsImage i2w; if (mask_name) { InitializeIOLibrary(); mask.Read(mask_name); attr = mask.Attributes(); } if (target_name) { InitializeIOLibrary(); target.Read(target_name); if (!IsInf(padding_value)) target.PutBackgroundValueAsDouble(padding_value, true); attr = target.Attributes(); } if (!attr) { FreeFormTransformation *ffd = dynamic_cast<FreeFormTransformation *>(dof.get()); if (!ffd) { cerr << "First input transformation is no 3D FFD. Either -target or -mask image is required!" << endl; exit(1); } attr = ffd->Attributes(); } if (!mask.IsEmpty() && !mask.Attributes().EqualInSpace(attr)) { cerr << "Mask and target image must have identical spatial attributs!" << endl; exit(1); } // Pre-compute world coordinates of reference voxels if (verbose) cout << "Pre-computing world coordinates of input points" << endl; i2w.Initialize(attr, 3); double *x = i2w.Data(0, 0, 0, 0); double *y = i2w.Data(0, 0, 0, 1); double *z = i2w.Data(0, 0, 0, 2); for (int k = 0; k < attr._z; ++k) for (int j = 0; j < attr._y; ++j) for (int i = 0; i < attr._x; ++i) { *x = i, *y = j, *z = k; i2w.ImageToWorld(*x, *y, *z); ++x, ++y, ++z; } // Compute inverse-consistency error for each pair of transformations GenericImage<float> output(attr); const int nvox = output.NumberOfVoxels(); int ntuple = 0; int ntotal = static_cast<int>(dofin_name.size() / dofs.size()); size_t i, j; double x2, y2, z2, d; for (i = 0; i < dofin_name.size(); i += dofs.size()) { ++ntuple; if (verbose) { const char *suffix = "th"; if (ntuple == 1) suffix = "st"; else if (ntuple == 2) suffix = "nd"; else if (ntuple == 3) suffix = "rd"; cout << "Performing evaluation of " << ntuple << suffix << " " << dofs.size() << "-tuple" << " out of " << ntotal << endl; } for (j = 0; j < dofs.size(); ++j) { if (i == 0 && j == 0) dofs[j] = dof; else { dofs[j].reset(Transformation::New(dofin_name[i + j].c_str())); if (cache_disp && dofs[j]->RequiresCachingOfDisplacements()) { int dims = 0; auto mffd = dynamic_cast<MultiLevelFreeFormTransformation *>(dofs[j].get()); if (mffd) { for (int l = 0; l < mffd->NumberOfLevels(); ++l) { int level_dims = 2; if (mffd->GetLocalTransformation(l)->T() > 1) level_dims = 4; else if (mffd->GetLocalTransformation(l)->Z() > 1) level_dims = 3; if (dims == 0) { dims = level_dims; } else if (dims != level_dims) { dims = 0; break; } } } else { auto ffd = dynamic_cast<FreeFormTransformation *>(dofs[j].get()); dims = 2; if (ffd->T() > 1) dims = 4; else if (ffd->Z() > 1) dims = 3; } if (dims == 2 || dims == 3) { if (verbose > 1) cout << " Convert input transformation to " << dims << "D LinearFFD" << endl; GenericImage<double> disp(attr, dims); dofs[j]->Displacement(disp); dofs[j].reset(new LinearFreeFormTransformation3D(disp)); } } } } const double *x1 = i2w.Data(0, 0, 0, 0); const double *y1 = i2w.Data(0, 0, 0, 1); const double *z1 = i2w.Data(0, 0, 0, 2); float *err = output.Data(); for (int n = 0; n < nvox; ++n) { if ((target.IsEmpty() || target.IsForeground(n)) && (mask.IsEmpty() || mask.Get(n))) { x2 = x1[n], y2 = y1[n], z2 = z1[n]; for (j = 0; j < dofs.size(); ++j) dofs[j]->Transform(x2, y2, z2); x2 -= x1[n], y2 -= y1[n], z2 -= z1[n]; d = x2 * x2 + y2 * y2 + z2 * z2; err[n] += static_cast<float>(squared ? d : sqrt(d)); } } } // Calculate mean inverse-consistency error if (!cumulative && ntuple > 0) output /= ntuple; // Write voxel-wise error map if (output_name) { InitializeIOLibrary(); output.Write(output_name); } } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2017 The OTS 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 <string> #include "os2.h" #include "head.h" // OS/2 - OS/2 and Windows Metrics // http://www.microsoft.com/typography/otspec/os2.htm namespace ots { bool OpenTypeOS2::Parse(const uint8_t *data, size_t length) { Buffer table(data, length); if (!table.ReadU16(&this->table.version) || !table.ReadS16(&this->table.avg_char_width) || !table.ReadU16(&this->table.weight_class) || !table.ReadU16(&this->table.width_class) || !table.ReadU16(&this->table.type) || !table.ReadS16(&this->table.subscript_x_size) || !table.ReadS16(&this->table.subscript_y_size) || !table.ReadS16(&this->table.subscript_x_offset) || !table.ReadS16(&this->table.subscript_y_offset) || !table.ReadS16(&this->table.superscript_x_size) || !table.ReadS16(&this->table.superscript_y_size) || !table.ReadS16(&this->table.superscript_x_offset) || !table.ReadS16(&this->table.superscript_y_offset) || !table.ReadS16(&this->table.strikeout_size) || !table.ReadS16(&this->table.strikeout_position) || !table.ReadS16(&this->table.family_class)) { return Error("Error reading basic table elements"); } if (this->table.version > 5) { return Error("Unsupported table version: %u", this->table.version); } // Follow WPF Font Selection Model's advice. if (1 <= this->table.weight_class && this->table.weight_class <= 9) { Warning("Bad usWeightClass: %u, changing it to %u", this->table.weight_class, this->table.weight_class * 100); this->table.weight_class *= 100; } // Ditto. if (this->table.weight_class > 999) { Warning("Bad usWeightClass: %u, changing it to %d", this->table.weight_class, 999); this->table.weight_class = 999; } if (this->table.width_class < 1) { Warning("Bad usWidthClass: %u, changing it to %d", this->table.width_class, 1); this->table.width_class = 1; } else if (this->table.width_class > 9) { Warning("Bad usWidthClass: %u, changing it to %d", this->table.width_class, 9); this->table.width_class = 9; } // lowest 3 bits of fsType are exclusive. if (this->table.type & 0x2) { // mask bits 2 & 3. this->table.type &= 0xfff3u; } else if (this->table.type & 0x4) { // mask bits 1 & 3. this->table.type &= 0xfff4u; } else if (this->table.type & 0x8) { // mask bits 1 & 2. this->table.type &= 0xfff9u; } // mask reserved bits. use only 0..3, 8, 9 bits. this->table.type &= 0x30f; #define SET_TO_ZERO(a, b) \ if (this->table.b < 0) { \ Warning("Bad " a ": %d, setting it to zero", this->table.b); \ this->table.b = 0; \ } SET_TO_ZERO("ySubscriptXSize", subscript_x_size); SET_TO_ZERO("ySubscriptYSize", subscript_y_size); SET_TO_ZERO("ySuperscriptXSize", superscript_x_size); SET_TO_ZERO("ySuperscriptYSize", superscript_y_size); SET_TO_ZERO("yStrikeoutSize", strikeout_size); #undef SET_TO_ZERO static const char* panose_strings[10] = { "bFamilyType", "bSerifStyle", "bWeight", "bProportion", "bContrast", "bStrokeVariation", "bArmStyle", "bLetterform", "bMidline", "bXHeight", }; for (unsigned i = 0; i < 10; ++i) { if (!table.ReadU8(&this->table.panose[i])) { return Error("Failed to read PANOSE %s", panose_strings[i]); } } if (!table.ReadU32(&this->table.unicode_range_1) || !table.ReadU32(&this->table.unicode_range_2) || !table.ReadU32(&this->table.unicode_range_3) || !table.ReadU32(&this->table.unicode_range_4) || !table.ReadU32(&this->table.vendor_id) || !table.ReadU16(&this->table.selection) || !table.ReadU16(&this->table.first_char_index) || !table.ReadU16(&this->table.last_char_index) || !table.ReadS16(&this->table.typo_ascender) || !table.ReadS16(&this->table.typo_descender) || !table.ReadS16(&this->table.typo_linegap) || !table.ReadU16(&this->table.win_ascent) || !table.ReadU16(&this->table.win_descent)) { return Error("Error reading more basic table fields"); } // If bit 6 is set, then bits 0 and 5 must be clear. if (this->table.selection & 0x40) { this->table.selection &= 0xffdeu; } // the settings of bits 0 and 1 must be reflected in the macStyle bits // in the 'head' table. OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>( GetFont()->GetTypedTable(OTS_TAG_HEAD)); if ((this->table.selection & 0x1) && head && !(head->mac_style & 0x2)) { Warning("Adjusting head.macStyle (italic) to match fsSelection"); head->mac_style |= 0x2; } if ((this->table.selection & 0x2) && head && !(head->mac_style & 0x4)) { Warning("Adjusting head.macStyle (underscore) to match fsSelection"); head->mac_style |= 0x4; } // While bit 6 on implies that bits 0 and 1 of macStyle are clear, // the reverse is not true. if ((this->table.selection & 0x40) && head && (head->mac_style & 0x3)) { Warning("Adjusting head.macStyle (regular) to match fsSelection"); head->mac_style &= 0xfffcu; } if ((this->table.version < 4) && (this->table.selection & 0x300)) { // bit 8 and 9 must be unset in OS/2 table versions less than 4. return Error("fSelection bits 8 and 9 must be unset for table version %d", this->table.version); } // mask reserved bits. use only 0..9 bits. this->table.selection &= 0x3ff; if (this->table.first_char_index > this->table.last_char_index) { return Error("usFirstCharIndex %d > usLastCharIndex %d", this->table.first_char_index, this->table.last_char_index); } if (this->table.typo_linegap < 0) { Warning("Bad sTypoLineGap, setting it to 0: %d", this->table.typo_linegap); this->table.typo_linegap = 0; } if (this->table.version < 1) { // http://www.microsoft.com/typography/otspec/os2ver0.htm return true; } if (length < offsetof(OS2Data, code_page_range_2)) { Warning("Bad version number, setting it to 0: %u", this->table.version); // Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version // numbers. Fix them. this->table.version = 0; return true; } if (!table.ReadU32(&this->table.code_page_range_1) || !table.ReadU32(&this->table.code_page_range_2)) { return Error("Failed to read ulCodePageRange1 or ulCodePageRange2"); } if (this->table.version < 2) { // http://www.microsoft.com/typography/otspec/os2ver1.htm return true; } if (length < offsetof(OS2Data, max_context)) { Warning("Bad version number, setting it to 1: %u", this->table.version); // some Japanese fonts (e.g., mona.ttf) have weird version number. // fix them. this->table.version = 1; return true; } if (!table.ReadS16(&this->table.x_height) || !table.ReadS16(&this->table.cap_height) || !table.ReadU16(&this->table.default_char) || !table.ReadU16(&this->table.break_char) || !table.ReadU16(&this->table.max_context)) { return Error("Failed to read version 2-specific fields"); } if (this->table.x_height < 0) { Warning("Bad sxHeight settig it to 0: %d", this->table.x_height); this->table.x_height = 0; } if (this->table.cap_height < 0) { Warning("Bad sCapHeight setting it to 0: %d", this->table.cap_height); this->table.cap_height = 0; } if (this->table.version < 5) { // http://www.microsoft.com/typography/otspec/os2ver4.htm return true; } if (!table.ReadU16(&this->table.lower_optical_pointsize) || !table.ReadU16(&this->table.upper_optical_pointsize)) { return Error("Failed to read version 5-specific fields"); } if (this->table.lower_optical_pointsize > 0xFFFE) { Warning("usLowerOpticalPointSize is bigger than 0xFFFE: %d", this->table.lower_optical_pointsize); this->table.lower_optical_pointsize = 0xFFFE; } if (this->table.upper_optical_pointsize < 2) { Warning("usUpperOpticalPointSize is lower than 2: %d", this->table.upper_optical_pointsize); this->table.upper_optical_pointsize = 2; } return true; } bool OpenTypeOS2::Serialize(OTSStream *out) { if (!out->WriteU16(this->table.version) || !out->WriteS16(this->table.avg_char_width) || !out->WriteU16(this->table.weight_class) || !out->WriteU16(this->table.width_class) || !out->WriteU16(this->table.type) || !out->WriteS16(this->table.subscript_x_size) || !out->WriteS16(this->table.subscript_y_size) || !out->WriteS16(this->table.subscript_x_offset) || !out->WriteS16(this->table.subscript_y_offset) || !out->WriteS16(this->table.superscript_x_size) || !out->WriteS16(this->table.superscript_y_size) || !out->WriteS16(this->table.superscript_x_offset) || !out->WriteS16(this->table.superscript_y_offset) || !out->WriteS16(this->table.strikeout_size) || !out->WriteS16(this->table.strikeout_position) || !out->WriteS16(this->table.family_class)) { return Error("Failed to write basic table data"); } for (unsigned i = 0; i < 10; ++i) { if (!out->Write(&this->table.panose[i], 1)) { return Error("Failed to write PANOSE data"); } } if (!out->WriteU32(this->table.unicode_range_1) || !out->WriteU32(this->table.unicode_range_2) || !out->WriteU32(this->table.unicode_range_3) || !out->WriteU32(this->table.unicode_range_4) || !out->WriteU32(this->table.vendor_id) || !out->WriteU16(this->table.selection) || !out->WriteU16(this->table.first_char_index) || !out->WriteU16(this->table.last_char_index) || !out->WriteS16(this->table.typo_ascender) || !out->WriteS16(this->table.typo_descender) || !out->WriteS16(this->table.typo_linegap) || !out->WriteU16(this->table.win_ascent) || !out->WriteU16(this->table.win_descent)) { return Error("Failed to write version 1-specific fields"); } if (this->table.version < 1) { return true; } if (!out->WriteU32(this->table.code_page_range_1) || !out->WriteU32(this->table.code_page_range_2)) { return Error("Failed to write codepage ranges"); } if (this->table.version < 2) { return true; } if (!out->WriteS16(this->table.x_height) || !out->WriteS16(this->table.cap_height) || !out->WriteU16(this->table.default_char) || !out->WriteU16(this->table.break_char) || !out->WriteU16(this->table.max_context)) { return Error("Failed to write version 2-specific fields"); } if (this->table.version < 5) { return true; } if (!out->WriteU16(this->table.lower_optical_pointsize) || !out->WriteU16(this->table.upper_optical_pointsize)) { return Error("Failed to write version 5-specific fields"); } return true; } } // namespace ots <commit_msg>[OS/2] Don’t reject for some set fSelection bits<commit_after>// Copyright (c) 2009-2017 The OTS 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 <string> #include "os2.h" #include "head.h" // OS/2 - OS/2 and Windows Metrics // http://www.microsoft.com/typography/otspec/os2.htm namespace ots { bool OpenTypeOS2::Parse(const uint8_t *data, size_t length) { Buffer table(data, length); if (!table.ReadU16(&this->table.version) || !table.ReadS16(&this->table.avg_char_width) || !table.ReadU16(&this->table.weight_class) || !table.ReadU16(&this->table.width_class) || !table.ReadU16(&this->table.type) || !table.ReadS16(&this->table.subscript_x_size) || !table.ReadS16(&this->table.subscript_y_size) || !table.ReadS16(&this->table.subscript_x_offset) || !table.ReadS16(&this->table.subscript_y_offset) || !table.ReadS16(&this->table.superscript_x_size) || !table.ReadS16(&this->table.superscript_y_size) || !table.ReadS16(&this->table.superscript_x_offset) || !table.ReadS16(&this->table.superscript_y_offset) || !table.ReadS16(&this->table.strikeout_size) || !table.ReadS16(&this->table.strikeout_position) || !table.ReadS16(&this->table.family_class)) { return Error("Error reading basic table elements"); } if (this->table.version > 5) { return Error("Unsupported table version: %u", this->table.version); } // Follow WPF Font Selection Model's advice. if (1 <= this->table.weight_class && this->table.weight_class <= 9) { Warning("Bad usWeightClass: %u, changing it to %u", this->table.weight_class, this->table.weight_class * 100); this->table.weight_class *= 100; } // Ditto. if (this->table.weight_class > 999) { Warning("Bad usWeightClass: %u, changing it to %d", this->table.weight_class, 999); this->table.weight_class = 999; } if (this->table.width_class < 1) { Warning("Bad usWidthClass: %u, changing it to %d", this->table.width_class, 1); this->table.width_class = 1; } else if (this->table.width_class > 9) { Warning("Bad usWidthClass: %u, changing it to %d", this->table.width_class, 9); this->table.width_class = 9; } // lowest 3 bits of fsType are exclusive. if (this->table.type & 0x2) { // mask bits 2 & 3. this->table.type &= 0xfff3u; } else if (this->table.type & 0x4) { // mask bits 1 & 3. this->table.type &= 0xfff4u; } else if (this->table.type & 0x8) { // mask bits 1 & 2. this->table.type &= 0xfff9u; } // mask reserved bits. use only 0..3, 8, 9 bits. this->table.type &= 0x30f; #define SET_TO_ZERO(a, b) \ if (this->table.b < 0) { \ Warning("Bad " a ": %d, setting it to zero", this->table.b); \ this->table.b = 0; \ } SET_TO_ZERO("ySubscriptXSize", subscript_x_size); SET_TO_ZERO("ySubscriptYSize", subscript_y_size); SET_TO_ZERO("ySuperscriptXSize", superscript_x_size); SET_TO_ZERO("ySuperscriptYSize", superscript_y_size); SET_TO_ZERO("yStrikeoutSize", strikeout_size); #undef SET_TO_ZERO static const char* panose_strings[10] = { "bFamilyType", "bSerifStyle", "bWeight", "bProportion", "bContrast", "bStrokeVariation", "bArmStyle", "bLetterform", "bMidline", "bXHeight", }; for (unsigned i = 0; i < 10; ++i) { if (!table.ReadU8(&this->table.panose[i])) { return Error("Failed to read PANOSE %s", panose_strings[i]); } } if (!table.ReadU32(&this->table.unicode_range_1) || !table.ReadU32(&this->table.unicode_range_2) || !table.ReadU32(&this->table.unicode_range_3) || !table.ReadU32(&this->table.unicode_range_4) || !table.ReadU32(&this->table.vendor_id) || !table.ReadU16(&this->table.selection) || !table.ReadU16(&this->table.first_char_index) || !table.ReadU16(&this->table.last_char_index) || !table.ReadS16(&this->table.typo_ascender) || !table.ReadS16(&this->table.typo_descender) || !table.ReadS16(&this->table.typo_linegap) || !table.ReadU16(&this->table.win_ascent) || !table.ReadU16(&this->table.win_descent)) { return Error("Error reading more basic table fields"); } // If bit 6 is set, then bits 0 and 5 must be clear. if (this->table.selection & 0x40) { this->table.selection &= 0xffdeu; } // the settings of bits 0 and 1 must be reflected in the macStyle bits // in the 'head' table. OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>( GetFont()->GetTypedTable(OTS_TAG_HEAD)); if ((this->table.selection & 0x1) && head && !(head->mac_style & 0x2)) { Warning("Adjusting head.macStyle (italic) to match fsSelection"); head->mac_style |= 0x2; } if ((this->table.selection & 0x2) && head && !(head->mac_style & 0x4)) { Warning("Adjusting head.macStyle (underscore) to match fsSelection"); head->mac_style |= 0x4; } // While bit 6 on implies that bits 0 and 1 of macStyle are clear, // the reverse is not true. if ((this->table.selection & 0x40) && head && (head->mac_style & 0x3)) { Warning("Adjusting head.macStyle (regular) to match fsSelection"); head->mac_style &= 0xfffcu; } if ((this->table.version < 4) && (this->table.selection & 0x300)) { // bit 8 and 9 must be unset in OS/2 table versions less than 4. Warning("fSelection bits 8 and 9 must be unset for table version %d", this->table.version); } // mask reserved bits. use only 0..9 bits. this->table.selection &= 0x3ff; if (this->table.first_char_index > this->table.last_char_index) { return Error("usFirstCharIndex %d > usLastCharIndex %d", this->table.first_char_index, this->table.last_char_index); } if (this->table.typo_linegap < 0) { Warning("Bad sTypoLineGap, setting it to 0: %d", this->table.typo_linegap); this->table.typo_linegap = 0; } if (this->table.version < 1) { // http://www.microsoft.com/typography/otspec/os2ver0.htm return true; } if (length < offsetof(OS2Data, code_page_range_2)) { Warning("Bad version number, setting it to 0: %u", this->table.version); // Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version // numbers. Fix them. this->table.version = 0; return true; } if (!table.ReadU32(&this->table.code_page_range_1) || !table.ReadU32(&this->table.code_page_range_2)) { return Error("Failed to read ulCodePageRange1 or ulCodePageRange2"); } if (this->table.version < 2) { // http://www.microsoft.com/typography/otspec/os2ver1.htm return true; } if (length < offsetof(OS2Data, max_context)) { Warning("Bad version number, setting it to 1: %u", this->table.version); // some Japanese fonts (e.g., mona.ttf) have weird version number. // fix them. this->table.version = 1; return true; } if (!table.ReadS16(&this->table.x_height) || !table.ReadS16(&this->table.cap_height) || !table.ReadU16(&this->table.default_char) || !table.ReadU16(&this->table.break_char) || !table.ReadU16(&this->table.max_context)) { return Error("Failed to read version 2-specific fields"); } if (this->table.x_height < 0) { Warning("Bad sxHeight settig it to 0: %d", this->table.x_height); this->table.x_height = 0; } if (this->table.cap_height < 0) { Warning("Bad sCapHeight setting it to 0: %d", this->table.cap_height); this->table.cap_height = 0; } if (this->table.version < 5) { // http://www.microsoft.com/typography/otspec/os2ver4.htm return true; } if (!table.ReadU16(&this->table.lower_optical_pointsize) || !table.ReadU16(&this->table.upper_optical_pointsize)) { return Error("Failed to read version 5-specific fields"); } if (this->table.lower_optical_pointsize > 0xFFFE) { Warning("usLowerOpticalPointSize is bigger than 0xFFFE: %d", this->table.lower_optical_pointsize); this->table.lower_optical_pointsize = 0xFFFE; } if (this->table.upper_optical_pointsize < 2) { Warning("usUpperOpticalPointSize is lower than 2: %d", this->table.upper_optical_pointsize); this->table.upper_optical_pointsize = 2; } return true; } bool OpenTypeOS2::Serialize(OTSStream *out) { if (!out->WriteU16(this->table.version) || !out->WriteS16(this->table.avg_char_width) || !out->WriteU16(this->table.weight_class) || !out->WriteU16(this->table.width_class) || !out->WriteU16(this->table.type) || !out->WriteS16(this->table.subscript_x_size) || !out->WriteS16(this->table.subscript_y_size) || !out->WriteS16(this->table.subscript_x_offset) || !out->WriteS16(this->table.subscript_y_offset) || !out->WriteS16(this->table.superscript_x_size) || !out->WriteS16(this->table.superscript_y_size) || !out->WriteS16(this->table.superscript_x_offset) || !out->WriteS16(this->table.superscript_y_offset) || !out->WriteS16(this->table.strikeout_size) || !out->WriteS16(this->table.strikeout_position) || !out->WriteS16(this->table.family_class)) { return Error("Failed to write basic table data"); } for (unsigned i = 0; i < 10; ++i) { if (!out->Write(&this->table.panose[i], 1)) { return Error("Failed to write PANOSE data"); } } if (!out->WriteU32(this->table.unicode_range_1) || !out->WriteU32(this->table.unicode_range_2) || !out->WriteU32(this->table.unicode_range_3) || !out->WriteU32(this->table.unicode_range_4) || !out->WriteU32(this->table.vendor_id) || !out->WriteU16(this->table.selection) || !out->WriteU16(this->table.first_char_index) || !out->WriteU16(this->table.last_char_index) || !out->WriteS16(this->table.typo_ascender) || !out->WriteS16(this->table.typo_descender) || !out->WriteS16(this->table.typo_linegap) || !out->WriteU16(this->table.win_ascent) || !out->WriteU16(this->table.win_descent)) { return Error("Failed to write version 1-specific fields"); } if (this->table.version < 1) { return true; } if (!out->WriteU32(this->table.code_page_range_1) || !out->WriteU32(this->table.code_page_range_2)) { return Error("Failed to write codepage ranges"); } if (this->table.version < 2) { return true; } if (!out->WriteS16(this->table.x_height) || !out->WriteS16(this->table.cap_height) || !out->WriteU16(this->table.default_char) || !out->WriteU16(this->table.break_char) || !out->WriteU16(this->table.max_context)) { return Error("Failed to write version 2-specific fields"); } if (this->table.version < 5) { return true; } if (!out->WriteU16(this->table.lower_optical_pointsize) || !out->WriteU16(this->table.upper_optical_pointsize)) { return Error("Failed to write version 5-specific fields"); } return true; } } // namespace ots <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Markus Frank 28/10/04 /************************************************************************* * 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. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TEmulatedMapProxy // // Streamer around an arbitrary container, which implements basic // functionality and iteration. // // In particular this is used to implement splitting and abstract // element access of any container. Access to compiled code is necessary // to implement the abstract iteration sequence and functionality like // size(), clear(), resize(). resize() may be a void operation. // ////////////////////////////////////////////////////////////////////////// #include "TEmulatedMapProxy.h" #include "TClassEdit.h" #include "TStreamerInfo.h" #include "TError.h" TEmulatedMapProxy::TEmulatedMapProxy(const TEmulatedMapProxy& copy) : TEmulatedCollectionProxy(copy) { // copy constructor if ( !(fSTL_type == TClassEdit::kMap || fSTL_type == TClassEdit::kMultiMap) ) { Fatal("TEmulatedMapProxy","Class %s is not a map-type!",fName.c_str()); } } TEmulatedMapProxy::TEmulatedMapProxy(const char* cl_name, Bool_t silent) : TEmulatedCollectionProxy(cl_name, silent) { // Build a Streamer for an emulated vector whose type is 'name'. if ( !(fSTL_type == TClassEdit::kMap || fSTL_type == TClassEdit::kMultiMap) ) { Fatal("TEmulatedMapProxy","Class %s is not a map-type!",fName.c_str()); } } TEmulatedMapProxy::~TEmulatedMapProxy() { // Standard destructor. } TVirtualCollectionProxy* TEmulatedMapProxy::Generate() const { // Virtual copy constructor. if ( !fClass ) Initialize(kFALSE); return new TEmulatedMapProxy(*this); } void* TEmulatedMapProxy::At(UInt_t idx) { // Return the address of the value at index 'idx'. if ( fEnv && fEnv->fObject ) { PCont_t c = PCont_t(fEnv->fObject); return idx<(c->size()/fValDiff) ? ((char*)&(*c->begin())) + idx*fValDiff : 0; } Fatal("TEmulatedMapProxy","At> Logic error - no proxy object set."); return 0; } UInt_t TEmulatedMapProxy::Size() const { // Return the current size of the container. if ( fEnv && fEnv->fObject ) { PCont_t c = PCont_t(fEnv->fObject); return fEnv->fSize = (c->size()/fValDiff); } Fatal("TEmulatedMapProxy","Size> Logic error - no proxy object set."); return 0; } void TEmulatedMapProxy::ReadMap(UInt_t nElements, TBuffer &b) { // Map input streamer. Bool_t vsn3 = b.GetInfo() && b.GetInfo()->GetOldVersion()<=3; int idx, loop, off[2] = {0, fValOffset }; Value *v, *val[2] = { fKey, fVal }; StreamHelper* helper; float f; char* addr = 0; char* temp = (char*)At(0); for ( idx = 0; idx < nElements; ++idx ) { addr = temp + idx*fValDiff; for ( loop=0; loop<2; loop++) { addr += off[loop]; helper = (StreamHelper*)addr; v = val[loop]; switch (v->fCase) { case G__BIT_ISFUNDAMENTAL: // Only handle primitives this way case G__BIT_ISENUM: switch( int(v->fKind) ) { case kBool_t: b >> helper->boolean; break; case kChar_t: b >> helper->s_char; break; case kShort_t: b >> helper->s_short; break; case kInt_t: b >> helper->s_int; break; case kLong_t: b >> helper->s_long; break; case kLong64_t: b >> helper->s_longlong; break; case kFloat_t: b >> helper->flt; break; case kFloat16_t: b >> f; helper->flt = float(f); break; case kDouble_t: b >> helper->dbl; break; case kBOOL_t: b >> helper->boolean; break; case kUChar_t: b >> helper->u_char; break; case kUShort_t: b >> helper->u_short; break; case kUInt_t: b >> helper->u_int; break; case kULong_t: b >> helper->u_long; break; case kULong64_t: b >> helper->u_longlong; break; case kDouble32_t:b >> f; helper->dbl = double(f); break; case kchar: case kNoType_t: case kOther_t: Error("TEmulatedMapProxy","fType %d is not supported yet!\n",v->fKind); } break; case G__BIT_ISCLASS: b.StreamObject(helper,v->fType); break; case kBIT_ISSTRING: helper->read_std_string(b); break; case G__BIT_ISPOINTER|G__BIT_ISCLASS: helper->set(b.ReadObjectAny(v->fType)); break; case G__BIT_ISPOINTER|kBIT_ISSTRING: helper->read_std_string_pointer(b); break; case G__BIT_ISPOINTER|kBIT_ISTSTRING|G__BIT_ISCLASS: helper->read_tstring_pointer(vsn3,b); break; } } } } void TEmulatedMapProxy::WriteMap(UInt_t nElements, TBuffer &b) { // Map output streamer. Value *v, *val[2] = { fKey, fVal }; int off[2] = { 0, fValOffset }; StreamHelper* i; char* addr = 0; char* temp = (char*)At(0); for (int loop, idx = 0; idx < nElements; ++idx ) { addr = temp + idx*fValDiff; for ( loop = 0; loop<2; ++loop ) { addr += off[loop]; i = (StreamHelper*)addr; v = val[loop]; switch (v->fCase) { case G__BIT_ISFUNDAMENTAL: // Only handle primitives this way case G__BIT_ISENUM: switch( int(v->fKind) ) { case kBool_t: b << i->boolean; break; case kChar_t: b << i->s_char; break; case kShort_t: b << i->s_short; break; case kInt_t: b << i->s_int; break; case kLong_t: b << i->s_long; break; case kLong64_t: b << i->s_longlong; break; case kFloat_t: b << i->flt; break; case kFloat16_t: b << float(i->flt); break; case kDouble_t: b << i->dbl; break; case kBOOL_t: b << i->boolean; break; case kUChar_t: b << i->u_char; break; case kUShort_t: b << i->u_short; break; case kUInt_t: b << i->u_int; break; case kULong_t: b << i->u_long; break; case kULong64_t: b << i->u_longlong; break; case kDouble32_t:b << float(i->dbl); break; case kchar: case kNoType_t: case kOther_t: Error("TEmulatedMapProxy","fType %d is not supported yet!\n",v->fKind); } break; case G__BIT_ISCLASS: b.StreamObject(i,v->fType); break; case kBIT_ISSTRING: TString(i->c_str()).Streamer(b); break; case G__BIT_ISPOINTER|G__BIT_ISCLASS: b.WriteObjectAny(i->ptr(),v->fType); break; case kBIT_ISSTRING|G__BIT_ISPOINTER: i->write_std_string_pointer(b); break; case kBIT_ISTSTRING|G__BIT_ISCLASS|G__BIT_ISPOINTER: i->write_tstring_pointer(b); break; } } } } void TEmulatedMapProxy::ReadBuffer(TBuffer &b, void *obj, const TClass *onfileClass) { // Read portion of the streamer. SetOnFileClass((TClass*)onfileClass); ReadBuffer(b,obj); } void TEmulatedMapProxy::ReadBuffer(TBuffer &b, void *obj) { // Read portion of the streamer. TPushPop env(this,obj); int nElements = 0; b >> nElements; if ( fEnv->fObject ) { Resize(nElements,true); } if ( nElements > 0 ) { ReadMap(nElements, b); } } void TEmulatedMapProxy::Streamer(TBuffer &b) { // TClassStreamer IO overload. if ( b.IsReading() ) { //Read mode UInt_t nElements = 0; b >> nElements; if ( fEnv->fObject ) { Resize(nElements,true); } if ( nElements > 0 ) { ReadMap(nElements, b); } } else { // Write case UInt_t nElements = fEnv->fObject ? Size() : 0; b << nElements; if ( nElements > 0 ) { WriteMap(nElements, b); } } } <commit_msg>two more instance of Int_t -> UInt_t<commit_after>// @(#)root/io:$Id$ // Author: Markus Frank 28/10/04 /************************************************************************* * 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. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TEmulatedMapProxy // // Streamer around an arbitrary container, which implements basic // functionality and iteration. // // In particular this is used to implement splitting and abstract // element access of any container. Access to compiled code is necessary // to implement the abstract iteration sequence and functionality like // size(), clear(), resize(). resize() may be a void operation. // ////////////////////////////////////////////////////////////////////////// #include "TEmulatedMapProxy.h" #include "TClassEdit.h" #include "TStreamerInfo.h" #include "TError.h" TEmulatedMapProxy::TEmulatedMapProxy(const TEmulatedMapProxy& copy) : TEmulatedCollectionProxy(copy) { // copy constructor if ( !(fSTL_type == TClassEdit::kMap || fSTL_type == TClassEdit::kMultiMap) ) { Fatal("TEmulatedMapProxy","Class %s is not a map-type!",fName.c_str()); } } TEmulatedMapProxy::TEmulatedMapProxy(const char* cl_name, Bool_t silent) : TEmulatedCollectionProxy(cl_name, silent) { // Build a Streamer for an emulated vector whose type is 'name'. if ( !(fSTL_type == TClassEdit::kMap || fSTL_type == TClassEdit::kMultiMap) ) { Fatal("TEmulatedMapProxy","Class %s is not a map-type!",fName.c_str()); } } TEmulatedMapProxy::~TEmulatedMapProxy() { // Standard destructor. } TVirtualCollectionProxy* TEmulatedMapProxy::Generate() const { // Virtual copy constructor. if ( !fClass ) Initialize(kFALSE); return new TEmulatedMapProxy(*this); } void* TEmulatedMapProxy::At(UInt_t idx) { // Return the address of the value at index 'idx'. if ( fEnv && fEnv->fObject ) { PCont_t c = PCont_t(fEnv->fObject); return idx<(c->size()/fValDiff) ? ((char*)&(*c->begin())) + idx*fValDiff : 0; } Fatal("TEmulatedMapProxy","At> Logic error - no proxy object set."); return 0; } UInt_t TEmulatedMapProxy::Size() const { // Return the current size of the container. if ( fEnv && fEnv->fObject ) { PCont_t c = PCont_t(fEnv->fObject); return fEnv->fSize = (c->size()/fValDiff); } Fatal("TEmulatedMapProxy","Size> Logic error - no proxy object set."); return 0; } void TEmulatedMapProxy::ReadMap(UInt_t nElements, TBuffer &b) { // Map input streamer. Bool_t vsn3 = b.GetInfo() && b.GetInfo()->GetOldVersion()<=3; UInt_t idx, loop; Int_t off[2] = {0, fValOffset }; Value *v, *val[2] = { fKey, fVal }; StreamHelper* helper; float f; char* addr = 0; char* temp = (char*)At(0); for ( idx = 0; idx < nElements; ++idx ) { addr = temp + idx*fValDiff; for ( loop=0; loop<2; loop++) { addr += off[loop]; helper = (StreamHelper*)addr; v = val[loop]; switch (v->fCase) { case G__BIT_ISFUNDAMENTAL: // Only handle primitives this way case G__BIT_ISENUM: switch( int(v->fKind) ) { case kBool_t: b >> helper->boolean; break; case kChar_t: b >> helper->s_char; break; case kShort_t: b >> helper->s_short; break; case kInt_t: b >> helper->s_int; break; case kLong_t: b >> helper->s_long; break; case kLong64_t: b >> helper->s_longlong; break; case kFloat_t: b >> helper->flt; break; case kFloat16_t: b >> f; helper->flt = float(f); break; case kDouble_t: b >> helper->dbl; break; case kBOOL_t: b >> helper->boolean; break; case kUChar_t: b >> helper->u_char; break; case kUShort_t: b >> helper->u_short; break; case kUInt_t: b >> helper->u_int; break; case kULong_t: b >> helper->u_long; break; case kULong64_t: b >> helper->u_longlong; break; case kDouble32_t:b >> f; helper->dbl = double(f); break; case kchar: case kNoType_t: case kOther_t: Error("TEmulatedMapProxy","fType %d is not supported yet!\n",v->fKind); } break; case G__BIT_ISCLASS: b.StreamObject(helper,v->fType); break; case kBIT_ISSTRING: helper->read_std_string(b); break; case G__BIT_ISPOINTER|G__BIT_ISCLASS: helper->set(b.ReadObjectAny(v->fType)); break; case G__BIT_ISPOINTER|kBIT_ISSTRING: helper->read_std_string_pointer(b); break; case G__BIT_ISPOINTER|kBIT_ISTSTRING|G__BIT_ISCLASS: helper->read_tstring_pointer(vsn3,b); break; } } } } void TEmulatedMapProxy::WriteMap(UInt_t nElements, TBuffer &b) { // Map output streamer. Value *v, *val[2] = { fKey, fVal }; int off[2] = { 0, fValOffset }; StreamHelper* i; char* addr = 0; char* temp = (char*)At(0); for (UInt_t loop, idx = 0; idx < nElements; ++idx ) { addr = temp + idx*fValDiff; for ( loop = 0; loop<2; ++loop ) { addr += off[loop]; i = (StreamHelper*)addr; v = val[loop]; switch (v->fCase) { case G__BIT_ISFUNDAMENTAL: // Only handle primitives this way case G__BIT_ISENUM: switch( int(v->fKind) ) { case kBool_t: b << i->boolean; break; case kChar_t: b << i->s_char; break; case kShort_t: b << i->s_short; break; case kInt_t: b << i->s_int; break; case kLong_t: b << i->s_long; break; case kLong64_t: b << i->s_longlong; break; case kFloat_t: b << i->flt; break; case kFloat16_t: b << float(i->flt); break; case kDouble_t: b << i->dbl; break; case kBOOL_t: b << i->boolean; break; case kUChar_t: b << i->u_char; break; case kUShort_t: b << i->u_short; break; case kUInt_t: b << i->u_int; break; case kULong_t: b << i->u_long; break; case kULong64_t: b << i->u_longlong; break; case kDouble32_t:b << float(i->dbl); break; case kchar: case kNoType_t: case kOther_t: Error("TEmulatedMapProxy","fType %d is not supported yet!\n",v->fKind); } break; case G__BIT_ISCLASS: b.StreamObject(i,v->fType); break; case kBIT_ISSTRING: TString(i->c_str()).Streamer(b); break; case G__BIT_ISPOINTER|G__BIT_ISCLASS: b.WriteObjectAny(i->ptr(),v->fType); break; case kBIT_ISSTRING|G__BIT_ISPOINTER: i->write_std_string_pointer(b); break; case kBIT_ISTSTRING|G__BIT_ISCLASS|G__BIT_ISPOINTER: i->write_tstring_pointer(b); break; } } } } void TEmulatedMapProxy::ReadBuffer(TBuffer &b, void *obj, const TClass *onfileClass) { // Read portion of the streamer. SetOnFileClass((TClass*)onfileClass); ReadBuffer(b,obj); } void TEmulatedMapProxy::ReadBuffer(TBuffer &b, void *obj) { // Read portion of the streamer. TPushPop env(this,obj); int nElements = 0; b >> nElements; if ( fEnv->fObject ) { Resize(nElements,true); } if ( nElements > 0 ) { ReadMap(nElements, b); } } void TEmulatedMapProxy::Streamer(TBuffer &b) { // TClassStreamer IO overload. if ( b.IsReading() ) { //Read mode UInt_t nElements = 0; b >> nElements; if ( fEnv->fObject ) { Resize(nElements,true); } if ( nElements > 0 ) { ReadMap(nElements, b); } } else { // Write case UInt_t nElements = fEnv->fObject ? Size() : 0; b << nElements; if ( nElements > 0 ) { WriteMap(nElements, b); } } } <|endoftext|>
<commit_before><commit_msg>Delete CPP_STRING.H<commit_after><|endoftext|>
<commit_before>#include "BasicCircular.h" #include "../../Utils.h" #include <cmath> using namespace DNest4; BasicCircular::BasicCircular(double x_min, double x_max, double y_min, double y_max, double mu_min, double mu_max) :x_min(x_min) ,x_max(x_max) ,y_min(y_min) ,y_max(y_max) ,size(sqrt((x_max - x_min)*(y_max - y_min))) ,mu_min(mu_min) ,mu_max(mu_max) { } void BasicCircular::from_prior(RNG& rng) { xc = x_min + (x_max - x_min)*rng.rand(); yc = y_min + (y_max - y_min)*rng.rand(); width = exp(log(1E-2*size) + log(1E3)*rng.rand()); mu = exp(log(mu_min) + log(mu_max/mu_min)*rng.rand()); } double BasicCircular::perturb_hyperparameters(RNG& rng) { double logH = 0.; int which = rng.rand_int(3); if(which == 0) { double scale = size*pow(10., 1.5 - 6.*rng.rand()); xc += scale*rng.randn(); yc += scale*rng.randn(); xc = DNest4::mod(xc - x_min, x_max - x_min) + x_min; yc = DNest4::mod(yc - y_min, y_max - y_min) + y_min; } else if(which == 1) { width = log(width); width += log(1E3)*rng.randh(); width = DNest4::mod(width - log(1E-2*size), log(1E3)) + log(1E-2*size); width = exp(width); } else if(which == 2) { mu = log(mu); mu += log(mu_max/mu_min)*rng.randh(); mu = DNest4::mod(mu - log(mu_min), log(mu_max/mu_min)) + log(mu_min); mu = exp(mu); } return logH; } double BasicCircular::log_pdf(const std::vector<double>& vec) const { if(vec[2] < 0.) return -1E300; double logp = 0.; double r = sqrt(pow(vec[0] - xc, 2) + pow(vec[1] - yc, 2)); logp += -log(r) - log(width) - r/width; logp += -log(mu) - vec[2]/mu; return logp; } void BasicCircular::from_uniform(std::vector<double>& vec) const { double r = -width*log(1. - vec[0]); double phi = 2.*M_PI*vec[1]; vec[0] = xc + r*cos(phi); vec[1] = yc + r*sin(phi); vec[2] = -mu*log(1. - vec[2]); } void BasicCircular::to_uniform(std::vector<double>& vec) const { double r = sqrt(pow(vec[0] - xc, 2) + pow(vec[1] - yc, 2)); double phi = atan2(vec[1] - yc, vec[0] - xc); if(phi < 0.) phi += 2.*M_PI; vec[0] = 1. - exp(-r/width); vec[1] = phi/(2.*M_PI); vec[2] = 1. - exp(-vec[2]/mu); } void BasicCircular::print(std::ostream& out) const { out<<xc<<' '<<yc<<' '<<width<<' '<<mu<<' '; } <commit_msg>Use randh here<commit_after>#include "BasicCircular.h" #include "../../Utils.h" #include <cmath> using namespace DNest4; BasicCircular::BasicCircular(double x_min, double x_max, double y_min, double y_max, double mu_min, double mu_max) :x_min(x_min) ,x_max(x_max) ,y_min(y_min) ,y_max(y_max) ,size(sqrt((x_max - x_min)*(y_max - y_min))) ,mu_min(mu_min) ,mu_max(mu_max) { } void BasicCircular::from_prior(RNG& rng) { xc = x_min + (x_max - x_min)*rng.rand(); yc = y_min + (y_max - y_min)*rng.rand(); width = exp(log(1E-2*size) + log(1E3)*rng.rand()); mu = exp(log(mu_min) + log(mu_max/mu_min)*rng.rand()); } double BasicCircular::perturb_hyperparameters(RNG& rng) { double logH = 0.; int which = rng.rand_int(3); if(which == 0) { xc += size*rng.randh(); yc += size*rng.randh(); xc = DNest4::mod(xc - x_min, x_max - x_min) + x_min; yc = DNest4::mod(yc - y_min, y_max - y_min) + y_min; } else if(which == 1) { width = log(width); width += log(1E3)*rng.randh(); width = DNest4::mod(width - log(1E-2*size), log(1E3)) + log(1E-2*size); width = exp(width); } else if(which == 2) { mu = log(mu); mu += log(mu_max/mu_min)*rng.randh(); mu = DNest4::mod(mu - log(mu_min), log(mu_max/mu_min)) + log(mu_min); mu = exp(mu); } return logH; } double BasicCircular::log_pdf(const std::vector<double>& vec) const { if(vec[2] < 0.) return -1E300; double logp = 0.; double r = sqrt(pow(vec[0] - xc, 2) + pow(vec[1] - yc, 2)); logp += -log(r) - log(width) - r/width; logp += -log(mu) - vec[2]/mu; return logp; } void BasicCircular::from_uniform(std::vector<double>& vec) const { double r = -width*log(1. - vec[0]); double phi = 2.*M_PI*vec[1]; vec[0] = xc + r*cos(phi); vec[1] = yc + r*sin(phi); vec[2] = -mu*log(1. - vec[2]); } void BasicCircular::to_uniform(std::vector<double>& vec) const { double r = sqrt(pow(vec[0] - xc, 2) + pow(vec[1] - yc, 2)); double phi = atan2(vec[1] - yc, vec[0] - xc); if(phi < 0.) phi += 2.*M_PI; vec[0] = 1. - exp(-r/width); vec[1] = phi/(2.*M_PI); vec[2] = 1. - exp(-vec[2]/mu); } void BasicCircular::print(std::ostream& out) const { out<<xc<<' '<<yc<<' '<<width<<' '<<mu<<' '; } <|endoftext|>
<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2003-2004 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gadueditaccount.cpp // // 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 2 // of the License, or (at your option) 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, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301, USA. #include "gadueditaccount.h" #include "gaduaccount.h" #include "gaduprotocol.h" #include "gadusession.h" #include <qradiobutton.h> #include <qcombobox.h> #include <qlabel.h> #include <qstring.h> #include <qcheckbox.h> #include <qlineedit.h> #include <q3button.h> #include <qregexp.h> #include <qpushbutton.h> #include <q3groupbox.h> #include <klineedit.h> #include <kmessagebox.h> #include <kdebug.h> #include <klocale.h> #include <kpassworddialog.h> #include "kopetepasswordwidget.h" GaduEditAccount::GaduEditAccount( GaduProtocol* proto, Kopete::Account* ident, QWidget* parent ) : QWidget( parent ), KopeteEditAccountWidget( ident ), protocol_( proto ), rcmd( 0 ) { setupUi(this); #ifdef __GG_LIBGADU_HAVE_OPENSSL isSsl = true; #else isSsl = false; #endif useTls_->setDisabled( !isSsl ); if ( account() == NULL ) { useTls_->setCurrentIndex( GaduAccount::TLS_no ); registerNew->setEnabled( true ); account_ = NULL; } else { account_ = static_cast<GaduAccount*>(ident); registerNew->setDisabled( true ); loginEdit_->setReadOnly( true ); loginEdit_->setText( account_->accountId() ); passwordWidget_->load( &account_->password() ); QString nick = account()->myself()->property( Kopete::Global::Properties::self()->nickName() ).value().toString(); if ( nick.isEmpty() ) { nick = account_->myself()->contactId(); } nickName->setText( nick ); autoLoginCheck_->setChecked( account_->excludeConnect() ); dccCheck_->setChecked( account_->dccEnabled() ); useTls_->setCurrentIndex( isSsl ? ( account_->useTls() ) : 2 ); ignoreCheck_->setChecked( account_->ignoreAnons() ); connect( account(), SIGNAL( pubDirSearchResult( const SearchResult&, unsigned int ) ), SLOT( slotSearchResult( const SearchResult&, unsigned int ) ) ); connectLabel->setText( i18nc( "personal information being fetched from server", "<p align=\"center\">Fetching from server</p>" ) ); seqNr = account_->getPersonalInformation(); } connect( registerNew, SIGNAL( clicked( ) ), SLOT( registerNewAccount( ) ) ); QWidget::setTabOrder( loginEdit_, passwordWidget_->mRemembered ); QWidget::setTabOrder( passwordWidget_->mRemembered, passwordWidget_->mPassword ); QWidget::setTabOrder( passwordWidget_->mPassword, autoLoginCheck_ ); } void GaduEditAccount::publishUserInfo() { ResLine sr; enableUserInfo( false ); sr.firstname = uiName->text(); sr.surname = uiSurname->text(); sr.nickname = nickName->text(); sr.age = uiYOB->text(); sr.city = uiCity->text(); sr.meiden = uiMeiden->text(); sr.orgin = uiOrgin->text(); kDebug(14100) << uiGender->currentIndex() << " gender "; if ( uiGender->currentIndex() == 1 ) { kDebug(14100) << "so you become female now"; sr.gender = QString( GG_PUBDIR50_GENDER_SET_FEMALE ); } if ( uiGender->currentIndex() == 2 ) { kDebug(14100) << "so you become male now"; sr.gender = QString( GG_PUBDIR50_GENDER_SET_MALE ); } if ( account_ ) { account_->publishPersonalInformation( sr ); } } void GaduEditAccount::slotSearchResult( const SearchResult& result, unsigned int seq ) { if ( !( seq != 0 && seqNr != 0 && seq == seqNr ) ) { return; } connectLabel->setText( " " ); uiName->setText( result[0].firstname ); uiSurname->setText( result[0].surname ); nickName->setText( result[0].nickname ); uiYOB->setText( result[0].age ); uiCity->setText( result[0].city ); kDebug( 14100 ) << "gender found: " << result[0].gender; if ( result[0].gender == QString( GG_PUBDIR50_GENDER_SET_FEMALE ) ) { uiGender->setCurrentIndex( 1 ); kDebug(14100) << "looks like female"; } else { if ( result[0].gender == QString( GG_PUBDIR50_GENDER_SET_MALE ) ) { uiGender->setCurrentIndex( 2 ); kDebug( 14100 ) <<" looks like male"; } } uiMeiden->setText( result[0].meiden ); uiOrgin->setText( result[0].orgin ); enableUserInfo( true ); disconnect( SLOT( slotSearchResult( const SearchResult&, unsigned int ) ) ); } void GaduEditAccount::enableUserInfo( bool e ) { uiName->setEnabled( e ); uiSurname->setEnabled( e ); uiYOB->setEnabled( e ); uiCity->setEnabled( e ); uiGender->setEnabled( e ); uiMeiden->setEnabled( e ); uiOrgin->setEnabled( e ); // connectLabel->setEnabled( !e ); } void GaduEditAccount::registerNewAccount() { registerNew->setDisabled( true ); regDialog = new GaduRegisterAccount( NULL ); regDialog->setObjectName( QLatin1String("Register account dialog") ); connect( regDialog, SIGNAL( registeredNumber( unsigned int, QString ) ), SLOT( newUin( unsigned int, QString ) ) ); if ( regDialog->exec() != QDialog::Accepted ) { loginEdit_->setText( "" ); return; } registerNew->setDisabled( false ); } void GaduEditAccount::registrationFailed() { KMessageBox::sorry( this, i18n( "<b>Registration FAILED.</b>" ), i18n( "Gadu-Gadu" ) ); } void GaduEditAccount::newUin( unsigned int uin, QString password ) { if ( uin ) { loginEdit_->setText( QString::number( uin ) ); passwordWidget_->setPassword( password ); } else { // registration failed, enable button again registerNew->setDisabled( false ); } } bool GaduEditAccount::validateData() { if ( loginEdit_->text().isEmpty() ) { KMessageBox::sorry( this, i18n( "<b>Enter UIN please.</b>" ), i18n( "Gadu-Gadu" ) ); return false; } if ( loginEdit_->text().toInt() < 0 || loginEdit_->text().toInt() == 0 ) { KMessageBox::sorry( this, i18n( "<b>UIN should be a positive number.</b>" ), i18n( "Gadu-Gadu" ) ); return false; } if ( !passwordWidget_->validate() ) { KMessageBox::sorry( this, i18n( "<b>Enter password please.</b>" ), i18n( "Gadu-Gadu" ) ); return false; } return true; } Kopete::Account* GaduEditAccount::apply() { publishUserInfo(); if ( account() == NULL ) { setAccount( new GaduAccount( protocol_, loginEdit_->text() ) ); account_ = static_cast<GaduAccount*>( account() ); } account_->setExcludeConnect( autoLoginCheck_->isChecked() ); passwordWidget_->save( &account_->password() ); account_->myself()->setProperty( Kopete::Global::Properties::self()->nickName(), nickName->text() ); // this is changed only here, so i won't add any proper handling now account_->configGroup()->writeEntry( QString::fromAscii( "nickName" ), nickName->text() ); account_->setExcludeConnect( autoLoginCheck_->isChecked() ); account_->setUseTls( (GaduAccount::tlsConnection) useTls_->currentIndex() ); account_->setIgnoreAnons( ignoreCheck_->isChecked() ); if ( account_->setDcc( dccCheck_->isChecked() ) == false ) { KMessageBox::sorry( this, i18n( "<b>Starting DCC listening socket failed; dcc is not working now.</b>" ), i18n( "Gadu-Gadu" ) ); } return account(); } #include "gadueditaccount.moc" <commit_msg>Fix crash<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2003-2004 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gadueditaccount.cpp // // 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 2 // of the License, or (at your option) 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, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301, USA. #include "gadueditaccount.h" #include "gaduaccount.h" #include "gaduprotocol.h" #include "gadusession.h" #include <qradiobutton.h> #include <qcombobox.h> #include <qlabel.h> #include <qstring.h> #include <qcheckbox.h> #include <qlineedit.h> #include <q3button.h> #include <qregexp.h> #include <qpushbutton.h> #include <q3groupbox.h> #include <klineedit.h> #include <kmessagebox.h> #include <kdebug.h> #include <klocale.h> #include <kpassworddialog.h> #include "kopetepasswordwidget.h" GaduEditAccount::GaduEditAccount( GaduProtocol* proto, Kopete::Account* ident, QWidget* parent ) : QWidget( parent ), KopeteEditAccountWidget( ident ), protocol_( proto ), rcmd( 0 ) { setupUi(this); #ifdef __GG_LIBGADU_HAVE_OPENSSL isSsl = true; #else isSsl = false; #endif useTls_->setDisabled( !isSsl ); if ( account() == NULL ) { useTls_->setCurrentIndex( GaduAccount::TLS_no ); registerNew->setEnabled( true ); account_ = NULL; } else { account_ = static_cast<GaduAccount*>(ident); registerNew->setDisabled( true ); loginEdit_->setReadOnly( true ); loginEdit_->setText( account_->accountId() ); passwordWidget_->load( &account_->password() ); QString nick = account()->myself()->property( Kopete::Global::Properties::self()->nickName() ).value().toString(); if ( nick.isEmpty() ) { nick = account_->myself()->contactId(); } nickName->setText( nick ); autoLoginCheck_->setChecked( account_->excludeConnect() ); dccCheck_->setChecked( account_->dccEnabled() ); useTls_->setCurrentIndex( isSsl ? ( account_->useTls() ) : 2 ); ignoreCheck_->setChecked( account_->ignoreAnons() ); connect( account(), SIGNAL( pubDirSearchResult( const SearchResult&, unsigned int ) ), SLOT( slotSearchResult( const SearchResult&, unsigned int ) ) ); connectLabel->setText( i18nc( "personal information being fetched from server", "<p align=\"center\">Fetching from server</p>" ) ); seqNr = account_->getPersonalInformation(); } connect( registerNew, SIGNAL( clicked( ) ), SLOT( registerNewAccount( ) ) ); QWidget::setTabOrder( loginEdit_, passwordWidget_->mRemembered ); QWidget::setTabOrder( passwordWidget_->mRemembered, passwordWidget_->mPassword ); QWidget::setTabOrder( passwordWidget_->mPassword, autoLoginCheck_ ); } void GaduEditAccount::publishUserInfo() { ResLine sr; enableUserInfo( false ); sr.firstname = uiName->text(); sr.surname = uiSurname->text(); sr.nickname = nickName->text(); sr.age = uiYOB->text(); sr.city = uiCity->text(); sr.meiden = uiMeiden->text(); sr.orgin = uiOrgin->text(); kDebug(14100) << uiGender->currentIndex() << " gender "; if ( uiGender->currentIndex() == 1 ) { kDebug(14100) << "so you become female now"; sr.gender = QString( GG_PUBDIR50_GENDER_SET_FEMALE ); } if ( uiGender->currentIndex() == 2 ) { kDebug(14100) << "so you become male now"; sr.gender = QString( GG_PUBDIR50_GENDER_SET_MALE ); } if ( account_ ) { account_->publishPersonalInformation( sr ); } } void GaduEditAccount::slotSearchResult( const SearchResult& result, unsigned int seq ) { if ( !( seq != 0 && seqNr != 0 && seq == seqNr ) || result.isEmpty() ) { return; } connectLabel->setText( " " ); uiName->setText( result[0].firstname ); uiSurname->setText( result[0].surname ); nickName->setText( result[0].nickname ); uiYOB->setText( result[0].age ); uiCity->setText( result[0].city ); kDebug( 14100 ) << "gender found: " << result[0].gender; if ( result[0].gender == QString( GG_PUBDIR50_GENDER_SET_FEMALE ) ) { uiGender->setCurrentIndex( 1 ); kDebug(14100) << "looks like female"; } else { if ( result[0].gender == QString( GG_PUBDIR50_GENDER_SET_MALE ) ) { uiGender->setCurrentIndex( 2 ); kDebug( 14100 ) <<" looks like male"; } } uiMeiden->setText( result[0].meiden ); uiOrgin->setText( result[0].orgin ); enableUserInfo( true ); disconnect( SLOT( slotSearchResult( const SearchResult&, unsigned int ) ) ); } void GaduEditAccount::enableUserInfo( bool e ) { uiName->setEnabled( e ); uiSurname->setEnabled( e ); uiYOB->setEnabled( e ); uiCity->setEnabled( e ); uiGender->setEnabled( e ); uiMeiden->setEnabled( e ); uiOrgin->setEnabled( e ); // connectLabel->setEnabled( !e ); } void GaduEditAccount::registerNewAccount() { registerNew->setDisabled( true ); regDialog = new GaduRegisterAccount( NULL ); regDialog->setObjectName( QLatin1String("Register account dialog") ); connect( regDialog, SIGNAL( registeredNumber( unsigned int, QString ) ), SLOT( newUin( unsigned int, QString ) ) ); if ( regDialog->exec() != QDialog::Accepted ) { loginEdit_->setText( "" ); return; } registerNew->setDisabled( false ); } void GaduEditAccount::registrationFailed() { KMessageBox::sorry( this, i18n( "<b>Registration FAILED.</b>" ), i18n( "Gadu-Gadu" ) ); } void GaduEditAccount::newUin( unsigned int uin, QString password ) { if ( uin ) { loginEdit_->setText( QString::number( uin ) ); passwordWidget_->setPassword( password ); } else { // registration failed, enable button again registerNew->setDisabled( false ); } } bool GaduEditAccount::validateData() { if ( loginEdit_->text().isEmpty() ) { KMessageBox::sorry( this, i18n( "<b>Enter UIN please.</b>" ), i18n( "Gadu-Gadu" ) ); return false; } if ( loginEdit_->text().toInt() < 0 || loginEdit_->text().toInt() == 0 ) { KMessageBox::sorry( this, i18n( "<b>UIN should be a positive number.</b>" ), i18n( "Gadu-Gadu" ) ); return false; } if ( !passwordWidget_->validate() ) { KMessageBox::sorry( this, i18n( "<b>Enter password please.</b>" ), i18n( "Gadu-Gadu" ) ); return false; } return true; } Kopete::Account* GaduEditAccount::apply() { publishUserInfo(); if ( account() == NULL ) { setAccount( new GaduAccount( protocol_, loginEdit_->text() ) ); account_ = static_cast<GaduAccount*>( account() ); } account_->setExcludeConnect( autoLoginCheck_->isChecked() ); passwordWidget_->save( &account_->password() ); account_->myself()->setProperty( Kopete::Global::Properties::self()->nickName(), nickName->text() ); // this is changed only here, so i won't add any proper handling now account_->configGroup()->writeEntry( QString::fromAscii( "nickName" ), nickName->text() ); account_->setExcludeConnect( autoLoginCheck_->isChecked() ); account_->setUseTls( (GaduAccount::tlsConnection) useTls_->currentIndex() ); account_->setIgnoreAnons( ignoreCheck_->isChecked() ); if ( account_->setDcc( dccCheck_->isChecked() ) == false ) { KMessageBox::sorry( this, i18n( "<b>Starting DCC listening socket failed; dcc is not working now.</b>" ), i18n( "Gadu-Gadu" ) ); } return account(); } #include "gadueditaccount.moc" <|endoftext|>
<commit_before>/* incomingtransfer.cpp - msn p2p protocol Copyright (c) 2003-2005 by Olivier Goffart <ogoffart@ kde.org> Copyright (c) 2005 by Gregg Edghill <gregg.edghill@gmail.com> ************************************************************************* * * * 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 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "incomingtransfer.h" using P2P::TransferContext; using P2P::IncomingTransfer; using P2P::Message; // Kde includes #include <kbufferedsocket.h> #include <kdebug.h> #include <klocale.h> #include <kserversocket.h> #include <kstandarddirs.h> #include <ktempfile.h> using namespace KNetwork; // Qt includes #include <qfile.h> #include <qregexp.h> // Kopete includes #include <kopetetransfermanager.h> IncomingTransfer::IncomingTransfer(const QString& from, P2P::Dispatcher *dispatcher, Q_UINT32 sessionId) : TransferContext(from,dispatcher,sessionId) { m_direction = P2P::Incoming; m_listener = 0l; } IncomingTransfer::~IncomingTransfer() { kdDebug(14140) << k_funcinfo << endl; if(m_listener) { delete m_listener; m_listener = 0l; } if(m_socket) { delete m_socket; m_socket = 0l; } } void IncomingTransfer::slotTransferAccepted(Kopete::Transfer* transfer, const QString& /*fileName*/) { Q_UINT32 sessionId = transfer->info().internalId().toUInt(); if(sessionId!=m_sessionId) return; QObject::connect(transfer , SIGNAL(transferCanceled()), this, SLOT(abort())); m_transfer = transfer; QString content = QString("SessionID: %1\r\n\r\n").arg(sessionId); sendMessage(OK, content); QObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l); } void IncomingTransfer::slotTransferRefused(const Kopete::FileTransferInfo& info) { Q_UINT32 sessionId = info.internalId().toUInt(); if(sessionId!=m_sessionId) return; QString content = QString("SessionID: %1\r\n\r\n").arg(sessionId); // Send the sending client a cancelation message. sendMessage(DECLINE, content); m_state=Finished; QObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l); } void IncomingTransfer::acknowledged() { kdDebug(14140) << k_funcinfo << endl; switch(m_state) { case Invitation: // NOTE UDI: base identifier acknowledge message, ignore. // UDI: 200 OK message should follow. if(m_type == File){ // FT: 200 OK acknowledged message. // Direct connection invitation should follow. m_state = Negotiation; } break; case Negotiation: // 200 OK acknowledge message. break; case DataTransfer: break; case Finished: // UDI: Bye acknowledge message. m_dispatcher->detach(this); break; } } void IncomingTransfer::processMessage(const Message& message) { if(m_file && (message.header.flag == 0x20 || message.header.flag == 0x01000030)) { // UserDisplayIcon data or File data is in this message. // Write the recieved data to the file. kdDebug(14140) << k_funcinfo << QString("Received, %1 bytes").arg(message.header.dataSize) << endl; m_file->writeBlock(message.body.data(), message.header.dataSize); if(m_transfer){ m_transfer->slotProcessed(message.header.dataOffset + message.header.dataSize); } if((message.header.dataOffset + message.header.dataSize) == message.header.totalDataSize) { // Transfer is complete. if(m_type == UserDisplayIcon){ m_tempFile->close(); m_dispatcher->displayIconReceived(m_tempFile, m_object); m_tempFile = 0l; m_file = 0l; } else { m_file->close(); } m_isComplete = true; // Send data acknowledge message. acknowledge(message); if(m_type == UserDisplayIcon) { m_state = Finished; // Send BYE message. sendMessage(BYE, "\r\n"); } } } else if(message.header.dataSize == 4 && message.applicationIdentifier == 1) { // Data preparation message. m_tempFile = new KTempFile(locateLocal("tmp", "msnpicture--"), ".png"); m_tempFile->setAutoDelete(true); m_file = m_tempFile->file(); m_state = DataTransfer; // Send data preparation acknowledge message. acknowledge(message); } else { QString body = QCString(message.body.data(), message.header.dataSize); // kdDebug(14140) << k_funcinfo << "received, " << body << endl; if(body.startsWith("INVITE")) { // Retrieve some MSNSLP headers used when // replying to this INVITE message. QRegExp regex(";branch=\\{([0-9A-F\\-]*)\\}\r\n"); regex.search(body); m_branch = regex.cap(1); // NOTE Call-ID never changes. regex = QRegExp("Call-ID: \\{([0-9A-F\\-]*)\\}\r\n"); regex.search(body); m_callId = regex.cap(1); regex = QRegExp("Bridges: ([^\r\n]*)\r\n"); regex.search(body); QString bridges = regex.cap(1); // The NetID field is 0 if the Conn-Type is // Direct-Connect or Firewall, otherwise, it is // a randomly generated number. regex = QRegExp("NetID: (\\-?\\d+)\r\n"); regex.search(body); QString netId = regex.cap(1); kdDebug(14140) << "net id, " << netId << endl; // Connection Types // - Direct-Connect // - Port-Restrict-NAT // - IP-Restrict-NAT // - Symmetric-NAT // - Firewall regex = QRegExp("Conn-Type: ([^\r\n]+)\r\n"); regex.search(body); QString connType = regex.cap(1); bool wouldListen = false; if(netId.toUInt() == 0 && connType == "Direct-Connect"){ wouldListen = true; } else if(connType == "IP-Restrict-NAT"){ wouldListen = true; } #if 1 wouldListen = false; // TODO Direct connection support #endif QString content; if(wouldListen) { // Create a listening socket for direct file transfer. m_listener = new KServerSocket("", ""); m_listener->setResolutionEnabled(true); // Create the callback that will try to accept incoming connections. QObject::connect(m_listener, SIGNAL(readyAccept()), SLOT(slotAccept())); QObject::connect(m_listener, SIGNAL(gotError(int)), this, SLOT(slotListenError(int))); // Listen for incoming connections. bool isListening = m_listener->listen(1); kdDebug(14140) << k_funcinfo << (isListening ? "listening" : "not listening") << endl; kdDebug(14140) << k_funcinfo << "local endpoint, " << m_listener->localAddress().nodeName() << endl; content = "Bridge: TCPv1\r\n" "Listening: true\r\n" + QString("Hashed-Nonce: {%1}\r\n").arg(P2P::Uid::createUid()) + QString("IPv4Internal-Addrs: %1\r\n").arg(m_listener->localAddress().nodeName()) + QString("IPv4Internal-Port: %1\r\n").arg(m_listener->localAddress().serviceName()) + "\r\n"; } else { content = "Bridge: TCPv1\r\n" "Listening: false\r\n" "Hashed-Nonce: {00000000-0000-0000-0000-000000000000}\r\n" "\r\n"; } acknowledge(message); if(m_transfer) { // NOTE The sending client can ask for a direct connections // if one was established before. if(!m_file) { QFile *destionation = new QFile(m_transfer->destinationURL().path()); if(!destionation->open(IO_WriteOnly)) { if(m_transfer){ m_transfer->slotError(KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n("Cannot open file for writing")); m_transfer = 0l; } error(); return; } m_file = destionation; } else { // TODO } } m_state = DataTransfer; // Send 200 OK message to the sending client. sendMessage(OK, content); } else if(body.startsWith("BYE")) { m_state = Finished; // Send the sending client an acknowledge message. acknowledge(message); if(m_file && m_transfer) { if(m_isComplete){ // The transfer is complete. m_transfer->slotComplete(); } else { // The transfer has been canceled remotely. if(m_transfer){ // Inform the user of the file transfer cancelation. m_transfer->slotError(KIO::ERR_ABORTED, i18n("File transfer canceled.")); } // Remove the partially received file. m_file->remove(); } } // Dispose of this transfer context. m_dispatcher->detach(this); } else if(body.startsWith("MSNSLP/1.0 200 OK")) { if(m_type == UserDisplayIcon){ m_state = Negotiation; // Acknowledge the 200 OK message. acknowledge(message); } } } } void IncomingTransfer::slotListenError(int /*errorCode*/) { kdDebug(14140) << k_funcinfo << m_listener->errorString() << endl; } void IncomingTransfer::slotAccept() { // Try to accept an incoming connection from the sending client. m_socket = static_cast<KBufferedSocket*>(m_listener->accept()); if(!m_socket) { // NOTE If direct connection fails, the sending // client wil transfer the file data through the // existing session. kdDebug(14140) << k_funcinfo << "Direct connection failed." << endl; // Close the listening endpoint. m_listener->close(); return; } kdDebug(14140) << k_funcinfo << "Direct connection established." << endl; // Set the socket to non blocking, // enable the ready read signal and disable // ready write signal. // NOTE readyWrite consumes too much cpu usage. m_socket->setBlocking(false); m_socket->enableRead(true); m_socket->enableWrite(false); // Create the callback that will try to read bytes from the accepted socket. QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(slotSocketRead())); // Create the callback that will try to handle the socket close event. QObject::connect(m_socket, SIGNAL(closed()), this, SLOT(slotSocketClosed())); // Create the callback that will try to handle the socket error event. QObject::connect(m_socket, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int))); } void IncomingTransfer::slotSocketRead() { int available = m_socket->bytesAvailable(); kdDebug(14140) << k_funcinfo << available << ", bytes available." << endl; if(available > 0) { QByteArray buffer(available); m_socket->readBlock(buffer.data(), buffer.size()); if(QString(buffer) == "foo"){ kdDebug(14140) << "Connection Check." << endl; } } } void IncomingTransfer::slotSocketClosed() { kdDebug(14140) << k_funcinfo << endl; } void IncomingTransfer::slotSocketError(int errorCode) { kdDebug(14140) << k_funcinfo << errorCode << endl; } #include "incomingtransfer.moc" <commit_msg>CCBUG: 113525 better fix for msn filetransfers. much faster receiving from 7.5 users, but might have issues with trillian n'stuff. Thanks to Bartosz Fabianowski for this great patch :)<commit_after>/* incomingtransfer.cpp - msn p2p protocol Copyright (c) 2003-2005 by Olivier Goffart <ogoffart@ kde.org> Copyright (c) 2005 by Gregg Edghill <gregg.edghill@gmail.com> ************************************************************************* * * * 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 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "incomingtransfer.h" using P2P::TransferContext; using P2P::IncomingTransfer; using P2P::Message; // Kde includes #include <kbufferedsocket.h> #include <kdebug.h> #include <klocale.h> #include <kserversocket.h> #include <kstandarddirs.h> #include <ktempfile.h> using namespace KNetwork; // Qt includes #include <qfile.h> #include <qregexp.h> // Kopete includes #include <kopetetransfermanager.h> IncomingTransfer::IncomingTransfer(const QString& from, P2P::Dispatcher *dispatcher, Q_UINT32 sessionId) : TransferContext(from,dispatcher,sessionId) { m_direction = P2P::Incoming; m_listener = 0l; } IncomingTransfer::~IncomingTransfer() { kdDebug(14140) << k_funcinfo << endl; if(m_listener) { delete m_listener; m_listener = 0l; } if(m_socket) { delete m_socket; m_socket = 0l; } } void IncomingTransfer::slotTransferAccepted(Kopete::Transfer* transfer, const QString& /*fileName*/) { Q_UINT32 sessionId = transfer->info().internalId().toUInt(); if(sessionId!=m_sessionId) return; QObject::connect(transfer , SIGNAL(transferCanceled()), this, SLOT(abort())); m_transfer = transfer; QString content = QString("SessionID: %1\r\n\r\n").arg(sessionId); sendMessage(OK, content); QObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l); } void IncomingTransfer::slotTransferRefused(const Kopete::FileTransferInfo& info) { Q_UINT32 sessionId = info.internalId().toUInt(); if(sessionId!=m_sessionId) return; QString content = QString("SessionID: %1\r\n\r\n").arg(sessionId); // Send the sending client a cancelation message. sendMessage(DECLINE, content); m_state=Finished; QObject::disconnect(Kopete::TransferManager::transferManager(), 0l, this, 0l); } void IncomingTransfer::acknowledged() { kdDebug(14140) << k_funcinfo << endl; switch(m_state) { case Invitation: // NOTE UDI: base identifier acknowledge message, ignore. // UDI: 200 OK message should follow. if(m_type == File) { // FT: 200 OK acknowledged message. // If this is the first connection between the two clients, a direct connection invitation // should follow. Otherwise, the file transfer may start right away. if(m_transfer) { QFile *destination = new QFile(m_transfer->destinationURL().path()); if(!destination->open(IO_WriteOnly)) { m_transfer->slotError(KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n("Cannot open file for writing")); m_transfer = 0l; error(); return; } m_file = destination; } m_state = Negotiation; } break; case Negotiation: // 200 OK acknowledge message. break; case DataTransfer: break; case Finished: // UDI: Bye acknowledge message. m_dispatcher->detach(this); break; } } void IncomingTransfer::processMessage(const Message& message) { if(m_file && (message.header.flag == 0x20 || message.header.flag == 0x01000030)) { // UserDisplayIcon data or File data is in this message. // Write the recieved data to the file. kdDebug(14140) << k_funcinfo << QString("Received, %1 bytes").arg(message.header.dataSize) << endl; m_file->writeBlock(message.body.data(), message.header.dataSize); if(m_transfer){ m_transfer->slotProcessed(message.header.dataOffset + message.header.dataSize); } if((message.header.dataOffset + message.header.dataSize) == message.header.totalDataSize) { // Transfer is complete. if(m_type == UserDisplayIcon){ m_tempFile->close(); m_dispatcher->displayIconReceived(m_tempFile, m_object); m_tempFile = 0l; m_file = 0l; } else { m_file->close(); } m_isComplete = true; // Send data acknowledge message. acknowledge(message); if(m_type == UserDisplayIcon) { m_state = Finished; // Send BYE message. sendMessage(BYE, "\r\n"); } } } else if(message.header.dataSize == 4 && message.applicationIdentifier == 1) { // Data preparation message. m_tempFile = new KTempFile(locateLocal("tmp", "msnpicture--"), ".png"); m_tempFile->setAutoDelete(true); m_file = m_tempFile->file(); m_state = DataTransfer; // Send data preparation acknowledge message. acknowledge(message); } else { QString body = QCString(message.body.data(), message.header.dataSize); // kdDebug(14140) << k_funcinfo << "received, " << body << endl; if(body.startsWith("INVITE")) { // Retrieve some MSNSLP headers used when // replying to this INVITE message. QRegExp regex(";branch=\\{([0-9A-F\\-]*)\\}\r\n"); regex.search(body); m_branch = regex.cap(1); // NOTE Call-ID never changes. regex = QRegExp("Call-ID: \\{([0-9A-F\\-]*)\\}\r\n"); regex.search(body); m_callId = regex.cap(1); regex = QRegExp("Bridges: ([^\r\n]*)\r\n"); regex.search(body); QString bridges = regex.cap(1); // The NetID field is 0 if the Conn-Type is // Direct-Connect or Firewall, otherwise, it is // a randomly generated number. regex = QRegExp("NetID: (\\-?\\d+)\r\n"); regex.search(body); QString netId = regex.cap(1); kdDebug(14140) << "net id, " << netId << endl; // Connection Types // - Direct-Connect // - Port-Restrict-NAT // - IP-Restrict-NAT // - Symmetric-NAT // - Firewall regex = QRegExp("Conn-Type: ([^\r\n]+)\r\n"); regex.search(body); QString connType = regex.cap(1); bool wouldListen = false; if(netId.toUInt() == 0 && connType == "Direct-Connect"){ wouldListen = true; } else if(connType == "IP-Restrict-NAT"){ wouldListen = true; } #if 1 wouldListen = false; // TODO Direct connection support #endif QString content; if(wouldListen) { // Create a listening socket for direct file transfer. m_listener = new KServerSocket("", ""); m_listener->setResolutionEnabled(true); // Create the callback that will try to accept incoming connections. QObject::connect(m_listener, SIGNAL(readyAccept()), SLOT(slotAccept())); QObject::connect(m_listener, SIGNAL(gotError(int)), this, SLOT(slotListenError(int))); // Listen for incoming connections. bool isListening = m_listener->listen(1); kdDebug(14140) << k_funcinfo << (isListening ? "listening" : "not listening") << endl; kdDebug(14140) << k_funcinfo << "local endpoint, " << m_listener->localAddress().nodeName() << endl; content = "Bridge: TCPv1\r\n" "Listening: true\r\n" + QString("Hashed-Nonce: {%1}\r\n").arg(P2P::Uid::createUid()) + QString("IPv4Internal-Addrs: %1\r\n").arg(m_listener->localAddress().nodeName()) + QString("IPv4Internal-Port: %1\r\n").arg(m_listener->localAddress().serviceName()) + "\r\n"; } else { content = "Bridge: TCPv1\r\n" "Listening: false\r\n" "Hashed-Nonce: {00000000-0000-0000-0000-000000000000}\r\n" "\r\n"; } m_state = DataTransfer; if (m_type != File) { // NOTE For file transfers, the connection invite *must not* be acknowledged in any way // as this trips MSN 7.5 acknowledge(message); // Send 200 OK message to the sending client. sendMessage(OK, content); } } else if(body.startsWith("BYE")) { m_state = Finished; // Send the sending client an acknowledge message. acknowledge(message); if(m_file && m_transfer) { if(m_isComplete){ // The transfer is complete. m_transfer->slotComplete(); } else { // The transfer has been canceled remotely. if(m_transfer){ // Inform the user of the file transfer cancelation. m_transfer->slotError(KIO::ERR_ABORTED, i18n("File transfer canceled.")); } // Remove the partially received file. m_file->remove(); } } // Dispose of this transfer context. m_dispatcher->detach(this); } else if(body.startsWith("MSNSLP/1.0 200 OK")) { if(m_type == UserDisplayIcon){ m_state = Negotiation; // Acknowledge the 200 OK message. acknowledge(message); } } } } void IncomingTransfer::slotListenError(int /*errorCode*/) { kdDebug(14140) << k_funcinfo << m_listener->errorString() << endl; } void IncomingTransfer::slotAccept() { // Try to accept an incoming connection from the sending client. m_socket = static_cast<KBufferedSocket*>(m_listener->accept()); if(!m_socket) { // NOTE If direct connection fails, the sending // client wil transfer the file data through the // existing session. kdDebug(14140) << k_funcinfo << "Direct connection failed." << endl; // Close the listening endpoint. m_listener->close(); return; } kdDebug(14140) << k_funcinfo << "Direct connection established." << endl; // Set the socket to non blocking, // enable the ready read signal and disable // ready write signal. // NOTE readyWrite consumes too much cpu usage. m_socket->setBlocking(false); m_socket->enableRead(true); m_socket->enableWrite(false); // Create the callback that will try to read bytes from the accepted socket. QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(slotSocketRead())); // Create the callback that will try to handle the socket close event. QObject::connect(m_socket, SIGNAL(closed()), this, SLOT(slotSocketClosed())); // Create the callback that will try to handle the socket error event. QObject::connect(m_socket, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int))); } void IncomingTransfer::slotSocketRead() { int available = m_socket->bytesAvailable(); kdDebug(14140) << k_funcinfo << available << ", bytes available." << endl; if(available > 0) { QByteArray buffer(available); m_socket->readBlock(buffer.data(), buffer.size()); if(QString(buffer) == "foo"){ kdDebug(14140) << "Connection Check." << endl; } } } void IncomingTransfer::slotSocketClosed() { kdDebug(14140) << k_funcinfo << endl; } void IncomingTransfer::slotSocketError(int errorCode) { kdDebug(14140) << k_funcinfo << errorCode << endl; } #include "incomingtransfer.moc" <|endoftext|>
<commit_before>AliProtonAnalysisBase *GetProtonAnalysisBaseObject(const char* analysisLevel = "ESD", const char* esdAnalysisType = "Hybrid", const char* pidMode = "Bayesian") { //Function to setup the AliProtonAnalysisBase object and return it AliProtonAnalysisBase *baseAnalysis = new AliProtonAnalysisBase(); //baseAnalysis->SetDebugMode(); baseAnalysis->SetAnalysisLevel(analysisLevel); if(analysisLevel == "ESD") { baseAnalysis->SetTriggerMode(AliProtonAnalysisBase::kMB2); baseAnalysis->SetMinTPCClusters(110); baseAnalysis->SetMaxChi2PerTPCCluster(2.2); baseAnalysis->SetMaxCov11(0.5); baseAnalysis->SetMaxCov22(0.5); baseAnalysis->SetMaxCov33(0.5); baseAnalysis->SetMaxCov44(0.5); baseAnalysis->SetMaxCov55(0.5); baseAnalysis->SetMinTPCdEdxPoints(80); switch(esdAnalysisType) { case "TPC": baseAnalysis->SetAnalysisMode(AliProtonAnalysisBase::kTPC); baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); baseAnalysis->SetTPCpid(); baseAnalysis->SetMaxSigmaToVertexTPC(2.0); //baseAnalysis->SetMaxDCAXYTPC(1.5); //baseAnalysis->SetMaxDCAZTPC(1.5); break; case "Hybrid": baseAnalysis->SetAnalysisMode(AliProtonAnalysisBase::kHybrid); baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); //baseAnalysis->SetPhaseSpace(18, -0.9, 0.9, 32, 0.5, 1.3); baseAnalysis->SetTPCpid(); baseAnalysis->SetMaxSigmaToVertex(2.0); /*baseAnalysis->SetMaxDCAXY(1.5); baseAnalysis->SetMaxDCAZ(1.5);*/ baseAnalysis->SetPointOnITSLayer6(); baseAnalysis->SetPointOnITSLayer5(); baseAnalysis->SetPointOnITSLayer4(); baseAnalysis->SetPointOnITSLayer3(); baseAnalysis->SetPointOnITSLayer2(); baseAnalysis->SetPointOnITSLayer1(); baseAnalysis->SetMinITSClusters(4); break; case "Global": baseAnalysis->SetAnalysisMode(AliProtonAnalysisBase::kGlobal); baseAnalysis->SetPhaseSpace(20, -1.0, 1.0, 48, 0.3, 1.5); baseAnalysis->SetMaxSigmaToVertex(2.0); //baseAnalysis->SetMaxDCAXY(2.0); //baseAnalysis->SetMaxDCAZ(2.0); baseAnalysis->SetTPCRefit(); baseAnalysis->SetPointOnITSLayer1(); baseAnalysis->SetPointOnITSLayer2(); //baseAnalysis->SetPointOnITSLayer3(); //baseAnalysis->SetPointOnITSLayer4(); baseAnalysis->SetPointOnITSLayer5(); baseAnalysis->SetPointOnITSLayer6(); baseAnalysis->SetMinITSClusters(5); baseAnalysis->SetITSRefit(); baseAnalysis->SetESDpid(); baseAnalysis->SetTOFpid(); break; default: break; } baseAnalysis->SetAcceptedVertexDiamond(5.,5.,15.); baseAnalysis->SetEtaMode(); switch(pidMode) { case "Bayesian": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kBayesian); //Momentum dependent priors /*TFile *f = TFile::Open("$ALICE_ROOT/PWG2/data/PriorProbabilities.root "); TF1 *fitElectrons = (TF1 *)f->Get("fitElectrons"); TF1 *fitMuons = (TF1 *)f->Get("fitMuons"); TF1 *fitPions = (TF1 *)f->Get("fitPions"); TF1 *fitKaons = (TF1 *)f->Get("fitKaons"); TF1 *fitProtons = (TF1 *)f->Get("fitProtons"); baseAnalysis->SetPriorProbabilityFunctions(fitElectrons, fitMuons, fitPions, fitKaons, fitProtons);*/ //Fixed prior probabilities Double_t partFrac[5] = {0.01, 0.01, 0.85, 0.10, 0.05}; if(!baseAnalysis->IsPriorProbabilityFunctionUsed()) baseAnalysis->SetPriorProbabilities(partFrac); break; case "Ratio": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kRatio); break; case "Sigma1": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kSigma1); baseAnalysis->SetNSigma(3); baseAnalysis->SetdEdxBandInfo("$ALICE_ROOT/PWG2/data/protonsdEdxInfo.dat"); break; case "Sigma2": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kSigma2); baseAnalysis->SetNSigma(3); baseAnalysis->SetdEdxBandInfo("$ALICE_ROOT/PWG2/data/protonsdEdxInfo.dat"); break; default: break; }//PID mode }//ESD if(analysisLevel == "MC") baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); if(analysisLevel == "AOD") { baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); return baseAnalysis; } <commit_msg>Extra { removed<commit_after>AliProtonAnalysisBase *GetProtonAnalysisBaseObject(const char* analysisLevel = "ESD", const char* esdAnalysisType = "Hybrid", const char* pidMode = "Bayesian") { //Function to setup the AliProtonAnalysisBase object and return it AliProtonAnalysisBase *baseAnalysis = new AliProtonAnalysisBase(); //baseAnalysis->SetDebugMode(); baseAnalysis->SetAnalysisLevel(analysisLevel); if(analysisLevel == "ESD") { baseAnalysis->SetTriggerMode(AliProtonAnalysisBase::kMB2); baseAnalysis->SetMinTPCClusters(110); baseAnalysis->SetMaxChi2PerTPCCluster(2.2); baseAnalysis->SetMaxCov11(0.5); baseAnalysis->SetMaxCov22(0.5); baseAnalysis->SetMaxCov33(0.5); baseAnalysis->SetMaxCov44(0.5); baseAnalysis->SetMaxCov55(0.5); baseAnalysis->SetMinTPCdEdxPoints(80); switch(esdAnalysisType) { case "TPC": baseAnalysis->SetAnalysisMode(AliProtonAnalysisBase::kTPC); baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); baseAnalysis->SetTPCpid(); baseAnalysis->SetMaxSigmaToVertexTPC(2.0); //baseAnalysis->SetMaxDCAXYTPC(1.5); //baseAnalysis->SetMaxDCAZTPC(1.5); break; case "Hybrid": baseAnalysis->SetAnalysisMode(AliProtonAnalysisBase::kHybrid); baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); //baseAnalysis->SetPhaseSpace(18, -0.9, 0.9, 32, 0.5, 1.3); baseAnalysis->SetTPCpid(); baseAnalysis->SetMaxSigmaToVertex(2.0); /*baseAnalysis->SetMaxDCAXY(1.5); baseAnalysis->SetMaxDCAZ(1.5);*/ baseAnalysis->SetPointOnITSLayer6(); baseAnalysis->SetPointOnITSLayer5(); baseAnalysis->SetPointOnITSLayer4(); baseAnalysis->SetPointOnITSLayer3(); baseAnalysis->SetPointOnITSLayer2(); baseAnalysis->SetPointOnITSLayer1(); baseAnalysis->SetMinITSClusters(4); break; case "Global": baseAnalysis->SetAnalysisMode(AliProtonAnalysisBase::kGlobal); baseAnalysis->SetPhaseSpace(20, -1.0, 1.0, 48, 0.3, 1.5); baseAnalysis->SetMaxSigmaToVertex(2.0); //baseAnalysis->SetMaxDCAXY(2.0); //baseAnalysis->SetMaxDCAZ(2.0); baseAnalysis->SetTPCRefit(); baseAnalysis->SetPointOnITSLayer1(); baseAnalysis->SetPointOnITSLayer2(); //baseAnalysis->SetPointOnITSLayer3(); //baseAnalysis->SetPointOnITSLayer4(); baseAnalysis->SetPointOnITSLayer5(); baseAnalysis->SetPointOnITSLayer6(); baseAnalysis->SetMinITSClusters(5); baseAnalysis->SetITSRefit(); baseAnalysis->SetESDpid(); baseAnalysis->SetTOFpid(); break; default: break; } baseAnalysis->SetAcceptedVertexDiamond(5.,5.,15.); baseAnalysis->SetEtaMode(); switch(pidMode) { case "Bayesian": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kBayesian); //Momentum dependent priors /*TFile *f = TFile::Open("$ALICE_ROOT/PWG2/data/PriorProbabilities.root "); TF1 *fitElectrons = (TF1 *)f->Get("fitElectrons"); TF1 *fitMuons = (TF1 *)f->Get("fitMuons"); TF1 *fitPions = (TF1 *)f->Get("fitPions"); TF1 *fitKaons = (TF1 *)f->Get("fitKaons"); TF1 *fitProtons = (TF1 *)f->Get("fitProtons"); baseAnalysis->SetPriorProbabilityFunctions(fitElectrons, fitMuons, fitPions, fitKaons, fitProtons);*/ //Fixed prior probabilities Double_t partFrac[5] = {0.01, 0.01, 0.85, 0.10, 0.05}; if(!baseAnalysis->IsPriorProbabilityFunctionUsed()) baseAnalysis->SetPriorProbabilities(partFrac); break; case "Ratio": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kRatio); break; case "Sigma1": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kSigma1); baseAnalysis->SetNSigma(3); baseAnalysis->SetdEdxBandInfo("$ALICE_ROOT/PWG2/data/protonsdEdxInfo.dat"); break; case "Sigma2": baseAnalysis->SetPIDMode(AliProtonAnalysisBase::kSigma2); baseAnalysis->SetNSigma(3); baseAnalysis->SetdEdxBandInfo("$ALICE_ROOT/PWG2/data/protonsdEdxInfo.dat"); break; default: break; }//PID mode }//ESD if(analysisLevel == "MC") baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); if(analysisLevel == "AOD") baseAnalysis->SetPhaseSpace(10, -0.5, 0.5, 16, 0.5, 0.9); return baseAnalysis; } <|endoftext|>
<commit_before>#include <Riostream.h> #include <TFile.h> #include <AliRDHFCutsDplustoKpipi.h> #include <TClonesArray.h> #include <TParameter.h> //macro to make a .root file which contains an AliRDHFCutsDplustoKpipi with loose set of cuts (for significance maximization) and TParameter with the tighest value of these cuts //Needed for AliAnalysisTaskSESignificance //Use: //Set hard coded commented with //set this!! //.x makeTFile4CutsDplustoKpipi.C++ //similar macros for the other D mesons //Author: Chiara Bianchin, cbianchi@pd.infn.it // Giacomo Ortona, ortona@to.infn.it void makeTFile5CutsDplustoKpipi(){ AliRDHFCutsDplustoKpipi* RDHFDplustoKpipi=new AliRDHFCutsDplustoKpipi(); RDHFDplustoKpipi->SetName("loosercuts"); RDHFDplustoKpipi->SetTitle("Cuts for significance maximization"); AliESDtrackCuts* esdTrackCuts=new AliESDtrackCuts(); esdTrackCuts->SetRequireSigmaToVertex(kFALSE); //default esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetRequireITSRefit(kTRUE); esdTrackCuts->SetMinNClustersITS(4); // default is 5 esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); // default is kBoth, otherwise kAny esdTrackCuts->SetMinDCAToVertexXY(0.); esdTrackCuts->SetPtRange(0.3,1.e10); RDHFDplustoKpipi->AddTrackCuts(esdTrackCuts); const Int_t nvars=12; const Int_t nptbins=4; Float_t* ptbins; ptbins=new Float_t[nptbins+1]; ptbins[0]=0.; ptbins[1]=2.; ptbins[2]=3.; ptbins[3]=5.; ptbins[4]=99999.; RDHFDplustoKpipi->SetPtBins(nptbins+1,ptbins); //setting my cut values Float_t** prodcutsval; prodcutsval=new Float_t*[nvars]; for(Int_t ic=0;ic<nvars;ic++){prodcutsval[ic]=new Float_t[nptbins];} for(Int_t ipt=0;ipt<nptbins;ipt++){ prodcutsval[0][ipt]=0.2; prodcutsval[1][ipt]=0.4; prodcutsval[2][ipt]=0.4; prodcutsval[3][ipt]=0.; prodcutsval[4][ipt]=0.; prodcutsval[5][ipt]=0.01; prodcutsval[6][ipt]=0.06; prodcutsval[7][ipt]=0.02; prodcutsval[8][ipt]=0.; prodcutsval[9][ipt]=0.85; prodcutsval[10][ipt]=0.; prodcutsval[11][ipt]=10000000.0; } RDHFDplustoKpipi->SetCuts(nvars,nptbins,prodcutsval); Int_t nvarsforopt=RDHFDplustoKpipi->GetNVarsForOpt(); const Int_t dim=4; //set this!! Bool_t *boolforopt; boolforopt=new Bool_t[nvars]; if(dim>nvarsforopt){ cout<<"Number of variables for optimization has probably changed, check and edit accordingly"<<endl; return; } else { if(dim==nvarsforopt){ boolforopt=RDHFDplustoKpipi->GetVarsForOpt(); }else{ TString *names; names=new TString[nvars]; TString answer=""; Int_t checktrue=0; names=RDHFDplustoKpipi->GetVarNames(); for(Int_t i=0;i<nvars;i++){ cout<<names[i]<<" for opt? (y/n)"<<endl; cin>>answer; if(answer=="y") { boolforopt[i]=kTRUE; checktrue++; } else boolforopt[i]=kFALSE; } if (checktrue!=dim) { cout<<"Error! You set "<<checktrue<<" kTRUE instead of "<<dim<<endl; return; } RDHFDplustoKpipi->SetVarsForOpt(dim,boolforopt); } } Float_t tighterval[dim][nptbins]; //sigmavert //declength //costhetapoint //sumd02 //number of steps for each variable is 4 now //set this!! // tighterval[var][ptbin] tighterval[0][0]=0.022100; tighterval[0][1]=0.034; tighterval[0][2]=0.020667; tighterval[0][3]=0.023333; tighterval[1][0]=0.08; tighterval[1][1]=0.09; tighterval[1][2]=0.095; tighterval[1][3]=0.115; tighterval[2][0]=0.979; tighterval[2][1]=0.9975; tighterval[2][2]=0.995; tighterval[2][3]=0.9975; tighterval[3][0]=0.0055; tighterval[3][1]=0.0028; tighterval[3][2]=0.000883; tighterval[3][3]=0.000883; TString name=""; Int_t arrdim=dim*nptbins; TClonesArray max("TParameter<float>",arrdim); for (Int_t ipt=0;ipt<nptbins;ipt++){ for(Int_t ival=0;ival<dim;ival++){ name=Form("par%dptbin%d",ival,ipt); new(max[ipt*nptbins+ival])TParameter<float>(name.Data(),tighterval[ival][ipt]); cout<<name.Data()<<" "<<tighterval[ival][ipt]<<endl; } } TFile* fout=new TFile("cuts4SignifMaximDplus.root","recreate"); //set this!! fout->cd(); RDHFDplustoKpipi->Write(); max.Write(); fout->Close(); } <commit_msg>Removed, obsolete<commit_after><|endoftext|>
<commit_before>#include "catch.hpp" #include "test/base_test_fixture.h" #include <cstdio> namespace { // According to the sqliteodbc documentation, // driver name is different on Windows and Unix. #ifdef _WIN32 const nanodbc::string_type driver_name(NANODBC_TEXT("SQLite3 ODBC Driver")); #else const nanodbc::string_type driver_name(NANODBC_TEXT("SQLite3")); #endif const nanodbc::string_type connection_string = NANODBC_TEXT("Driver=") + driver_name + NANODBC_TEXT(";Database=nanodbc.db;"); struct sqlite_fixture : public base_test_fixture { sqlite_fixture() : base_test_fixture(connection_string) { sqlite_cleanup(); // in case prior test exited without proper cleanup } virtual ~sqlite_fixture() NANODBC_NOEXCEPT { sqlite_cleanup(); } void sqlite_cleanup() NANODBC_NOEXCEPT { int success = std::remove("nanodbc.db"); (void)success; } }; } // NOTE: No catlog_* tests; not supported by SQLite. // Unicode build on Ubuntu 12.04 with unixODBC 2.2.14p2 and libsqliteodbc 0.91-3 throws: // test/sqlite_test.cpp:42: FAILED: // due to a fatal error condition: // SIGSEGV - Segmentation violation signal // See discussions at // https://github.com/lexicalunit/nanodbc/pull/154 // https://groups.google.com/forum/#!msg/catch-forum/7tIpgm8SvDA/1QZZESIuCQAJ // TODO: Uncomment as soon as the SIGSEGV issue has been fixed. #ifndef NANODBC_USE_UNICODE TEST_CASE_METHOD(sqlite_fixture, "affected_rows_test", "[sqlite][affected_rows]") { nanodbc::connection conn = connect(); // CREATE TABLE (CREATE DATABASE not supported) { auto result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)")); REQUIRE(result.affected_rows() == 0); } // INSERT { nanodbc::result result; result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)")); REQUIRE(result.affected_rows() == 1); result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)")); REQUIRE(result.affected_rows() == 1); } // SELECT { //auto result = execute(conn, NANODBC_TEXT("SELECT i FROM nanodbc_test_temp_table")); //REQUIRE(result.affected_rows() == 0); } // DELETE { auto result = execute(conn, NANODBC_TEXT("DELETE FROM nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == 2); // then DROP TABLE { auto result2 = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table")); REQUIRE(result2.affected_rows() == 2); } } // DROP TABLE, without prior DELETE { execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)")); execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)")); execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)")); auto result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == 1); } } #endif TEST_CASE_METHOD(sqlite_fixture, "blob_test", "[sqlite][blob]") { blob_test(); } TEST_CASE_METHOD(sqlite_fixture, "dbms_info_test", "[sqlite][dmbs][metadata][info]") { dbms_info_test(); // Additional SQLite-specific checks nanodbc::connection connection = connect(); REQUIRE(connection.dbms_name() == NANODBC_TEXT("SQLite")); } TEST_CASE_METHOD(sqlite_fixture, "decimal_conversion_test", "[sqlite][decimal][conversion]") { // SQLite ODBC driver requires dedicated test. // The driver converts SQL DECIMAL value to C float value // without preserving DECIMAL(N,M) dimensions // and strips any trailing zeros. nanodbc::connection connection = connect(); nanodbc::result results; create_table(connection, NANODBC_TEXT("decimal_conversion_test"), NANODBC_TEXT("(d decimal(9, 3))")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (12345.987);")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (5.6);")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (1);")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (-1.333);")); results = execute(connection, NANODBC_TEXT("select * from decimal_conversion_test order by 1 desc;")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("12345.987")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("5.6")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("1")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("-1.333")); } TEST_CASE_METHOD(sqlite_fixture, "exception_test", "[sqlite][exception]") { exception_test(); } TEST_CASE_METHOD(sqlite_fixture, "execute_multiple_transaction_test", "[sqlite][execute][transaction]") { execute_multiple_transaction_test(); } TEST_CASE_METHOD(sqlite_fixture, "execute_multiple_test", "[sqlite][execute]") { execute_multiple_test(); } TEST_CASE_METHOD(sqlite_fixture, "integral_test", "[sqlite][integral]") { integral_test<sqlite_fixture>(); } TEST_CASE_METHOD(sqlite_fixture, "move_test", "[sqlite][move]") { move_test(); } TEST_CASE_METHOD(sqlite_fixture, "null_test", "[sqlite][null]") { null_test(); } TEST_CASE_METHOD(sqlite_fixture, "nullptr_nulls_test", "[sqlite][null]") { nullptr_nulls_test(); } TEST_CASE_METHOD(sqlite_fixture, "result_iterator_test", "[sqlite][iterator]") { result_iterator_test(); } TEST_CASE_METHOD(sqlite_fixture, "simple_test", "[sqlite]") { simple_test(); } TEST_CASE_METHOD(sqlite_fixture, "string_test", "[sqlite][string]") { string_test(); } TEST_CASE_METHOD(sqlite_fixture, "transaction_test", "[sqlite][transaction]") { transaction_test(); } TEST_CASE_METHOD(sqlite_fixture, "while_not_end_iteration_test", "[sqlite][looping]") { while_not_end_iteration_test(); } TEST_CASE_METHOD(sqlite_fixture, "while_next_iteration_test", "[sqlite][looping]") { while_next_iteration_test(); } <commit_msg>Add test for integer to string conversion (SQLite only).<commit_after>#include "catch.hpp" #include "test/base_test_fixture.h" #include <cstdio> namespace { // According to the sqliteodbc documentation, // driver name is different on Windows and Unix. #ifdef _WIN32 const nanodbc::string_type driver_name(NANODBC_TEXT("SQLite3 ODBC Driver")); #else const nanodbc::string_type driver_name(NANODBC_TEXT("SQLite3")); #endif const nanodbc::string_type connection_string = NANODBC_TEXT("Driver=") + driver_name + NANODBC_TEXT(";Database=nanodbc.db;"); struct sqlite_fixture : public base_test_fixture { sqlite_fixture() : base_test_fixture(connection_string) { sqlite_cleanup(); // in case prior test exited without proper cleanup } virtual ~sqlite_fixture() NANODBC_NOEXCEPT { sqlite_cleanup(); } void sqlite_cleanup() NANODBC_NOEXCEPT { int success = std::remove("nanodbc.db"); (void)success; } }; } // NOTE: No catlog_* tests; not supported by SQLite. // Unicode build on Ubuntu 12.04 with unixODBC 2.2.14p2 and libsqliteodbc 0.91-3 throws: // test/sqlite_test.cpp:42: FAILED: // due to a fatal error condition: // SIGSEGV - Segmentation violation signal // See discussions at // https://github.com/lexicalunit/nanodbc/pull/154 // https://groups.google.com/forum/#!msg/catch-forum/7tIpgm8SvDA/1QZZESIuCQAJ // TODO: Uncomment as soon as the SIGSEGV issue has been fixed. #ifndef NANODBC_USE_UNICODE TEST_CASE_METHOD(sqlite_fixture, "affected_rows_test", "[sqlite][affected_rows]") { nanodbc::connection conn = connect(); // CREATE TABLE (CREATE DATABASE not supported) { auto result = execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)")); REQUIRE(result.affected_rows() == 0); } // INSERT { nanodbc::result result; result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)")); REQUIRE(result.affected_rows() == 1); result = execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)")); REQUIRE(result.affected_rows() == 1); } // SELECT { //auto result = execute(conn, NANODBC_TEXT("SELECT i FROM nanodbc_test_temp_table")); //REQUIRE(result.affected_rows() == 0); } // DELETE { auto result = execute(conn, NANODBC_TEXT("DELETE FROM nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == 2); // then DROP TABLE { auto result2 = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table")); REQUIRE(result2.affected_rows() == 2); } } // DROP TABLE, without prior DELETE { execute(conn, NANODBC_TEXT("CREATE TABLE nanodbc_test_temp_table (i int)")); execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (1)")); execute(conn, NANODBC_TEXT("INSERT INTO nanodbc_test_temp_table VALUES (2)")); auto result = execute(conn, NANODBC_TEXT("DROP TABLE nanodbc_test_temp_table")); REQUIRE(result.affected_rows() == 1); } } #endif TEST_CASE_METHOD(sqlite_fixture, "blob_test", "[sqlite][blob]") { blob_test(); } TEST_CASE_METHOD(sqlite_fixture, "dbms_info_test", "[sqlite][dmbs][metadata][info]") { dbms_info_test(); // Additional SQLite-specific checks nanodbc::connection connection = connect(); REQUIRE(connection.dbms_name() == NANODBC_TEXT("SQLite")); } TEST_CASE_METHOD(sqlite_fixture, "decimal_conversion_test", "[sqlite][decimal][conversion]") { // SQLite ODBC driver requires dedicated test. // The driver converts SQL DECIMAL value to C float value // without preserving DECIMAL(N,M) dimensions // and strips any trailing zeros. nanodbc::connection connection = connect(); nanodbc::result results; create_table(connection, NANODBC_TEXT("decimal_conversion_test"), NANODBC_TEXT("(d decimal(9, 3))")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (12345.987);")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (5.6);")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (1);")); execute(connection, NANODBC_TEXT("insert into decimal_conversion_test values (-1.333);")); results = execute(connection, NANODBC_TEXT("select * from decimal_conversion_test order by 1 desc;")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("12345.987")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("5.6")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("1")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(0) == NANODBC_TEXT("-1.333")); } TEST_CASE_METHOD(sqlite_fixture, "exception_test", "[sqlite][exception]") { exception_test(); } TEST_CASE_METHOD(sqlite_fixture, "execute_multiple_transaction_test", "[sqlite][execute][transaction]") { execute_multiple_transaction_test(); } TEST_CASE_METHOD(sqlite_fixture, "execute_multiple_test", "[sqlite][execute]") { execute_multiple_test(); } TEST_CASE_METHOD(sqlite_fixture, "integral_test", "[sqlite][integral]") { integral_test<sqlite_fixture>(); } TEST_CASE_METHOD(sqlite_fixture, "integral_to_string_conversion_test", "[sqlite][integral]") { // TODO: Move to common tests nanodbc::connection connection = connect(); create_table(connection, NANODBC_TEXT("integral_to_string_conversion_test"), NANODBC_TEXT("(i int, n int)")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (1, 0);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (2, 255);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (3, -128);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (4, 127);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (5, -32768);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (6, 32767);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (7, -2147483648);")); execute(connection, NANODBC_TEXT("insert into integral_to_string_conversion_test values (8, 2147483647);")); auto results = execute(connection, NANODBC_TEXT("select * from integral_to_string_conversion_test order by i asc;")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("0")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("255")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("-128")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("127")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("-32768")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("32767")); REQUIRE(results.next()); // FIXME: SQLite ODBC driver reports column size of 10 leading to truncation // "-214748364" == "-2147483648" // The driver bug? //REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("-2147483648")); REQUIRE(results.next()); REQUIRE(results.get<nanodbc::string_type>(1) == NANODBC_TEXT("2147483647")); } TEST_CASE_METHOD(sqlite_fixture, "move_test", "[sqlite][move]") { move_test(); } TEST_CASE_METHOD(sqlite_fixture, "null_test", "[sqlite][null]") { null_test(); } TEST_CASE_METHOD(sqlite_fixture, "nullptr_nulls_test", "[sqlite][null]") { nullptr_nulls_test(); } TEST_CASE_METHOD(sqlite_fixture, "result_iterator_test", "[sqlite][iterator]") { result_iterator_test(); } TEST_CASE_METHOD(sqlite_fixture, "simple_test", "[sqlite]") { simple_test(); } TEST_CASE_METHOD(sqlite_fixture, "string_test", "[sqlite][string]") { string_test(); } TEST_CASE_METHOD(sqlite_fixture, "transaction_test", "[sqlite][transaction]") { transaction_test(); } TEST_CASE_METHOD(sqlite_fixture, "while_not_end_iteration_test", "[sqlite][looping]") { while_not_end_iteration_test(); } TEST_CASE_METHOD(sqlite_fixture, "while_next_iteration_test", "[sqlite][looping]") { while_next_iteration_test(); } <|endoftext|>
<commit_before>//__________________________________________________// AliBalancePsi *GetBalanceFunctionObject(const char* analysisLevel = "ESD", const char* centralityName = 0x0, Double_t centrMin = 0., Double_t centrMax = 100., Bool_t bShuffle = kFALSE, Bool_t bHBTcut = kFALSE, Bool_t bConversionCut = kFALSE) { //Function to setup the AliBalance object and return it AliBalancePsi *gBalance = new AliBalancePsi(); gBalance->SetAnalysisLevel(analysisLevel); gBalance->SetShuffle(bShuffle); gBalance->SetHBTcut(bHBTcut); gBalance->SetConversionCut(bConversionCut); if(centralityName) gBalance->SetCentralityIdentifier(centralityName); gBalance->SetCentralityInterval(centrMin,centrMax); //Set all analyses separately //Rapidity //gBalance->SetInterval(AliBalance::kRapidity,-0.8,0.8,32,-1.6,1.6,15.); //Eta //gBalance->SetInterval(AliBalance::kEta,-0.8,0.8,32,-1.6,1.6,15); //Qlong //gBalance->SetInterval(AliBalance::kQlong,-1,1,200,0.0,4.0,15); //Qout //gBalance->SetInterval(AliBalance::kQout,-1,1,200,0.0,4.0,15); //Qside //gBalance->SetInterval(AliBalance::kQside,-1,1,200,0.0,4.0,15); //Qinv //gBalance->SetInterval(AliBalance::kQinv,-1,1,200,0.0,4.0,15); //Phi //gBalance->SetInterval(AliBalance::kPhi,0.,360.,90,-180.,180.0,15); //Init the histograms gBalance->InitHistograms(); return gBalance; } //__________________________________________________// AliESDtrackCuts *GetTrackCutsObject(Double_t ptMin, Double_t ptMax, Double_t etaMin, Double_t etaMax, Double_t maxTPCchi2, Double_t maxDCAz, Double_t maxDCAxy, Int_t minNClustersTPC) { // only used for ESDs // Function to setup the AliESDtrackCuts object and return it AliESDtrackCuts *cuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); cuts->SetRequireTPCStandAlone(kTRUE); // TPC only cuts! // extra TPC cuts (Syst studies) if(minNClustersTPC != -1) cuts->SetMinNClustersTPC(minNClustersTPC); else cuts->SetMinNClustersTPC(70); // standard for filter bit 128 if(maxTPCchi2 != -1) cuts->SetMaxChi2PerClusterTPC(maxTPCchi2); // extra DCA cuts (Syst studies) if(maxDCAz!=-1 && maxDCAxy != -1){ cuts->SetMaxDCAToVertexZ(maxDCAz); cuts->SetMaxDCAToVertexXY(maxDCAxy); } cuts->SetPtRange(ptMin,ptMax); cuts->SetEtaRange(etaMin,etaMax); cuts->DefineHistograms(1); //cuts->SaveHistograms("trackCuts"); return cuts; } <commit_msg>Correcting the config file<commit_after>//__________________________________________________// AliBalancePsi *GetBalanceFunctionObject(const char* analysisLevel = "ESD", const char* centralityName = 0x0, Double_t centrMin = 0., Double_t centrMax = 100., Bool_t bShuffle = kFALSE, Bool_t bHBTCut = kFALSE, Bool_t bConversionCut = kFALSE) { //Function to setup the AliBalance object and return it AliBalancePsi *gBalance = new AliBalancePsi(); gBalance->SetAnalysisLevel(analysisLevel); gBalance->SetShuffle(bShuffle); if(bHBTCut) gBalance->UseHBTCut(); if(bConversionCut) gBalance->UseConversionCut(); if(centralityName) gBalance->SetCentralityIdentifier(centralityName); gBalance->SetCentralityInterval(centrMin,centrMax); //Set all analyses separately //Rapidity //gBalance->SetInterval(AliBalance::kRapidity,-0.8,0.8,32,-1.6,1.6,15.); //Eta //gBalance->SetInterval(AliBalance::kEta,-0.8,0.8,32,-1.6,1.6,15); //Qlong //gBalance->SetInterval(AliBalance::kQlong,-1,1,200,0.0,4.0,15); //Qout //gBalance->SetInterval(AliBalance::kQout,-1,1,200,0.0,4.0,15); //Qside //gBalance->SetInterval(AliBalance::kQside,-1,1,200,0.0,4.0,15); //Qinv //gBalance->SetInterval(AliBalance::kQinv,-1,1,200,0.0,4.0,15); //Phi //gBalance->SetInterval(AliBalance::kPhi,0.,360.,90,-180.,180.0,15); //Init the histograms gBalance->InitHistograms(); return gBalance; } //__________________________________________________// AliESDtrackCuts *GetTrackCutsObject(Double_t ptMin, Double_t ptMax, Double_t etaMin, Double_t etaMax, Double_t maxTPCchi2, Double_t maxDCAz, Double_t maxDCAxy, Int_t minNClustersTPC) { // only used for ESDs // Function to setup the AliESDtrackCuts object and return it AliESDtrackCuts *cuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts(); cuts->SetRequireTPCStandAlone(kTRUE); // TPC only cuts! // extra TPC cuts (Syst studies) if(minNClustersTPC != -1) cuts->SetMinNClustersTPC(minNClustersTPC); else cuts->SetMinNClustersTPC(70); // standard for filter bit 128 if(maxTPCchi2 != -1) cuts->SetMaxChi2PerClusterTPC(maxTPCchi2); // extra DCA cuts (Syst studies) if(maxDCAz!=-1 && maxDCAxy != -1){ cuts->SetMaxDCAToVertexZ(maxDCAz); cuts->SetMaxDCAToVertexXY(maxDCAxy); } cuts->SetPtRange(ptMin,ptMax); cuts->SetEtaRange(etaMin,etaMax); cuts->DefineHistograms(1); //cuts->SaveHistograms("trackCuts"); return cuts; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test.hpp" #include "conv_test.hpp" // conv_4d_valid CONV4_VALID_TEST_CASE("conv_4d/valid_1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 2, 5, 5> I(etl::sequence_generator(10.0) * 4.0); etl::fast_matrix<T, 12, 2, 3, 3> K(etl::sequence_generator(2.0) * 0.3); etl::fast_matrix<T, 10, 12, 3, 3> ref; etl::fast_matrix<T, 10, 12, 3, 3> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(k) += conv_2d_valid(I(i)(c), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_VALID_TEST_CASE("conv_4d/valid_2", "[conv][conv4][valid]") { etl::fast_matrix<T, 9, 4, 5, 5> I(etl::sequence_generator(-10.0) * 0.04); etl::fast_matrix<T, 10, 4, 2, 2> K(etl::sequence_generator(-2.0) * 1.56); etl::fast_matrix<T, 9, 10, 4, 4> ref; etl::fast_matrix<T, 9, 10, 4, 4> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(k) += conv_2d_valid(I(i)(c), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_VALID_FLIPPED_TEST_CASE("conv_4d/valid_3", "[conv][conv4][valid]") { etl::fast_matrix<T, 9, 4, 5, 5> I(etl::sequence_generator(-10.0) * 0.04); etl::fast_matrix<T, 10, 4, 2, 2> K(etl::sequence_generator(-2.0) * 1.56); etl::fast_matrix<T, 9, 10, 4, 4> ref; etl::fast_matrix<T, 9, 10, 4, 4> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(k) += conv_2d_valid(I(i)(c), fflip(K(k)(c))); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX_E(c[i], ref[i], 0.1); } } // conv_4d_full CONV4_FULL_TEST_CASE("conv_4d/full_1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 12, 5, 5> I(etl::sequence_generator(10.0) * 4.0); etl::fast_matrix<T, 12, 2, 3, 3> K(etl::sequence_generator(2.0) * 0.3); etl::fast_matrix<T, 10, 2, 7, 7> ref; etl::fast_matrix<T, 10, 2, 7, 7> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(c) += conv_2d_full(I(i)(k), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_FULL_TEST_CASE("conv_4d/full_2", "[conv][conv4][valid]") { etl::fast_matrix<T, 8, 9, 6, 6> I(etl::sequence_generator(15.0) * -3.0); etl::fast_matrix<T, 9, 3, 3, 3> K(etl::sequence_generator(-4.0) * 1.6); etl::fast_matrix<T, 8, 3, 8, 8> ref; etl::fast_matrix<T, 8, 3, 8, 8> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(c) += conv_2d_full(I(i)(k), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_FULL_FLIPPED_TEST_CASE("conv_4d/full_3", "[conv][conv4][valid]") { etl::fast_matrix<T, 8, 9, 6, 6> I(etl::sequence_generator(15.0) * -3.0); etl::fast_matrix<T, 9, 3, 3, 3> K(etl::sequence_generator(-4.0) * 1.6); etl::fast_matrix<T, 8, 3, 8, 8> ref; etl::fast_matrix<T, 8, 3, 8, 8> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(c) += conv_2d_full(I(i)(k), fflip(K(k)(c))); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } // conv_4d_valid_filter CONV4_VALID_FILTER_TEST_CASE("conv/4d/valid/filter/1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 3, 5, 5> I(etl::sequence_generator(-10.0) * 0.01); etl::fast_matrix<T, 10, 4, 3, 3> K(etl::sequence_generator(-20.0) * 0.03); etl::fast_matrix<T, 4, 3, 3, 3> ref; etl::fast_matrix<T, 4, 3, 3, 3> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for (std::size_t k = 0; k < etl::dim<1>(K); ++k) { for (std::size_t c = 0; c < etl::dim<1>(I); ++c) { ref(k)(c) += conv_2d_valid(I(i)(c), K(i)(k)); } } }; Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX_E(c[i], ref[i], base_eps * 10000); } } // conv_4d_valid_filter_flipped CONV4_VALID_FILTER_FLIPPED_TEST_CASE("conv/4d/valid/filter/flipped/1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 3, 5, 5> I(etl::sequence_generator(3.0) * 0.04); etl::fast_matrix<T, 10, 4, 3, 3> K(etl::sequence_generator(2.0) * 0.3); etl::fast_matrix<T, 4, 3, 3, 3> ref; etl::fast_matrix<T, 4, 3, 3, 3> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for (std::size_t k = 0; k < etl::dim<1>(K); ++k) { for (std::size_t c = 0; c < etl::dim<1>(I); ++c) { ref(k)(c) += conv_2d_valid_flipped(I(i)(c), fflip(K(i)(k))); } } }; Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX_E(c[i], ref[i], 0.05); } } <commit_msg>Update tests<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test.hpp" #include "conv_test.hpp" // conv_4d_valid CONV4_VALID_TEST_CASE("conv_4d/valid_1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 2, 5, 5> I(etl::sequence_generator(10.0) * 4.0); etl::fast_matrix<T, 12, 2, 3, 3> K(etl::sequence_generator(2.0) * 0.3); etl::fast_matrix<T, 10, 12, 3, 3> ref; etl::fast_matrix<T, 10, 12, 3, 3> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(k) += conv_2d_valid(I(i)(c), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_VALID_TEST_CASE("conv_4d/valid_2", "[conv][conv4][valid]") { etl::fast_matrix<T, 9, 4, 5, 5> I(etl::sequence_generator(-10.0) * 0.04); etl::fast_matrix<T, 10, 4, 2, 2> K(etl::sequence_generator(-2.0) * 1.56); etl::fast_matrix<T, 9, 10, 4, 4> ref; etl::fast_matrix<T, 9, 10, 4, 4> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(k) += conv_2d_valid(I(i)(c), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_VALID_FLIPPED_TEST_CASE("conv_4d/valid_3", "[conv][conv4][valid]") { etl::fast_matrix<T, 9, 4, 5, 5> I(etl::sequence_generator(-10.0) * 0.04); etl::fast_matrix<T, 10, 4, 2, 2> K(etl::sequence_generator(-2.0) * 1.56); etl::fast_matrix<T, 9, 10, 4, 4> ref; etl::fast_matrix<T, 9, 10, 4, 4> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(k) += conv_2d_valid(I(i)(c), fflip(K(k)(c))); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX_E(c[i], ref[i], 0.1); } } // conv_4d_full CONV4_FULL_TEST_CASE("conv_4d/full_1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 12, 5, 5> I(etl::sequence_generator(10.0) * 4.0); etl::fast_matrix<T, 12, 2, 3, 3> K(etl::sequence_generator(2.0) * 0.3); etl::fast_matrix<T, 10, 2, 7, 7> ref; etl::fast_matrix<T, 10, 2, 7, 7> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(c) += conv_2d_full(I(i)(k), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_FULL_TEST_CASE("conv_4d/full_2", "[conv][conv4][valid]") { etl::fast_matrix<T, 8, 9, 6, 6> I(etl::sequence_generator(15.0) * -3.0); etl::fast_matrix<T, 9, 3, 3, 3> K(etl::sequence_generator(-4.0) * 1.6); etl::fast_matrix<T, 8, 3, 8, 8> ref; etl::fast_matrix<T, 8, 3, 8, 8> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(c) += conv_2d_full(I(i)(k), K(k)(c)); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } CONV4_FULL_FLIPPED_TEST_CASE("conv_4d/full_3", "[conv][conv4][valid]") { etl::fast_matrix<T, 8, 9, 6, 6> I(etl::sequence_generator(15.0) * -3.0); etl::fast_matrix<T, 9, 3, 3, 3> K(etl::sequence_generator(-4.0) * 1.6); etl::fast_matrix<T, 8, 3, 8, 8> ref; etl::fast_matrix<T, 8, 3, 8, 8> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for(std::size_t c = 0; c < etl::dim<1>(K); ++c){ for(std::size_t k = 0; k < etl::dim<0>(K); ++k){ ref(i)(c) += conv_2d_full(I(i)(k), fflip(K(k)(c))); } } } Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX(c[i], ref[i]); } } // conv_4d_valid_filter CONV4_VALID_FILTER_TEST_CASE("conv/4d/valid/filter/1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 3, 5, 5> I(etl::sequence_generator(-10.0) * 0.01); etl::fast_matrix<T, 10, 4, 3, 3> K(etl::sequence_generator(-20.0) * 0.03); etl::fast_matrix<T, 4, 3, 3, 3> ref; etl::fast_matrix<T, 4, 3, 3, 3> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for (std::size_t k = 0; k < etl::dim<1>(K); ++k) { for (std::size_t c = 0; c < etl::dim<1>(I); ++c) { ref(k)(c) += conv_2d_valid(I(i)(c), K(i)(k)); } } }; Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX_E(c[i], ref[i], base_eps * 10000); } } // conv_4d_valid_filter_flipped CONV4_VALID_FILTER_FLIPPED_TEST_CASE("conv/4d/valid/filter/flipped/1", "[conv][conv4][valid]") { etl::fast_matrix<T, 10, 3, 5, 5> I(etl::sequence_generator(3.0) * 2.4); etl::fast_matrix<T, 10, 4, 3, 3> K(etl::sequence_generator(2.0) * 4.3); etl::fast_matrix<T, 4, 3, 3, 3> ref; etl::fast_matrix<T, 4, 3, 3, 3> c; ref = 0.0; for(std::size_t i = 0; i < etl::dim<0>(I); ++i){ for (std::size_t k = 0; k < etl::dim<1>(K); ++k) { for (std::size_t c = 0; c < etl::dim<1>(I); ++c) { ref(k)(c) += conv_2d_valid_flipped(I(i)(c), fflip(K(i)(k))); } } }; Impl::apply(I, K, c); for(std::size_t i = 0; i < ref.size(); ++i){ REQUIRE_EQUALS_APPROX_E(c[i], ref[i], 0.05); } } <|endoftext|>
<commit_before>/************************************************************************* * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // // // Basic Analysis Task // // // /////////////////////////////////////////////////////////////////////////// #include <TChain.h> #include <TH1D.h> #include <AliLog.h> #include <AliAODHandler.h> #include <AliAODInputHandler.h> #include <AliAnalysisManager.h> #include <AliVEvent.h> #include <AliTriggerAnalysis.h> #include <AliInputEventHandler.h> #include <AliAODInputHandler.h> #include <AliESDInputHandler.h> #include "AliDielectron.h" #include "AliDielectronMC.h" #include "AliDielectronHistos.h" #include "AliDielectronVarManager.h" #include "AliAnalysisTaskDielectronFilter.h" ClassImp(AliAnalysisTaskDielectronFilter) //_________________________________________________________________________________ AliAnalysisTaskDielectronFilter::AliAnalysisTaskDielectronFilter() : AliAnalysisTaskSE(), fDielectron(0), fSelectPhysics(kTRUE), fTriggerMask(AliVEvent::kMB), fExcludeTriggerMask(0), fTriggerOnV0AND(kFALSE), fRejectPileup(kFALSE), fEventStat(0x0), fTriggerLogic(kAny), fTriggerAnalysis(0x0), fStoreLikeSign(kFALSE), fStoreRotatedPairs(kFALSE), fStoreTrackLegs(kFALSE), fEventFilter(0x0) { // // Constructor // } //_________________________________________________________________________________ AliAnalysisTaskDielectronFilter::AliAnalysisTaskDielectronFilter(const char *name) : AliAnalysisTaskSE(name), fDielectron(0), fSelectPhysics(kTRUE), fTriggerMask(AliVEvent::kMB), fExcludeTriggerMask(0), fTriggerOnV0AND(kFALSE), fRejectPileup(kFALSE), fEventStat(0x0), fTriggerLogic(kAny), fTriggerAnalysis(0x0), fStoreLikeSign(kFALSE), fStoreRotatedPairs(kFALSE), fStoreTrackLegs(kFALSE), fEventFilter(0x0) { // // Constructor // DefineInput(0,TChain::Class()); DefineOutput(1, THashList::Class()); DefineOutput(2, TH1D::Class()); } //_________________________________________________________________________________ void AliAnalysisTaskDielectronFilter::Init() { // Initialization if (fDebug > 1) AliInfo("Init() \n"); // require AOD handler AliAODHandler *aodH = (AliAODHandler*)((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (!aodH) AliFatal("No AOD handler. Halting."); aodH->AddFilteredAOD("AliAOD.Dielectron.root", "DielectronEvents"); // AddAODBranch("AliDielectronCandidates",fDielectron->GetPairArraysPointer(),"deltaAOD.Dielectron.root"); } //_________________________________________________________________________________ void AliAnalysisTaskDielectronFilter::UserCreateOutputObjects() { // // Initilise histograms // //require dielectron framework if (!fDielectron) { AliFatal("Dielectron framework class required. Please create and instance with proper cuts and set it via 'SetDielectron' before executing this task!!!"); return; } if(fStoreRotatedPairs) fDielectron->SetStoreRotatedPairs(kTRUE); fDielectron->SetDontClearArrays(); fDielectron->Init(); Int_t nbins=kNbinsEvent+2; if (!fEventStat){ fEventStat=new TH1D("hEventStat","Event statistics",nbins,0,nbins); fEventStat->GetXaxis()->SetBinLabel(1,"Before Phys. Sel."); fEventStat->GetXaxis()->SetBinLabel(2,"After Phys. Sel."); //default names fEventStat->GetXaxis()->SetBinLabel(3,"Bin3 not used"); fEventStat->GetXaxis()->SetBinLabel(4,"Bin4 not used"); fEventStat->GetXaxis()->SetBinLabel(5,"Bin5 not used"); if(fTriggerOnV0AND) fEventStat->GetXaxis()->SetBinLabel(3,"V0and triggers"); if (fEventFilter) fEventStat->GetXaxis()->SetBinLabel(4,"After Event Filter"); if (fRejectPileup) fEventStat->GetXaxis()->SetBinLabel(5,"After Pileup rejection"); fEventStat->GetXaxis()->SetBinLabel((kNbinsEvent+1),Form("#splitline{1 candidate}{%s}",fDielectron->GetName())); fEventStat->GetXaxis()->SetBinLabel((kNbinsEvent+2),Form("#splitline{With >1 candidate}{%s}",fDielectron->GetName())); } PostData(2,fEventStat); } //_________________________________________________________________________________ void AliAnalysisTaskDielectronFilter::UserExec(Option_t *) { // // Main loop. Called for every event // if (!fDielectron) return; AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager(); Bool_t isESD=man->GetInputEventHandler()->IsA()==AliESDInputHandler::Class(); Bool_t isAOD=man->GetInputEventHandler()->IsA()==AliAODInputHandler::Class(); AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler()); if (!inputHandler) return; if ( inputHandler->GetPIDResponse() ){ AliDielectronVarManager::SetPIDResponse( inputHandler->GetPIDResponse() ); } else { AliFatal("This task needs the PID response attached to the input event handler!"); } // Was event selected ? ULong64_t isSelected = AliVEvent::kAny; Bool_t isRejected = kFALSE; if( fSelectPhysics && inputHandler){ if((isESD && inputHandler->GetEventSelection()) || isAOD){ isSelected = inputHandler->IsEventSelected(); if (fExcludeTriggerMask && (isSelected&fExcludeTriggerMask)) isRejected=kTRUE; if (fTriggerLogic==kAny) isSelected&=fTriggerMask; else if (fTriggerLogic==kExact) isSelected=((isSelected&fTriggerMask)==fTriggerMask); } } //before physics selection fEventStat->Fill(kAllEvents); if (isSelected==0||isRejected) { PostData(3,fEventStat); return; } //after physics selection fEventStat->Fill(kSelectedEvents); //V0and if(fTriggerOnV0AND){ if(isESD){if (!fTriggerAnalysis->IsOfflineTriggerFired(static_cast<AliESDEvent*>(InputEvent()), AliTriggerAnalysis::kV0AND)) return;} if(isAOD){if(!((static_cast<AliAODEvent*>(InputEvent()))->GetVZEROData()->GetV0ADecision() == AliVVZERO::kV0BB && (static_cast<AliAODEvent*>(InputEvent()))->GetVZEROData()->GetV0CDecision() == AliVVZERO::kV0BB) ) return;} } fEventStat->Fill(kV0andEvents); //Fill Event histograms before the event filter Double_t values[AliDielectronVarManager::kNMaxValues]={0}; Double_t valuesMC[AliDielectronVarManager::kNMaxValues]={0}; AliDielectronVarManager::SetEvent(InputEvent()); AliDielectronVarManager::Fill(InputEvent(),values); AliDielectronVarManager::Fill(InputEvent(),valuesMC); Bool_t hasMC=AliDielectronMC::Instance()->HasMC(); if (hasMC) { if (AliDielectronMC::Instance()->ConnectMCEvent()) AliDielectronVarManager::Fill(AliDielectronMC::Instance()->GetMCEvent(),valuesMC); } AliDielectronHistos *h=fDielectron->GetHistoManager(); if (h){ if (h->GetHistogramList()->FindObject("Event_noCuts")) h->FillClass("Event_noCuts",AliDielectronVarManager::kNMaxValues,values); if (hasMC && h->GetHistogramList()->FindObject("MCEvent_noCuts")) h->FillClass("Event_noCuts",AliDielectronVarManager::kNMaxValues,valuesMC); } //event filter if (fEventFilter) { if (!fEventFilter->IsSelected(InputEvent())) return; } fEventStat->Fill(kFilteredEvents); //pileup if (fRejectPileup){ if (InputEvent()->IsPileupFromSPD(3,0.8,3.,2.,5.)) return; } fEventStat->Fill(kPileupEvents); //bz for AliKF Double_t bz = InputEvent()->GetMagneticField(); AliKFParticle::SetField( bz ); AliDielectronPID::SetCorrVal((Double_t)InputEvent()->GetRunNumber()); fDielectron->Process(InputEvent()); Bool_t hasCand = kFALSE; if(fStoreLikeSign) hasCand = (fDielectron->HasCandidates() || fDielectron->HasCandidatesLikeSign()); else hasCand = (fDielectron->HasCandidates()); if(fStoreRotatedPairs) hasCand = (hasCand || fDielectron->HasCandidatesTR()); if(hasCand){ AliAODHandler *aodH=(AliAODHandler*)((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); AliAODEvent *aod = aodH->GetAOD(); // reset bit for all tracks if(isAOD){ for(Int_t it=0;it<aod->GetNumberOfTracks();it++){ aod->GetTrack(it)->ResetBit(kIsReferenced); aod->GetTrack(it)->SetUniqueID(0); } } //replace the references of the legs with the AOD references TObjArray *obj = 0x0; for(Int_t i=0; i < 11; i++ ){ obj = (TObjArray*)((*(fDielectron->GetPairArraysPointer()))->UncheckedAt(i)); if(!obj) continue; for(int j=0;j<obj->GetEntriesFast();j++){ AliDielectronPair *pairObj = (AliDielectronPair*)obj->UncheckedAt(j); Int_t id1 = ((AliVTrack*)pairObj->GetFirstDaughter())->GetID(); Int_t id2 = ((AliVTrack*)pairObj->GetSecondDaughter())->GetID(); for(Int_t it=0;it<aod->GetNumberOfTracks();it++){ if(aod->GetTrack(it)->GetID() == id1) pairObj->SetRefFirstDaughter(aod->GetTrack(it)); if(aod->GetTrack(it)->GetID() == id2) pairObj->SetRefSecondDaughter(aod->GetTrack(it)); } } } AliAODExtension *extDielectron = aodH->GetFilteredAOD("AliAOD.Dielectron.root"); extDielectron->SelectEvent(); Int_t ncandidates=fDielectron->GetPairArray(1)->GetEntriesFast(); if (ncandidates==1) fEventStat->Fill((kNbinsEvent)); else if (ncandidates>1) fEventStat->Fill((kNbinsEvent+1)); //see if dielectron candidate branch exists, if not create is TTree *t=extDielectron->GetTree(); if(!t->GetListOfBranches()->GetEntries() && isAOD) t->Branch(aod->GetList()); if (!t->GetBranch("dielectrons")){ t->Bronch("dielectrons","TObjArray",fDielectron->GetPairArraysPointer()); // store positive and negative tracks if(fStoreTrackLegs){ t->Branch("positiveTracks","TObjArray", (TObjArray*)(fDielectron->GetTrackArray(0))); t->Branch("negativeTracks","TObjArray", (TObjArray*)(fDielectron->GetTrackArray(1))); } } if(isAOD) t->Fill(); } PostData(1, const_cast<THashList*>(fDielectron->GetHistogramList())); PostData(2,fEventStat); } <commit_msg>o updates for nanoAODs (Fiorella)<commit_after>/************************************************************************* * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // // // Basic Analysis Task // // // /////////////////////////////////////////////////////////////////////////// #include <TChain.h> #include <TH1D.h> #include <AliLog.h> #include <AliAODHandler.h> #include <AliAODInputHandler.h> #include <AliAnalysisManager.h> #include <AliVEvent.h> #include <AliTriggerAnalysis.h> #include <AliInputEventHandler.h> #include <AliAODInputHandler.h> #include <AliESDInputHandler.h> #include "AliDielectron.h" #include "AliDielectronMC.h" #include "AliDielectronHistos.h" #include "AliDielectronVarManager.h" #include "AliAnalysisTaskDielectronFilter.h" ClassImp(AliAnalysisTaskDielectronFilter) //_________________________________________________________________________________ AliAnalysisTaskDielectronFilter::AliAnalysisTaskDielectronFilter() : AliAnalysisTaskSE(), fDielectron(0), fSelectPhysics(kTRUE), fTriggerMask(AliVEvent::kMB), fExcludeTriggerMask(0), fTriggerOnV0AND(kFALSE), fRejectPileup(kFALSE), fEventStat(0x0), fTriggerLogic(kAny), fTriggerAnalysis(0x0), fStoreLikeSign(kFALSE), fStoreRotatedPairs(kFALSE), fStoreTrackLegs(kFALSE), fEventFilter(0x0) { // // Constructor // } //_________________________________________________________________________________ AliAnalysisTaskDielectronFilter::AliAnalysisTaskDielectronFilter(const char *name) : AliAnalysisTaskSE(name), fDielectron(0), fSelectPhysics(kTRUE), fTriggerMask(AliVEvent::kMB), fExcludeTriggerMask(0), fTriggerOnV0AND(kFALSE), fRejectPileup(kFALSE), fEventStat(0x0), fTriggerLogic(kAny), fTriggerAnalysis(0x0), fStoreLikeSign(kFALSE), fStoreRotatedPairs(kFALSE), fStoreTrackLegs(kFALSE), fEventFilter(0x0) { // // Constructor // DefineInput(0,TChain::Class()); DefineOutput(1, THashList::Class()); DefineOutput(2, TH1D::Class()); } //_________________________________________________________________________________ void AliAnalysisTaskDielectronFilter::Init() { // Initialization if (fDebug > 1) AliInfo("Init() \n"); // require AOD handler AliAODHandler *aodH = (AliAODHandler*)((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (!aodH) AliFatal("No AOD handler. Halting."); aodH->AddFilteredAOD("AliAOD.Dielectron.root", "DielectronEvents"); // AddAODBranch("AliDielectronCandidates",fDielectron->GetPairArraysPointer(),"deltaAOD.Dielectron.root"); } //_________________________________________________________________________________ void AliAnalysisTaskDielectronFilter::UserCreateOutputObjects() { // // Initilise histograms // //require dielectron framework if (!fDielectron) { AliFatal("Dielectron framework class required. Please create and instance with proper cuts and set it via 'SetDielectron' before executing this task!!!"); return; } if(fStoreRotatedPairs) fDielectron->SetStoreRotatedPairs(kTRUE); fDielectron->SetDontClearArrays(); fDielectron->Init(); Int_t nbins=kNbinsEvent+2; if (!fEventStat){ fEventStat=new TH1D("hEventStat","Event statistics",nbins,0,nbins); fEventStat->GetXaxis()->SetBinLabel(1,"Before Phys. Sel."); fEventStat->GetXaxis()->SetBinLabel(2,"After Phys. Sel."); //default names fEventStat->GetXaxis()->SetBinLabel(3,"Bin3 not used"); fEventStat->GetXaxis()->SetBinLabel(4,"Bin4 not used"); fEventStat->GetXaxis()->SetBinLabel(5,"Bin5 not used"); if(fTriggerOnV0AND) fEventStat->GetXaxis()->SetBinLabel(3,"V0and triggers"); if (fEventFilter) fEventStat->GetXaxis()->SetBinLabel(4,"After Event Filter"); if (fRejectPileup) fEventStat->GetXaxis()->SetBinLabel(5,"After Pileup rejection"); fEventStat->GetXaxis()->SetBinLabel((kNbinsEvent+1),Form("#splitline{1 candidate}{%s}",fDielectron->GetName())); fEventStat->GetXaxis()->SetBinLabel((kNbinsEvent+2),Form("#splitline{With >1 candidate}{%s}",fDielectron->GetName())); } PostData(2,fEventStat); } //_________________________________________________________________________________ void AliAnalysisTaskDielectronFilter::UserExec(Option_t *) { // // Main loop. Called for every event // if (!fDielectron) return; AliAnalysisManager *man=AliAnalysisManager::GetAnalysisManager(); Bool_t isESD=man->GetInputEventHandler()->IsA()==AliESDInputHandler::Class(); Bool_t isAOD=man->GetInputEventHandler()->IsA()==AliAODInputHandler::Class(); AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler()); if (!inputHandler) return; if ( inputHandler->GetPIDResponse() ){ AliDielectronVarManager::SetPIDResponse( inputHandler->GetPIDResponse() ); } else { AliFatal("This task needs the PID response attached to the input event handler!"); } // Was event selected ? ULong64_t isSelected = AliVEvent::kAny; Bool_t isRejected = kFALSE; if( fSelectPhysics && inputHandler){ if((isESD && inputHandler->GetEventSelection()) || isAOD){ isSelected = inputHandler->IsEventSelected(); if (fExcludeTriggerMask && (isSelected&fExcludeTriggerMask)) isRejected=kTRUE; if (fTriggerLogic==kAny) isSelected&=fTriggerMask; else if (fTriggerLogic==kExact) isSelected=((isSelected&fTriggerMask)==fTriggerMask); } } //before physics selection fEventStat->Fill(kAllEvents); if (isSelected==0||isRejected) { PostData(3,fEventStat); return; } //after physics selection fEventStat->Fill(kSelectedEvents); //V0and if(fTriggerOnV0AND){ if(isESD){if (!fTriggerAnalysis->IsOfflineTriggerFired(static_cast<AliESDEvent*>(InputEvent()), AliTriggerAnalysis::kV0AND)) return;} if(isAOD){if(!((static_cast<AliAODEvent*>(InputEvent()))->GetVZEROData()->GetV0ADecision() == AliVVZERO::kV0BB && (static_cast<AliAODEvent*>(InputEvent()))->GetVZEROData()->GetV0CDecision() == AliVVZERO::kV0BB) ) return;} } fEventStat->Fill(kV0andEvents); //Fill Event histograms before the event filter Double_t values[AliDielectronVarManager::kNMaxValues]={0}; Double_t valuesMC[AliDielectronVarManager::kNMaxValues]={0}; AliDielectronVarManager::SetEvent(InputEvent()); AliDielectronVarManager::Fill(InputEvent(),values); AliDielectronVarManager::Fill(InputEvent(),valuesMC); Bool_t hasMC=AliDielectronMC::Instance()->HasMC(); if (hasMC) { if (AliDielectronMC::Instance()->ConnectMCEvent()) AliDielectronVarManager::Fill(AliDielectronMC::Instance()->GetMCEvent(),valuesMC); } AliDielectronHistos *h=fDielectron->GetHistoManager(); if (h){ if (h->GetHistogramList()->FindObject("Event_noCuts")) h->FillClass("Event_noCuts",AliDielectronVarManager::kNMaxValues,values); if (hasMC && h->GetHistogramList()->FindObject("MCEvent_noCuts")) h->FillClass("Event_noCuts",AliDielectronVarManager::kNMaxValues,valuesMC); } //event filter if (fEventFilter) { if (!fEventFilter->IsSelected(InputEvent())) return; } fEventStat->Fill(kFilteredEvents); //pileup if (fRejectPileup){ if (InputEvent()->IsPileupFromSPD(3,0.8,3.,2.,5.)) return; } fEventStat->Fill(kPileupEvents); //bz for AliKF Double_t bz = InputEvent()->GetMagneticField(); AliKFParticle::SetField( bz ); AliDielectronPID::SetCorrVal((Double_t)InputEvent()->GetRunNumber()); fDielectron->Process(InputEvent()); Bool_t hasCand = kFALSE; if(fStoreLikeSign) hasCand = (fDielectron->HasCandidates() || fDielectron->HasCandidatesLikeSign()); else hasCand = (fDielectron->HasCandidates()); if(fStoreRotatedPairs) hasCand = (hasCand || fDielectron->HasCandidatesTR()); if(hasCand){ AliAODHandler *aodH=(AliAODHandler*)((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); AliAODEvent *aod = aodH->GetAOD(); // reset bit for all tracks if(isAOD){ for(Int_t it=0;it<aod->GetNumberOfTracks();it++){ aod->GetTrack(it)->ResetBit(kIsReferenced); aod->GetTrack(it)->SetUniqueID(0); } } //replace the references of the legs with the AOD references TObjArray *obj = 0x0; for(Int_t i=0; i < 11; i++ ){ obj = (TObjArray*)((*(fDielectron->GetPairArraysPointer()))->UncheckedAt(i)); if(!obj) continue; for(int j=0;j<obj->GetEntriesFast();j++){ AliDielectronPair *pairObj = (AliDielectronPair*)obj->UncheckedAt(j); Int_t id1 = ((AliVTrack*)pairObj->GetFirstDaughter())->GetID(); Int_t id2 = ((AliVTrack*)pairObj->GetSecondDaughter())->GetID(); for(Int_t it=0;it<aod->GetNumberOfTracks();it++){ if(aod->GetTrack(it)->GetID() == id1) pairObj->SetRefFirstDaughter(aod->GetTrack(it)); if(aod->GetTrack(it)->GetID() == id2) pairObj->SetRefSecondDaughter(aod->GetTrack(it)); } } } AliAODExtension *extDielectron = aodH->GetFilteredAOD("AliAOD.Dielectron.root"); extDielectron->SelectEvent(); Int_t ncandidates=fDielectron->GetPairArray(1)->GetEntriesFast(); if (ncandidates==1) fEventStat->Fill((kNbinsEvent)); else if (ncandidates>1) fEventStat->Fill((kNbinsEvent+1)); //see if dielectron candidate branch exists, if not create is TTree *t=extDielectron->GetTree(); if(!t->GetListOfBranches()->GetEntries() && isAOD) t->Branch(aod->GetList()); if (!t->GetBranch("dielectrons")) t->Bronch("dielectrons","TObjArray",fDielectron->GetPairArraysPointer()); // store positive and negative tracks if(fStoreTrackLegs && t->GetBranch("tracks")){ Int_t nTracks = (fDielectron->GetTrackArray(0))->GetEntries() + (fDielectron->GetTrackArray(1))->GetEntries(); extDielectron->GetAOD()->ResetStd(nTracks); for(int kj=0; kj<(fDielectron->GetTrackArray(0))->GetEntries(); kj++) extDielectron->GetAOD()->AddTrack((AliAODTrack*)fDielectron->GetTrackArray(0)->At(kj)); for(int kj=0; kj<(fDielectron->GetTrackArray(1))->GetEntries(); kj++) extDielectron->GetAOD()->AddTrack((AliAODTrack*)fDielectron->GetTrackArray(1)->At(kj)); } if(isAOD) t->Fill(); } PostData(1, const_cast<THashList*>(fDielectron->GetHistogramList())); PostData(2,fEventStat); } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "StubViewTree.h" #include <glog/logging.h> #include <react/debug/react_native_assert.h> #ifdef STUB_VIEW_TREE_VERBOSE #define STUB_VIEW_LOG(code) code #else #define STUB_VIEW_LOG(code) #endif namespace facebook { namespace react { StubViewTree::StubViewTree(ShadowView const &shadowView) { auto view = std::make_shared<StubView>(); view->update(shadowView); rootTag = shadowView.tag; registry[shadowView.tag] = view; } StubView const &StubViewTree::getRootStubView() const { return *registry.at(rootTag); } StubView const &StubViewTree::getStubView(Tag tag) const { return *registry.at(tag); } size_t StubViewTree::size() const { return registry.size(); } void StubViewTree::mutate(ShadowViewMutationList const &mutations) { STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating Begin"; }); for (auto const &mutation : mutations) { switch (mutation.type) { case ShadowViewMutation::Create: { react_native_assert(mutation.parentShadowView == ShadowView{}); react_native_assert(mutation.oldChildShadowView == ShadowView{}); react_native_assert(mutation.newChildShadowView.props); auto stubView = std::make_shared<StubView>(); stubView->update(mutation.newChildShadowView); auto tag = mutation.newChildShadowView.tag; STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Create [" << tag << "] ##" << std::hash<ShadowView>{}((ShadowView)*stubView); }); react_native_assert(registry.find(tag) == registry.end()); registry[tag] = stubView; break; } case ShadowViewMutation::Delete: { STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Delete [" << mutation.oldChildShadowView.tag << "] ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); }); react_native_assert(mutation.parentShadowView == ShadowView{}); react_native_assert(mutation.newChildShadowView == ShadowView{}); auto tag = mutation.oldChildShadowView.tag; /* Disable this assert until T76057501 is resolved. react_native_assert(registry.find(tag) != registry.end()); auto stubView = registry[tag]; if ((ShadowView)(*stubView) != mutation.oldChildShadowView) { LOG(ERROR) << "StubView: ASSERT FAILURE: DELETE mutation assertion failure: oldChildShadowView doesn't match stubView: [" << mutation.oldChildShadowView.tag << "] stub hash: ##" << std::hash<ShadowView>{}((ShadowView)*stubView) << " old mutation hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "StubView: " << getDebugPropsDescription((ShadowView)*stubView, {}); LOG(ERROR) << "OldChildShadowView: " << getDebugPropsDescription( mutation.oldChildShadowView, {}); #endif } react_native_assert( (ShadowView)(*stubView) == mutation.oldChildShadowView); */ registry.erase(tag); break; } case ShadowViewMutation::Insert: { if (!mutation.mutatedViewIsVirtual()) { react_native_assert(mutation.oldChildShadowView == ShadowView{}); auto parentTag = mutation.parentShadowView.tag; auto childTag = mutation.newChildShadowView.tag; if (registry.find(parentTag) == registry.end()) { LOG(ERROR) << "StubView: ASSERT FAILURE: INSERT mutation assertion failure: parentTag not found: [" << parentTag << "] inserting child: [" << childTag << "]"; } if (registry.find(childTag) == registry.end()) { LOG(ERROR) << "StubView: ASSERT FAILURE: INSERT mutation assertion failure: childTag not found: [" << parentTag << "] inserting child: [" << childTag << "]"; } react_native_assert(registry.find(parentTag) != registry.end()); auto parentStubView = registry[parentTag]; react_native_assert(registry.find(childTag) != registry.end()); auto childStubView = registry[childTag]; react_native_assert(childStubView->parentTag == NO_VIEW_TAG); childStubView->update(mutation.newChildShadowView); STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Insert [" << childTag << "] into [" << parentTag << "] @" << mutation.index << "(" << parentStubView->children.size() << " children)"; }); react_native_assert( parentStubView->children.size() >= mutation.index); childStubView->parentTag = parentTag; parentStubView->children.insert( parentStubView->children.begin() + mutation.index, childStubView); } else { auto childTag = mutation.newChildShadowView.tag; react_native_assert(registry.find(childTag) != registry.end()); auto childStubView = registry[childTag]; childStubView->update(mutation.newChildShadowView); } break; } case ShadowViewMutation::Remove: { if (!mutation.mutatedViewIsVirtual()) { react_native_assert(mutation.newChildShadowView == ShadowView{}); auto parentTag = mutation.parentShadowView.tag; auto childTag = mutation.oldChildShadowView.tag; if (registry.find(parentTag) == registry.end()) { LOG(ERROR) << "StubView: ASSERT FAILURE: REMOVE mutation assertion failure: parentTag not found: [" << parentTag << "] removing child: [" << childTag << "]"; } react_native_assert(registry.find(parentTag) != registry.end()); auto parentStubView = registry[parentTag]; STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Remove [" << childTag << "] from [" << parentTag << "] @" << mutation.index << " with " << parentStubView->children.size() << " children"; }); react_native_assert(parentStubView->children.size() > mutation.index); react_native_assert(registry.find(childTag) != registry.end()); auto childStubView = registry[childTag]; if ((ShadowView)(*childStubView) != mutation.oldChildShadowView) { LOG(ERROR) << "StubView: ASSERT FAILURE: REMOVE mutation assertion failure: oldChildShadowView doesn't match oldStubView: [" << mutation.oldChildShadowView.tag << "] stub hash: ##" << std::hash<ShadowView>{}((ShadowView)*childStubView) << " old mutation hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "ChildStubView: " << getDebugPropsDescription( (ShadowView)*childStubView, {}); LOG(ERROR) << "OldChildShadowView: " << getDebugPropsDescription( mutation.oldChildShadowView, {}); #endif } react_native_assert( (ShadowView)(*childStubView) == mutation.oldChildShadowView); react_native_assert(childStubView->parentTag == parentTag); STUB_VIEW_LOG({ std::string strChildList = ""; int i = 0; for (auto const &child : parentStubView->children) { strChildList.append(std::to_string(i)); strChildList.append(":"); strChildList.append(std::to_string(child->tag)); strChildList.append(", "); i++; } LOG(ERROR) << "StubView: BEFORE REMOVE: Children of " << parentTag << ": " << strChildList; }); react_native_assert( parentStubView->children.size() > mutation.index && parentStubView->children[mutation.index]->tag == childStubView->tag); childStubView->parentTag = NO_VIEW_TAG; parentStubView->children.erase( parentStubView->children.begin() + mutation.index); } break; } case ShadowViewMutation::Update: { STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Update [" << mutation.newChildShadowView.tag << "] old hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView) << " new hash: ##" << std::hash<ShadowView>{}(mutation.newChildShadowView); }); react_native_assert(mutation.oldChildShadowView.tag != 0); react_native_assert(mutation.newChildShadowView.tag != 0); react_native_assert(mutation.newChildShadowView.props); react_native_assert( mutation.newChildShadowView.tag == mutation.oldChildShadowView.tag); react_native_assert( registry.find(mutation.newChildShadowView.tag) != registry.end()); auto oldStubView = registry[mutation.newChildShadowView.tag]; react_native_assert(oldStubView->tag != 0); if ((ShadowView)(*oldStubView) != mutation.oldChildShadowView) { LOG(ERROR) << "StubView: ASSERT FAILURE: UPDATE mutation assertion failure: oldChildShadowView doesn't match oldStubView: [" << mutation.oldChildShadowView.tag << "] old stub hash: ##" << std::hash<ShadowView>{}((ShadowView)*oldStubView) << " old mutation hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "OldStubView: " << getDebugPropsDescription((ShadowView)*oldStubView, {}); LOG(ERROR) << "OldChildShadowView: " << getDebugPropsDescription( mutation.oldChildShadowView, {}); #endif } react_native_assert( (ShadowView)(*oldStubView) == mutation.oldChildShadowView); oldStubView->update(mutation.newChildShadowView); // Hash for stub view and the ShadowView should be identical - this // tests that StubView and ShadowView hash are equivalent. react_native_assert( std::hash<ShadowView>{}((ShadowView)*oldStubView) == std::hash<ShadowView>{}(mutation.newChildShadowView)); break; } } } STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating End"; }); // For iOS especially: flush logs because some might be lost on iOS if an // assert is hit right after this. google::FlushLogFiles(google::INFO); } bool operator==(StubViewTree const &lhs, StubViewTree const &rhs) { if (lhs.registry.size() != rhs.registry.size()) { STUB_VIEW_LOG({ LOG(ERROR) << "Registry sizes are different. Sizes: LHS: " << lhs.registry.size() << " RHS: " << rhs.registry.size(); [&](std::ostream &stream) -> std::ostream & { stream << "Tags in LHS: "; for (auto const &pair : lhs.registry) { auto &lhsStubView = *lhs.registry.at(pair.first); stream << "[" << lhsStubView.tag << "]##" << std::hash<ShadowView>{}((ShadowView)lhsStubView) << " "; } return stream; }(LOG(ERROR)); [&](std::ostream &stream) -> std::ostream & { stream << "Tags in RHS: "; for (auto const &pair : rhs.registry) { auto &rhsStubView = *rhs.registry.at(pair.first); stream << "[" << rhsStubView.tag << "]##" << std::hash<ShadowView>{}((ShadowView)rhsStubView) << " "; } return stream; }(LOG(ERROR)); }); return false; } for (auto const &pair : lhs.registry) { auto &lhsStubView = *lhs.registry.at(pair.first); auto &rhsStubView = *rhs.registry.at(pair.first); if (lhsStubView != rhsStubView) { STUB_VIEW_LOG({ LOG(ERROR) << "Registry entries are different. LHS: [" << lhsStubView.tag << "] ##" << std::hash<ShadowView>{}((ShadowView)lhsStubView) << " RHS: [" << rhsStubView.tag << "] ##" << std::hash<ShadowView>{}((ShadowView)rhsStubView); }); return false; } } return true; } bool operator!=(StubViewTree const &lhs, StubViewTree const &rhs) { return !(lhs == rhs); } } // namespace react } // namespace facebook <commit_msg>StubViewTree: move assert to get better debug logging<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "StubViewTree.h" #include <glog/logging.h> #include <react/debug/react_native_assert.h> #ifdef STUB_VIEW_TREE_VERBOSE #define STUB_VIEW_LOG(code) code #else #define STUB_VIEW_LOG(code) #endif namespace facebook { namespace react { StubViewTree::StubViewTree(ShadowView const &shadowView) { auto view = std::make_shared<StubView>(); view->update(shadowView); rootTag = shadowView.tag; registry[shadowView.tag] = view; } StubView const &StubViewTree::getRootStubView() const { return *registry.at(rootTag); } StubView const &StubViewTree::getStubView(Tag tag) const { return *registry.at(tag); } size_t StubViewTree::size() const { return registry.size(); } void StubViewTree::mutate(ShadowViewMutationList const &mutations) { STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating Begin"; }); for (auto const &mutation : mutations) { switch (mutation.type) { case ShadowViewMutation::Create: { react_native_assert(mutation.parentShadowView == ShadowView{}); react_native_assert(mutation.oldChildShadowView == ShadowView{}); react_native_assert(mutation.newChildShadowView.props); auto stubView = std::make_shared<StubView>(); stubView->update(mutation.newChildShadowView); auto tag = mutation.newChildShadowView.tag; STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Create [" << tag << "] ##" << std::hash<ShadowView>{}((ShadowView)*stubView); }); react_native_assert(registry.find(tag) == registry.end()); registry[tag] = stubView; break; } case ShadowViewMutation::Delete: { STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Delete [" << mutation.oldChildShadowView.tag << "] ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); }); react_native_assert(mutation.parentShadowView == ShadowView{}); react_native_assert(mutation.newChildShadowView == ShadowView{}); auto tag = mutation.oldChildShadowView.tag; /* Disable this assert until T76057501 is resolved. react_native_assert(registry.find(tag) != registry.end()); auto stubView = registry[tag]; if ((ShadowView)(*stubView) != mutation.oldChildShadowView) { LOG(ERROR) << "StubView: ASSERT FAILURE: DELETE mutation assertion failure: oldChildShadowView doesn't match stubView: [" << mutation.oldChildShadowView.tag << "] stub hash: ##" << std::hash<ShadowView>{}((ShadowView)*stubView) << " old mutation hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "StubView: " << getDebugPropsDescription((ShadowView)*stubView, {}); LOG(ERROR) << "OldChildShadowView: " << getDebugPropsDescription( mutation.oldChildShadowView, {}); #endif } react_native_assert( (ShadowView)(*stubView) == mutation.oldChildShadowView); */ registry.erase(tag); break; } case ShadowViewMutation::Insert: { if (!mutation.mutatedViewIsVirtual()) { react_native_assert(mutation.oldChildShadowView == ShadowView{}); auto parentTag = mutation.parentShadowView.tag; auto childTag = mutation.newChildShadowView.tag; if (registry.find(parentTag) == registry.end()) { LOG(ERROR) << "StubView: ASSERT FAILURE: INSERT mutation assertion failure: parentTag not found: [" << parentTag << "] inserting child: [" << childTag << "]"; } if (registry.find(childTag) == registry.end()) { LOG(ERROR) << "StubView: ASSERT FAILURE: INSERT mutation assertion failure: childTag not found: [" << parentTag << "] inserting child: [" << childTag << "]"; } react_native_assert(registry.find(parentTag) != registry.end()); auto parentStubView = registry[parentTag]; react_native_assert(registry.find(childTag) != registry.end()); auto childStubView = registry[childTag]; childStubView->update(mutation.newChildShadowView); STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Insert [" << childTag << "] into [" << parentTag << "] @" << mutation.index << "(" << parentStubView->children.size() << " children)"; }); react_native_assert(childStubView->parentTag == NO_VIEW_TAG); react_native_assert( parentStubView->children.size() >= mutation.index); childStubView->parentTag = parentTag; parentStubView->children.insert( parentStubView->children.begin() + mutation.index, childStubView); } else { auto childTag = mutation.newChildShadowView.tag; react_native_assert(registry.find(childTag) != registry.end()); auto childStubView = registry[childTag]; childStubView->update(mutation.newChildShadowView); } break; } case ShadowViewMutation::Remove: { if (!mutation.mutatedViewIsVirtual()) { react_native_assert(mutation.newChildShadowView == ShadowView{}); auto parentTag = mutation.parentShadowView.tag; auto childTag = mutation.oldChildShadowView.tag; if (registry.find(parentTag) == registry.end()) { LOG(ERROR) << "StubView: ASSERT FAILURE: REMOVE mutation assertion failure: parentTag not found: [" << parentTag << "] removing child: [" << childTag << "]"; } react_native_assert(registry.find(parentTag) != registry.end()); auto parentStubView = registry[parentTag]; STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Remove [" << childTag << "] from [" << parentTag << "] @" << mutation.index << " with " << parentStubView->children.size() << " children"; }); react_native_assert(parentStubView->children.size() > mutation.index); react_native_assert(registry.find(childTag) != registry.end()); auto childStubView = registry[childTag]; if ((ShadowView)(*childStubView) != mutation.oldChildShadowView) { LOG(ERROR) << "StubView: ASSERT FAILURE: REMOVE mutation assertion failure: oldChildShadowView doesn't match oldStubView: [" << mutation.oldChildShadowView.tag << "] stub hash: ##" << std::hash<ShadowView>{}((ShadowView)*childStubView) << " old mutation hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "ChildStubView: " << getDebugPropsDescription( (ShadowView)*childStubView, {}); LOG(ERROR) << "OldChildShadowView: " << getDebugPropsDescription( mutation.oldChildShadowView, {}); #endif } react_native_assert( (ShadowView)(*childStubView) == mutation.oldChildShadowView); react_native_assert(childStubView->parentTag == parentTag); STUB_VIEW_LOG({ std::string strChildList = ""; int i = 0; for (auto const &child : parentStubView->children) { strChildList.append(std::to_string(i)); strChildList.append(":"); strChildList.append(std::to_string(child->tag)); strChildList.append(", "); i++; } LOG(ERROR) << "StubView: BEFORE REMOVE: Children of " << parentTag << ": " << strChildList; }); react_native_assert( parentStubView->children.size() > mutation.index && parentStubView->children[mutation.index]->tag == childStubView->tag); childStubView->parentTag = NO_VIEW_TAG; parentStubView->children.erase( parentStubView->children.begin() + mutation.index); } break; } case ShadowViewMutation::Update: { STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Update [" << mutation.newChildShadowView.tag << "] old hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView) << " new hash: ##" << std::hash<ShadowView>{}(mutation.newChildShadowView); }); react_native_assert(mutation.oldChildShadowView.tag != 0); react_native_assert(mutation.newChildShadowView.tag != 0); react_native_assert(mutation.newChildShadowView.props); react_native_assert( mutation.newChildShadowView.tag == mutation.oldChildShadowView.tag); react_native_assert( registry.find(mutation.newChildShadowView.tag) != registry.end()); auto oldStubView = registry[mutation.newChildShadowView.tag]; react_native_assert(oldStubView->tag != 0); if ((ShadowView)(*oldStubView) != mutation.oldChildShadowView) { LOG(ERROR) << "StubView: ASSERT FAILURE: UPDATE mutation assertion failure: oldChildShadowView doesn't match oldStubView: [" << mutation.oldChildShadowView.tag << "] old stub hash: ##" << std::hash<ShadowView>{}((ShadowView)*oldStubView) << " old mutation hash: ##" << std::hash<ShadowView>{}(mutation.oldChildShadowView); #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "OldStubView: " << getDebugPropsDescription((ShadowView)*oldStubView, {}); LOG(ERROR) << "OldChildShadowView: " << getDebugPropsDescription( mutation.oldChildShadowView, {}); #endif } react_native_assert( (ShadowView)(*oldStubView) == mutation.oldChildShadowView); oldStubView->update(mutation.newChildShadowView); // Hash for stub view and the ShadowView should be identical - this // tests that StubView and ShadowView hash are equivalent. react_native_assert( std::hash<ShadowView>{}((ShadowView)*oldStubView) == std::hash<ShadowView>{}(mutation.newChildShadowView)); break; } } } STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating End"; }); // For iOS especially: flush logs because some might be lost on iOS if an // assert is hit right after this. google::FlushLogFiles(google::INFO); } bool operator==(StubViewTree const &lhs, StubViewTree const &rhs) { if (lhs.registry.size() != rhs.registry.size()) { STUB_VIEW_LOG({ LOG(ERROR) << "Registry sizes are different. Sizes: LHS: " << lhs.registry.size() << " RHS: " << rhs.registry.size(); [&](std::ostream &stream) -> std::ostream & { stream << "Tags in LHS: "; for (auto const &pair : lhs.registry) { auto &lhsStubView = *lhs.registry.at(pair.first); stream << "[" << lhsStubView.tag << "]##" << std::hash<ShadowView>{}((ShadowView)lhsStubView) << " "; } return stream; }(LOG(ERROR)); [&](std::ostream &stream) -> std::ostream & { stream << "Tags in RHS: "; for (auto const &pair : rhs.registry) { auto &rhsStubView = *rhs.registry.at(pair.first); stream << "[" << rhsStubView.tag << "]##" << std::hash<ShadowView>{}((ShadowView)rhsStubView) << " "; } return stream; }(LOG(ERROR)); }); return false; } for (auto const &pair : lhs.registry) { auto &lhsStubView = *lhs.registry.at(pair.first); auto &rhsStubView = *rhs.registry.at(pair.first); if (lhsStubView != rhsStubView) { STUB_VIEW_LOG({ LOG(ERROR) << "Registry entries are different. LHS: [" << lhsStubView.tag << "] ##" << std::hash<ShadowView>{}((ShadowView)lhsStubView) << " RHS: [" << rhsStubView.tag << "] ##" << std::hash<ShadowView>{}((ShadowView)rhsStubView); }); return false; } } return true; } bool operator!=(StubViewTree const &lhs, StubViewTree const &rhs) { return !(lhs == rhs); } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>#ifndef MPACK_DEBUG_HPP #define MPACK_DEBUG_HPP #define DEBUG #include "Types.hpp" #include "Helper.hpp" #include "Log.hpp" #ifndef DEBUG #define PRINT(x) #define D if(0) #else #define PRINT(x) \ LOGD("%s\t%s\n",#x,x) #define D if(1) #endif #ifndef DEBUG #define LOGE(...) #define LOGW(...) #define LOGI(...) #define LOGD(...) #else #define LOGE(...) MPACK::Core::Log::Error(__VA_ARGS__) #define LOGW(...) MPACK::Core::Log::Warn(__VA_ARGS__) #define LOGI(...) MPACK::Core::Log::Info(__VA_ARGS__) #define LOGD(...) MPACK::Core::Log::Debug(__VA_ARGS__) #endif #ifndef DEBUG #define GL_CHECK(something) something #else #define GL_CHECK(something) do { \ something; \ Debug::OpenGL::CheckErrorMacro(#something, __FILE__, __LINE__); \ } while (0) #endif #ifndef DEBUG #define EGL_CHECK(something) something #else #define EGL_CHECK(something) do { \ something; \ Debug::EGL::CheckErrorMacro(#something, __FILE__, __LINE__); \ } while (0) #endif namespace MPACK { namespace Graphics { class TextureMappedFont; } } namespace MPACK { namespace Debug { extern int printLines; extern int circlePoints; extern float printFontSize; extern float layer; void InitFrame(); void Print(Graphics::TextureMappedFont *font, const char *message, ...); namespace OpenGL { GLenum GetError(); const char* GetErrorString(const GLenum &error); void SetMaxErrorCounter(int number); int GetMaxErrorCounter(); int GetErrorCounter(); void Assert(const char *pMessage); void FlushErrors(const char *pMessage); void CheckErrorMacro(const char* pContent, const char* pFilename, int line); } namespace EGL { EGLint GetError(); const char* GetErrorString(const EGLint &error); void SetMaxErrorCounter(int number); int GetMaxErrorCounter(); int GetErrorCounter(); void Assert(const char *pMessage); void CheckErrorMacro(const char* pContent, const char* pFilename, int line); } } } #endif <commit_msg>GL_CHECK and EGL_CHECK can now be used from anywhere<commit_after>#ifndef MPACK_DEBUG_HPP #define MPACK_DEBUG_HPP #define DEBUG #include "Types.hpp" #include "Helper.hpp" #include "Log.hpp" #ifndef DEBUG #define PRINT(x) #define D if(0) #else #define PRINT(x) \ LOGD("%s\t%s\n",#x,x) #define D if(1) #endif #ifndef DEBUG #define LOGE(...) #define LOGW(...) #define LOGI(...) #define LOGD(...) #else #define LOGE(...) MPACK::Core::Log::Error(__VA_ARGS__) #define LOGW(...) MPACK::Core::Log::Warn(__VA_ARGS__) #define LOGI(...) MPACK::Core::Log::Info(__VA_ARGS__) #define LOGD(...) MPACK::Core::Log::Debug(__VA_ARGS__) #endif #ifndef DEBUG #define GL_CHECK(something) something #else #define GL_CHECK(something) do { \ something; \ MPACK::Debug::OpenGL::CheckErrorMacro(#something, __FILE__, __LINE__); \ } while (0) #endif #ifndef DEBUG #define EGL_CHECK(something) something #else #define EGL_CHECK(something) do { \ something; \ MPACK::Debug::EGL::CheckErrorMacro(#something, __FILE__, __LINE__); \ } while (0) #endif namespace MPACK { namespace Graphics { class TextureMappedFont; } } namespace MPACK { namespace Debug { extern int printLines; extern int circlePoints; extern float printFontSize; extern float layer; void InitFrame(); void Print(Graphics::TextureMappedFont *font, const char *message, ...); namespace OpenGL { GLenum GetError(); const char* GetErrorString(const GLenum &error); void SetMaxErrorCounter(int number); int GetMaxErrorCounter(); int GetErrorCounter(); void Assert(const char *pMessage); void FlushErrors(const char *pMessage); void CheckErrorMacro(const char* pContent, const char* pFilename, int line); } namespace EGL { EGLint GetError(); const char* GetErrorString(const EGLint &error); void SetMaxErrorCounter(int number); int GetMaxErrorCounter(); int GetErrorCounter(); void Assert(const char *pMessage); void CheckErrorMacro(const char* pContent, const char* pFilename, int line); } } } #endif <|endoftext|>
<commit_before>// $Id: metis_partitioner.C,v 1.21 2005-09-09 12:26:51 jwpeterson Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ Includes ----------------------------------- // Local Includes ----------------------------------- #include "libmesh_config.h" #include "mesh_base.h" #include "metis_partitioner.h" #include "libmesh_logging.h" #include "elem.h" #ifdef HAVE_METIS namespace Metis { extern "C" { # include "metis.h" } } #else # include "sfc_partitioner.h" #endif // ------------------------------------------------------------ // MetisPartitioner implementation void MetisPartitioner::_do_partition (MeshBase& mesh, const unsigned int n_pieces) { assert (n_pieces > 0); // Check for an easy return if (n_pieces == 1) { this->single_partition (mesh); return; } // What to do if the Metis library IS NOT present #ifndef HAVE_METIS here(); std::cerr << "ERROR: The library has been built without" << std::endl << "Metis support. Using a space-filling curve" << std::endl << "partitioner instead!" << std::endl; SFCPartitioner sfcp; sfcp.partition (mesh, n_pieces); // What to do if the Metis library IS present #else START_LOG("partition()", "MetisPartitioner"); const unsigned int n_active_elem = mesh.n_active_elem(); const unsigned int n_elem = mesh.n_elem(); // build the graph // the forward_map maps each active element id // into a contiguous block of indices for Metis std::vector<unsigned int> forward_map (n_elem, libMesh::invalid_uint); std::vector<int> xadj; std::vector<int> adjncy; std::vector<int> options(5); std::vector<int> vwgt(n_active_elem); std::vector<int> part(n_active_elem); xadj.reserve(n_active_elem+1); int n = static_cast<int>(n_active_elem), // number of "nodes" (elements) // in the graph wgtflag = 2, // weights on vertices only, // none on edges numflag = 0, // C-style 0-based numbering nparts = static_cast<int>(n_pieces), // number of subdomains to create edgecut = 0; // the numbers of edges cut by the // resulting partition // Set the options options[0] = 0; // use default options // Metis will only consider the active elements. // We need to map the active element ids into a // contiguous range. { MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); unsigned int el_num = 0; for (; elem_it != elem_end; ++elem_it) { assert ((*elem_it)->id() < forward_map.size()); forward_map[(*elem_it)->id()] = el_num++; } assert (el_num == n_active_elem); } // build the graph in CSR format. Note that // the edges in the graph will correspond to // face neighbors { std::vector<const Elem*> neighbors_offspring; MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); // This will be exact when there is no refinement and all the // elements are of the same type. adjncy.reserve (n_active_elem*(*elem_it)->n_neighbors()); for (; elem_it != elem_end; ++elem_it) { const Elem* elem = *elem_it; assert (elem->id() < forward_map.size()); assert (forward_map[elem->id()] != libMesh::invalid_uint); // maybe there is a better weight? // The weight is used to define what a balanced graph is vwgt[forward_map[elem->id()]] = elem->n_nodes(); // The beginning of the adjacency array for this elem xadj.push_back(adjncy.size()); // Loop over the element's neighbors. An element // adjacency corresponds to a face neighbor for (unsigned int ms=0; ms<elem->n_neighbors(); ms++) { const Elem* neighbor = elem->neighbor(ms); if (neighbor != NULL) { // If the neighbor is active treat it // as a connection if (neighbor->active()) { assert (neighbor->id() < forward_map.size()); assert (forward_map[neighbor->id()] != libMesh::invalid_uint); adjncy.push_back (forward_map[neighbor->id()]); } #ifdef ENABLE_AMR // Otherwise we need to find all of the // neighbor's children that are connected to // us and add them else { // The side of the neighbor to which // we are connected const unsigned int ns = neighbor->which_neighbor_am_i (elem); // Get all the active children (& grandchildren, etc...) // of the neighbor. neighbor->active_family_tree (neighbors_offspring); // Get all the neighbor's children that // live on that side and are thus connected // to us for (unsigned int nc=0; nc<neighbors_offspring.size(); nc++) { const Elem* child = neighbors_offspring[nc]; // This does not assume a level-1 mesh. // Note that since children have sides numbered // coincident with the parent then this is a sufficient test. if (child->neighbor(ns) == elem) { assert (child->active()); assert (child->id() < forward_map.size()); assert (forward_map[child->id()] != libMesh::invalid_uint); adjncy.push_back (forward_map[child->id()]); } } } #endif /* ifdef ENABLE_AMR */ } } } // The end of the adjacency array for the last elem xadj.push_back(adjncy.size()); } // done building the graph // Select which type of partitioning to create // Use recursive if the number of partitions is less than or equal to 8 if (n_pieces <= 8) Metis::METIS_PartGraphRecursive(&n, &xadj[0], &adjncy[0], &vwgt[0], NULL, &wgtflag, &numflag, &nparts, &options[0], &edgecut, &part[0]); // Otherwise use kway else Metis::METIS_PartGraphKway(&n, &xadj[0], &adjncy[0], &vwgt[0], NULL, &wgtflag, &numflag, &nparts, &options[0], &edgecut, &part[0]); // Assign the returned processor ids. The part array contains // the processor id for each active element, but in terms of // the contiguous indexing we defined above { MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; assert (elem->id() < forward_map.size()); assert (forward_map[elem->id()] != libMesh::invalid_uint); elem->processor_id() = static_cast<short int>(part[forward_map[elem->id()]]); } } STOP_LOG("partition()", "MetisPartitioner"); #endif } <commit_msg>fixed for MIPSPro<commit_after>// $Id: metis_partitioner.C,v 1.22 2005-09-30 20:14:12 benkirk Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ Includes ----------------------------------- // Local Includes ----------------------------------- #include "libmesh_config.h" #include "mesh_base.h" #include "metis_partitioner.h" #include "libmesh_logging.h" #include "elem.h" #ifdef HAVE_METIS // MIPSPro 7.4.2 gets confused about these nested namespaces # ifdef __sgi # include <cstdarg> # endif namespace Metis { extern "C" { # include "metis.h" } } #else # include "sfc_partitioner.h" #endif // ------------------------------------------------------------ // MetisPartitioner implementation void MetisPartitioner::_do_partition (MeshBase& mesh, const unsigned int n_pieces) { assert (n_pieces > 0); // Check for an easy return if (n_pieces == 1) { this->single_partition (mesh); return; } // What to do if the Metis library IS NOT present #ifndef HAVE_METIS here(); std::cerr << "ERROR: The library has been built without" << std::endl << "Metis support. Using a space-filling curve" << std::endl << "partitioner instead!" << std::endl; SFCPartitioner sfcp; sfcp.partition (mesh, n_pieces); // What to do if the Metis library IS present #else START_LOG("partition()", "MetisPartitioner"); const unsigned int n_active_elem = mesh.n_active_elem(); const unsigned int n_elem = mesh.n_elem(); // build the graph // the forward_map maps each active element id // into a contiguous block of indices for Metis std::vector<unsigned int> forward_map (n_elem, libMesh::invalid_uint); std::vector<int> xadj; std::vector<int> adjncy; std::vector<int> options(5); std::vector<int> vwgt(n_active_elem); std::vector<int> part(n_active_elem); xadj.reserve(n_active_elem+1); int n = static_cast<int>(n_active_elem), // number of "nodes" (elements) // in the graph wgtflag = 2, // weights on vertices only, // none on edges numflag = 0, // C-style 0-based numbering nparts = static_cast<int>(n_pieces), // number of subdomains to create edgecut = 0; // the numbers of edges cut by the // resulting partition // Set the options options[0] = 0; // use default options // Metis will only consider the active elements. // We need to map the active element ids into a // contiguous range. { MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); unsigned int el_num = 0; for (; elem_it != elem_end; ++elem_it) { assert ((*elem_it)->id() < forward_map.size()); forward_map[(*elem_it)->id()] = el_num++; } assert (el_num == n_active_elem); } // build the graph in CSR format. Note that // the edges in the graph will correspond to // face neighbors { std::vector<const Elem*> neighbors_offspring; MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); // This will be exact when there is no refinement and all the // elements are of the same type. adjncy.reserve (n_active_elem*(*elem_it)->n_neighbors()); for (; elem_it != elem_end; ++elem_it) { const Elem* elem = *elem_it; assert (elem->id() < forward_map.size()); assert (forward_map[elem->id()] != libMesh::invalid_uint); // maybe there is a better weight? // The weight is used to define what a balanced graph is vwgt[forward_map[elem->id()]] = elem->n_nodes(); // The beginning of the adjacency array for this elem xadj.push_back(adjncy.size()); // Loop over the element's neighbors. An element // adjacency corresponds to a face neighbor for (unsigned int ms=0; ms<elem->n_neighbors(); ms++) { const Elem* neighbor = elem->neighbor(ms); if (neighbor != NULL) { // If the neighbor is active treat it // as a connection if (neighbor->active()) { assert (neighbor->id() < forward_map.size()); assert (forward_map[neighbor->id()] != libMesh::invalid_uint); adjncy.push_back (forward_map[neighbor->id()]); } #ifdef ENABLE_AMR // Otherwise we need to find all of the // neighbor's children that are connected to // us and add them else { // The side of the neighbor to which // we are connected const unsigned int ns = neighbor->which_neighbor_am_i (elem); // Get all the active children (& grandchildren, etc...) // of the neighbor. neighbor->active_family_tree (neighbors_offspring); // Get all the neighbor's children that // live on that side and are thus connected // to us for (unsigned int nc=0; nc<neighbors_offspring.size(); nc++) { const Elem* child = neighbors_offspring[nc]; // This does not assume a level-1 mesh. // Note that since children have sides numbered // coincident with the parent then this is a sufficient test. if (child->neighbor(ns) == elem) { assert (child->active()); assert (child->id() < forward_map.size()); assert (forward_map[child->id()] != libMesh::invalid_uint); adjncy.push_back (forward_map[child->id()]); } } } #endif /* ifdef ENABLE_AMR */ } } } // The end of the adjacency array for the last elem xadj.push_back(adjncy.size()); } // done building the graph // Select which type of partitioning to create // Use recursive if the number of partitions is less than or equal to 8 if (n_pieces <= 8) Metis::METIS_PartGraphRecursive(&n, &xadj[0], &adjncy[0], &vwgt[0], NULL, &wgtflag, &numflag, &nparts, &options[0], &edgecut, &part[0]); // Otherwise use kway else Metis::METIS_PartGraphKway(&n, &xadj[0], &adjncy[0], &vwgt[0], NULL, &wgtflag, &numflag, &nparts, &options[0], &edgecut, &part[0]); // Assign the returned processor ids. The part array contains // the processor id for each active element, but in terms of // the contiguous indexing we defined above { MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; assert (elem->id() < forward_map.size()); assert (forward_map[elem->id()] != libMesh::invalid_uint); elem->processor_id() = static_cast<short int>(part[forward_map[elem->id()]]); } } STOP_LOG("partition()", "MetisPartitioner"); #endif } <|endoftext|>
<commit_before>#include <stdexcept> #include <unordered_map> #include "Windowsx.h" #include "windowswindow.hh" #include "system/mousebutton.hh" #include "system/keycode.hh" static char appName[] = "Test Application"; using System::KeyCode; class KeyMap : public std::unordered_map<WPARAM, System::KeyCode> { public: KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() { (*this)[VK_PRIOR] = KeyCode::KeyPageUp; (*this)[VK_NEXT] = KeyCode::KeyPageDown; (*this)[VK_END] = KeyCode::KeyEnd; (*this)[VK_HOME] = KeyCode::KeyHome; (*this)[VK_INSERT] = KeyCode::KeyInsert; (*this)[VK_DELETE] = KeyCode::KeyDelete; (*this)[VK_RIGHT] = KeyCode::KeyRightArrow; (*this)[VK_DOWN] = KeyCode::KeyDownArrow; (*this)[VK_LEFT] = KeyCode::KeyLeftArrow; (*this)[VK_UP] = KeyCode::KeyUpArrow; (*this)[VK_ESCAPE] = KeyCode::KeyEscape; (*this)[VK_TAB] = KeyCode::KeyTab; (*this)[VK_SHIFT] = KeyCode::KeyShift; (*this)[VK_MENU] = KeyCode::KeyAlt; (*this)[VK_CONTROL] = KeyCode::KeyControl; (*this)[VK_CAPITAL] = KeyCode::KeyCapsLock; (*this)[VK_RCONTROL] = KeyCode::KeyRightControl; (*this)[VK_LCONTROL] = KeyCode::KeyLeftControl; (*this)[VK_RSHIFT] = KeyCode::KeyRightShift; (*this)[VK_LSHIFT] = KeyCode::KeyLeftShift; (*this)[VK_BACK] = KeyCode::KeyBackspace; (*this)[VK_RETURN] = KeyCode::KeyEnter; (*this)[VK_SPACE] = KeyCode::KeySpace; (*this)[0x30] = KeyCode::Key0; (*this)[0x31] = KeyCode::Key1; (*this)[0x32] = KeyCode::Key2; (*this)[0x33] = KeyCode::Key3; (*this)[0x34] = KeyCode::Key4; (*this)[0x35] = KeyCode::Key5; (*this)[0x36] = KeyCode::Key6; (*this)[0x37] = KeyCode::Key7; (*this)[0x38] = KeyCode::Key8; (*this)[0x39] = KeyCode::Key9; (*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0; (*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1; (*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2; (*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3; (*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4; (*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5; (*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6; (*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7; (*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8; (*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9; (*this)[VK_MULTIPLY] = KeyCode::KeyMultiply; (*this)[VK_ADD] = KeyCode::KeyPlus; (*this)[VK_SUBTRACT] = KeyCode::KeyMinus; (*this)[VK_DIVIDE] = KeyCode::KeyDivide; (*this)[VK_DECIMAL] = KeyCode::KeyDecimal; (*this)[0x41] = KeyCode::KeyA; (*this)[0x42] = KeyCode::KeyB; (*this)[0x43] = KeyCode::KeyC; (*this)[0x44] = KeyCode::KeyD; (*this)[0x45] = KeyCode::KeyE; (*this)[0x46] = KeyCode::KeyF; (*this)[0x47] = KeyCode::KeyG; (*this)[0x48] = KeyCode::KeyH; (*this)[0x49] = KeyCode::KeyI; (*this)[0x4A] = KeyCode::KeyJ; (*this)[0x4B] = KeyCode::KeyK; (*this)[0x4C] = KeyCode::KeyL; (*this)[0x4D] = KeyCode::KeyM; (*this)[0x4E] = KeyCode::KeyN; (*this)[0x4F] = KeyCode::KeyO; (*this)[0x50] = KeyCode::KeyP; (*this)[0x51] = KeyCode::KeyQ; (*this)[0x52] = KeyCode::KeyR; (*this)[0x53] = KeyCode::KeyS; (*this)[0x54] = KeyCode::KeyT; (*this)[0x55] = KeyCode::KeyU; (*this)[0x56] = KeyCode::KeyV; (*this)[0x57] = KeyCode::KeyW; (*this)[0x59] = KeyCode::KeyY; (*this)[0x5A] = KeyCode::KeyZ; } }; static KeyMap keyMap; static std::unordered_map<HWND, WindowsWindow*> windowMap; WindowsWindow::WindowsWindow(const char *windowName, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow) : m_controller(controller), m_openGLContext(NULL) { m_windowHandle = WindowsWindow::makeWindow(windowName, processInstance, commandShow); ShowWindow(m_windowHandle, commandShow); UpdateWindow(m_windowHandle); unsigned int windowWidth, windowHeight; GetWindowSize(&windowWidth, &windowHeight); m_controller->OnWindowResize(windowWidth, windowHeight); windowMap[m_windowHandle] = this; } HWND WindowsWindow::makeWindow(const char *windowName, HINSTANCE processInstance, int commandShow) { WNDCLASSEX windowClass; windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_VREDRAW | CS_HREDRAW; windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = processInstance; windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH); windowClass.lpszClassName = appName; windowClass.lpszMenuName = NULL; RegisterClassEx(&windowClass); return CreateWindow(appName, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, processInstance, NULL); } WindowsWindow::~WindowsWindow() { windowMap[m_windowHandle] = NULL; } int WindowsWindow::DoMessageLoop() { MSG message; Ready(); while (GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } return message.wParam; } void WindowsWindow::GetWindowSize(unsigned int *width, unsigned int *height) { RECT rect; GetClientRect(m_windowHandle, &rect); *width = rect.right - rect.left; *height = rect.bottom - rect.top; } bool WindowsWindow::SetMousePosition(unsigned int posX, unsigned int posY) { POINT point; point.x = posX; point.y = posY; bool success = ClientToScreen(m_windowHandle, &point) ? SetCursorPos(point.x, point.y) : false; if (success) m_controller->OnMouseMove(point.x, point.y); return success; } void WindowsWindow::Destroy() { SendNotifyMessage(m_windowHandle, WM_DESTROY, 0, 0); } void WindowsWindow::Close() { SendNotifyMessage(m_windowHandle, WM_CLOSE, 0, 0); } void WindowsWindow::Ready() { m_controller->OnWindowReady(); } void WindowsWindow::onClose() { m_controller->OnWindowClose(); } void WindowsWindow::KeyDown(WPARAM key) { m_controller->OnKeyDown(keyMap[key]); } void WindowsWindow::WindowResize(WPARAM wParam, LPARAM lParam) { m_controller->OnWindowResize(LOWORD(lParam), HIWORD(lParam)); } void WindowsWindow::KeyUp(WPARAM key) { m_controller->OnKeyUp(keyMap[key]); } void WindowsWindow::MouseMove(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); } void WindowsWindow::LeftMouseButtonDown(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonDown(System::MouseButton::Button1); } void WindowsWindow::RightMouseButtonDown(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonDown(System::MouseButton::Button2); } void WindowsWindow::LeftMouseButtonUp(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonUp(System::MouseButton::Button1); } void WindowsWindow::RightMouseButtonUp(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonUp(System::MouseButton::Button2); } void WindowsWindow::MouseScrollWheel(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA); } LRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam) { switch(message) { case WM_KEYDOWN: windowMap[windowHandle]->KeyDown(wparam); return 0; case WM_KEYUP: windowMap[windowHandle]->KeyUp(wparam); return 0; case WM_MOUSEMOVE: windowMap[windowHandle]->MouseMove(wparam, lparam); return 0; case WM_LBUTTONDOWN: windowMap[windowHandle]->LeftMouseButtonDown(wparam, lparam); return 0; case WM_LBUTTONUP: windowMap[windowHandle]->LeftMouseButtonUp(wparam, lparam); return 0; case WM_RBUTTONDOWN: windowMap[windowHandle]->RightMouseButtonDown(wparam, lparam); return 0; case WM_RBUTTONUP: windowMap[windowHandle]->RightMouseButtonUp(wparam, lparam); return 0; case WM_MOUSEWHEEL: windowMap[windowHandle]->MouseScrollWheel(wparam, lparam); return 0; case WM_SIZE: windowMap[windowHandle]->WindowResize(wparam, lparam); return 0; case WM_CLOSE: windowMap[windowHandle]->onClose(); return 0; case WM_DESTROY: PostQuitMessage(0); windowMap[windowHandle] = NULL; return 0; default: return DefWindowProc(windowHandle, message, wparam, lparam); } } <commit_msg>Fix windows build<commit_after>#include <stdexcept> #include <unordered_map> #include "Windowsx.h" #include "windowswindow.hh" #include "system/mousebutton.hh" #include "system/keycode.hh" static char appName[] = "Test Application"; using System::KeyCode; class KeyMap : public std::unordered_map<WPARAM, System::KeyCode> { public: KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() { (*this)[VK_PRIOR] = KeyCode::KeyPageUp; (*this)[VK_NEXT] = KeyCode::KeyPageDown; (*this)[VK_END] = KeyCode::KeyEnd; (*this)[VK_HOME] = KeyCode::KeyHome; (*this)[VK_INSERT] = KeyCode::KeyInsert; (*this)[VK_DELETE] = KeyCode::KeyDelete; (*this)[VK_RIGHT] = KeyCode::KeyRightArrow; (*this)[VK_DOWN] = KeyCode::KeyDownArrow; (*this)[VK_LEFT] = KeyCode::KeyLeftArrow; (*this)[VK_UP] = KeyCode::KeyUpArrow; (*this)[VK_ESCAPE] = KeyCode::KeyEscape; (*this)[VK_TAB] = KeyCode::KeyTab; (*this)[VK_SHIFT] = KeyCode::KeyShift; (*this)[VK_MENU] = KeyCode::KeyAlt; (*this)[VK_CONTROL] = KeyCode::KeyControl; (*this)[VK_CAPITAL] = KeyCode::KeyCapsLock; (*this)[VK_RCONTROL] = KeyCode::KeyRightControl; (*this)[VK_LCONTROL] = KeyCode::KeyLeftControl; (*this)[VK_RSHIFT] = KeyCode::KeyRightShift; (*this)[VK_LSHIFT] = KeyCode::KeyLeftShift; (*this)[VK_BACK] = KeyCode::KeyBackspace; (*this)[VK_RETURN] = KeyCode::KeyEnter; (*this)[VK_SPACE] = KeyCode::KeySpace; (*this)[0x30] = KeyCode::Key0; (*this)[0x31] = KeyCode::Key1; (*this)[0x32] = KeyCode::Key2; (*this)[0x33] = KeyCode::Key3; (*this)[0x34] = KeyCode::Key4; (*this)[0x35] = KeyCode::Key5; (*this)[0x36] = KeyCode::Key6; (*this)[0x37] = KeyCode::Key7; (*this)[0x38] = KeyCode::Key8; (*this)[0x39] = KeyCode::Key9; (*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0; (*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1; (*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2; (*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3; (*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4; (*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5; (*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6; (*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7; (*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8; (*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9; (*this)[VK_MULTIPLY] = KeyCode::KeyMultiply; (*this)[VK_ADD] = KeyCode::KeyPlus; (*this)[VK_SUBTRACT] = KeyCode::KeyMinus; (*this)[VK_DIVIDE] = KeyCode::KeyDivide; (*this)[VK_DECIMAL] = KeyCode::KeyDecimal; (*this)[0x41] = KeyCode::KeyA; (*this)[0x42] = KeyCode::KeyB; (*this)[0x43] = KeyCode::KeyC; (*this)[0x44] = KeyCode::KeyD; (*this)[0x45] = KeyCode::KeyE; (*this)[0x46] = KeyCode::KeyF; (*this)[0x47] = KeyCode::KeyG; (*this)[0x48] = KeyCode::KeyH; (*this)[0x49] = KeyCode::KeyI; (*this)[0x4A] = KeyCode::KeyJ; (*this)[0x4B] = KeyCode::KeyK; (*this)[0x4C] = KeyCode::KeyL; (*this)[0x4D] = KeyCode::KeyM; (*this)[0x4E] = KeyCode::KeyN; (*this)[0x4F] = KeyCode::KeyO; (*this)[0x50] = KeyCode::KeyP; (*this)[0x51] = KeyCode::KeyQ; (*this)[0x52] = KeyCode::KeyR; (*this)[0x53] = KeyCode::KeyS; (*this)[0x54] = KeyCode::KeyT; (*this)[0x55] = KeyCode::KeyU; (*this)[0x56] = KeyCode::KeyV; (*this)[0x57] = KeyCode::KeyW; (*this)[0x59] = KeyCode::KeyY; (*this)[0x5A] = KeyCode::KeyZ; } }; static KeyMap keyMap; static std::unordered_map<HWND, WindowsWindow*> windowMap; WindowsWindow::WindowsWindow(const char *windowName, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow) : m_controller(controller), m_openGLContext(NULL) { m_windowHandle = WindowsWindow::makeWindow(windowName, processInstance, commandShow); ShowWindow(m_windowHandle, commandShow); UpdateWindow(m_windowHandle); unsigned int windowWidth, windowHeight; GetWindowSize(&windowWidth, &windowHeight); m_controller->OnWindowResize(windowWidth, windowHeight); windowMap[m_windowHandle] = this; } HWND WindowsWindow::makeWindow(const char *windowName, HINSTANCE processInstance, int commandShow) { WNDCLASSEX windowClass; windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_VREDRAW | CS_HREDRAW; windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = processInstance; windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH); windowClass.lpszClassName = appName; windowClass.lpszMenuName = NULL; RegisterClassEx(&windowClass); return CreateWindow(appName, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, processInstance, NULL); } WindowsWindow::~WindowsWindow() { windowMap[m_windowHandle] = NULL; } int WindowsWindow::DoMessageLoop() { MSG message; Ready(); while (GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } return message.wParam; } void WindowsWindow::GetWindowSize(unsigned int *width, unsigned int *height) { RECT rect; GetClientRect(m_windowHandle, &rect); *width = rect.right - rect.left; *height = rect.bottom - rect.top; } bool WindowsWindow::SetMousePosition(unsigned int posX, unsigned int posY) { POINT point; point.x = posX; point.y = posY; bool success = ClientToScreen(m_windowHandle, &point) ? SetCursorPos(point.x, point.y) : false; if (success) m_controller->OnMouseMove(point.x, point.y); return success; } void WindowsWindow::Destroy() { SendNotifyMessage(m_windowHandle, WM_DESTROY, 0, 0); } void WindowsWindow::Close() { SendNotifyMessage(m_windowHandle, WM_CLOSE, 0, 0); } void WindowsWindow::Ready() { m_controller->OnWindowReady(); } void WindowsWindow::onClose() { m_controller->OnWindowClose(); } void WindowsWindow::KeyDown(WPARAM key) { m_controller->OnKeyDown(keyMap[key]); } void WindowsWindow::WindowResize(WPARAM wParam, LPARAM lParam) { m_controller->OnWindowResize(LOWORD(lParam), HIWORD(lParam)); } void WindowsWindow::KeyUp(WPARAM key) { m_controller->OnKeyUp(keyMap[key]); } void WindowsWindow::MouseMove(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); } void WindowsWindow::LeftMouseButtonDown(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonDown(System::MouseButton::ButtonOne); } void WindowsWindow::RightMouseButtonDown(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonDown(System::MouseButton::ButtonTwo); } void WindowsWindow::LeftMouseButtonUp(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonUp(System::MouseButton::ButtonOne); } void WindowsWindow::RightMouseButtonUp(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseButtonUp(System::MouseButton::ButtonTwo); } void WindowsWindow::MouseScrollWheel(WPARAM wParam, LPARAM lParam) { m_controller->OnMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA); } LRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam) { switch(message) { case WM_KEYDOWN: windowMap[windowHandle]->KeyDown(wparam); return 0; case WM_KEYUP: windowMap[windowHandle]->KeyUp(wparam); return 0; case WM_MOUSEMOVE: windowMap[windowHandle]->MouseMove(wparam, lparam); return 0; case WM_LBUTTONDOWN: windowMap[windowHandle]->LeftMouseButtonDown(wparam, lparam); return 0; case WM_LBUTTONUP: windowMap[windowHandle]->LeftMouseButtonUp(wparam, lparam); return 0; case WM_RBUTTONDOWN: windowMap[windowHandle]->RightMouseButtonDown(wparam, lparam); return 0; case WM_RBUTTONUP: windowMap[windowHandle]->RightMouseButtonUp(wparam, lparam); return 0; case WM_MOUSEWHEEL: windowMap[windowHandle]->MouseScrollWheel(wparam, lparam); return 0; case WM_SIZE: windowMap[windowHandle]->WindowResize(wparam, lparam); return 0; case WM_CLOSE: windowMap[windowHandle]->onClose(); return 0; case WM_DESTROY: PostQuitMessage(0); windowMap[windowHandle] = NULL; return 0; default: return DefWindowProc(windowHandle, message, wparam, lparam); } } <|endoftext|>
<commit_before>#include <sys/time.h> #include <sys/resource.h> #include <fcntl.h> #include "GrContextFactory.h" #include "SkBase64.h" #include "SkCanvas.h" #include "SkCommandLineFlags.h" #include "SkData.h" #include "SkDocument.h" #include "SkFontMgr.h" #include "SkForceLinking.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkImageInfo.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkSurface.h" __SK_FORCE_IMAGE_DECODER_LINKING; DEFINE_string(source, "", "Filename of the source image."); DEFINE_int32(width, 256, "Width of output image."); DEFINE_int32(height, 256, "Height of output image."); DEFINE_bool(gpu, false, "Use GPU (Mesa) rendering."); DEFINE_bool(raster, true, "Use Raster rendering."); DEFINE_bool(pdf, false, "Use PDF rendering."); // Defined in template.cpp. extern SkBitmap source; extern void draw(SkCanvas* canvas); static void drawAndDump(SkSurface* surface, SkWStream* stream) { SkCanvas *canvas = surface->getCanvas(); draw(canvas); // Write out the image as a PNG. SkAutoTUnref<SkImage> image(surface->newImageSnapshot()); SkAutoTUnref<SkData> data(image->encode(SkImageEncoder::kPNG_Type, 100)); if (NULL == data.get()) { printf("Failed to encode\n"); exit(1); } stream->write(data->data(), data->size()); } static void drawRaster(SkWStream* stream, SkImageInfo info) { SkAutoTUnref<SkSurface> surface; surface.reset(SkSurface::NewRaster(info)); drawAndDump(surface, stream); } static void drawGPU(SkWStream* stream, GrContext* gr, SkImageInfo info) { SkAutoTUnref<SkSurface> surface; surface.reset(SkSurface::NewRenderTarget(gr,SkSurface::kNo_Budgeted,info)); drawAndDump(surface, stream); } static void drawPDF(SkWStream* stream, SkImageInfo info) { SkAutoTUnref<SkDocument> document(SkDocument::CreatePDF(stream)); SkCanvas *canvas = document->beginPage(info.width(), info.height()); SkAutoTDelete<SkStreamAsset> pdfData; draw(canvas); canvas->flush(); document->endPage(); document->close(); } static void dumpOutput(SkDynamicMemoryWStream *stream, const char *name, bool last=true) { SkAutoDataUnref pngData(stream->copyToData()); size_t b64Size = SkBase64::Encode(pngData->data(), pngData->size(), NULL); SkAutoTMalloc<char> b64Data(b64Size); SkBase64::Encode(pngData->data(), pngData->size(), b64Data.get()); printf( "\t\"%s\": \"%.*s\"", name, (int) b64Size, b64Data.get() ); if (!last) { printf( "," ); } printf( "\n" ); } int main(int argc, char** argv) { SkCommandLineFlags::Parse(argc, argv); SkAutoGraphics init; if (FLAGS_source.count() == 1) { const char *sourceDir = getenv("WEBTRY_INOUT"); if (NULL == sourceDir) { sourceDir = "/skia_build/inout"; } SkString sourcePath = SkOSPath::Join(sourceDir, FLAGS_source[0]); if (!SkImageDecoder::DecodeFile(sourcePath.c_str(), &source)) { perror("Unable to read the source image."); } } // make sure to open any needed output files before we set up the security // jail SkDynamicMemoryWStream* streams[3] = {NULL, NULL, NULL}; if (FLAGS_raster) { streams[0] = SkNEW(SkDynamicMemoryWStream); } if (FLAGS_gpu) { streams[1] = SkNEW(SkDynamicMemoryWStream); } if (FLAGS_pdf) { streams[2] = SkNEW(SkDynamicMemoryWStream); } SkImageInfo info = SkImageInfo::MakeN32(FLAGS_width, FLAGS_height, kPremul_SkAlphaType); GrContext *gr = NULL; GrContextFactory* grFactory = NULL; // need to set up the GPU context before we install system call restrictions if (FLAGS_gpu) { GrContextOptions grContextOpts; grFactory = new GrContextFactory(grContextOpts); gr = grFactory->get(GrContextFactory::kMESA_GLContextType); } printf( "{\n" ); if (NULL != streams[0]) { drawRaster(streams[0], info); dumpOutput(streams[0], "Raster", NULL == streams[1] && NULL == streams[2] ); } if (NULL != streams[1]) { drawGPU(streams[1], gr, info); dumpOutput(streams[1], "Gpu", NULL == streams[2] ); } if (NULL != streams[2]) { drawPDF(streams[2], info); dumpOutput(streams[2], "Pdf" ); } printf( "}\n" ); if (gr) { delete grFactory; } } <commit_msg>Migrate webtry from SkNEW to just new.<commit_after>#include <sys/time.h> #include <sys/resource.h> #include <fcntl.h> #include "GrContextFactory.h" #include "SkBase64.h" #include "SkCanvas.h" #include "SkCommandLineFlags.h" #include "SkData.h" #include "SkDocument.h" #include "SkFontMgr.h" #include "SkForceLinking.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkImageInfo.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkSurface.h" __SK_FORCE_IMAGE_DECODER_LINKING; DEFINE_string(source, "", "Filename of the source image."); DEFINE_int32(width, 256, "Width of output image."); DEFINE_int32(height, 256, "Height of output image."); DEFINE_bool(gpu, false, "Use GPU (Mesa) rendering."); DEFINE_bool(raster, true, "Use Raster rendering."); DEFINE_bool(pdf, false, "Use PDF rendering."); // Defined in template.cpp. extern SkBitmap source; extern void draw(SkCanvas* canvas); static void drawAndDump(SkSurface* surface, SkWStream* stream) { SkCanvas *canvas = surface->getCanvas(); draw(canvas); // Write out the image as a PNG. SkAutoTUnref<SkImage> image(surface->newImageSnapshot()); SkAutoTUnref<SkData> data(image->encode(SkImageEncoder::kPNG_Type, 100)); if (NULL == data.get()) { printf("Failed to encode\n"); exit(1); } stream->write(data->data(), data->size()); } static void drawRaster(SkWStream* stream, SkImageInfo info) { SkAutoTUnref<SkSurface> surface; surface.reset(SkSurface::NewRaster(info)); drawAndDump(surface, stream); } static void drawGPU(SkWStream* stream, GrContext* gr, SkImageInfo info) { SkAutoTUnref<SkSurface> surface; surface.reset(SkSurface::NewRenderTarget(gr,SkSurface::kNo_Budgeted,info)); drawAndDump(surface, stream); } static void drawPDF(SkWStream* stream, SkImageInfo info) { SkAutoTUnref<SkDocument> document(SkDocument::CreatePDF(stream)); SkCanvas *canvas = document->beginPage(info.width(), info.height()); SkAutoTDelete<SkStreamAsset> pdfData; draw(canvas); canvas->flush(); document->endPage(); document->close(); } static void dumpOutput(SkDynamicMemoryWStream *stream, const char *name, bool last=true) { SkAutoDataUnref pngData(stream->copyToData()); size_t b64Size = SkBase64::Encode(pngData->data(), pngData->size(), NULL); SkAutoTMalloc<char> b64Data(b64Size); SkBase64::Encode(pngData->data(), pngData->size(), b64Data.get()); printf( "\t\"%s\": \"%.*s\"", name, (int) b64Size, b64Data.get() ); if (!last) { printf( "," ); } printf( "\n" ); } int main(int argc, char** argv) { SkCommandLineFlags::Parse(argc, argv); SkAutoGraphics init; if (FLAGS_source.count() == 1) { const char *sourceDir = getenv("WEBTRY_INOUT"); if (NULL == sourceDir) { sourceDir = "/skia_build/inout"; } SkString sourcePath = SkOSPath::Join(sourceDir, FLAGS_source[0]); if (!SkImageDecoder::DecodeFile(sourcePath.c_str(), &source)) { perror("Unable to read the source image."); } } // make sure to open any needed output files before we set up the security // jail SkDynamicMemoryWStream* streams[3] = {NULL, NULL, NULL}; if (FLAGS_raster) { streams[0] = new SkDynamicMemoryWStream; } if (FLAGS_gpu) { streams[1] = new SkDynamicMemoryWStream; } if (FLAGS_pdf) { streams[2] = new SkDynamicMemoryWStream; } SkImageInfo info = SkImageInfo::MakeN32(FLAGS_width, FLAGS_height, kPremul_SkAlphaType); GrContext *gr = NULL; GrContextFactory* grFactory = NULL; // need to set up the GPU context before we install system call restrictions if (FLAGS_gpu) { GrContextOptions grContextOpts; grFactory = new GrContextFactory(grContextOpts); gr = grFactory->get(GrContextFactory::kMESA_GLContextType); } printf( "{\n" ); if (NULL != streams[0]) { drawRaster(streams[0], info); dumpOutput(streams[0], "Raster", NULL == streams[1] && NULL == streams[2] ); } if (NULL != streams[1]) { drawGPU(streams[1], gr, info); dumpOutput(streams[1], "Gpu", NULL == streams[2] ); } if (NULL != streams[2]) { drawPDF(streams[2], info); dumpOutput(streams[2], "Pdf" ); } printf( "}\n" ); if (gr) { delete grFactory; } } <|endoftext|>
<commit_before>#include "Math.h" #include <glm/gtc/matrix_transform.hpp> #include "OpenGL.h" #include "Vertex.h" #include "Window.h" #include "Reference.h" #include "PhysicsManager.h" #include "ModelManager.h" #include "RenderManager.h" static float CameraFieldOfView = 90; static Solid* CameraAttachmentTarget = NULL; static glm::mat4 CameraViewTransformation; static glm::mat4 CameraProjectionTransformation; static void UpdateProjectionTransformation(); static void OnFramebufferResize( int width, int height ); bool InitRenderManager() { CameraAttachmentTarget = NULL; EnableVertexArrays(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); //glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.5, 0.5, 0.5, 1); SetFrambufferFn(OnFramebufferResize); return true; } void DestroyRenderManager() { SetCameraAttachmentTarget(NULL); } void SetCameraAttachmentTarget( Solid* target ) { if(CameraAttachmentTarget) ReleaseSolid(CameraAttachmentTarget); CameraAttachmentTarget = target; if(CameraAttachmentTarget) ReferenceSolid(CameraAttachmentTarget); } void SetCameraViewTransformation( glm::mat4 transformation ) { CameraViewTransformation = transformation; } void SetCameraFieldOfView( float fov ) { CameraFieldOfView = fov; UpdateProjectionTransformation(); } static void OnFramebufferResize( int width, int height ) { glViewport(0, 0, width, height); UpdateProjectionTransformation(); } static void UpdateProjectionTransformation() { using namespace glm; const ivec2 framebufferSize = GetFramebufferSize(); const float aspect = float(framebufferSize[0]) / float(framebufferSize[1]); CameraProjectionTransformation = perspective(CameraFieldOfView, aspect, 0.1f, 100.0f); } void RenderScene() { glm::mat4 cameraTargetTransformation; if(CameraAttachmentTarget) GetSolidTransformation(CameraAttachmentTarget, &cameraTargetTransformation); const glm::mat4 cameraTransformation = cameraTargetTransformation * CameraViewTransformation * CameraProjectionTransformation; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); DrawModels(&cameraTransformation); SwapBuffers(); /* // Render shadow map BeginRenderShadowTexture(); glClear(GL_DEPTH_BUFFER_BIT); DrawGraphicsObjects(); DrawPlayer(); EndRenderShadowTexture(); // Render world BeginRender(); glClear(GL_DEPTH_BUFFER_BIT); BindProgram(GetDefaultProgram()); SetModelViewProjectionMatrix(GetDefaultProgram(), &mvpMatrix); DrawGraphicsObjects(); DrawPlayer(); EndRender(); // Render HUD glClear(GL_DEPTH_BUFFER_BIT); glLoadIdentity(); */ } <commit_msg>Fixed calculation of camera matrix.<commit_after>#include "Math.h" #include <glm/gtc/matrix_transform.hpp> #include "OpenGL.h" #include "Vertex.h" #include "Window.h" #include "Reference.h" #include "PhysicsManager.h" #include "ModelManager.h" #include "RenderManager.h" static float CameraFieldOfView = 90; static Solid* CameraAttachmentTarget = NULL; static glm::mat4 CameraViewTransformation; static glm::mat4 CameraProjectionTransformation; static void UpdateProjectionTransformation(); static void OnFramebufferResize( int width, int height ); bool InitRenderManager() { CameraAttachmentTarget = NULL; EnableVertexArrays(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); //glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.5, 0.5, 0.5, 1); SetFrambufferFn(OnFramebufferResize); return true; } void DestroyRenderManager() { SetCameraAttachmentTarget(NULL); } void SetCameraAttachmentTarget( Solid* target ) { if(CameraAttachmentTarget) ReleaseSolid(CameraAttachmentTarget); CameraAttachmentTarget = target; if(CameraAttachmentTarget) ReferenceSolid(CameraAttachmentTarget); } void SetCameraViewTransformation( glm::mat4 transformation ) { CameraViewTransformation = transformation; } void SetCameraFieldOfView( float fov ) { CameraFieldOfView = fov; UpdateProjectionTransformation(); } static void OnFramebufferResize( int width, int height ) { glViewport(0, 0, width, height); UpdateProjectionTransformation(); } static void UpdateProjectionTransformation() { using namespace glm; const ivec2 framebufferSize = GetFramebufferSize(); const float aspect = float(framebufferSize[0]) / float(framebufferSize[1]); CameraProjectionTransformation = perspective(CameraFieldOfView, aspect, 0.1f, 100.0f); } void RenderScene() { glm::mat4 cameraTargetTransformation; if(CameraAttachmentTarget) GetSolidTransformation(CameraAttachmentTarget, &cameraTargetTransformation); const glm::mat4 cameraTransformation = CameraProjectionTransformation * CameraViewTransformation * cameraTargetTransformation; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); DrawModels(&cameraTransformation); SwapBuffers(); /* // Render shadow map BeginRenderShadowTexture(); glClear(GL_DEPTH_BUFFER_BIT); DrawGraphicsObjects(); DrawPlayer(); EndRenderShadowTexture(); // Render world BeginRender(); glClear(GL_DEPTH_BUFFER_BIT); BindProgram(GetDefaultProgram()); SetModelViewProjectionMatrix(GetDefaultProgram(), &mvpMatrix); DrawGraphicsObjects(); DrawPlayer(); EndRender(); // Render HUD glClear(GL_DEPTH_BUFFER_BIT); glLoadIdentity(); */ } <|endoftext|>
<commit_before>//===- llvm/unittest/ADT/ArrayRefTest.cpp - ArrayRef unit tests -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { TEST(ArrayRefTest, AllocatorCopy) { BumpPtrAllocator Alloc; static const uint16_t Words1[] = { 1, 4, 200, 37 }; ArrayRef<uint16_t> Array1 = makeArrayRef(Words1, 4); static const uint16_t Words2[] = { 11, 4003, 67, 64000, 13 }; ArrayRef<uint16_t> Array2 = makeArrayRef(Words2, 5); ArrayRef<uint16_t> Array1c = Array1.copy(Alloc); ArrayRef<uint16_t> Array2c = Array2.copy(Alloc);; EXPECT_TRUE(Array1.equals(Array1c)); EXPECT_NE(Array1.data(), Array1c.data()); EXPECT_TRUE(Array2.equals(Array2c)); EXPECT_NE(Array2.data(), Array2c.data()); } TEST(ArrayRefTest, DropBack) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(TheNumbers, AR1.size() - 1); EXPECT_TRUE(AR1.drop_back().equals(AR2)); } TEST(ArrayRefTest, Equals) { static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8}; ArrayRef<int> AR1(A1); EXPECT_TRUE(AR1.equals(1, 2, 3, 4, 5, 6, 7, 8)); EXPECT_FALSE(AR1.equals(8, 1, 2, 4, 5, 6, 6, 7)); EXPECT_FALSE(AR1.equals(2, 4, 5, 6, 6, 7, 8, 1)); EXPECT_FALSE(AR1.equals(0, 1, 2, 4, 5, 6, 6, 7)); EXPECT_FALSE(AR1.equals(1, 2, 42, 4, 5, 6, 7, 8)); EXPECT_FALSE(AR1.equals(42, 2, 3, 4, 5, 6, 7, 8)); EXPECT_FALSE(AR1.equals(1, 2, 3, 4, 5, 6, 7, 42)); EXPECT_FALSE(AR1.equals(1, 2, 3, 4, 5, 6, 7)); EXPECT_FALSE(AR1.equals(1, 2, 3, 4, 5, 6, 7, 8, 9)); ArrayRef<int> AR1a = AR1.drop_back(); EXPECT_TRUE(AR1a.equals(1, 2, 3, 4, 5, 6, 7)); EXPECT_FALSE(AR1a.equals(1, 2, 3, 4, 5, 6, 7, 8)); ArrayRef<int> AR1b = AR1a.slice(2, 4); EXPECT_TRUE(AR1b.equals(3, 4, 5, 6)); EXPECT_FALSE(AR1b.equals(2, 3, 4, 5, 6)); EXPECT_FALSE(AR1b.equals(3, 4, 5, 6, 7)); } TEST(ArrayRefTest, EmptyEquals) { EXPECT_TRUE(ArrayRef<unsigned>() == ArrayRef<unsigned>()); } } // end anonymous namespace <commit_msg>Add a test for converting ArrayRef<T *> to ArrayRef<const T *>.<commit_after>//===- llvm/unittest/ADT/ArrayRefTest.cpp - ArrayRef unit tests -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { TEST(ArrayRefTest, AllocatorCopy) { BumpPtrAllocator Alloc; static const uint16_t Words1[] = { 1, 4, 200, 37 }; ArrayRef<uint16_t> Array1 = makeArrayRef(Words1, 4); static const uint16_t Words2[] = { 11, 4003, 67, 64000, 13 }; ArrayRef<uint16_t> Array2 = makeArrayRef(Words2, 5); ArrayRef<uint16_t> Array1c = Array1.copy(Alloc); ArrayRef<uint16_t> Array2c = Array2.copy(Alloc);; EXPECT_TRUE(Array1.equals(Array1c)); EXPECT_NE(Array1.data(), Array1c.data()); EXPECT_TRUE(Array2.equals(Array2c)); EXPECT_NE(Array2.data(), Array2c.data()); } TEST(ArrayRefTest, DropBack) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(TheNumbers, AR1.size() - 1); EXPECT_TRUE(AR1.drop_back().equals(AR2)); } TEST(ArrayRefTest, Equals) { static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8}; ArrayRef<int> AR1(A1); EXPECT_TRUE(AR1.equals(1, 2, 3, 4, 5, 6, 7, 8)); EXPECT_FALSE(AR1.equals(8, 1, 2, 4, 5, 6, 6, 7)); EXPECT_FALSE(AR1.equals(2, 4, 5, 6, 6, 7, 8, 1)); EXPECT_FALSE(AR1.equals(0, 1, 2, 4, 5, 6, 6, 7)); EXPECT_FALSE(AR1.equals(1, 2, 42, 4, 5, 6, 7, 8)); EXPECT_FALSE(AR1.equals(42, 2, 3, 4, 5, 6, 7, 8)); EXPECT_FALSE(AR1.equals(1, 2, 3, 4, 5, 6, 7, 42)); EXPECT_FALSE(AR1.equals(1, 2, 3, 4, 5, 6, 7)); EXPECT_FALSE(AR1.equals(1, 2, 3, 4, 5, 6, 7, 8, 9)); ArrayRef<int> AR1a = AR1.drop_back(); EXPECT_TRUE(AR1a.equals(1, 2, 3, 4, 5, 6, 7)); EXPECT_FALSE(AR1a.equals(1, 2, 3, 4, 5, 6, 7, 8)); ArrayRef<int> AR1b = AR1a.slice(2, 4); EXPECT_TRUE(AR1b.equals(3, 4, 5, 6)); EXPECT_FALSE(AR1b.equals(2, 3, 4, 5, 6)); EXPECT_FALSE(AR1b.equals(3, 4, 5, 6, 7)); } TEST(ArrayRefTest, EmptyEquals) { EXPECT_TRUE(ArrayRef<unsigned>() == ArrayRef<unsigned>()); } TEST(ArrayRefTest, ConstConvert) { int buf[4]; for (int i = 0; i < 4; ++i) buf[i] = i; static int *A[] = {&buf[0], &buf[1], &buf[2], &buf[3]}; ArrayRef<const int *> a((ArrayRef<int *>(A))); a = ArrayRef<int *>(A); } } // end anonymous namespace <|endoftext|>
<commit_before>//===- unittests/Analysis/CFGTest.cpp - CFG tests -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Analysis/CFG.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" #include <string> #include <vector> namespace clang { namespace analysis { namespace { // Constructing a CFG for a range-based for over a dependent type fails (but // should not crash). TEST(CFG, RangeBasedForOverDependentType) { const char *Code = "class Foo;\n" "template <typename T>\n" "void f(const T &Range) {\n" " for (const Foo *TheFoo : Range) {\n" " }\n" "}\n"; class CFGCallback : public ast_matchers::MatchFinder::MatchCallback { public: bool SawFunctionBody = false; void run(const ast_matchers::MatchFinder::MatchResult &Result) override { const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func"); Stmt *Body = Func->getBody(); if (!Body) return; SawFunctionBody = true; std::unique_ptr<CFG> cfg = CFG::buildCFG(nullptr, Body, Result.Context, CFG::BuildOptions()); EXPECT_EQ(nullptr, cfg); } } Callback; ast_matchers::MatchFinder Finder; Finder.addMatcher(ast_matchers::functionDecl().bind("func"), &Callback); std::unique_ptr<tooling::FrontendActionFactory> Factory( tooling::newFrontendActionFactory(&Finder)); std::vector<std::string> Args = {"-std=c++11"}; ASSERT_TRUE(tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args)); EXPECT_TRUE(Callback.SawFunctionBody); } } // namespace } // namespace analysis } // namespace clang <commit_msg>clang/unittests/Analysis/CFGTest.cpp: Appease msc targets with -fno-delayed-template-parsing.<commit_after>//===- unittests/Analysis/CFGTest.cpp - CFG tests -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Analysis/CFG.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" #include <string> #include <vector> namespace clang { namespace analysis { namespace { // Constructing a CFG for a range-based for over a dependent type fails (but // should not crash). TEST(CFG, RangeBasedForOverDependentType) { const char *Code = "class Foo;\n" "template <typename T>\n" "void f(const T &Range) {\n" " for (const Foo *TheFoo : Range) {\n" " }\n" "}\n"; class CFGCallback : public ast_matchers::MatchFinder::MatchCallback { public: bool SawFunctionBody = false; void run(const ast_matchers::MatchFinder::MatchResult &Result) override { const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func"); Stmt *Body = Func->getBody(); if (!Body) return; SawFunctionBody = true; std::unique_ptr<CFG> cfg = CFG::buildCFG(nullptr, Body, Result.Context, CFG::BuildOptions()); EXPECT_EQ(nullptr, cfg); } } Callback; ast_matchers::MatchFinder Finder; Finder.addMatcher(ast_matchers::functionDecl().bind("func"), &Callback); std::unique_ptr<tooling::FrontendActionFactory> Factory( tooling::newFrontendActionFactory(&Finder)); std::vector<std::string> Args = {"-std=c++11", "-fno-delayed-template-parsing"}; ASSERT_TRUE(tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args)); EXPECT_TRUE(Callback.SawFunctionBody); } } // namespace } // namespace analysis } // namespace clang <|endoftext|>
<commit_before>//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This diagnostic client prints out their diagnostic messages. // //===----------------------------------------------------------------------===// #include "TextDiagnosticPrinter.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Streams.h" #include <string> using namespace clang; static llvm::cl::opt<bool> NoShowColumn("fno-show-column", llvm::cl::desc("Do not include column number on diagnostics")); static llvm::cl::opt<bool> NoCaretDiagnostics("fno-caret-diagnostics", llvm::cl::desc("Do not include source line and caret with" " diagnostics")); void TextDiagnosticPrinter:: PrintIncludeStack(FullSourceLoc Pos) { if (Pos.isInvalid()) return; Pos = Pos.getLogicalLoc(); // Print out the other include frames first. PrintIncludeStack(Pos.getIncludeLoc()); unsigned LineNo = Pos.getLineNumber(); llvm::cerr << "In file included from " << Pos.getSourceName() << ":" << LineNo << ":\n"; } /// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s) /// any characters in LineNo that intersect the SourceRange. void TextDiagnosticPrinter::HighlightRange(const SourceRange &R, SourceManager& SourceMgr, unsigned LineNo, unsigned FileID, std::string &CaratLine, const std::string &SourceLine) { assert(CaratLine.size() == SourceLine.size() && "Expect a correspondence between source and carat line!"); if (!R.isValid()) return; SourceLocation LogicalStart = SourceMgr.getLogicalLoc(R.getBegin()); unsigned StartLineNo = SourceMgr.getLineNumber(LogicalStart); if (StartLineNo > LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. SourceLocation LogicalEnd = SourceMgr.getLogicalLoc(R.getEnd()); unsigned EndLineNo = SourceMgr.getLineNumber(LogicalEnd); if (EndLineNo < LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. // Compute the column number of the start. unsigned StartColNo = 0; if (StartLineNo == LineNo) { StartColNo = SourceMgr.getLogicalColumnNumber(R.getBegin()); if (StartColNo) --StartColNo; // Zero base the col #. } // Pick the first non-whitespace column. while (StartColNo < SourceLine.size() && (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) ++StartColNo; // Compute the column number of the end. unsigned EndColNo = CaratLine.size(); if (EndLineNo == LineNo) { EndColNo = SourceMgr.getLogicalColumnNumber(R.getEnd()); if (EndColNo) { --EndColNo; // Zero base the col #. // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(R.getEnd(), SourceMgr); } else { EndColNo = CaratLine.size(); } } // Pick the last non-whitespace column. while (EndColNo-1 && (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) --EndColNo; // Fill the range with ~'s. assert(StartColNo <= EndColNo && "Invalid range!"); for (unsigned i = StartColNo; i != EndColNo; ++i) CaratLine[i] = '~'; } void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic &Diags, Diagnostic::Level Level, FullSourceLoc Pos, diag::kind ID, const std::string *Strs, unsigned NumStrs, const SourceRange *Ranges, unsigned NumRanges) { unsigned LineNo = 0, ColNo = 0; unsigned FileID = 0; const char *LineStart = 0, *LineEnd = 0; if (Pos.isValid()) { FullSourceLoc LPos = Pos.getLogicalLoc(); LineNo = LPos.getLineNumber(); FileID = LPos.getLocation().getFileID(); // First, if this diagnostic is not in the main file, print out the // "included from" lines. if (LastWarningLoc != LPos.getIncludeLoc()) { LastWarningLoc = LPos.getIncludeLoc(); PrintIncludeStack(LastWarningLoc); } // Compute the column number. Rewind from the current position to the start // of the line. ColNo = LPos.getColumnNumber(); const char *TokLogicalPtr = LPos.getCharacterData(); LineStart = TokLogicalPtr-ColNo+1; // Column # is 1-based // Compute the line end. Scan forward from the error position to the end of // the line. const llvm::MemoryBuffer *Buffer = LPos.getBuffer(); const char *BufEnd = Buffer->getBufferEnd(); LineEnd = TokLogicalPtr; while (LineEnd != BufEnd && *LineEnd != '\n' && *LineEnd != '\r') ++LineEnd; llvm::cerr << Buffer->getBufferIdentifier() << ":" << LineNo << ":"; if (ColNo && !NoShowColumn) llvm::cerr << ColNo << ":"; llvm::cerr << " "; } switch (Level) { default: assert(0 && "Unknown diagnostic type!"); case Diagnostic::Note: llvm::cerr << "note: "; break; case Diagnostic::Warning: llvm::cerr << "warning: "; break; case Diagnostic::Error: llvm::cerr << "error: "; break; case Diagnostic::Fatal: llvm::cerr << "fatal error: "; break; break; } llvm::cerr << FormatDiagnostic(Diags, Level, ID, Strs, NumStrs) << "\n"; if (!NoCaretDiagnostics && Pos.isValid() && ((LastLoc != Pos) || Ranges)) { // Cache the LastLoc, it allows us to omit duplicate source/caret spewage. LastLoc = Pos; // Get the line of the source file. std::string SourceLine(LineStart, LineEnd); // Create a line for the carat that is filled with spaces that is the same // length as the line of source code. std::string CaratLine(LineEnd-LineStart, ' '); // Highlight all of the characters covered by Ranges with ~ characters. for (unsigned i = 0; i != NumRanges; ++i) HighlightRange(Ranges[i], Pos.getManager(), LineNo, FileID, CaratLine, SourceLine); // Next, insert the carat itself. if (ColNo-1 < CaratLine.size()) CaratLine[ColNo-1] = '^'; else CaratLine.push_back('^'); // Scan the source line, looking for tabs. If we find any, manually expand // them to 8 characters and update the CaratLine to match. for (unsigned i = 0; i != SourceLine.size(); ++i) { if (SourceLine[i] != '\t') continue; // Replace this tab with at least one space. SourceLine[i] = ' '; // Compute the number of spaces we need to insert. unsigned NumSpaces = ((i+8)&~7) - (i+1); assert(NumSpaces < 8 && "Invalid computation of space amt"); // Insert spaces into the SourceLine. SourceLine.insert(i+1, NumSpaces, ' '); // Insert spaces or ~'s into CaratLine. CaratLine.insert(i+1, NumSpaces, CaratLine[i] == '~' ? '~' : ' '); } // Finally, remove any blank spaces from the end of CaratLine. while (CaratLine[CaratLine.size()-1] == ' ') CaratLine.erase(CaratLine.end()-1); // Emit what we have computed. llvm::cerr << SourceLine << "\n"; llvm::cerr << CaratLine << "\n"; } } <commit_msg>Fixed copy-paste error.<commit_after>//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This diagnostic client prints out their diagnostic messages. // //===----------------------------------------------------------------------===// #include "TextDiagnosticPrinter.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Streams.h" #include <string> using namespace clang; static llvm::cl::opt<bool> NoShowColumn("fno-show-column", llvm::cl::desc("Do not include column number on diagnostics")); static llvm::cl::opt<bool> NoCaretDiagnostics("fno-caret-diagnostics", llvm::cl::desc("Do not include source line and caret with" " diagnostics")); void TextDiagnosticPrinter:: PrintIncludeStack(FullSourceLoc Pos) { if (Pos.isInvalid()) return; Pos = Pos.getLogicalLoc(); // Print out the other include frames first. PrintIncludeStack(Pos.getIncludeLoc()); unsigned LineNo = Pos.getLineNumber(); llvm::cerr << "In file included from " << Pos.getSourceName() << ":" << LineNo << ":\n"; } /// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s) /// any characters in LineNo that intersect the SourceRange. void TextDiagnosticPrinter::HighlightRange(const SourceRange &R, SourceManager& SourceMgr, unsigned LineNo, unsigned FileID, std::string &CaratLine, const std::string &SourceLine) { assert(CaratLine.size() == SourceLine.size() && "Expect a correspondence between source and carat line!"); if (!R.isValid()) return; SourceLocation LogicalStart = SourceMgr.getLogicalLoc(R.getBegin()); unsigned StartLineNo = SourceMgr.getLineNumber(LogicalStart); if (StartLineNo > LineNo || LogicalStart.getFileID() != FileID) return; // No intersection. SourceLocation LogicalEnd = SourceMgr.getLogicalLoc(R.getEnd()); unsigned EndLineNo = SourceMgr.getLineNumber(LogicalEnd); if (EndLineNo < LineNo || LogicalEnd.getFileID() != FileID) return; // No intersection. // Compute the column number of the start. unsigned StartColNo = 0; if (StartLineNo == LineNo) { StartColNo = SourceMgr.getLogicalColumnNumber(R.getBegin()); if (StartColNo) --StartColNo; // Zero base the col #. } // Pick the first non-whitespace column. while (StartColNo < SourceLine.size() && (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) ++StartColNo; // Compute the column number of the end. unsigned EndColNo = CaratLine.size(); if (EndLineNo == LineNo) { EndColNo = SourceMgr.getLogicalColumnNumber(R.getEnd()); if (EndColNo) { --EndColNo; // Zero base the col #. // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(R.getEnd(), SourceMgr); } else { EndColNo = CaratLine.size(); } } // Pick the last non-whitespace column. while (EndColNo-1 && (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) --EndColNo; // Fill the range with ~'s. assert(StartColNo <= EndColNo && "Invalid range!"); for (unsigned i = StartColNo; i != EndColNo; ++i) CaratLine[i] = '~'; } void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic &Diags, Diagnostic::Level Level, FullSourceLoc Pos, diag::kind ID, const std::string *Strs, unsigned NumStrs, const SourceRange *Ranges, unsigned NumRanges) { unsigned LineNo = 0, ColNo = 0; unsigned FileID = 0; const char *LineStart = 0, *LineEnd = 0; if (Pos.isValid()) { FullSourceLoc LPos = Pos.getLogicalLoc(); LineNo = LPos.getLineNumber(); FileID = LPos.getLocation().getFileID(); // First, if this diagnostic is not in the main file, print out the // "included from" lines. if (LastWarningLoc != LPos.getIncludeLoc()) { LastWarningLoc = LPos.getIncludeLoc(); PrintIncludeStack(LastWarningLoc); } // Compute the column number. Rewind from the current position to the start // of the line. ColNo = LPos.getColumnNumber(); const char *TokLogicalPtr = LPos.getCharacterData(); LineStart = TokLogicalPtr-ColNo+1; // Column # is 1-based // Compute the line end. Scan forward from the error position to the end of // the line. const llvm::MemoryBuffer *Buffer = LPos.getBuffer(); const char *BufEnd = Buffer->getBufferEnd(); LineEnd = TokLogicalPtr; while (LineEnd != BufEnd && *LineEnd != '\n' && *LineEnd != '\r') ++LineEnd; llvm::cerr << Buffer->getBufferIdentifier() << ":" << LineNo << ":"; if (ColNo && !NoShowColumn) llvm::cerr << ColNo << ":"; llvm::cerr << " "; } switch (Level) { default: assert(0 && "Unknown diagnostic type!"); case Diagnostic::Note: llvm::cerr << "note: "; break; case Diagnostic::Warning: llvm::cerr << "warning: "; break; case Diagnostic::Error: llvm::cerr << "error: "; break; case Diagnostic::Fatal: llvm::cerr << "fatal error: "; break; break; } llvm::cerr << FormatDiagnostic(Diags, Level, ID, Strs, NumStrs) << "\n"; if (!NoCaretDiagnostics && Pos.isValid() && ((LastLoc != Pos) || Ranges)) { // Cache the LastLoc, it allows us to omit duplicate source/caret spewage. LastLoc = Pos; // Get the line of the source file. std::string SourceLine(LineStart, LineEnd); // Create a line for the carat that is filled with spaces that is the same // length as the line of source code. std::string CaratLine(LineEnd-LineStart, ' '); // Highlight all of the characters covered by Ranges with ~ characters. for (unsigned i = 0; i != NumRanges; ++i) HighlightRange(Ranges[i], Pos.getManager(), LineNo, FileID, CaratLine, SourceLine); // Next, insert the carat itself. if (ColNo-1 < CaratLine.size()) CaratLine[ColNo-1] = '^'; else CaratLine.push_back('^'); // Scan the source line, looking for tabs. If we find any, manually expand // them to 8 characters and update the CaratLine to match. for (unsigned i = 0; i != SourceLine.size(); ++i) { if (SourceLine[i] != '\t') continue; // Replace this tab with at least one space. SourceLine[i] = ' '; // Compute the number of spaces we need to insert. unsigned NumSpaces = ((i+8)&~7) - (i+1); assert(NumSpaces < 8 && "Invalid computation of space amt"); // Insert spaces into the SourceLine. SourceLine.insert(i+1, NumSpaces, ' '); // Insert spaces or ~'s into CaratLine. CaratLine.insert(i+1, NumSpaces, CaratLine[i] == '~' ? '~' : ' '); } // Finally, remove any blank spaces from the end of CaratLine. while (CaratLine[CaratLine.size()-1] == ' ') CaratLine.erase(CaratLine.end()-1); // Emit what we have computed. llvm::cerr << SourceLine << "\n"; llvm::cerr << CaratLine << "\n"; } } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*- * vi: set shiftwidth=4 tabstop=8: * :indentSize=4:tabSize=8: */ #include "../console.h" #include "../types.h" #include "../errno.h" #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <io.h> bool open_tty_as_stdin() { // open the CON device and make it STDIN int fd = -1; errno_t e = _sopen_s(&fd, "con", _O_RDONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE); if (e != 0 || fd < 0) { std::cerr << "could not open con: " << errno_str() << std::endl; return false; } if (fd != 0) { if (_dup2(fd, 0) < 0) { std::cerr << "could not dup con to STDIN: " << errno_str() << std::endl; return false; } _close(fd); } return true; } <commit_msg>windows build fixes<commit_after>/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*- * vi: set shiftwidth=4 tabstop=8: * :indentSize=4:tabSize=8: */ #include "../console.h" #include "../types.h" #include "../errno_str.h" #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <io.h> bool open_tty_as_stdin() { // open the CON device and make it STDIN int fd = -1; errno_t e = _sopen_s(&fd, "con", _O_RDONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE); if (e != 0 || fd < 0) { std::cerr << "could not open con: " << errno_str() << std::endl; return false; } if (fd != 0) { if (_dup2(fd, 0) < 0) { std::cerr << "could not dup con to STDIN: " << errno_str() << std::endl; return false; } _close(fd); } return true; } <|endoftext|>
<commit_before>#include "Settings.h" #include "Log.h" #include "pugixml/pugixml.hpp" #include "platform.h" #include <boost/filesystem.hpp> #include <boost/assign.hpp> Settings *Settings::sInstance = NULL; // these values are NOT saved to es_settings.xml // since they're set through command-line arguments, and not the in-program settings menu std::vector<const char *> settings_dont_save = boost::assign::list_of ("Debug") ("DebugGrid") ("DebugText") ("ParseGamelistOnly") ("ShowExit") ("Windowed") ("VSync") ("HideConsole") ("IgnoreGamelist"); Settings::Settings() { setDefaults(); loadFile(); } Settings *Settings::getInstance() { if (sInstance == NULL) sInstance = new Settings(); return sInstance; } void Settings::setDefaults() { mBoolMap.clear(); mIntMap.clear(); mBoolMap["BackgroundJoystickInput"] = false; mBoolMap["ParseGamelistOnly"] = false; mBoolMap["DrawFramerate"] = false; mBoolMap["ShowExit"] = true; mBoolMap["Windowed"] = false; #ifdef _RPI_ // don't enable VSync by default on the Pi, since it already // has trouble trying to render things at 60fps in certain menus mBoolMap["VSync"] = false; #else mBoolMap["VSync"] = true; #endif mBoolMap["ShowHelpPrompts"] = true; mBoolMap["ScrapeRatings"] = true; mBoolMap["IgnoreGamelist"] = false; mBoolMap["HideConsole"] = true; mBoolMap["QuickSystemSelect"] = true; mBoolMap["FavoritesOnly"] = false; mBoolMap["Debug"] = false; mBoolMap["DebugGrid"] = false; mBoolMap["DebugText"] = false; mBoolMap["Overscan"] = false; mIntMap["ScreenSaverTime"] = 5 * 60 * 1000; // 5 minutes mIntMap["ScraperResizeWidth"] = 400; mIntMap["ScraperResizeHeight"] = 0; mIntMap["SystemVolume"] = 96; mStringMap["TransitionStyle"] = "fade"; mStringMap["ThemeSet"] = ""; mStringMap["ScreenSaverBehavior"] = "dim"; mStringMap["Scraper"] = "TheGamesDB"; mStringMap["UpdateCommand"] = ""; mStringMap["UpdateServer"] = ""; mStringMap["VersionFile"] = ""; mStringMap["SharePartition"] = ""; mStringMap["Lang"] = "en_US"; mStringMap["INPUT P1"] = "DEFAULT"; mStringMap["INPUT P2"] = "DEFAULT"; mStringMap["INPUT P3"] = "DEFAULT"; mStringMap["INPUT P4"] = "DEFAULT"; mStringMap["Overclock"] = "none"; mStringMap["RecalboxSettingScript"] = "/recalbox/scripts/recalbox-config.sh"; mStringMap["RecalboxConfigScript"] = ""; mStringMap["LastVersionFile"] = "/root/update.done"; mStringMap["VersionMessage"] = "/recalbox/recalbox.msg"; } template<typename K, typename V> void saveMap(pugi::xml_node &node, std::map<K, V> &map, const char *type) { for (auto iter = map.begin(); iter != map.end(); iter++) { // key is on the "don't save" list, so don't save it if (std::find(settings_dont_save.begin(), settings_dont_save.end(), iter->first) != settings_dont_save.end()) continue; pugi::xml_node node = node.append_child(type); node.append_attribute("name").set_value(iter->first.c_str()); node.append_attribute("value").set_value(iter->second); } } void Settings::saveFile() { const std::string path = getHomePath() + "/.emulationstation/es_settings.cfg"; pugi::xml_document doc; pugi::xml_node config = doc.append_child("config"); saveMap<std::string, bool>(config, mBoolMap, "bool"); saveMap<std::string, int>(config, mIntMap, "int"); saveMap<std::string, float>(config, mFloatMap, "float"); //saveMap<std::string, std::string>(config, mStringMap, "string"); for (auto iter = mStringMap.begin(); iter != mStringMap.end(); iter++) { pugi::xml_node node = config.append_child("string"); node.append_attribute("name").set_value(iter->first.c_str()); node.append_attribute("value").set_value(iter->second.c_str()); } doc.save_file(path.c_str()); } void Settings::loadFile() { const std::string path = getHomePath() + "/.emulationstation/es_settings.cfg"; if (!boost::filesystem::exists(path)) return; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(path.c_str()); if (!result) { LOG(LogError) << "Could not parse Settings file!\n " << result.description(); return; } pugi::xml_node config = doc.child("config"); if(config) { /* correct file format, having a config root node */ for (pugi::xml_node node = config.child("bool"); node; node = node.next_sibling("bool")) setBool(node.attribute("name").as_string(), node.attribute("value").as_bool()); for (pugi::xml_node node = config.child("int"); node; node = node.next_sibling("int")) setInt(node.attribute("name").as_string(), node.attribute("value").as_int()); for (pugi::xml_node node = config.child("float"); node; node = node.next_sibling("float")) setFloat(node.attribute("name").as_string(), node.attribute("value").as_float()); for (pugi::xml_node node = config.child("string"); node; node = node.next_sibling("string")) setString(node.attribute("name").as_string(), node.attribute("value").as_string()); } else { /* the old format, without the root config node -- keep for a transparent upgrade */ for (pugi::xml_node node = doc.child("bool"); node; node = node.next_sibling("bool")) setBool(node.attribute("name").as_string(), node.attribute("value").as_bool()); for (pugi::xml_node node = doc.child("int"); node; node = node.next_sibling("int")) setInt(node.attribute("name").as_string(), node.attribute("value").as_int()); for (pugi::xml_node node = doc.child("float"); node; node = node.next_sibling("float")) setFloat(node.attribute("name").as_string(), node.attribute("value").as_float()); for (pugi::xml_node node = doc.child("string"); node; node = node.next_sibling("string")) setString(node.attribute("name").as_string(), node.attribute("value").as_string()); } } //Print a warning message if the setting we're trying to get doesn't already exist in the map, then return the value in the map. #define SETTINGS_GETSET(type, mapName, getMethodName, setMethodName) type Settings::getMethodName(const std::string& name) \ { \ if(mapName.find(name) == mapName.end()) \ { \ LOG(LogError) << "Tried to use unset setting " << name << "!"; \ } \ return mapName[name]; \ } \ void Settings::setMethodName(const std::string& name, type value) \ { \ mapName[name] = value; \ } SETTINGS_GETSET(bool, mBoolMap, getBool, setBool); SETTINGS_GETSET(int, mIntMap, getInt, setInt); SETTINGS_GETSET(float, mFloatMap, getFloat, setFloat); SETTINGS_GETSET(const std::string&, mStringMap, getString, setString); <commit_msg>corrected settings save<commit_after>#include "Settings.h" #include "Log.h" #include "pugixml/pugixml.hpp" #include "platform.h" #include <boost/filesystem.hpp> #include <boost/assign.hpp> Settings *Settings::sInstance = NULL; // these values are NOT saved to es_settings.xml // since they're set through command-line arguments, and not the in-program settings menu std::vector<const char *> settings_dont_save = boost::assign::list_of ("Debug") ("DebugGrid") ("DebugText") ("ParseGamelistOnly") ("ShowExit") ("Windowed") ("VSync") ("HideConsole") ("IgnoreGamelist"); Settings::Settings() { setDefaults(); loadFile(); } Settings *Settings::getInstance() { if (sInstance == NULL) sInstance = new Settings(); return sInstance; } void Settings::setDefaults() { mBoolMap.clear(); mIntMap.clear(); mBoolMap["BackgroundJoystickInput"] = false; mBoolMap["ParseGamelistOnly"] = false; mBoolMap["DrawFramerate"] = false; mBoolMap["ShowExit"] = true; mBoolMap["Windowed"] = false; #ifdef _RPI_ // don't enable VSync by default on the Pi, since it already // has trouble trying to render things at 60fps in certain menus mBoolMap["VSync"] = false; #else mBoolMap["VSync"] = true; #endif mBoolMap["ShowHelpPrompts"] = true; mBoolMap["ScrapeRatings"] = true; mBoolMap["IgnoreGamelist"] = false; mBoolMap["HideConsole"] = true; mBoolMap["QuickSystemSelect"] = true; mBoolMap["FavoritesOnly"] = false; mBoolMap["Debug"] = false; mBoolMap["DebugGrid"] = false; mBoolMap["DebugText"] = false; mBoolMap["Overscan"] = false; mIntMap["ScreenSaverTime"] = 5 * 60 * 1000; // 5 minutes mIntMap["ScraperResizeWidth"] = 400; mIntMap["ScraperResizeHeight"] = 0; mIntMap["SystemVolume"] = 96; mStringMap["TransitionStyle"] = "fade"; mStringMap["ThemeSet"] = ""; mStringMap["ScreenSaverBehavior"] = "dim"; mStringMap["Scraper"] = "TheGamesDB"; mStringMap["UpdateCommand"] = ""; mStringMap["UpdateServer"] = ""; mStringMap["VersionFile"] = ""; mStringMap["SharePartition"] = ""; mStringMap["Lang"] = "en_US"; mStringMap["INPUT P1"] = "DEFAULT"; mStringMap["INPUT P2"] = "DEFAULT"; mStringMap["INPUT P3"] = "DEFAULT"; mStringMap["INPUT P4"] = "DEFAULT"; mStringMap["Overclock"] = "none"; mStringMap["RecalboxSettingScript"] = "/recalbox/scripts/recalbox-config.sh"; mStringMap["RecalboxConfigScript"] = ""; mStringMap["LastVersionFile"] = "/root/update.done"; mStringMap["VersionMessage"] = "/recalbox/recalbox.msg"; } template<typename K, typename V> void saveMap(pugi::xml_node &node, std::map<K, V> &map, const char *type) { for (auto iter = map.begin(); iter != map.end(); iter++) { // key is on the "don't save" list, so don't save it if (std::find(settings_dont_save.begin(), settings_dont_save.end(), iter->first) != settings_dont_save.end()) continue; pugi::xml_node parent_node = node.append_child(type); parent_node.append_attribute("name").set_value(iter->first.c_str()); parent_node.append_attribute("value").set_value(iter->second); } } void Settings::saveFile() { const std::string path = getHomePath() + "/.emulationstation/es_settings.cfg"; pugi::xml_document doc; pugi::xml_node config = doc.append_child("config"); saveMap<std::string, bool>(config, mBoolMap, "bool"); saveMap<std::string, int>(config, mIntMap, "int"); saveMap<std::string, float>(config, mFloatMap, "float"); //saveMap<std::string, std::string>(config, mStringMap, "string"); for (auto iter = mStringMap.begin(); iter != mStringMap.end(); iter++) { pugi::xml_node node = config.append_child("string"); node.append_attribute("name").set_value(iter->first.c_str()); node.append_attribute("value").set_value(iter->second.c_str()); } doc.save_file(path.c_str()); } void Settings::loadFile() { const std::string path = getHomePath() + "/.emulationstation/es_settings.cfg"; if (!boost::filesystem::exists(path)) return; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(path.c_str()); if (!result) { LOG(LogError) << "Could not parse Settings file!\n " << result.description(); return; } pugi::xml_node config = doc.child("config"); if(config) { /* correct file format, having a config root node */ for (pugi::xml_node node = config.child("bool"); node; node = node.next_sibling("bool")) setBool(node.attribute("name").as_string(), node.attribute("value").as_bool()); for (pugi::xml_node node = config.child("int"); node; node = node.next_sibling("int")) setInt(node.attribute("name").as_string(), node.attribute("value").as_int()); for (pugi::xml_node node = config.child("float"); node; node = node.next_sibling("float")) setFloat(node.attribute("name").as_string(), node.attribute("value").as_float()); for (pugi::xml_node node = config.child("string"); node; node = node.next_sibling("string")) setString(node.attribute("name").as_string(), node.attribute("value").as_string()); } else { /* the old format, without the root config node -- keep for a transparent upgrade */ for (pugi::xml_node node = doc.child("bool"); node; node = node.next_sibling("bool")) setBool(node.attribute("name").as_string(), node.attribute("value").as_bool()); for (pugi::xml_node node = doc.child("int"); node; node = node.next_sibling("int")) setInt(node.attribute("name").as_string(), node.attribute("value").as_int()); for (pugi::xml_node node = doc.child("float"); node; node = node.next_sibling("float")) setFloat(node.attribute("name").as_string(), node.attribute("value").as_float()); for (pugi::xml_node node = doc.child("string"); node; node = node.next_sibling("string")) setString(node.attribute("name").as_string(), node.attribute("value").as_string()); } } //Print a warning message if the setting we're trying to get doesn't already exist in the map, then return the value in the map. #define SETTINGS_GETSET(type, mapName, getMethodName, setMethodName) type Settings::getMethodName(const std::string& name) \ { \ if(mapName.find(name) == mapName.end()) \ { \ LOG(LogError) << "Tried to use unset setting " << name << "!"; \ } \ return mapName[name]; \ } \ void Settings::setMethodName(const std::string& name, type value) \ { \ mapName[name] = value; \ } SETTINGS_GETSET(bool, mBoolMap, getBool, setBool); SETTINGS_GETSET(int, mIntMap, getInt, setInt); SETTINGS_GETSET(float, mFloatMap, getFloat, setFloat); SETTINGS_GETSET(const std::string&, mStringMap, getString, setString); <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/jsonformatter.h> #include <cxxtools/convert.h> #include <cxxtools/log.h> #include <limits> log_define("cxxtools.jsonformatter") namespace cxxtools { namespace { void checkTs(std::basic_ostream<Char>* _ts) { if (_ts == 0) throw std::logic_error("textstream is not set in JsonFormatter"); } } void JsonFormatter::begin(std::basic_ostream<Char>& ts) { _ts = &ts; _level = 0; _lastLevel = std::numeric_limits<unsigned>::max(); } void JsonFormatter::finish() { log_trace("finish"); if (_beautify) *_ts << L'\n'; _level = 0; _lastLevel = std::numeric_limits<unsigned>::max(); } void JsonFormatter::addValueString(const std::string& name, const std::string& type, const String& value) { log_trace("addValueString name=\"" << name << "\", type=\"" << type << "\", value=\"" << value << '"'); if (type == "bool") { addValueBool(name, type, convert<bool>(value)); } else { beginValue(name); if (type == "int" || type == "double") { stringOut(value); } else if (type == "json") { *_ts << value; } else if (type == "null") { *_ts << L"null"; } else { *_ts << L'"'; stringOut(value); *_ts << L'"'; } finishValue(); } } void JsonFormatter::addValueStdString(const std::string& name, const std::string& type, const std::string& value) { log_trace("addValueStdString name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"'); if (type == "bool") { addValueBool(name, type, convert<bool>(value)); } else { beginValue(name); if (type == "int" || type == "double") { stringOut(value); } else if (type == "json") { *_ts << String(value); } else if (type == "null") { *_ts << L"null"; } else { *_ts << L'"'; stringOut(value); *_ts << L'"'; } finishValue(); } } void JsonFormatter::addValueBool(const std::string& name, const std::string& type, bool value) { log_trace("addValueBool name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"'); beginValue(name); *_ts << (value ? L"true" : L"false"); finishValue(); } void JsonFormatter::addValueInt(const std::string& name, const std::string& type, int_type value) { log_trace("addValueInt name=\"" << name << "\", type=\"" << type << "\", \" value=" << value); beginValue(name); if (type == "bool") *_ts << (value ? L"true" : L"false"); else *_ts << value; finishValue(); } void JsonFormatter::addValueUnsigned(const std::string& name, const std::string& type, unsigned_type value) { log_trace("addValueUnsigned name=\"" << name << "\", type=\"" << type << "\", \" value=" << value); beginValue(name); if (type == "bool") *_ts << (value ? L"true" : L"false"); else *_ts << value; finishValue(); } void JsonFormatter::addValueFloat(const std::string& name, const std::string& type, long double value) { log_trace("addValueFloat name=\"" << name << "\", type=\"" << type << "\", \" value=" << value); beginValue(name); if (value != value // check for nan || value == std::numeric_limits<long double>::infinity() || value == -std::numeric_limits<long double>::infinity()) { *_ts << L"null"; } else { *_ts << convert<String>(value); } finishValue(); } void JsonFormatter::addNull(const std::string& name, const std::string& type) { beginValue(name); *_ts << L"null"; finishValue(); } void JsonFormatter::beginArray(const std::string& name, const std::string& type) { checkTs(_ts); if (_level == _lastLevel) { *_ts << L','; if (_beautify) *_ts << L'\n'; } else _lastLevel = _level; if (_beautify) indent(); ++_level; if (!name.empty()) { *_ts << L'"'; stringOut(name); *_ts << L'"' << L':'; if (_beautify) *_ts << L' '; } *_ts << L'['; if (_beautify) *_ts << L'\n'; } void JsonFormatter::finishArray() { checkTs(_ts); --_level; _lastLevel = _level; if (_beautify) { *_ts << L'\n'; indent(); } *_ts << L']'; } void JsonFormatter::beginObject(const std::string& name, const std::string& type) { checkTs(_ts); log_trace("beginObject name=\"" << name << '"'); if (_level == _lastLevel) { *_ts << L','; if (_beautify) *_ts << L'\n'; } else _lastLevel = _level; if (_beautify) indent(); ++_level; if (!name.empty()) { *_ts << L'"'; stringOut(name); *_ts << L'"' << L':'; if (_beautify) *_ts << L' '; } *_ts << L'{'; if (_beautify) *_ts << L'\n'; } void JsonFormatter::beginMember(const std::string& name) { } void JsonFormatter::finishMember() { } void JsonFormatter::finishObject() { checkTs(_ts); log_trace("finishObject"); --_level; _lastLevel = _level; if (_beautify) { *_ts << L'\n'; indent(); } *_ts << L'}'; } void JsonFormatter::indent() { for (unsigned n = 0; n < _level; ++n) *_ts << L'\t'; } void JsonFormatter::stringOut(const std::string& str) { for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == '"') *_ts << L'\\' << L'\"'; else if (*it == '\\') *_ts << L'\\' << L'\\'; else if (*it == '\b') *_ts << L'\\' << L'b'; else if (*it == '\f') *_ts << L'\\' << L'f'; else if (*it == '\n') *_ts << L'\\' << L'n'; else if (*it == '\r') *_ts << L'\\' << L'r'; else if (*it == '\t') *_ts << L'\\' << L't'; else if (static_cast<unsigned char>(*it) >= 0x80 || static_cast<unsigned char>(*it) < 0x20) { *_ts << L'\\' << L'u'; static const char hex[] = "0123456789abcdef"; uint32_t v = static_cast<unsigned char>(*it); for (uint32_t s = 16; s > 0; s -= 4) { *_ts << Char(hex[(v >> (s - 4)) & 0xf]); } } else *_ts << Char(*it); } } void JsonFormatter::stringOut(const cxxtools::String& str) { for (cxxtools::String::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == L'"') *_ts << L'\\' << L'\"'; else if (*it == L'\\') *_ts << L'\\' << L'\\'; else if (*it == L'\b') *_ts << L'\\' << L'b'; else if (*it == L'\f') *_ts << L'\\' << L'f'; else if (*it == L'\n') *_ts << L'\\' << L'n'; else if (*it == L'\r') *_ts << L'\\' << L'r'; else if (*it == L'\t') *_ts << L'\\' << L't'; else if (it->value() >= 0x80 || it->value() < 0x20) { *_ts << L'\\' << L'u'; static const char hex[] = "0123456789abcdef"; uint32_t v = it->value(); for (uint32_t s = 16; s > 0; s -= 4) { *_ts << Char(hex[(v >> (s - 4)) & 0xf]); } } else *_ts << *it; } } void JsonFormatter::beginValue(const std::string& name) { checkTs(_ts); if (_level == _lastLevel) { *_ts << L','; if (_beautify) { *_ts << L'\n'; indent(); } } else { _lastLevel = _level; if (_beautify) indent(); } if (!name.empty()) { *_ts << L'"'; stringOut(name); *_ts << L'"' << L':'; if (_beautify) *_ts << L' '; } ++_level; } void JsonFormatter::finishValue() { --_level; } } <commit_msg>optimization in copying preformatted json data in json serializer<commit_after>/* * Copyright (C) 2011 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/jsonformatter.h> #include <cxxtools/convert.h> #include <cxxtools/log.h> #include <limits> log_define("cxxtools.jsonformatter") namespace cxxtools { namespace { void checkTs(std::basic_ostream<Char>* _ts) { if (_ts == 0) throw std::logic_error("textstream is not set in JsonFormatter"); } } void JsonFormatter::begin(std::basic_ostream<Char>& ts) { _ts = &ts; _level = 0; _lastLevel = std::numeric_limits<unsigned>::max(); } void JsonFormatter::finish() { log_trace("finish"); if (_beautify) *_ts << L'\n'; _level = 0; _lastLevel = std::numeric_limits<unsigned>::max(); } void JsonFormatter::addValueString(const std::string& name, const std::string& type, const String& value) { log_trace("addValueString name=\"" << name << "\", type=\"" << type << "\", value=\"" << value << '"'); if (type == "bool") { addValueBool(name, type, convert<bool>(value)); } else { beginValue(name); if (type == "int" || type == "double") { stringOut(value); } else if (type == "json") { *_ts << value; } else if (type == "null") { *_ts << L"null"; } else { *_ts << L'"'; stringOut(value); *_ts << L'"'; } finishValue(); } } void JsonFormatter::addValueStdString(const std::string& name, const std::string& type, const std::string& value) { log_trace("addValueStdString name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"'); if (type == "bool") { addValueBool(name, type, convert<bool>(value)); } else { beginValue(name); if (type == "int" || type == "double") { stringOut(value); } else if (type == "json") { for (std::string::const_iterator it = value.begin(); it != value.end(); ++it) *_ts << Char(*it); } else if (type == "null") { *_ts << L"null"; } else { *_ts << L'"'; stringOut(value); *_ts << L'"'; } finishValue(); } } void JsonFormatter::addValueBool(const std::string& name, const std::string& type, bool value) { log_trace("addValueBool name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"'); beginValue(name); *_ts << (value ? L"true" : L"false"); finishValue(); } void JsonFormatter::addValueInt(const std::string& name, const std::string& type, int_type value) { log_trace("addValueInt name=\"" << name << "\", type=\"" << type << "\", \" value=" << value); beginValue(name); if (type == "bool") *_ts << (value ? L"true" : L"false"); else *_ts << value; finishValue(); } void JsonFormatter::addValueUnsigned(const std::string& name, const std::string& type, unsigned_type value) { log_trace("addValueUnsigned name=\"" << name << "\", type=\"" << type << "\", \" value=" << value); beginValue(name); if (type == "bool") *_ts << (value ? L"true" : L"false"); else *_ts << value; finishValue(); } void JsonFormatter::addValueFloat(const std::string& name, const std::string& type, long double value) { log_trace("addValueFloat name=\"" << name << "\", type=\"" << type << "\", \" value=" << value); beginValue(name); if (value != value // check for nan || value == std::numeric_limits<long double>::infinity() || value == -std::numeric_limits<long double>::infinity()) { *_ts << L"null"; } else { *_ts << convert<String>(value); } finishValue(); } void JsonFormatter::addNull(const std::string& name, const std::string& type) { beginValue(name); *_ts << L"null"; finishValue(); } void JsonFormatter::beginArray(const std::string& name, const std::string& type) { checkTs(_ts); if (_level == _lastLevel) { *_ts << L','; if (_beautify) *_ts << L'\n'; } else _lastLevel = _level; if (_beautify) indent(); ++_level; if (!name.empty()) { *_ts << L'"'; stringOut(name); *_ts << L'"' << L':'; if (_beautify) *_ts << L' '; } *_ts << L'['; if (_beautify) *_ts << L'\n'; } void JsonFormatter::finishArray() { checkTs(_ts); --_level; _lastLevel = _level; if (_beautify) { *_ts << L'\n'; indent(); } *_ts << L']'; } void JsonFormatter::beginObject(const std::string& name, const std::string& type) { checkTs(_ts); log_trace("beginObject name=\"" << name << '"'); if (_level == _lastLevel) { *_ts << L','; if (_beautify) *_ts << L'\n'; } else _lastLevel = _level; if (_beautify) indent(); ++_level; if (!name.empty()) { *_ts << L'"'; stringOut(name); *_ts << L'"' << L':'; if (_beautify) *_ts << L' '; } *_ts << L'{'; if (_beautify) *_ts << L'\n'; } void JsonFormatter::beginMember(const std::string& name) { } void JsonFormatter::finishMember() { } void JsonFormatter::finishObject() { checkTs(_ts); log_trace("finishObject"); --_level; _lastLevel = _level; if (_beautify) { *_ts << L'\n'; indent(); } *_ts << L'}'; } void JsonFormatter::indent() { for (unsigned n = 0; n < _level; ++n) *_ts << L'\t'; } void JsonFormatter::stringOut(const std::string& str) { for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == '"') *_ts << L'\\' << L'\"'; else if (*it == '\\') *_ts << L'\\' << L'\\'; else if (*it == '\b') *_ts << L'\\' << L'b'; else if (*it == '\f') *_ts << L'\\' << L'f'; else if (*it == '\n') *_ts << L'\\' << L'n'; else if (*it == '\r') *_ts << L'\\' << L'r'; else if (*it == '\t') *_ts << L'\\' << L't'; else if (static_cast<unsigned char>(*it) >= 0x80 || static_cast<unsigned char>(*it) < 0x20) { *_ts << L'\\' << L'u'; static const char hex[] = "0123456789abcdef"; uint32_t v = static_cast<unsigned char>(*it); for (uint32_t s = 16; s > 0; s -= 4) { *_ts << Char(hex[(v >> (s - 4)) & 0xf]); } } else *_ts << Char(*it); } } void JsonFormatter::stringOut(const cxxtools::String& str) { for (cxxtools::String::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == L'"') *_ts << L'\\' << L'\"'; else if (*it == L'\\') *_ts << L'\\' << L'\\'; else if (*it == L'\b') *_ts << L'\\' << L'b'; else if (*it == L'\f') *_ts << L'\\' << L'f'; else if (*it == L'\n') *_ts << L'\\' << L'n'; else if (*it == L'\r') *_ts << L'\\' << L'r'; else if (*it == L'\t') *_ts << L'\\' << L't'; else if (it->value() >= 0x80 || it->value() < 0x20) { *_ts << L'\\' << L'u'; static const char hex[] = "0123456789abcdef"; uint32_t v = it->value(); for (uint32_t s = 16; s > 0; s -= 4) { *_ts << Char(hex[(v >> (s - 4)) & 0xf]); } } else *_ts << *it; } } void JsonFormatter::beginValue(const std::string& name) { checkTs(_ts); if (_level == _lastLevel) { *_ts << L','; if (_beautify) { *_ts << L'\n'; indent(); } } else { _lastLevel = _level; if (_beautify) indent(); } if (!name.empty()) { *_ts << L'"'; stringOut(name); *_ts << L'"' << L':'; if (_beautify) *_ts << L' '; } ++_level; } void JsonFormatter::finishValue() { --_level; } } <|endoftext|>
<commit_before>/** * \file * \brief Unit Test for GPIO config class * * \author Uilian Ries <uilianries@gmail.com> */ /** Should not link with unit test lib */ #define BOOST_TEST_NO_LIB #include <string> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/test/unit_test.hpp> #include "config.hpp" /** * \brief Test config gpio class. * Create a fake environment for GPIO support on x86 */ BOOST_AUTO_TEST_SUITE(ConfigGPIO) namespace test_gpio_config { static const boost::filesystem::path fake_class_dir("fake_gpio_dir"); static constexpr auto gpio_pin = 66; static const std::string pin = "gpio" + std::to_string(gpio_pin); static const boost::filesystem::path fake_gpio_dir = fake_class_dir / pin; static const boost::filesystem::path export_path = fake_class_dir / "export"; static const boost::filesystem::path unexport_path = fake_class_dir / "unexport"; static const boost::filesystem::path direction_path = fake_gpio_dir / "direction"; static const boost::filesystem::path value_path = fake_gpio_dir / "value"; /** * \brief Create fake environment for test run on x86 arch */ struct fake_environment { /** * \brief Create some file and check. * If could not create the file, then abort. * \param path file path to be created */ template <typename T> void create_file(T&& path) noexcept(false) { using boost::filesystem::ofstream; ofstream ofs(std::forward<T>(path)); BOOST_CHECK(ofs); ofs.close(); } /** * \brief Create default config file with some data */ static void create_config_file() noexcept(false) { boost::filesystem::ofstream ofconfig{ bbb::gpio::SETTINGS_FILE_PATH }; BOOST_CHECK(ofconfig); ofconfig << "gpio-dir-path=fake_gpio_dir"; } /** * \brief Produces a fake directory tree, as GPIO class structure on file system. * Create the default gpio config file and hollow files for GPIO */ fake_environment() noexcept(false) { using boost::filesystem::path; using boost::filesystem::create_directories; create_directories(fake_gpio_dir); create_file(export_path); create_file(unexport_path); create_file(value_path); create_file(direction_path); create_config_file(); } /** * \brief Remove the fake environment from file system */ ~fake_environment() { BOOST_CHECK(boost::filesystem::remove_all(fake_gpio_dir)); BOOST_CHECK(boost::filesystem::remove(bbb::gpio::SETTINGS_FILE_PATH)); } }; } // namespace test_gpio_config /** * \brief Produces a tree structure as GPIO class, * and load gpio config. Verify each member, if the * path is equal in fake environment. * */ BOOST_FIXTURE_TEST_CASE(FakeEnvironment, test_gpio_config::fake_environment) { auto gconfig = bbb::gpio::config{ bbb::gpio::SETTINGS_FILE_PATH, test_gpio_config::gpio_pin }; BOOST_CHECK_EQUAL(test_gpio_config::export_path, gconfig.get_export()); BOOST_CHECK_EQUAL(test_gpio_config::unexport_path, gconfig.get_unexport()); BOOST_CHECK_EQUAL(test_gpio_config::value_path, gconfig.get_value()); BOOST_CHECK_EQUAL(test_gpio_config::direction_path, gconfig.get_direction()); } BOOST_AUTO_TEST_SUITE_END() // BOOST_AUTO_TEST_SUITE(ConfigGPIO) <commit_msg>Add config test for ARM arch<commit_after>/** * \file * \brief Unit Test for GPIO config class * * \author Uilian Ries <uilianries@gmail.com> */ /** Should not link with unit test lib */ #define BOOST_TEST_NO_LIB #include <string> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/test/unit_test.hpp> #include "config.hpp" /** * \brief Test config gpio class. * Create a fake environment for GPIO support on x86 */ BOOST_AUTO_TEST_SUITE(ConfigGPIO) namespace test_gpio_config { static const boost::filesystem::path fake_class_dir("fake_gpio_dir"); static constexpr auto gpio_pin = 66; static const std::string pin = "gpio" + std::to_string(gpio_pin); static const boost::filesystem::path fake_gpio_dir = fake_class_dir / pin; static const boost::filesystem::path export_path = fake_class_dir / "export"; static const boost::filesystem::path unexport_path = fake_class_dir / "unexport"; static const boost::filesystem::path direction_path = fake_gpio_dir / "direction"; static const boost::filesystem::path value_path = fake_gpio_dir / "value"; /** * \brief Create fake environment for test run on x86 arch */ struct fake_environment { /** * \brief Create some file and check. * If could not create the file, then abort. * \param path file path to be created */ template <typename T> void create_file(T&& path) noexcept(false) { using boost::filesystem::ofstream; ofstream ofs(std::forward<T>(path)); BOOST_CHECK(ofs); ofs.close(); } /** * \brief Create default config file with some data */ static void create_config_file() noexcept(false) { boost::filesystem::ofstream ofconfig{ bbb::gpio::SETTINGS_FILE_PATH }; BOOST_CHECK(ofconfig); ofconfig << "gpio-dir-path=fake_gpio_dir"; } /** * \brief Produces a fake directory tree, as GPIO class structure on file system. * Create the default gpio config file and hollow files for GPIO */ fake_environment() noexcept(false) { using boost::filesystem::path; using boost::filesystem::create_directories; create_directories(fake_gpio_dir); create_file(export_path); create_file(unexport_path); create_file(value_path); create_file(direction_path); create_config_file(); } /** * \brief Remove the fake environment from file system */ ~fake_environment() { BOOST_CHECK(boost::filesystem::remove_all(fake_gpio_dir)); BOOST_CHECK(boost::filesystem::remove(bbb::gpio::SETTINGS_FILE_PATH)); } }; } // namespace test_gpio_config #ifndef __arm__ /** * \brief Produces a tree structure as GPIO class, * and load gpio config. Verify each member, if the * path is equal in fake environment. * */ BOOST_FIXTURE_TEST_CASE(FakeEnvironment, test_gpio_config::fake_environment) { auto gconfig = bbb::gpio::config{ bbb::gpio::SETTINGS_FILE_PATH, test_gpio_config::gpio_pin }; BOOST_CHECK_EQUAL(test_gpio_config::export_path, gconfig.get_export()); BOOST_CHECK_EQUAL(test_gpio_config::unexport_path, gconfig.get_unexport()); BOOST_CHECK_EQUAL(test_gpio_config::value_path, gconfig.get_value()); BOOST_CHECK_EQUAL(test_gpio_config::direction_path, gconfig.get_direction()); } #else /** * \brief Execute config test for real environment */ BOOST_AUTO_TEST_CASE(RealEnvironment) { const boost::filesystem::path gpio_class_path("/sys/class/gpio"); { boost::filesystem::ofstream ofconfig{ bbb::gpio::SETTINGS_FILE_PATH }; BOOST_CHECK(ofconfig); ofconfig << "gpio-dir-path=" << gpio_class_path; } { boost::filesystem::ofstream ofs(gpio_class_path / "export"); BOOST_CHECK(ofs); ofs << test_gpio_config::gpio_pin; } auto gconfig = bbb::gpio::config{ bbb::gpio::SETTINGS_FILE_PATH, test_gpio_config::gpio_pin }; boost::filesystem::path gpio_pin_dir = gpio_class_path / test_gpio_config::pin; BOOST_CHECK_EQUAL(gpio_class_path / "export", gconfig.get_export()); BOOST_CHECK_EQUAL(gpio_class_path / "unexport", gconfig.get_unexport()); BOOST_CHECK_EQUAL(gpio_pin_dir / "value", gconfig.get_value()); BOOST_CHECK_EQUAL(gpio_pin_dir / "direction", gconfig.get_direction()); } #endif // #ifndef __arm__ BOOST_AUTO_TEST_SUITE_END() // BOOST_AUTO_TEST_SUITE(ConfigGPIO) <|endoftext|>
<commit_before>/* * JSP: https://github.com/arielm/jsp * COPYRIGHT (C) 2014-2015, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE SIMPLIFIED BSD LICENSE: * https://github.com/arielm/jsp/blob/master/LICENSE */ #include "jsp/BaseProto.h" using namespace std; using namespace chr; namespace jsp { BaseProto* BaseProto::target() { static shared_ptr<BaseProto> target; if (!target) { target = shared_ptr<BaseProto>(new BaseProto); } return target.get(); } #pragma mark ---------------------------------------- EVALUATION ---------------------------------------- bool BaseProto::exec(const string &source, const ReadOnlyCompileOptions &options) { RootedValue result(cx); bool success = Evaluate(cx, globalHandle(), options, source.data(), source.size(), &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } return success; } bool BaseProto::eval(const std::string &source, const ReadOnlyCompileOptions &options, MutableHandleValue result) { bool success = Evaluate(cx, globalHandle(), options, source.data(), source.size(), result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } return success; } #pragma mark ---------------------------------------- FUNCTIONS ---------------------------------------- Value BaseProto::call(HandleObject object, const char *functionName, const HandleValueArray& args) { RootedValue result(cx); bool success = JS_CallFunctionName(cx, object, functionName, args, &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } if (success) { return result; } throw EXCEPTION(BaseProto, "FUNCTION-CALL FAILED"); } Value BaseProto::call(HandleObject object, HandleValue functionValue, const HandleValueArray& args) { RootedValue result(cx); bool success = JS_CallFunctionValue(cx, object, functionValue, args, &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } if (success) { return result; } throw EXCEPTION(BaseProto, "FUNCTION-CALL FAILED"); } Value BaseProto::call(HandleObject object, HandleFunction function, const HandleValueArray& args) { RootedValue result(cx); bool success = JS_CallFunction(cx, object, function, args, &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } if (success) { return result; } throw EXCEPTION(BaseProto, "FUNCTION-CALL FAILED"); } #pragma mark ---------------------------------------- OBJECTS AND PROPERTIES ---------------------------------------- JSObject* BaseProto::newPlainObject() { return JS_NewObject(cx, nullptr, NullPtr(), NullPtr()); } /* * REFERENCES: * * - https://github.com/mozilla/gecko-dev/blob/esr31/js/src/vm/Stack.h#L1100-1113 * - https://github.com/mozilla/gecko-dev/blob/esr31/js/src/vm/Interpreter.cpp#L504-510 * - https://github.com/mozilla/gecko-dev/blob/esr31/js/src/vm/Interpreter.cpp#L543-572 */ JSObject* BaseProto::newNativeObject(const std::string &className, const HandleValueArray& args) { RootedValue value(cx); if (JS_GetProperty(cx, globalHandle(), className.data(), &value)) { if (!value.isUndefined() && value.isObject()) { JSObject &object = value.toObject(); Value values[args.length() + 2]; CallArgs callArgs = CallArgsFromVp(args.length(), values); mozilla::PodCopy(callArgs.array(), args.begin(), args.length()); callArgs.setCallee(value); callArgs.setThis(MagicValue(JS_IS_CONSTRUCTING)); if (object.is<JSFunction>()) { RootedFunction function(cx, &object.as<JSFunction>()); if (function->isNativeConstructor()) { if (js::CallJSNative(cx, function->native(), callArgs)) { return callArgs.rval().toObjectOrNull(); } } } else { RootedObject constructor(cx, &object); return JS_New(cx, constructor, callArgs); } } } return nullptr; } bool BaseProto::hasProperty(HandleObject object, const char *name) { if (object) { bool found; if (JS_HasProperty(cx, object, name, &found)) { return found; } } return false; } bool BaseProto::hasOwnProperty(HandleObject object, const char *name) { if (object) { bool found; if (JS_AlreadyHasOwnProperty(cx, object, name, &found)) { return found; } } return false; } bool BaseProto::getProperty(HandleObject object, const char *name, MutableHandleValue result) { if (object) { return JS_GetProperty(cx, object, name, result); } return false; } bool BaseProto::setProperty(HandleObject object, const char *name, HandleValue value) { if (object) { return JS_SetProperty(cx, object, name, value); } return false; } bool BaseProto::deleteProperty(HandleObject object, const char *name) { if (object) { return JS_DeleteProperty(cx, object, name); } return false; } #pragma mark ---------------------------------------- ARRAYS AND ELEMENTS ---------------------------------------- JSObject* BaseProto::newArray(size_t length) { return JS_NewArrayObject(cx, length); } JSObject* BaseProto::newArray(const HandleValueArray& contents) { return JS_NewArrayObject(cx, contents); } uint32_t BaseProto::getLength(HandleObject array) { if (array) { uint32_t length; if (JS_GetArrayLength(cx, array, &length)) { return length; } } return 0; } bool BaseProto::getElement(HandleObject array, uint32_t index, MutableHandleValue result) { if (array) { return JS_GetElement(cx, array, index, result); } return false; } bool BaseProto::setElement(HandleObject array, uint32_t index, HandleValue value) { if (array) { return JS_SetElement(cx, array, index, value); } return false; } bool BaseProto::deleteElement(HandleObject array, uint32_t index) { if (array) { return JS_DeleteElement(cx, array, index); } return false; } } <commit_msg>BaseProto: USING JS_DeleteProperty2 INSTEAD OF JS_DeleteProperty (OTHERWISE: FAILURE IS NOT PROPERLY REPORTED)<commit_after>/* * JSP: https://github.com/arielm/jsp * COPYRIGHT (C) 2014-2015, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE SIMPLIFIED BSD LICENSE: * https://github.com/arielm/jsp/blob/master/LICENSE */ #include "jsp/BaseProto.h" using namespace std; using namespace chr; namespace jsp { BaseProto* BaseProto::target() { static shared_ptr<BaseProto> target; if (!target) { target = shared_ptr<BaseProto>(new BaseProto); } return target.get(); } #pragma mark ---------------------------------------- EVALUATION ---------------------------------------- bool BaseProto::exec(const string &source, const ReadOnlyCompileOptions &options) { RootedValue result(cx); bool success = Evaluate(cx, globalHandle(), options, source.data(), source.size(), &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } return success; } bool BaseProto::eval(const std::string &source, const ReadOnlyCompileOptions &options, MutableHandleValue result) { bool success = Evaluate(cx, globalHandle(), options, source.data(), source.size(), result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } return success; } #pragma mark ---------------------------------------- FUNCTIONS ---------------------------------------- Value BaseProto::call(HandleObject object, const char *functionName, const HandleValueArray& args) { RootedValue result(cx); bool success = JS_CallFunctionName(cx, object, functionName, args, &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } if (success) { return result; } throw EXCEPTION(BaseProto, "FUNCTION-CALL FAILED"); } Value BaseProto::call(HandleObject object, HandleValue functionValue, const HandleValueArray& args) { RootedValue result(cx); bool success = JS_CallFunctionValue(cx, object, functionValue, args, &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } if (success) { return result; } throw EXCEPTION(BaseProto, "FUNCTION-CALL FAILED"); } Value BaseProto::call(HandleObject object, HandleFunction function, const HandleValueArray& args) { RootedValue result(cx); bool success = JS_CallFunction(cx, object, function, args, &result); if (JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); JS_ClearPendingException(cx); } if (success) { return result; } throw EXCEPTION(BaseProto, "FUNCTION-CALL FAILED"); } #pragma mark ---------------------------------------- OBJECTS AND PROPERTIES ---------------------------------------- JSObject* BaseProto::newPlainObject() { return JS_NewObject(cx, nullptr, NullPtr(), NullPtr()); } /* * REFERENCES: * * - https://github.com/mozilla/gecko-dev/blob/esr31/js/src/vm/Stack.h#L1100-1113 * - https://github.com/mozilla/gecko-dev/blob/esr31/js/src/vm/Interpreter.cpp#L504-510 * - https://github.com/mozilla/gecko-dev/blob/esr31/js/src/vm/Interpreter.cpp#L543-572 */ JSObject* BaseProto::newNativeObject(const std::string &className, const HandleValueArray& args) { RootedValue value(cx); if (JS_GetProperty(cx, globalHandle(), className.data(), &value)) { if (!value.isUndefined() && value.isObject()) { JSObject &object = value.toObject(); Value values[args.length() + 2]; CallArgs callArgs = CallArgsFromVp(args.length(), values); mozilla::PodCopy(callArgs.array(), args.begin(), args.length()); callArgs.setCallee(value); callArgs.setThis(MagicValue(JS_IS_CONSTRUCTING)); if (object.is<JSFunction>()) { RootedFunction function(cx, &object.as<JSFunction>()); if (function->isNativeConstructor()) { if (js::CallJSNative(cx, function->native(), callArgs)) { return callArgs.rval().toObjectOrNull(); } } } else { RootedObject constructor(cx, &object); return JS_New(cx, constructor, callArgs); } } } return nullptr; } bool BaseProto::hasProperty(HandleObject object, const char *name) { if (object) { bool found; if (JS_HasProperty(cx, object, name, &found)) { return found; } } return false; } bool BaseProto::hasOwnProperty(HandleObject object, const char *name) { if (object) { bool found; if (JS_AlreadyHasOwnProperty(cx, object, name, &found)) { return found; } } return false; } bool BaseProto::getProperty(HandleObject object, const char *name, MutableHandleValue result) { if (object) { return JS_GetProperty(cx, object, name, result); } return false; } bool BaseProto::setProperty(HandleObject object, const char *name, HandleValue value) { if (object) { return JS_SetProperty(cx, object, name, value); } return false; } bool BaseProto::deleteProperty(HandleObject object, const char *name) { if (object) { bool success; if (JS_DeleteProperty2(cx, object, name, &success)) { return success; } } return false; } #pragma mark ---------------------------------------- ARRAYS AND ELEMENTS ---------------------------------------- JSObject* BaseProto::newArray(size_t length) { return JS_NewArrayObject(cx, length); } JSObject* BaseProto::newArray(const HandleValueArray& contents) { return JS_NewArrayObject(cx, contents); } uint32_t BaseProto::getLength(HandleObject array) { if (array) { uint32_t length; if (JS_GetArrayLength(cx, array, &length)) { return length; } } return 0; } bool BaseProto::getElement(HandleObject array, uint32_t index, MutableHandleValue result) { if (array) { return JS_GetElement(cx, array, index, result); } return false; } bool BaseProto::setElement(HandleObject array, uint32_t index, HandleValue value) { if (array) { return JS_SetElement(cx, array, index, value); } return false; } bool BaseProto::deleteElement(HandleObject array, uint32_t index) { if (array) { return JS_DeleteElement(cx, array, index); } return false; } } <|endoftext|>
<commit_before>#include "utest.h" #include "function.h" #include "math/epsilon.h" #include "layers/conv3d_naive.h" #include "layers/conv3d_toeplitz.h" using namespace nano; template <typename top> struct wrt_params_function_t final : public function_t { explicit wrt_params_function_t(const top& op) : function_t("conv3d", op.params().psize(), op.params().psize(), op.params().psize(), convexity::no, 1e+6), m_op(op), m_idata(op.params().make_idata()), m_kdata(op.params().make_kdata()), m_bdata(op.params().make_bdata()), m_odata(op.params().make_odata()) { m_bdata.setRandom(); m_idata.vector().setRandom(); m_kdata.vector().setRandom(); m_odata.vector().setRandom(); } scalar_t vgrad(const vector_t& x, vector_t* gx) const override { m_kdata = map_tensor(x.data(), m_kdata.dims()); m_bdata = map_vector(x.data() + m_kdata.size(), m_bdata.size()); m_op.output(m_idata, m_kdata, m_bdata, m_odata); if (gx) { gx->resize(x.size()); m_op.gparam(m_idata, map_tensor(gx->data(), m_kdata.dims()), map_vector(gx->data() + m_kdata.size(), m_bdata.size()), m_odata); } return m_odata.array().square().sum() / 2; } mutable top m_op; tensor3d_t m_idata; mutable tensor4d_t m_kdata; mutable vector_t m_bdata; mutable tensor3d_t m_odata; }; template <typename top> struct wrt_inputs_function_t final : public function_t { explicit wrt_inputs_function_t(const top& op) : function_t("conv3d", op.params().isize(), op.params().isize(), op.params().isize(), convexity::no, 1e+6), m_op(op), m_idata(op.params().make_idata()), m_kdata(op.params().make_kdata()), m_bdata(op.params().make_bdata()), m_odata(op.params().make_odata()) { m_bdata.setRandom(); m_idata.vector().setRandom(); m_kdata.vector().setRandom(); m_odata.vector().setRandom(); } scalar_t vgrad(const vector_t& x, vector_t* gx) const override { m_idata = map_tensor(x.data(), m_idata.dims()); m_op.output(m_idata, m_kdata, m_bdata, m_odata); if (gx) { gx->resize(x.size()); m_op.ginput(map_tensor(gx->data(), m_idata.dims()), m_kdata, m_bdata, m_odata); } return m_odata.array().square().sum() / 2; } mutable top m_op; mutable tensor3d_t m_idata; tensor4d_t m_kdata; vector_t m_bdata; mutable tensor3d_t m_odata; }; auto make_default_params() { const auto imaps = 8; const auto irows = 11; const auto icols = 15; const auto omaps = 4; const auto kconn = 2; const auto krows = 3; const auto kcols = 5; const auto kdrow = 2; const auto kdcol = 1; return conv3d_params_t{imaps, irows, icols, omaps, kconn, krows, kcols, kdrow, kdcol}; } template <typename top> auto make_wrt_params_function(const conv3d_params_t& params) { return wrt_params_function_t<top>(top{params}); } template <typename top> auto make_wrt_inputs_function(const conv3d_params_t& params) { return wrt_inputs_function_t<top>(top{params}); } NANO_BEGIN_MODULE(test_conv3d) NANO_CASE(params_valid) { const auto imaps = 8; const auto irows = 11; const auto icols = 15; const auto omaps = 4; const auto kconn = 2; const auto krows = 3; const auto kcols = 5; const auto kdrow = 2; const auto kdcol = 1; const auto params = conv3d_params_t{imaps, irows, icols, omaps, kconn, krows, kcols, kdrow, kdcol}; NANO_CHECK(params.valid_kernel()); NANO_CHECK(params.valid_connectivity()); NANO_CHECK(params.valid()); NANO_CHECK_EQUAL(params.imaps(), imaps); NANO_CHECK_EQUAL(params.irows(), irows); NANO_CHECK_EQUAL(params.icols(), icols); NANO_CHECK_EQUAL(params.omaps(), omaps); NANO_CHECK_EQUAL(params.orows(), (irows - krows + 1) / kdrow); NANO_CHECK_EQUAL(params.ocols(), (icols - kcols + 1) / kdcol); NANO_CHECK_EQUAL(params.bdims(), omaps); } NANO_CASE(params_invalid) { const auto imaps = 8; const auto irows = 11; const auto icols = 15; const auto omaps = 6; const auto kconn = 3; const auto krows = 13; const auto kcols = 5; const auto kdrow = 2; const auto kdcol = 7; const auto params = conv3d_params_t{imaps, irows, icols, omaps, kconn, krows, kcols, kdrow, kdcol}; NANO_CHECK(!params.valid_kernel()); NANO_CHECK(!params.valid_connectivity()); NANO_CHECK(!params.valid()); } NANO_CASE(gparam_accuracy) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto pfunct = make_wrt_params_function<conv3d_naive_t>(params); for (int i = 0; i < 8; ++ i) { vector_t px(pfunct.size()); px.setRandom(); NANO_CHECK_LESS(pfunct.grad_accuracy(px), epsilon2<scalar_t>()); } } NANO_CASE(ginput_accuracy) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto ifunct = make_wrt_inputs_function<conv3d_naive_t>(params); for (int i = 0; i < 8; ++ i) { vector_t ix(ifunct.size()); ix.setRandom(); NANO_CHECK_LESS(ifunct.grad_accuracy(ix), epsilon2<scalar_t>()); } } NANO_CASE(naive_vs_toeplitz) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto op_naive = conv3d_naive_t{params}; const auto op_toeplitz = conv3d_toeplitz_t{params}; for (int i = 0; i < 8; ++ i) { { auto bdata = params.make_bdata(); bdata.setRandom(); auto idata = params.make_idata(); idata.vector().setRandom(); auto kdata = params.make_kdata(); kdata.vector().setRandom(); auto odata = params.make_odata(); odata.vector().setRandom(); auto bdatax = params.make_bdata(); bdatax.setRandom(); auto idatax = params.make_idata(); idatax.vector().setRandom(); auto kdatax = params.make_kdata(); kdatax.vector().setRandom(); auto odatax = params.make_odata(); odatax.vector().setRandom(); op_naive.output(idata, kdata, bdata, odata); op_toeplitz.output(idata, kdata, bdata, odatax); NANO_CHECK_EIGEN_CLOSE(odata.array(), odatax.array(), 10 * epsilon0<scalar_t>()); } { auto bdata = params.make_bdata(); bdata.setRandom(); auto idata = params.make_idata(); idata.vector().setRandom(); auto kdata = params.make_kdata(); kdata.vector().setRandom(); auto odata = params.make_odata(); odata.vector().setRandom(); auto bdatax = params.make_bdata(); bdatax.setRandom(); auto idatax = params.make_idata(); idatax.vector().setRandom(); auto kdatax = params.make_kdata(); kdatax.vector().setRandom(); auto odatax = params.make_odata(); odatax.vector().setRandom(); op_naive.output(idata, kdata, bdata, odata); op_toeplitz.output(idata, kdata, bdata, odatax); NANO_CHECK_EIGEN_CLOSE(odata.array(), odatax.array(), 10 * epsilon0<scalar_t>()); op_naive.gparam(idata, kdata, bdata, odata); op_toeplitz.gparam(idata, kdatax, bdatax, odata); NANO_CHECK_EIGEN_CLOSE(kdata.array(), kdatax.array(), 10 * epsilon0<scalar_t>()); NANO_CHECK_EIGEN_CLOSE(bdata.array(), bdatax.array(), 10 * epsilon0<scalar_t>()); } { auto bdata = params.make_bdata(); bdata.setRandom(); auto idata = params.make_idata(); idata.vector().setRandom(); auto kdata = params.make_kdata(); kdata.vector().setRandom(); auto odata = params.make_odata(); odata.vector().setRandom(); auto bdatax = params.make_bdata(); bdatax.setRandom(); auto idatax = params.make_idata(); idatax.vector().setRandom(); auto kdatax = params.make_kdata(); kdatax.vector().setRandom(); auto odatax = params.make_odata(); odatax.vector().setRandom(); op_naive.output(idata, kdata, bdata, odata); op_toeplitz.output(idata, kdata, bdata, odatax); NANO_CHECK_EIGEN_CLOSE(odata.array(), odatax.array(), 10 * epsilon0<scalar_t>()); op_naive.ginput(idata, kdata, bdata, odata); op_toeplitz.ginput(idatax, kdata, bdata, odata); NANO_CHECK_EIGEN_CLOSE(idata.array(), idatax.array(), epsilon1<scalar_t>()); } } } NANO_END_MODULE() <commit_msg>split unit test<commit_after>#include "utest.h" #include "function.h" #include "math/epsilon.h" #include "layers/conv3d_naive.h" #include "layers/conv3d_toeplitz.h" using namespace nano; template <typename top> struct wrt_params_function_t final : public function_t { explicit wrt_params_function_t(const top& op) : function_t("conv3d", op.params().psize(), op.params().psize(), op.params().psize(), convexity::no, 1e+6), m_op(op), m_idata(op.params().make_idata()), m_kdata(op.params().make_kdata()), m_bdata(op.params().make_bdata()), m_odata(op.params().make_odata()) { m_bdata.setRandom(); m_idata.vector().setRandom(); m_kdata.vector().setRandom(); m_odata.vector().setRandom(); } scalar_t vgrad(const vector_t& x, vector_t* gx) const override { m_kdata = map_tensor(x.data(), m_kdata.dims()); m_bdata = map_vector(x.data() + m_kdata.size(), m_bdata.size()); m_op.output(m_idata, m_kdata, m_bdata, m_odata); if (gx) { gx->resize(x.size()); m_op.gparam(m_idata, map_tensor(gx->data(), m_kdata.dims()), map_vector(gx->data() + m_kdata.size(), m_bdata.size()), m_odata); } return m_odata.array().square().sum() / 2; } mutable top m_op; tensor3d_t m_idata; mutable tensor4d_t m_kdata; mutable vector_t m_bdata; mutable tensor3d_t m_odata; }; template <typename top> struct wrt_inputs_function_t final : public function_t { explicit wrt_inputs_function_t(const top& op) : function_t("conv3d", op.params().isize(), op.params().isize(), op.params().isize(), convexity::no, 1e+6), m_op(op), m_idata(op.params().make_idata()), m_kdata(op.params().make_kdata()), m_bdata(op.params().make_bdata()), m_odata(op.params().make_odata()) { m_bdata.setRandom(); m_idata.vector().setRandom(); m_kdata.vector().setRandom(); m_odata.vector().setRandom(); } scalar_t vgrad(const vector_t& x, vector_t* gx) const override { m_idata = map_tensor(x.data(), m_idata.dims()); m_op.output(m_idata, m_kdata, m_bdata, m_odata); if (gx) { gx->resize(x.size()); m_op.ginput(map_tensor(gx->data(), m_idata.dims()), m_kdata, m_bdata, m_odata); } return m_odata.array().square().sum() / 2; } mutable top m_op; mutable tensor3d_t m_idata; tensor4d_t m_kdata; vector_t m_bdata; mutable tensor3d_t m_odata; }; auto make_default_params() { const auto imaps = 8; const auto irows = 11; const auto icols = 15; const auto omaps = 4; const auto kconn = 2; const auto krows = 3; const auto kcols = 5; const auto kdrow = 2; const auto kdcol = 1; return conv3d_params_t{imaps, irows, icols, omaps, kconn, krows, kcols, kdrow, kdcol}; } template <typename top> auto make_wrt_params_function(const conv3d_params_t& params) { return wrt_params_function_t<top>(top{params}); } template <typename top> auto make_wrt_inputs_function(const conv3d_params_t& params) { return wrt_inputs_function_t<top>(top{params}); } NANO_BEGIN_MODULE(test_conv3d) NANO_CASE(params_valid) { const auto imaps = 8; const auto irows = 11; const auto icols = 15; const auto omaps = 4; const auto kconn = 2; const auto krows = 3; const auto kcols = 5; const auto kdrow = 2; const auto kdcol = 1; const auto params = conv3d_params_t{imaps, irows, icols, omaps, kconn, krows, kcols, kdrow, kdcol}; NANO_CHECK(params.valid_kernel()); NANO_CHECK(params.valid_connectivity()); NANO_CHECK(params.valid()); NANO_CHECK_EQUAL(params.imaps(), imaps); NANO_CHECK_EQUAL(params.irows(), irows); NANO_CHECK_EQUAL(params.icols(), icols); NANO_CHECK_EQUAL(params.omaps(), omaps); NANO_CHECK_EQUAL(params.orows(), (irows - krows + 1) / kdrow); NANO_CHECK_EQUAL(params.ocols(), (icols - kcols + 1) / kdcol); NANO_CHECK_EQUAL(params.bdims(), omaps); } NANO_CASE(params_invalid) { const auto imaps = 8; const auto irows = 11; const auto icols = 15; const auto omaps = 6; const auto kconn = 3; const auto krows = 13; const auto kcols = 5; const auto kdrow = 2; const auto kdcol = 7; const auto params = conv3d_params_t{imaps, irows, icols, omaps, kconn, krows, kcols, kdrow, kdcol}; NANO_CHECK(!params.valid_kernel()); NANO_CHECK(!params.valid_connectivity()); NANO_CHECK(!params.valid()); } NANO_CASE(gparam_accuracy) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto pfunct = make_wrt_params_function<conv3d_naive_t>(params); for (int i = 0; i < 8; ++ i) { vector_t px(pfunct.size()); px.setRandom(); NANO_CHECK_LESS(pfunct.grad_accuracy(px), epsilon2<scalar_t>()); } } NANO_CASE(ginput_accuracy) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto ifunct = make_wrt_inputs_function<conv3d_naive_t>(params); for (int i = 0; i < 8; ++ i) { vector_t ix(ifunct.size()); ix.setRandom(); NANO_CHECK_LESS(ifunct.grad_accuracy(ix), epsilon2<scalar_t>()); } } NANO_CASE(naive_vs_toeplitz_output) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto op_naive = conv3d_naive_t{params}; const auto op_toeplitz = conv3d_toeplitz_t{params}; for (int i = 0; i < 8; ++ i) { auto bdata = params.make_bdata(); bdata.setRandom(); auto idata = params.make_idata(); idata.vector().setRandom(); auto kdata = params.make_kdata(); kdata.vector().setRandom(); auto odata = params.make_odata(); odata.vector().setRandom(); auto bdatax = params.make_bdata(); bdatax.setRandom(); auto idatax = params.make_idata(); idatax.vector().setRandom(); auto kdatax = params.make_kdata(); kdatax.vector().setRandom(); auto odatax = params.make_odata(); odatax.vector().setRandom(); op_naive.output(idata, kdata, bdata, odata); op_toeplitz.output(idata, kdata, bdata, odatax); NANO_CHECK_EIGEN_CLOSE(odata.array(), odatax.array(), 10 * epsilon0<scalar_t>()); } } NANO_CASE(naive_vs_toeplitz_gparam) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto op_naive = conv3d_naive_t{params}; const auto op_toeplitz = conv3d_toeplitz_t{params}; for (int i = 0; i < 8; ++ i) { auto bdata = params.make_bdata(); bdata.setRandom(); auto idata = params.make_idata(); idata.vector().setRandom(); auto kdata = params.make_kdata(); kdata.vector().setRandom(); auto odata = params.make_odata(); odata.vector().setRandom(); auto bdatax = params.make_bdata(); bdatax.setRandom(); auto idatax = params.make_idata(); idatax.vector().setRandom(); auto kdatax = params.make_kdata(); kdatax.vector().setRandom(); auto odatax = params.make_odata(); odatax.vector().setRandom(); op_naive.output(idata, kdata, bdata, odata); op_toeplitz.output(idata, kdata, bdata, odatax); NANO_CHECK_EIGEN_CLOSE(odata.array(), odatax.array(), 10 * epsilon0<scalar_t>()); op_naive.gparam(idata, kdata, bdata, odata); op_toeplitz.gparam(idata, kdatax, bdatax, odata); NANO_CHECK_EIGEN_CLOSE(kdata.array(), kdatax.array(), 10 * epsilon0<scalar_t>()); NANO_CHECK_EIGEN_CLOSE(bdata.array(), bdatax.array(), 10 * epsilon0<scalar_t>()); } } NANO_CASE(naive_vs_toeplitz_ginput) { const auto params = make_default_params(); NANO_REQUIRE(params.valid()); const auto op_naive = conv3d_naive_t{params}; const auto op_toeplitz = conv3d_toeplitz_t{params}; for (int i = 0; i < 8; ++ i) { auto bdata = params.make_bdata(); bdata.setRandom(); auto idata = params.make_idata(); idata.vector().setRandom(); auto kdata = params.make_kdata(); kdata.vector().setRandom(); auto odata = params.make_odata(); odata.vector().setRandom(); auto bdatax = params.make_bdata(); bdatax.setRandom(); auto idatax = params.make_idata(); idatax.vector().setRandom(); auto kdatax = params.make_kdata(); kdatax.vector().setRandom(); auto odatax = params.make_odata(); odatax.vector().setRandom(); op_naive.output(idata, kdata, bdata, odata); op_toeplitz.output(idata, kdata, bdata, odatax); NANO_CHECK_EIGEN_CLOSE(odata.array(), odatax.array(), 10 * epsilon0<scalar_t>()); op_naive.ginput(idata, kdata, bdata, odata); op_toeplitz.ginput(idatax, kdata, bdata, odata); NANO_CHECK_EIGEN_CLOSE(idata.array(), idatax.array(), epsilon1<scalar_t>()); } } NANO_END_MODULE() <|endoftext|>
<commit_before>/* * File: test_helper.hpp * Author: kjell * * Created on April 14, 2014, 12:47 AM */ #pragma once #include <string> #include <cassert> #include <chrono> #include <memory> #include <atomic> #include <future> #include <thread> #include <iostream> #include <stdexcept> #include "concurrent.hpp" #include "moveoncopy.hpp" namespace test_helper { typedef std::chrono::steady_clock clock; /** Random int function from http://www2.research.att.com/~bs/C++0xFAQ.html#std-random */ int random_int(int low, int high); struct DummyObject { void doNothing() {} }; struct Greeting { std::string sayHello() { return {"Hello World"}; } std::string ping(size_t number) { return {"Hello World" + std::to_string(number)}; } }; typedef std::unique_ptr<Greeting> UniqueGreeting; struct GreetingWithUnique { std::string talkBack(MoveOnCopy<UniqueGreeting> obj) { return obj.get()->sayHello(); } }; struct DummyObjectWithUniqueString { std::string talkBack(std::unique_ptr<std::string> str) { return *(str.get()); } std::string talkBack2(std::shared_ptr<std::string> str) { return *(str.get()); } std::string talkBack3(MoveOnCopy<std::unique_ptr<std::string>> str) { return *(str.get()); } }; /** Verify clean destruction */ struct TrueAtExit { std::atomic<bool>* flag; explicit TrueAtExit(std::atomic<bool>* f) : flag(f) { flag->store(false); } bool value() { return *flag; } ~TrueAtExit() { flag->store(true); } // concurrent improvement from the original Herb Sutter example // Which would copy/move the object into the concurrent wrapper // i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter) TrueAtExit(const TrueAtExit&) = delete; TrueAtExit& operator=(const TrueAtExit&) = delete; }; /** Verify concurrent runs,. "no" delay for the caller. */ struct DelayedCaller { void DoDelayedCall() { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } }; /** To verify that it is FIFO access */ class FlipOnce { std::atomic<size_t>* _stored_counter; std::atomic<size_t>* _stored_attempts; bool _is_flipped; public: explicit FlipOnce(std::atomic<size_t>* c, std::atomic<size_t>* t) : _stored_counter(c), _stored_attempts(t) , _is_flipped(false) { } ~FlipOnce() {} /** Void flip will count up NON ATOMIC internal variables. They are non atomic to avoid * any kind of unforseen atomic synchronization. Only in the destructor will the values * be saved to the atomic storages */ void doFlipAtomic() { if (!_is_flipped) { std::this_thread::sleep_for(std::chrono::milliseconds(random_int(0, 500))); _is_flipped = true; ++(*_stored_counter); } ++(*_stored_attempts); } }; // calls from a async... returning the "void" after a future.get() so as not to have a future-of-a-future void DoAFlipAtomic(concurrent<FlipOnce>& flipper); void DoALambdaFlipAtomic(concurrent<FlipOnce>& flipper); struct Animal { virtual std::string sound() = 0; }; struct Dog : public Animal { std::string sound() override { return {"Wof Wof"}; } }; struct Cat : public Animal { std::string sound() override { return {"Miauu Miauu"}; } }; struct ThrowUp { explicit ThrowUp(const std::string& puke) { throw std::runtime_error(puke); } void neverCalled() { std::cout << "I'm never called" << std::endl; } }; } // namespace test_helper <commit_msg>Use default trivial dtor to help compiler in code gen<commit_after>/* * File: test_helper.hpp * Author: kjell * * Created on April 14, 2014, 12:47 AM */ #pragma once #include <string> #include <cassert> #include <chrono> #include <memory> #include <atomic> #include <future> #include <thread> #include <iostream> #include <stdexcept> #include "concurrent.hpp" #include "moveoncopy.hpp" namespace test_helper { typedef std::chrono::steady_clock clock; /** Random int function from http://www2.research.att.com/~bs/C++0xFAQ.html#std-random */ int random_int(int low, int high); struct DummyObject { void doNothing() {} }; struct Greeting { std::string sayHello() { return {"Hello World"}; } std::string ping(size_t number) { return {"Hello World" + std::to_string(number)}; } }; typedef std::unique_ptr<Greeting> UniqueGreeting; struct GreetingWithUnique { std::string talkBack(MoveOnCopy<UniqueGreeting> obj) { return obj.get()->sayHello(); } }; struct DummyObjectWithUniqueString { std::string talkBack(std::unique_ptr<std::string> str) { return *(str.get()); } std::string talkBack2(std::shared_ptr<std::string> str) { return *(str.get()); } std::string talkBack3(MoveOnCopy<std::unique_ptr<std::string>> str) { return *(str.get()); } }; /** Verify clean destruction */ struct TrueAtExit { std::atomic<bool>* flag; explicit TrueAtExit(std::atomic<bool>* f) : flag(f) { flag->store(false); } bool value() { return *flag; } ~TrueAtExit() { flag->store(true); } // concurrent improvement from the original Herb Sutter example // Which would copy/move the object into the concurrent wrapper // i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter) TrueAtExit(const TrueAtExit&) = delete; TrueAtExit& operator=(const TrueAtExit&) = delete; }; /** Verify concurrent runs,. "no" delay for the caller. */ struct DelayedCaller { void DoDelayedCall() { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } }; /** To verify that it is FIFO access */ class FlipOnce { std::atomic<size_t>* _stored_counter; std::atomic<size_t>* _stored_attempts; bool _is_flipped; public: explicit FlipOnce(std::atomic<size_t>* c, std::atomic<size_t>* t) : _stored_counter(c), _stored_attempts(t) , _is_flipped(false) { } ~FlipOnce() = default; /** Void flip will count up NON ATOMIC internal variables. They are non atomic to avoid * any kind of unforseen atomic synchronization. Only in the destructor will the values * be saved to the atomic storages */ void doFlipAtomic() { if (!_is_flipped) { std::this_thread::sleep_for(std::chrono::milliseconds(random_int(0, 500))); _is_flipped = true; ++(*_stored_counter); } ++(*_stored_attempts); } }; // calls from a async... returning the "void" after a future.get() so as not to have a future-of-a-future void DoAFlipAtomic(concurrent<FlipOnce>& flipper); void DoALambdaFlipAtomic(concurrent<FlipOnce>& flipper); struct Animal { virtual std::string sound() = 0; }; struct Dog : public Animal { std::string sound() override { return {"Wof Wof"}; } }; struct Cat : public Animal { std::string sound() override { return {"Miauu Miauu"}; } }; struct ThrowUp { explicit ThrowUp(const std::string& puke) { throw std::runtime_error(puke); } void neverCalled() { std::cout << "I'm never called" << std::endl; } }; } // namespace test_helper <|endoftext|>
<commit_before>#include "RequestHandler.hh" #include <Poco/Logger.h> #include <Poco/URI.h> #include <vector> // // /<topic> POST -> create topic // /<topic> DELETE -> delete topic // /<topic>/messages POST -> push message // /<topic>/messages GET -> get message // /<topic>/messages HEAD -> header // // HTTP/1.1 200 OK // Date: Tue, 07 Jul 2015 15:58:56 GMT // Connection: Keep-Alive // Content-Length: 0 // X-Praline-First: 1234 // X-Praline-Last: 1400 // const auto HTTP_OK = Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK; const auto HTTP_BAD_REQUEST = Poco::Net::HTTPResponse::HTTPStatus::HTTP_BAD_REQUEST; const auto HTTP_CREATED = Poco::Net::HTTPResponse::HTTPStatus::HTTP_CREATED; const auto HTTP_INTERNAL_SERVER_ERROR = Poco::Net::HTTPResponse::HTTPStatus::HTTP_INTERNAL_SERVER_ERROR; const auto HTTP_NOT_FOUND = Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND; namespace { void internalError(Poco::Net::HTTPServerResponse& response) { response.setStatusAndReason(HTTP_INTERNAL_SERVER_ERROR); response.setContentLength(0); response.send().flush(); } } using namespace praline; RequestHandler::RequestHandler(praline::TopicList& topicList, Poco::Logger& logger) : topicListM(topicList), logM(logger) { } void RequestHandler::handleTopicPost(Request& request, Response& response, const std::string& topicName) { logM.information("posting message to topic '%s'", topicName); auto res = topicListM.find(topicName); if (!res.first) { logM.information("topic '%s' is not existing or open", topicName); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); } else { auto topic = res.second; if (!topic.write(request.stream())) { logM.information("error writing to topic '%s'", topicName); internalError(response); } else { // or ACCEPTED when we go async? response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } } } void RequestHandler::handleTopicGet(Request& request, Response& response, const std::string& topicName) { uint64_t seqno; try { auto sequenceHeader = request.get("X-Praline-Offset"); seqno = std::stoull(sequenceHeader); } catch (std::exception& ex) { logM.error("invalid or missing X-Praline-Offset, dropping request"); response.setStatusAndReason(HTTP_BAD_REQUEST); response.setContentLength(0); response.send().flush(); return; } logM.information("getting message '%lu' from topic '%s'", (unsigned long)seqno, topicName); auto res = topicListM.find(topicName); if (!res.first) { logM.information("topic '%s' is not existing or open", topicName); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); return; } auto topic = res.second; MessagePointer message; if (!topic.lookup(seqno, message)) { logM.information("topic '%s' does not have message %lu", topicName, (unsigned long)seqno); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); return; } response.setStatusAndReason(HTTP_OK); response.set("X-Praline-Offset", std::to_string(seqno)); if (!topic.read(response.send(), message)) { logM.information("error reading from '%s'", topicName); internalError(response); } else { response.send().flush(); } } void RequestHandler::handleTopicPut(Request&, Response& response, const std::string& topicName) { logM.information("creating topic '%s'", topicName); auto topic = praline::Topic(topicName); bool success = topicListM.insert(topic); if (success) { if (!topic.open()) { internalError(response); return; } response.setStatusAndReason(HTTP_CREATED); response.setContentLength(0); response.send().flush(); } else { response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } } void RequestHandler::handleTopicDelete(Request&, Response& response, const std::string& topicName) { logM.information("deleting topic '%s'", topicName); auto topic = praline::Topic(topicName); bool success = topicListM.remove(topic); if (success) { response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } else { response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); } } void RequestHandler::handleSubscribe(Request& request, Response& response, const std::string& topicName, uint64_t id) { auto res = topicListM.find(topicName); if (!res.first) { logM.information("topic '%s' is not existing or open", topicName); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); return; } response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } void RequestHandler::handleRequest(Request& request, Response& response) { logM.debug("URL: %s", request.getURI()); logM.debug("Method: %s", request.getMethod()); std::vector<std::string> path; Poco::URI(request.getURI()).getPathSegments(path); if (path.size() == 1) { if (request.getMethod() == "PUT") { handleTopicPut(request, response, path[0]); return; } else if (request.getMethod() == "DELETE") { handleTopicDelete(request, response, path[0]); return; } else if (request.getMethod() == "POST") { handleTopicPost(request, response, path[0]); return; } else if (request.getMethod() == "GET") { handleTopicGet(request, response, path[0]); return; } } else if (path.size() == 2) { if (request.getMethod() == "GET") { try { auto messageId = std::stoull(path[1], nullptr, 10); handleSubscribe(request, response, path[0], messageId); } catch (std::exception& ex) { logM.warning("Badly formatted message id in request: %s", path[1]); } } } logM.information("dropping invalid request"); response.setStatusAndReason(HTTP_BAD_REQUEST); response.setContentLength(0); response.send().flush(); } <commit_msg>Cleanup<commit_after>#include "RequestHandler.hh" #include <Poco/Logger.h> #include <Poco/URI.h> #include <vector> const auto HTTP_OK = Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK; const auto HTTP_BAD_REQUEST = Poco::Net::HTTPResponse::HTTPStatus::HTTP_BAD_REQUEST; const auto HTTP_CREATED = Poco::Net::HTTPResponse::HTTPStatus::HTTP_CREATED; const auto HTTP_INTERNAL_SERVER_ERROR = Poco::Net::HTTPResponse::HTTPStatus::HTTP_INTERNAL_SERVER_ERROR; const auto HTTP_NOT_FOUND = Poco::Net::HTTPResponse::HTTPStatus::HTTP_NOT_FOUND; namespace { void internalError(Poco::Net::HTTPServerResponse& response) { response.setStatusAndReason(HTTP_INTERNAL_SERVER_ERROR); response.setContentLength(0); response.send().flush(); } } using namespace praline; RequestHandler::RequestHandler(praline::TopicList& topicList, Poco::Logger& logger) : topicListM(topicList), logM(logger) { } void RequestHandler::handleTopicPost(Request& request, Response& response, const std::string& topicName) { logM.information("posting message to topic '%s'", topicName); auto res = topicListM.find(topicName); if (!res.first) { logM.information("topic '%s' is not existing or open", topicName); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); } else { auto topic = res.second; if (!topic.write(request.stream())) { logM.information("error writing to topic '%s'", topicName); internalError(response); } else { // or ACCEPTED when we go async? response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } } } void RequestHandler::handleTopicGet(Request& request, Response& response, const std::string& topicName) { uint64_t seqno; try { auto sequenceHeader = request.get("X-Praline-Offset"); seqno = std::stoull(sequenceHeader); } catch (std::exception& ex) { logM.warning("invalid or missing X-Praline-Offset, dropping request"); response.setStatusAndReason(HTTP_BAD_REQUEST); response.setContentLength(0); response.send().flush(); return; } logM.information("getting message '%lu' from topic '%s'", (unsigned long)seqno, topicName); auto res = topicListM.find(topicName); if (!res.first) { logM.information("topic '%s' is not existing or open", topicName); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); return; } auto topic = res.second; MessagePointer message; if (!topic.lookup(seqno, message)) { logM.information("topic '%s' does not have message %lu", topicName, (unsigned long)seqno); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); return; } response.setStatusAndReason(HTTP_OK); response.set("X-Praline-Offset", std::to_string(seqno)); if (!topic.read(response.send(), message)) { logM.information("error reading from '%s'", topicName); internalError(response); } else { response.send().flush(); } } void RequestHandler::handleTopicPut(Request&, Response& response, const std::string& topicName) { logM.information("creating topic '%s'", topicName); auto topic = praline::Topic(topicName); bool success = topicListM.insert(topic); if (success) { if (!topic.open()) { internalError(response); return; } response.setStatusAndReason(HTTP_CREATED); response.setContentLength(0); response.send().flush(); } else { response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } } void RequestHandler::handleTopicDelete(Request&, Response& response, const std::string& topicName) { logM.information("deleting topic '%s'", topicName); auto topic = praline::Topic(topicName); bool success = topicListM.remove(topic); if (success) { response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } else { response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); } } void RequestHandler::handleSubscribe(Request& request, Response& response, const std::string& topicName, uint64_t id) { auto res = topicListM.find(topicName); if (!res.first) { logM.information("topic '%s' is not existing or open", topicName); response.setStatusAndReason(HTTP_NOT_FOUND); response.setContentLength(0); response.send().flush(); return; } response.setStatusAndReason(HTTP_OK); response.setContentLength(0); response.send().flush(); } void RequestHandler::handleRequest(Request& request, Response& response) { logM.debug("URL: %s", request.getURI()); logM.debug("Method: %s", request.getMethod()); std::vector<std::string> path; Poco::URI(request.getURI()).getPathSegments(path); if (path.size() == 1) { if (request.getMethod() == "PUT") { handleTopicPut(request, response, path[0]); return; } else if (request.getMethod() == "DELETE") { handleTopicDelete(request, response, path[0]); return; } else if (request.getMethod() == "POST") { handleTopicPost(request, response, path[0]); return; } else if (request.getMethod() == "GET") { handleTopicGet(request, response, path[0]); return; } } else if (path.size() == 2) { if (request.getMethod() == "GET") { try { auto messageId = std::stoull(path[1], nullptr, 10); handleSubscribe(request, response, path[0], messageId); } catch (std::exception& ex) { logM.warning("Badly formatted message id in request: %s", path[1]); } } } logM.warning("Dropping invalid request: %s %s", request.getMethod(), request.getURI()); response.setStatusAndReason(HTTP_BAD_REQUEST); response.setContentLength(0); response.send().flush(); } <|endoftext|>
<commit_before>/* This file is part of the Nepomuk KDE project. Copyright (C) 2011 Sebastian Trueg <trueg@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "recommendationmanager.h" #include "recommendationmanageradaptor.h" #include "recommendation.h" #include "recommendationaction.h" #include "locationmanager.h" #include "kext.h" #include <kworkspace/kactivityinfo.h> #include <kworkspace/kactivityconsumer.h> #include <KRandom> #include <KRun> #include <KDebug> #include <Nepomuk/Query/Query> #include <Nepomuk/Query/QueryServiceClient> #include <Nepomuk/Query/ComparisonTerm> #include <Nepomuk/Query/LiteralTerm> #include <Nepomuk/Query/AndTerm> #include <Nepomuk/Query/QueryServiceClient> #include <Nepomuk/Query/Result> #include <Nepomuk/Resource> #include <Nepomuk/Variant> #include <Soprano/Vocabulary/NAO> #include <QtDBus/QDBusConnection> #include <QtDBus/QDBusMetaType> #include <QtLocation/QLandmark> using namespace Soprano::Vocabulary; using namespace Nepomuk::Vocabulary; QTM_USE_NAMESPACE //Q_DECLARE_METATYPE(Contour::Recommendation*) // TODO: act on several changes: // * later: triggers from the dms class Contour::RecommendationManager::Private { public: KActivityConsumer* m_activityConsumer; LocationManager* m_locationManager; QList<Recommendation> m_recommendations; QHash<QString, RecommendationAction> m_actionHash; QHash<QString, Recommendation> m_RecommendationForAction; Nepomuk::Query::QueryServiceClient m_queryClient; RecommendationManager* q; void updateRecommendations(); void _k_locationChanged(const QList<QLandmark>&); void _k_currentActivityChanged(const QString&); void _k_newResults(const QList<Nepomuk::Query::Result>&); void _k_queryFinished(); }; void Contour::RecommendationManager::Private::updateRecommendations() { // remove old recommendations m_recommendations.clear(); m_actionHash.clear(); m_RecommendationForAction.clear(); // get resources that have been touched in the current activity (the dumb way for now) const QString query = QString::fromLatin1( "select distinct ?resource, " " ( " " ( " " SUM ( " " ?lastScore * bif:exp( " " - bif:datediff('day', ?lastUpdate, %1) " " ) " " ) " " ) " " as ?score " " ) where { " " ?cache kext:targettedResource ?resource . " " ?cache a kext:ResourceScoreCache . " " ?cache nao:lastModified ?lastUpdate . " " ?cache kext:cachedScore ?lastScore . " " ?cache kext:usedActivity %2 . " " } " " GROUP BY (?resource) " " ORDER BY DESC (?score) " " LIMIT 10 " ).arg( Soprano::Node::literalToN3( QDateTime::currentDateTime() ), Soprano::Node::resourceToN3( Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri() ) ); kDebug() << query; m_queryClient.sparqlQuery(query); // IDEA: for files use usage events // for everything else use changes in data via graph metadata } void Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&) { updateRecommendations(); } void Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&) { updateRecommendations(); } void Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results) { foreach(const Nepomuk::Query::Result& result, results) { Recommendation r; Nepomuk::Resource resource(result.additionalBinding("resource").toString()); r.resourceUri = KUrl(resource.resourceUri()).url(); r.relevance = result.additionalBinding("score").toDouble(); kWarning() << "Got a new result:" << r.resourceUri << result.excerpt() << result.additionalBinding("score"); // for now we create the one dummy action: open the resource QString id; do { id = KRandom::randomString(5); } while(m_actionHash.contains(id)); RecommendationAction action; action.id = id; action.text = i18n("Open '%1'", resource.genericLabel()); action.iconName = "document-open"; //TODO action.relevance = 1; m_actionHash[id] = action; m_RecommendationForAction[id] = r; r.actions << action; m_recommendations << r; } } void Contour::RecommendationManager::Private::_k_queryFinished() { emit q->recommendationsChanged(m_recommendations); } Contour::RecommendationManager::RecommendationManager(QObject *parent) : QObject(parent), d(new Private()) { d->q = this; connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)), this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>))); connect(&d->m_queryClient, SIGNAL(finishedListing()), this, SLOT(_k_queryFinished())); d->m_activityConsumer = new KActivityConsumer(this); connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)), this, SLOT(_k_currentActivityChanged(QString))); d->m_locationManager = new LocationManager(this); connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)), this, SLOT(_k_locationChanged(QList<QLandmark>))); d->updateRecommendations(); // export via DBus qDBusRegisterMetaType<Contour::Recommendation>(); qDBusRegisterMetaType<QList<Contour::Recommendation> >(); qDBusRegisterMetaType<Contour::RecommendationAction>(); (void)new RecommendationManagerAdaptor(this); QDBusConnection::sessionBus().registerObject(QLatin1String("/recommendationmanager"), this); } Contour::RecommendationManager::~RecommendationManager() { delete d; } QList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const { return d->m_recommendations; } void Contour::RecommendationManager::executeAction(const QString &actionId) { if(d->m_actionHash.contains(actionId)) { RecommendationAction action = d->m_actionHash.value(actionId); // FIXME: this is the hacky execution of the action, make it correct Recommendation r = d->m_RecommendationForAction.value(actionId); Nepomuk::Resource res(r.resourceUri); QString url = res.property(QUrl("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#url")).toString(); //FIXME: why it exits (not even crash) with nepomuk uris? if (url.isEmpty() || url.startsWith("nepomuk:/")) { return; } KRun *run = new KRun(url, 0); run->setAutoDelete(true); } else { kDebug() << "Invalid action id encountered:" << actionId; } } #include "recommendationmanager.moc" <commit_msg>emit recommendationschanged for each new results<commit_after>/* This file is part of the Nepomuk KDE project. Copyright (C) 2011 Sebastian Trueg <trueg@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "recommendationmanager.h" #include "recommendationmanageradaptor.h" #include "recommendation.h" #include "recommendationaction.h" #include "locationmanager.h" #include "kext.h" #include <kworkspace/kactivityinfo.h> #include <kworkspace/kactivityconsumer.h> #include <KRandom> #include <KRun> #include <KDebug> #include <Nepomuk/Query/Query> #include <Nepomuk/Query/QueryServiceClient> #include <Nepomuk/Query/ComparisonTerm> #include <Nepomuk/Query/LiteralTerm> #include <Nepomuk/Query/AndTerm> #include <Nepomuk/Query/QueryServiceClient> #include <Nepomuk/Query/Result> #include <Nepomuk/Resource> #include <Nepomuk/Variant> #include <Soprano/Vocabulary/NAO> #include <QtDBus/QDBusConnection> #include <QtDBus/QDBusMetaType> #include <QtLocation/QLandmark> using namespace Soprano::Vocabulary; using namespace Nepomuk::Vocabulary; QTM_USE_NAMESPACE //Q_DECLARE_METATYPE(Contour::Recommendation*) // TODO: act on several changes: // * later: triggers from the dms class Contour::RecommendationManager::Private { public: KActivityConsumer* m_activityConsumer; LocationManager* m_locationManager; QList<Recommendation> m_recommendations; QHash<QString, RecommendationAction> m_actionHash; QHash<QString, Recommendation> m_RecommendationForAction; Nepomuk::Query::QueryServiceClient m_queryClient; RecommendationManager* q; QTimer *m_changedSignalTimer; void updateRecommendations(); void _k_locationChanged(const QList<QLandmark>&); void _k_currentActivityChanged(const QString&); void _k_newResults(const QList<Nepomuk::Query::Result>&); void _k_queryFinished(); }; void Contour::RecommendationManager::Private::updateRecommendations() { // remove old recommendations m_recommendations.clear(); m_actionHash.clear(); m_RecommendationForAction.clear(); // get resources that have been touched in the current activity (the dumb way for now) const QString query = QString::fromLatin1( "select distinct ?resource, " " ( " " ( " " SUM ( " " ?lastScore * bif:exp( " " - bif:datediff('day', ?lastUpdate, %1) " " ) " " ) " " ) " " as ?score " " ) where { " " ?cache kext:targettedResource ?resource . " " ?cache a kext:ResourceScoreCache . " " ?cache nao:lastModified ?lastUpdate . " " ?cache kext:cachedScore ?lastScore . " " ?cache kext:usedActivity %2 . " " } " " GROUP BY (?resource) " " ORDER BY DESC (?score) " " LIMIT 10 " ).arg( Soprano::Node::literalToN3( QDateTime::currentDateTime() ), Soprano::Node::resourceToN3( Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri() ) ); kDebug() << query; m_queryClient.sparqlQuery(query); // IDEA: for files use usage events // for everything else use changes in data via graph metadata } void Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&) { updateRecommendations(); } void Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&) { updateRecommendations(); } void Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results) { foreach(const Nepomuk::Query::Result& result, results) { Recommendation r; Nepomuk::Resource resource(result.additionalBinding("resource").toString()); r.resourceUri = KUrl(resource.resourceUri()).url(); r.relevance = result.additionalBinding("score").toDouble(); kWarning() << "Got a new result:" << r.resourceUri << result.excerpt() << result.additionalBinding("score"); // for now we create the one dummy action: open the resource QString id; do { id = KRandom::randomString(5); } while(m_actionHash.contains(id)); RecommendationAction action; action.id = id; action.text = i18n("Open '%1'", resource.genericLabel()); action.iconName = "document-open"; //TODO action.relevance = 1; m_actionHash[id] = action; m_RecommendationForAction[id] = r; r.actions << action; m_recommendations << r; } m_changedSignalTimer->start(300); } void Contour::RecommendationManager::Private::_k_queryFinished() { m_changedSignalTimer->stop(); emit q->recommendationsChanged(m_recommendations); } Contour::RecommendationManager::RecommendationManager(QObject *parent) : QObject(parent), d(new Private()) { d->q = this; d->m_changedSignalTimer = new QTimer(this); d->m_changedSignalTimer->setSingleShot(true); connect(d->m_changedSignalTimer, SIGNAL(timeout()), this, SLOT(_k_queryFinished())); connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)), this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>))); connect(&d->m_queryClient, SIGNAL(finishedListing()), this, SLOT(_k_queryFinished())); d->m_activityConsumer = new KActivityConsumer(this); connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)), this, SLOT(_k_currentActivityChanged(QString))); d->m_locationManager = new LocationManager(this); connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)), this, SLOT(_k_locationChanged(QList<QLandmark>))); d->updateRecommendations(); // export via DBus qDBusRegisterMetaType<Contour::Recommendation>(); qDBusRegisterMetaType<QList<Contour::Recommendation> >(); qDBusRegisterMetaType<Contour::RecommendationAction>(); (void)new RecommendationManagerAdaptor(this); QDBusConnection::sessionBus().registerObject(QLatin1String("/recommendationmanager"), this); } Contour::RecommendationManager::~RecommendationManager() { delete d; } QList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const { return d->m_recommendations; } void Contour::RecommendationManager::executeAction(const QString &actionId) { if(d->m_actionHash.contains(actionId)) { RecommendationAction action = d->m_actionHash.value(actionId); // FIXME: this is the hacky execution of the action, make it correct Recommendation r = d->m_RecommendationForAction.value(actionId); Nepomuk::Resource res(r.resourceUri); QString url = res.property(QUrl("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#url")).toString(); //FIXME: why it exits (not even crash) with nepomuk uris? if (url.isEmpty() || url.startsWith("nepomuk:/")) { return; } KRun *run = new KRun(url, 0); run->setAutoDelete(true); } else { kDebug() << "Invalid action id encountered:" << actionId; } } #include "recommendationmanager.moc" <|endoftext|>
<commit_before><commit_msg>add missing ostringstream line<commit_after><|endoftext|>
<commit_before>//Modulo principal que simula e gernecia as partes do pseudo-so #include "../include/arquivos.hpp" #include "../include/Processos/processo.hpp" #include "../include/modulo_filas.hpp" #include "../include/escalonamento.hpp" #include "../include/Memoria.hpp" #include "../include/Recursos.hpp" #include <stdio.h> #include <stdlib.h> /** A interface que propicia o gerenciamento das filas de prioridade é a biblioteca deque, que ja fornece uma lista do tipo parametrizada e com as operações de inserção, retirada e exclusão da lista. http://www.cplusplus.com/reference/deque/deque/ **/ int main(int argc, char* argv[]){ //Memoria::inicializa_memoria(); arquivos leitor_arquivos; Recursos recursos; filas processos; escalonador gerenciamento_de_processos; leitor_arquivos.le_arquivos(argc,argv); /** //Laco for abaixo eh uma das maneiras de se acessar a lista de processos //Outras formas de acesso a lista (std::vector) podem ser encontradas na //secao "Element access " de http://www.cplusplus.com/reference/vector/vector/ //(acessado em 26/10/2017 as 11:50) int i; for (i = 0; i < (int) leitor_arquivos.lista_processos.size(); i++){ //Metodo imprime_infomacoes_processo() espera como argumento de entrada //o PID, que eh simplesmente o (indice atual da lista de processsos +1) leitor_arquivos.lista_processos[i].imprime_infomacoes_processo(i+1); } **/ Memoria::inicializa_memoria(); recursos.inicializaRecursos(); recursos.imprimeStatus(); processos.insereFilas(leitor_arquivos); gerenciamento_de_processos.algoritmoEscalonamento(leitor_arquivos, processos); leitor_arquivos.informacao_disco.executa_operacoes_sobre_arquivo(leitor_arquivos.lista_processos); leitor_arquivos.informacao_disco.imprime_informacoes_disco(); processos.destroiFilas(); leitor_arquivos.libera_lista_processos(); return 0; } <commit_msg>Update so.cpp<commit_after>//Modulo principal que simula e gernecia as partes do pseudo-so #include "../include/arquivos.hpp" #include "../include/Processos/processo.hpp" #include "../include/modulo_filas.hpp" #include "../include/escalonamento.hpp" #include "../include/Memoria.hpp" #include "../include/Recursos.hpp" #include <stdio.h> #include <stdlib.h> /** A interface que propicia o gerenciamento das filas de prioridade é a biblioteca deque, que ja fornece uma lista do tipo parametrizada e com as operações de inserção, retirada e exclusão da lista. http://www.cplusplus.com/reference/deque/deque/ **/ int main(int argc, char* argv[]){ arquivos leitor_arquivos; Recursos recursos; filas processos; escalonador gerenciamento_de_processos; leitor_arquivos.le_arquivos(argc,argv); /** //Laco for abaixo eh uma das maneiras de se acessar a lista de processos //Outras formas de acesso a lista (std::vector) podem ser encontradas na //secao "Element access " de http://www.cplusplus.com/reference/vector/vector/ //(acessado em 26/10/2017 as 11:50) int i; for (i = 0; i < (int) leitor_arquivos.lista_processos.size(); i++){ //Metodo imprime_infomacoes_processo() espera como argumento de entrada //o PID, que eh simplesmente o (indice atual da lista de processsos +1) leitor_arquivos.lista_processos[i].imprime_infomacoes_processo(i+1); } **/ Memoria::inicializa_memoria(); recursos.inicializaRecursos(); recursos.imprimeStatus(); processos.insereFilas(leitor_arquivos); gerenciamento_de_processos.algoritmoEscalonamento(leitor_arquivos, processos); leitor_arquivos.informacao_disco.executa_operacoes_sobre_arquivo(leitor_arquivos.lista_processos); leitor_arquivos.informacao_disco.imprime_informacoes_disco(); processos.destroiFilas(); leitor_arquivos.libera_lista_processos(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 NVIDIA Corporation * * 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. */ /*! \file fill.inl * \brief Inline file for fill.h. */ #include <thrust/detail/config.h> #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC ///////////////////// // NVCC definition // ///////////////////// #include <thrust/detail/util/align.h> #include <thrust/detail/device/generate.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/type_traits.h> #include <thrust/extrema.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { template <typename T> struct fill_functor { T exemplar; fill_functor(T _exemplar) : exemplar(_exemplar) {} __host__ __device__ T operator()(void) { return exemplar; } }; // end fill_functor template<typename Pointer, typename T> void wide_fill(Pointer first, Pointer last, const T &exemplar) { typedef typename thrust::iterator_value<Pointer>::type OutputType; typedef unsigned long long WideType; // type used to pack the Ts size_t ALIGNMENT_BOUNDARY = 128; // begin copying blocks at this byte boundary size_t n = last - first; // use this union idiom to avoid warnings concerning type-punning union { WideType wide_exemplar; OutputType narrow_exemplars[sizeof(WideType) / sizeof(OutputType)]; } work_around_aliasing_warning; for(size_t i = 0; i < sizeof(WideType)/sizeof(OutputType); ++i) work_around_aliasing_warning.narrow_exemplars[i] = static_cast<OutputType>(exemplar); OutputType *first_raw = thrust::raw_pointer_cast(first); OutputType *last_raw = thrust::raw_pointer_cast(last); OutputType *block_first_raw = thrust::min(first_raw + n, thrust::detail::util::align_up(first_raw, ALIGNMENT_BOUNDARY)); OutputType *block_last_raw = thrust::max(block_first_raw, thrust::detail::util::align_down(last_raw, sizeof(WideType))); thrust::device_ptr<WideType> block_first_wide = thrust::device_pointer_cast(reinterpret_cast<WideType*>(block_first_raw)); thrust::device_ptr<WideType> block_last_wide = thrust::device_pointer_cast(reinterpret_cast<WideType*>(block_last_raw)); thrust::detail::device::generate(first, thrust::device_pointer_cast(block_first_raw), fill_functor<OutputType>(exemplar)); thrust::detail::device::generate(block_first_wide, block_last_wide, fill_functor<WideType>(work_around_aliasing_warning.wide_exemplar)); thrust::detail::device::generate(thrust::device_pointer_cast(block_last_raw), last, fill_functor<OutputType>(exemplar)); } template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar, thrust::detail::false_type) { fill_functor<T> func(exemplar); thrust::detail::device::generate(first, last, func); } template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar, thrust::detail::true_type) { typedef typename thrust::iterator_traits<ForwardIterator>::value_type OutputType; if ( thrust::detail::util::is_aligned<OutputType>(thrust::raw_pointer_cast(&*first)) ) { wide_fill(&*first, &*last, exemplar); } else { fill(first, last, exemplar, thrust::detail::false_type()); } } } // end detail template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar) { typedef typename thrust::iterator_traits<ForwardIterator>::value_type OutputType; typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType; // we're compiling with nvcc, launch a kernel const bool use_wide_fill = thrust::detail::is_trivial_iterator<ForwardIterator>::value && thrust::detail::has_trivial_assign<OutputType>::value && (sizeof(OutputType) == 1 || sizeof(OutputType) == 2 || sizeof(OutputType) == 4); // XXX WAR nvcc 3.0 usused variable warning (void)use_wide_fill; detail::fill(first, last, exemplar, thrust::detail::integral_constant<bool, use_wide_fill>()); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #else /////////////////////////// // C++ (only) definition // /////////////////////////// #include <thrust/copy.h> #include <thrust/device_ptr.h> #include <thrust/distance.h> namespace thrust { namespace detail { namespace device { namespace cuda { template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar) { typedef typename thrust::iterator_traits<ForwardIterator>::value_type OutputType; typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType; // we can't launch a kernel, implement this with a copy IndexType n = thrust::distance(first,last); raw_host_buffer<OutputType> temp(n); thrust::fill(temp.begin(), temp.end(), exemplar); thrust::copy(temp.begin(), temp.end(), first); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER_NVCC <commit_msg>Workaround type-punning problems with a type-safe idiom.<commit_after>/* * Copyright 2008-2010 NVIDIA Corporation * * 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. */ /*! \file fill.inl * \brief Inline file for fill.h. */ #include <thrust/detail/config.h> #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC ///////////////////// // NVCC definition // ///////////////////// #include <thrust/detail/util/align.h> #include <thrust/detail/device/generate.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/type_traits.h> #include <thrust/extrema.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { template <typename T> struct fill_functor { T exemplar; fill_functor(T _exemplar) : exemplar(_exemplar) {} __host__ __device__ T operator()(void) { return exemplar; } }; // end fill_functor // XXX use this verbose idiom to WAR type-punning problems template<typename T, size_t num_narrow = sizeof(unsigned long long) / sizeof(T)> struct wide_type; template<typename T> struct wide_type<T,2> { wide_type(const T &x) : narrow_element1(x), narrow_element2(x) {} T narrow_element1; T narrow_element2; }; template<typename T> struct wide_type<T,4> { wide_type(const T &x) : narrow_element1(x), narrow_element2(x), narrow_element3(x), narrow_element4(x) {} T narrow_element1; T narrow_element2; T narrow_element3; T narrow_element4; }; template<typename T> struct wide_type<T,8> { wide_type(const T &x) : narrow_element1(x), narrow_element2(x), narrow_element3(x), narrow_element4(x), narrow_element5(x), narrow_element6(x), narrow_element7(x), narrow_element8(x) {} T narrow_element1; T narrow_element2; T narrow_element3; T narrow_element4; T narrow_element5; T narrow_element6; T narrow_element7; T narrow_element8; }; template<typename Pointer, typename T> void wide_fill(Pointer first, Pointer last, const T &exemplar) { typedef typename thrust::iterator_value<Pointer>::type OutputType; size_t ALIGNMENT_BOUNDARY = 128; // begin copying blocks at this byte boundary size_t n = last - first; // type used to pack the Ts typedef wide_type<OutputType> WideType; WideType wide_exemplar(static_cast<OutputType>(exemplar)); OutputType *first_raw = thrust::raw_pointer_cast(first); OutputType *last_raw = thrust::raw_pointer_cast(last); OutputType *block_first_raw = thrust::min(first_raw + n, thrust::detail::util::align_up(first_raw, ALIGNMENT_BOUNDARY)); OutputType *block_last_raw = thrust::max(block_first_raw, thrust::detail::util::align_down(last_raw, sizeof(WideType))); thrust::device_ptr<WideType> block_first_wide = thrust::device_pointer_cast(reinterpret_cast<WideType*>(block_first_raw)); thrust::device_ptr<WideType> block_last_wide = thrust::device_pointer_cast(reinterpret_cast<WideType*>(block_last_raw)); thrust::detail::device::generate(first, thrust::device_pointer_cast(block_first_raw), fill_functor<OutputType>(exemplar)); thrust::detail::device::generate(block_first_wide, block_last_wide, fill_functor<WideType>(wide_exemplar)); thrust::detail::device::generate(thrust::device_pointer_cast(block_last_raw), last, fill_functor<OutputType>(exemplar)); } template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar, thrust::detail::false_type) { fill_functor<T> func(exemplar); thrust::detail::device::generate(first, last, func); } template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar, thrust::detail::true_type) { typedef typename thrust::iterator_traits<ForwardIterator>::value_type OutputType; if ( thrust::detail::util::is_aligned<OutputType>(thrust::raw_pointer_cast(&*first)) ) { wide_fill(&*first, &*last, exemplar); } else { fill(first, last, exemplar, thrust::detail::false_type()); } } } // end detail template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar) { typedef typename thrust::iterator_traits<ForwardIterator>::value_type OutputType; typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType; // we're compiling with nvcc, launch a kernel const bool use_wide_fill = thrust::detail::is_trivial_iterator<ForwardIterator>::value && thrust::detail::has_trivial_assign<OutputType>::value && (sizeof(OutputType) == 1 || sizeof(OutputType) == 2 || sizeof(OutputType) == 4); // XXX WAR nvcc 3.0 usused variable warning (void)use_wide_fill; detail::fill(first, last, exemplar, thrust::detail::integral_constant<bool, use_wide_fill>()); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #else /////////////////////////// // C++ (only) definition // /////////////////////////// #include <thrust/copy.h> #include <thrust/device_ptr.h> #include <thrust/distance.h> namespace thrust { namespace detail { namespace device { namespace cuda { template<typename ForwardIterator, typename T> void fill(ForwardIterator first, ForwardIterator last, const T &exemplar) { typedef typename thrust::iterator_traits<ForwardIterator>::value_type OutputType; typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType; // we can't launch a kernel, implement this with a copy IndexType n = thrust::distance(first,last); raw_host_buffer<OutputType> temp(n); thrust::fill(temp.begin(), temp.end(), exemplar); thrust::copy(temp.begin(), temp.end(), first); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER_NVCC <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: autoreferencemap.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:15:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_AUTOREFERENCEMAP_HXX #define CONFIGMGR_AUTOREFERENCEMAP_HXX #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef INCLUDED_MAP #include <map> #define INCLUDED_MAP #endif namespace configmgr { //////////////////////////////////////////////////////////////////////////////// using ::rtl::OUString; //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare = std::less<Key> > class AutoReferenceMap { public: typedef rtl::Reference<Object> Ref; typedef std::map<Key,Ref,KeyCompare> Map; typedef Object object_type; typedef Key key_type; typedef KeyCompare key_compare; typedef typename Map::value_type value_type; public: AutoReferenceMap() {} ~AutoReferenceMap() {} Map copy() const { return m_aMap; } void swap(Map & _rOtherData) { m_aMap.swap( _rOtherData ); } void swap(AutoReferenceMap & _rOther) { this->swap( _rOther.m_aMap ); } bool has(Key const & _aKey) const; Ref get(Key const & _aKey) const; Ref insert(Key const & _aKey, Ref const & _anEntry); Ref remove(Key const & _aKey); private: Ref internalGet(Key const & _aKey) const { typename Map::const_iterator it = m_aMap.find(_aKey); return it != m_aMap.end() ? it->second : Ref(); } Ref internalAdd(Key const & _aKey, Ref const & _aNewRef) { return m_aMap[_aKey] = _aNewRef; } void internalDrop(Key const & _aKey) { m_aMap.erase(_aKey); } private: Map m_aMap; }; //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > bool AutoReferenceMap<Key,Object,KeyCompare>::has(Key const & _aKey) const { return internalGet(_aKey).is(); } //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > rtl::Reference<Object> AutoReferenceMap<Key,Object,KeyCompare>::get(Key const & _aKey) const { return internalGet(_aKey); } //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > rtl::Reference<Object> AutoReferenceMap<Key,Object,KeyCompare>::insert(Key const & _aKey, Ref const & _anEntry) { Ref aRef = internalAdd(_aKey,_anEntry); return aRef; } //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > rtl::Reference<Object> AutoReferenceMap<Key,Object,KeyCompare>::remove(Key const & _aKey) { Ref aRef = internalGet(_aKey); internalDrop(_aKey); return aRef; } //----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// } // namespace configmgr #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.16); FILE MERGED 2008/04/01 15:06:42 thb 1.5.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:43 rt 1.5.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: autoreferencemap.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIGMGR_AUTOREFERENCEMAP_HXX #define CONFIGMGR_AUTOREFERENCEMAP_HXX #include <rtl/ref.hxx> #ifndef INCLUDED_MAP #include <map> #define INCLUDED_MAP #endif namespace configmgr { //////////////////////////////////////////////////////////////////////////////// using ::rtl::OUString; //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare = std::less<Key> > class AutoReferenceMap { public: typedef rtl::Reference<Object> Ref; typedef std::map<Key,Ref,KeyCompare> Map; typedef Object object_type; typedef Key key_type; typedef KeyCompare key_compare; typedef typename Map::value_type value_type; public: AutoReferenceMap() {} ~AutoReferenceMap() {} Map copy() const { return m_aMap; } void swap(Map & _rOtherData) { m_aMap.swap( _rOtherData ); } void swap(AutoReferenceMap & _rOther) { this->swap( _rOther.m_aMap ); } bool has(Key const & _aKey) const; Ref get(Key const & _aKey) const; Ref insert(Key const & _aKey, Ref const & _anEntry); Ref remove(Key const & _aKey); private: Ref internalGet(Key const & _aKey) const { typename Map::const_iterator it = m_aMap.find(_aKey); return it != m_aMap.end() ? it->second : Ref(); } Ref internalAdd(Key const & _aKey, Ref const & _aNewRef) { return m_aMap[_aKey] = _aNewRef; } void internalDrop(Key const & _aKey) { m_aMap.erase(_aKey); } private: Map m_aMap; }; //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > bool AutoReferenceMap<Key,Object,KeyCompare>::has(Key const & _aKey) const { return internalGet(_aKey).is(); } //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > rtl::Reference<Object> AutoReferenceMap<Key,Object,KeyCompare>::get(Key const & _aKey) const { return internalGet(_aKey); } //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > rtl::Reference<Object> AutoReferenceMap<Key,Object,KeyCompare>::insert(Key const & _aKey, Ref const & _anEntry) { Ref aRef = internalAdd(_aKey,_anEntry); return aRef; } //----------------------------------------------------------------------------- template < class Key, class Object, class KeyCompare > rtl::Reference<Object> AutoReferenceMap<Key,Object,KeyCompare>::remove(Key const & _aKey) { Ref aRef = internalGet(_aKey); internalDrop(_aKey); return aRef; } //----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// } // namespace configmgr #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: providerwrapper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:11:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "providerwrapper.hxx" #ifndef CONFIGMGR_BOOTSTRAP_HXX_ #include "bootstrap.hxx" #endif #ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_ #include "bootstrapcontext.hxx" #endif #ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_ #include <com/sun/star/lang/NullPointerException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #include <algorithm> namespace configmgr { //========================================================================== namespace uno = com::sun::star::uno; namespace lang = com::sun::star::lang; using rtl::OUString; //========================================================================== //= ProviderWrapper //========================================================================== uno::Reference< uno::XInterface > ProviderWrapper::create( uno::Reference< uno::XInterface > xDelegate, NamedValues const & aPresets) { Provider xProvDelegate(xDelegate, uno::UNO_QUERY); if (!xProvDelegate.is()) { OUString sMsg(RTL_CONSTASCII_USTRINGPARAM("ProviderWrapper: Cannot wrap a NULL provider")); throw lang::NullPointerException(sMsg,NULL); } //Strip prefixes NamedValues aStrippedPresets = aPresets; for (sal_Int32 i = 0; i < aPresets.getLength(); ++i) { if(aPresets[i].Name.matchAsciiL(RTL_CONSTASCII_STRINGPARAM(CONTEXT_ITEM_PREFIX_ ))) { aStrippedPresets[i].Name = aPresets[i].Name.copy(RTL_CONSTASCII_LENGTH(CONTEXT_ITEM_PREFIX_ )); } } Provider xResult( new ProviderWrapper(xProvDelegate,aStrippedPresets) ); typedef uno::Reference< lang::XComponent > Comp; DisposingForwarder::forward( Comp::query(xProvDelegate),Comp::query(xResult) ); return xResult; } ProviderWrapper::ProviderWrapper(Provider const & xDelegate, NamedValues const & aPresets) : ProviderWrapper_Base( PWMutexHolder::mutex ) , m_xDelegate(xDelegate) , m_aDefaults(aPresets.getLength()) { OSL_ASSERT(m_xDelegate.is()); for (sal_Int32 i = 0; i<aPresets.getLength(); ++i) { m_aDefaults[i] <<= aPresets[i]; } } ProviderWrapper::~ProviderWrapper() {} void SAL_CALL ProviderWrapper::disposing() { osl::MutexGuard lock(mutex); m_xDelegate.clear(); } ProviderWrapper::Provider ProviderWrapper::getDelegate() { osl::MutexGuard lock(mutex); if (!m_xDelegate.is()) { OUString sMsg(RTL_CONSTASCII_USTRINGPARAM("ProviderWrapper: Delegate Provider has been disposed")); throw lang::DisposedException(sMsg,*this); } return m_xDelegate; } uno::Reference<lang::XServiceInfo> ProviderWrapper::getDelegateInfo() { uno::Reference<lang::XServiceInfo> xDelegate( this->getDelegate(), uno::UNO_QUERY ); if (!xDelegate.is()) { OUString sMsg(RTL_CONSTASCII_USTRINGPARAM("ProviderWrapper: Delegate Provider has no service info")); throw uno::RuntimeException(sMsg,*this); } return xDelegate; } /// XMultiServiceFactory static inline uno::Any const * begin(ProviderWrapper::Arguments const & aArgs) { return aArgs.getConstArray(); } static inline uno::Any const * end(ProviderWrapper::Arguments const & aArgs) { return aArgs.getConstArray() + aArgs.getLength(); } static inline uno::Any * begin(ProviderWrapper::Arguments & aArgs) { return aArgs.getArray(); } static inline uno::Any * end(ProviderWrapper::Arguments & aArgs) { return aArgs.getArray() + aArgs.getLength(); } ProviderWrapper::Arguments ProviderWrapper::patchArguments(Arguments const & aArgs) const { // rely on evaluation order front to back if (m_aDefaults.getLength() == 0) return aArgs; Arguments aResult(m_aDefaults.getLength() + aArgs.getLength()); uno::Any * pNext = std::copy(begin(m_aDefaults),end(m_aDefaults),begin(aResult)); pNext = std::copy(begin(aArgs),end(aArgs),pNext); OSL_ASSERT(end(aResult) == pNext); return aResult; } uno::Reference< uno::XInterface > SAL_CALL ProviderWrapper::createInstance( const OUString& aServiceSpecifier ) throw(uno::Exception, uno::RuntimeException) { return getDelegate()->createInstanceWithArguments(aServiceSpecifier,m_aDefaults); } uno::Reference< uno::XInterface > SAL_CALL ProviderWrapper::createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const uno::Sequence< uno::Any >& Arguments ) throw(uno::Exception, uno::RuntimeException) { return getDelegate()->createInstanceWithArguments(ServiceSpecifier,patchArguments(Arguments)); } uno::Sequence< OUString > SAL_CALL ProviderWrapper::getAvailableServiceNames( ) throw(uno::RuntimeException) { return getDelegate()->getAvailableServiceNames( ); } /// XServiceInfo OUString SAL_CALL ProviderWrapper::getImplementationName( ) throw(uno::RuntimeException) { return OUString::createFromAscii("com.sun.star.comp.configuration.ConfigurationProviderWrapper"); } sal_Bool SAL_CALL ProviderWrapper::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException) { return getDelegateInfo()->supportsService( ServiceName ); } uno::Sequence< OUString > SAL_CALL ProviderWrapper::getSupportedServiceNames( ) throw(uno::RuntimeException) { return getDelegateInfo()->getSupportedServiceNames( ); } } // namespace configmgr <commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2006/02/14 10:17:36 cd 1.4.4.2: #i55991# Fix warnings for ms c++ compiler 2005/11/09 18:02:41 pl 1.4.4.1: #i53898# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: providerwrapper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 23:27:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "providerwrapper.hxx" #ifndef CONFIGMGR_BOOTSTRAP_HXX_ #include "bootstrap.hxx" #endif #ifndef CONFIGMGR_BOOTSTRAPCONTEXT_HXX_ #include "bootstrapcontext.hxx" #endif #ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_ #include <com/sun/star/lang/NullPointerException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #include <algorithm> namespace configmgr { //========================================================================== namespace uno = com::sun::star::uno; namespace lang = com::sun::star::lang; using rtl::OUString; //========================================================================== //= ProviderWrapper //========================================================================== uno::Reference< uno::XInterface > ProviderWrapper::create( uno::Reference< uno::XInterface > xDelegate, NamedValues const & aPresets) { Provider xProvDelegate(xDelegate, uno::UNO_QUERY); if (!xProvDelegate.is()) { OUString sMsg(RTL_CONSTASCII_USTRINGPARAM("ProviderWrapper: Cannot wrap a NULL provider")); throw lang::NullPointerException(sMsg,NULL); } //Strip prefixes NamedValues aStrippedPresets = aPresets; for (sal_Int32 i = 0; i < aPresets.getLength(); ++i) { if(aPresets[i].Name.matchAsciiL(RTL_CONSTASCII_STRINGPARAM(CONTEXT_ITEM_PREFIX_ ))) { aStrippedPresets[i].Name = aPresets[i].Name.copy(RTL_CONSTASCII_LENGTH(CONTEXT_ITEM_PREFIX_ )); } } Provider xResult( new ProviderWrapper(xProvDelegate,aStrippedPresets) ); typedef uno::Reference< lang::XComponent > Comp; DisposingForwarder::forward( Comp::query(xProvDelegate),Comp::query(xResult) ); return uno::Reference< uno::XInterface >( xResult, uno::UNO_QUERY ); } ProviderWrapper::ProviderWrapper(Provider const & xDelegate, NamedValues const & aPresets) : ProviderWrapper_Base( PWMutexHolder::mutex ) , m_xDelegate(xDelegate) , m_aDefaults(aPresets.getLength()) { OSL_ASSERT(m_xDelegate.is()); for (sal_Int32 i = 0; i<aPresets.getLength(); ++i) { m_aDefaults[i] <<= aPresets[i]; } } ProviderWrapper::~ProviderWrapper() {} void SAL_CALL ProviderWrapper::disposing() { osl::MutexGuard lock(mutex); m_xDelegate.clear(); } ProviderWrapper::Provider ProviderWrapper::getDelegate() { osl::MutexGuard lock(mutex); if (!m_xDelegate.is()) { OUString sMsg(RTL_CONSTASCII_USTRINGPARAM("ProviderWrapper: Delegate Provider has been disposed")); throw lang::DisposedException(sMsg,*this); } return m_xDelegate; } uno::Reference<lang::XServiceInfo> ProviderWrapper::getDelegateInfo() { uno::Reference<lang::XServiceInfo> xDelegate( this->getDelegate(), uno::UNO_QUERY ); if (!xDelegate.is()) { OUString sMsg(RTL_CONSTASCII_USTRINGPARAM("ProviderWrapper: Delegate Provider has no service info")); throw uno::RuntimeException(sMsg,*this); } return xDelegate; } /// XMultiServiceFactory static inline uno::Any const * begin(ProviderWrapper::Arguments const & aArgs) { return aArgs.getConstArray(); } static inline uno::Any const * end(ProviderWrapper::Arguments const & aArgs) { return aArgs.getConstArray() + aArgs.getLength(); } static inline uno::Any * begin(ProviderWrapper::Arguments & aArgs) { return aArgs.getArray(); } static inline uno::Any * end(ProviderWrapper::Arguments & aArgs) { return aArgs.getArray() + aArgs.getLength(); } ProviderWrapper::Arguments ProviderWrapper::patchArguments(Arguments const & aArgs) const { // rely on evaluation order front to back if (m_aDefaults.getLength() == 0) return aArgs; Arguments aResult(m_aDefaults.getLength() + aArgs.getLength()); uno::Any * pNext = std::copy(begin(m_aDefaults),end(m_aDefaults),begin(aResult)); pNext = std::copy(begin(aArgs),end(aArgs),pNext); OSL_ASSERT(end(aResult) == pNext); return aResult; } uno::Reference< uno::XInterface > SAL_CALL ProviderWrapper::createInstance( const OUString& aServiceSpecifier ) throw(uno::Exception, uno::RuntimeException) { return getDelegate()->createInstanceWithArguments(aServiceSpecifier,m_aDefaults); } uno::Reference< uno::XInterface > SAL_CALL ProviderWrapper::createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const uno::Sequence< uno::Any >& rArguments ) throw(uno::Exception, uno::RuntimeException) { return getDelegate()->createInstanceWithArguments(ServiceSpecifier,patchArguments(rArguments)); } uno::Sequence< OUString > SAL_CALL ProviderWrapper::getAvailableServiceNames( ) throw(uno::RuntimeException) { return getDelegate()->getAvailableServiceNames( ); } /// XServiceInfo OUString SAL_CALL ProviderWrapper::getImplementationName( ) throw(uno::RuntimeException) { return OUString::createFromAscii("com.sun.star.comp.configuration.ConfigurationProviderWrapper"); } sal_Bool SAL_CALL ProviderWrapper::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException) { return getDelegateInfo()->supportsService( ServiceName ); } uno::Sequence< OUString > SAL_CALL ProviderWrapper::getSupportedServiceNames( ) throw(uno::RuntimeException) { return getDelegateInfo()->getSupportedServiceNames( ); } } // namespace configmgr <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/worker.h" #include "tnt/dispatcher.h" #include "tnt/job.h" #include <tnt/httprequest.h> #include <tnt/httpreply.h> #include <tnt/httperror.h> #include <tnt/http.h> #include <tnt/poller.h> #include <tnt/tntconfig.h> #include <cxxtools/log.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/poll.h> #include <cxxtools/dlloader.h> #include <cxxtools/ioerror.h> #include <cxxtools/atomicity.h> #include <pthread.h> #include <string.h> log_define("tntnet.worker") namespace { static const char stateStarting[] = "0 starting"; static const char stateWaitingForJob[] = "1 waiting for job"; static const char stateParsing[] = "2 parsing request"; static const char statePostParsing[] = "3 post parsing"; static const char stateDispatch[] = "4 dispatch"; static const char stateProcessingRequest[] = "5 processing request"; static const char stateFlush[] = "6 flush"; static const char stateSendReply[] = "7 send reply"; static const char stateSendError[] = "8 send error"; static const char stateStopping[] = "9 stopping"; } namespace tnt { cxxtools::Mutex Worker::mutex; Worker::workers_type Worker::workers; Comploader Worker::comploader; Worker::Worker(Tntnet& app) : application(app), threadId(0), state(stateStarting), lastWaitTime(0) { cxxtools::MutexLock lock(mutex); workers.insert(this); } void Worker::run() { threadId = pthread_self(); Jobqueue& queue = application.getQueue(); log_debug("start thread " << threadId); while (queue.getWaitThreadCount() < application.getMinThreads()) { state = stateWaitingForJob; Jobqueue::JobPtr j = queue.get(); if (Tntnet::shouldStop()) { // put job back to queue to wake up next worker if any left queue.put(j); break; } try { std::iostream& socket = j->getStream(); if (Tntnet::shouldStop()) break; bool keepAlive; do { time(&lastWaitTime); keepAlive = false; state = stateParsing; try { j->getParser().parse(socket); state = statePostParsing; if (socket.eof()) log_debug("eof"); else if (j->getParser().failed()) { state = stateSendError; log_warn("bad request"); tnt::HttpReply errorReply(socket); errorReply.setVersion(1, 0); errorReply.setContentType("text/html"); errorReply.setKeepAliveCounter(0); errorReply.out() << "<html><body><h1>Error</h1><p>bad request</p></body></html>\n"; errorReply.sendReply(400, "Bad Request"); logRequest(j->getRequest(), errorReply, 400); } else if (socket.fail()) log_debug("socket failed"); else { j->getRequest().doPostParse(); j->setWrite(); keepAlive = processRequest(j->getRequest(), socket, j->decrementKeepAliveCounter()); if (keepAlive) { j->setRead(); j->clear(); if (!socket.rdbuf()->in_avail()) { if (queue.getWaitThreadCount() == 0 && !queue.empty()) { // if there is something to do and no threads waiting, we take // the next job just to improve responsiveness. log_debug("put job back into queue"); queue.put(j, true); keepAlive = false; } else { struct pollfd fd; fd.fd = j->getFd(); fd.events = POLLIN; if (::poll(&fd, 1, TntConfig::it().socketReadTimeout) == 0) { log_debug("pass job to poll-thread"); application.getPoller().addIdleJob(j); keepAlive = false; } } } } } } catch (const HttpError& e) { keepAlive = false; state = stateSendError; log_warn("http-Error: " << e.what()); HttpReply errorReply(socket); errorReply.setVersion(1, 0); errorReply.setKeepAliveCounter(0); for (HttpMessage::header_type::const_iterator it = e.header_begin(); it != e.header_end(); ++it) errorReply.setHeader(it->first, it->second); errorReply.out() << e.getBody() << '\n'; errorReply.sendReply(e.getErrcode(), e.getErrmsg()); logRequest(j->getRequest(), errorReply, e.getErrcode()); } } while (keepAlive); } catch (const cxxtools::IOTimeout& e) { application.getPoller().addIdleJob(j); } catch (const std::exception& e) { log_warn("unexpected exception: " << e.what()); } } time(&lastWaitTime); state = stateStopping; cxxtools::MutexLock lock(mutex); workers.erase(this); log_debug("end worker thread " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads"); } bool Worker::processRequest(HttpRequest& request, std::iostream& socket, unsigned keepAliveCount) { // log message log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent() << "\" user \"" << request.getUsername() << '"'); // create reply-object HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); if (request.isMethodHEAD()) reply.setHeadRequest(); reply.setLocale(request.getLocale()); if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); if (TntConfig::it().enableCompression) reply.setAcceptEncoding(request.getEncoding()); // process request try { try { dispatch(request, reply); if (!request.keepAlive() || !reply.keepAlive()) keepAliveCount = 0; if (keepAliveCount > 0) log_debug("keep alive"); else { log_debug("no keep alive request/reply=" << request.keepAlive() << '/' << reply.keepAlive()); } } catch (const HttpError& e) { throw; } catch (const std::exception& e) { throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what()); } catch (...) { log_error("unknown exception"); throw HttpError(HTTP_INTERNAL_SERVER_ERROR, "unknown error"); } } catch (const HttpError& e) { state = stateSendError; log_warn("http-Error: " << e.what()); HttpReply errorReply(socket); errorReply.setVersion(request.getMajorVersion(), request.getMinorVersion()); if (request.keepAlive()) errorReply.setKeepAliveCounter(keepAliveCount); else keepAliveCount = 0; for (HttpMessage::header_type::const_iterator it = e.header_begin(); it != e.header_end(); ++it) errorReply.setHeader(it->first, it->second); errorReply.out() << e.getBody() << '\n'; errorReply.sendReply(e.getErrcode(), e.getErrmsg()); logRequest(request, errorReply, e.getErrcode()); } return keepAliveCount > 0; } void Worker::logRequest(const HttpRequest& request, const HttpReply& reply, unsigned httpReturn) { static cxxtools::atomic_t waitCount = 0; cxxtools::atomicIncrement(waitCount); std::ofstream& accessLog = application.accessLog; if (!accessLog.is_open()) { std::string fname = TntConfig::it().accessLog; if (!fname.empty()) { cxxtools::MutexLock lock(application.accessLogMutex); if (!accessLog.is_open()) { log_debug("access log is not open - open now"); accessLog.open(fname.c_str(), std::ios::out | std::ios::app); if (accessLog.fail()) { std::cerr << "failed to open access log \"" << fname << '"' << std::endl; TntConfig::it().accessLog.clear(); } } } } log_debug("log request to access log with return code " << httpReturn); static const std::string unknown("-"); std::string user = request.getUsername(); if (user.empty()) user = unknown; std::string peerIp = request.getPeerIp(); if (peerIp.empty()) peerIp = unknown; std::string query = request.getQuery(); if (query.empty()) query = unknown; time_t t; ::time(&t); cxxtools::MutexLock lock(application.accessLogMutex); // cache for timestamp of access log static time_t lastLogTime = 0; static char timebuf[40]; if (t != lastLogTime) { struct tm tm; ::localtime_r(&t, &tm); strftime(timebuf, sizeof(timebuf), "%d/%b/%Y:%H:%M:%S %z", &tm); lastLogTime = t; } accessLog << peerIp << " - " << user << " [" << timebuf << "] \"" << request.getMethod_cstr() << ' ' << query << ' ' << "HTTP/" << request.getMajorVersion() << '.' << request.getMinorVersion() << "\" " << httpReturn << ' '; std::string::size_type contentSize = reply.getContentSize(); if (contentSize != 0) accessLog << contentSize; else accessLog << '-'; accessLog << " \"" << request.getHeader(httpheader::referer, "-") << "\" \"" << request.getHeader(httpheader::userAgent, "-") << "\"\n"; if (cxxtools::atomicDecrement(waitCount) == 0) accessLog.flush(); } void Worker::dispatch(HttpRequest& request, HttpReply& reply) { state = stateDispatch; const std::string& url = request.getUrl(); if (!HttpRequest::checkUrl(url)) { log_info("illegal url <" << url << '>'); throw HttpError(HTTP_BAD_REQUEST, "illegal url"); } request.setThreadContext(this); Dispatcher::PosType pos(application.getDispatcher(), request); while (true) { state = stateDispatch; // pos.getNext() throws NotFoundException at end Maptarget ci = pos.getNext(); try { Component* comp = 0; try { if (ci.libname == application.getAppName()) { // if the libname is the app name look first, if the component is // linked directly try { Compident cii = ci; cii.libname = std::string(); comp = &comploader.fetchComp(cii, application.getDispatcher()); } catch (const NotFoundException&) { // if the component is not found in the binary, fetchComp throws // NotFoundException and comp remains 0. // so we can ignore the exceptioni and just continue } } if (comp == 0) comp = &comploader.fetchComp(ci, application.getDispatcher()); } catch (const NotFoundException& e) { log_debug("NotFoundException catched - url " << e.getUrl() << " try next mapping"); continue; } request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url); request.setArgs(ci.getArgs()); std::string appname = application.getAppName().empty() ? ci.libname : application.getAppName(); application.getScopemanager().preCall(request, appname); state = stateProcessingRequest; unsigned http_return; const char* http_msg; std::string msg; try { http_return = comp->topCall(request, reply, request.getQueryParams()); http_msg = HttpReturn::httpMessage(http_return); } catch (const HttpReturn& e) { http_return = e.getReturnCode(); msg = e.getMessage(); http_msg = msg.c_str(); } if (http_return != DECLINED) { if (reply.isDirectMode()) { log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg); state = stateFlush; reply.out().flush(); } else { log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg << " - ContentSize: " << reply.getContentSize()); application.getScopemanager().postCall(request, reply, appname); state = stateSendReply; reply.sendReply(http_return, http_msg); } logRequest(request, reply, http_return); if (reply.out()) log_debug("reply sent"); else { reply.setKeepAliveCounter(0); log_warn("sending failed"); } return; } else log_debug("component " << ci << " returned DECLINED"); } catch (const LibraryNotFound& e) { log_warn("library " << e.getLibname() << " not found"); } } throw NotFoundException(request.getUrl()); } void Worker::timer() { time_t currentTime; time(&currentTime); cxxtools::MutexLock lock(mutex); for (workers_type::iterator it = workers.begin(); it != workers.end(); ++it) { (*it)->healthCheck(currentTime); } } void Worker::healthCheck(time_t currentTime) { if (state == stateProcessingRequest && lastWaitTime != 0 && TntConfig::it().maxRequestTime > 0) { if (static_cast<unsigned>(currentTime - lastWaitTime) > TntConfig::it().maxRequestTime) { log_fatal("requesttime " << TntConfig::it().maxRequestTime << " seconds in thread " << threadId << " exceeded - exit process"); log_info("current state: " << state); ::exit(111); } } } void Worker::touch() { time(&lastWaitTime); } Scope& Worker::getScope() { return threadScope; } Worker::workers_type::size_type Worker::getCountThreads() { cxxtools::MutexLock lock(mutex); return workers.size(); } } <commit_msg>call _exit instead of exit when tntnet tries to restart itself to make restarting more robust<commit_after>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/worker.h" #include "tnt/dispatcher.h" #include "tnt/job.h" #include <tnt/httprequest.h> #include <tnt/httpreply.h> #include <tnt/httperror.h> #include <tnt/http.h> #include <tnt/poller.h> #include <tnt/tntconfig.h> #include <cxxtools/log.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/poll.h> #include <cxxtools/dlloader.h> #include <cxxtools/ioerror.h> #include <cxxtools/atomicity.h> #include <pthread.h> #include <string.h> log_define("tntnet.worker") namespace { static const char stateStarting[] = "0 starting"; static const char stateWaitingForJob[] = "1 waiting for job"; static const char stateParsing[] = "2 parsing request"; static const char statePostParsing[] = "3 post parsing"; static const char stateDispatch[] = "4 dispatch"; static const char stateProcessingRequest[] = "5 processing request"; static const char stateFlush[] = "6 flush"; static const char stateSendReply[] = "7 send reply"; static const char stateSendError[] = "8 send error"; static const char stateStopping[] = "9 stopping"; } namespace tnt { cxxtools::Mutex Worker::mutex; Worker::workers_type Worker::workers; Comploader Worker::comploader; Worker::Worker(Tntnet& app) : application(app), threadId(0), state(stateStarting), lastWaitTime(0) { cxxtools::MutexLock lock(mutex); workers.insert(this); } void Worker::run() { threadId = pthread_self(); Jobqueue& queue = application.getQueue(); log_debug("start thread " << threadId); while (queue.getWaitThreadCount() < application.getMinThreads()) { state = stateWaitingForJob; Jobqueue::JobPtr j = queue.get(); if (Tntnet::shouldStop()) { // put job back to queue to wake up next worker if any left queue.put(j); break; } try { std::iostream& socket = j->getStream(); if (Tntnet::shouldStop()) break; bool keepAlive; do { time(&lastWaitTime); keepAlive = false; state = stateParsing; try { j->getParser().parse(socket); state = statePostParsing; if (socket.eof()) log_debug("eof"); else if (j->getParser().failed()) { state = stateSendError; log_warn("bad request"); tnt::HttpReply errorReply(socket); errorReply.setVersion(1, 0); errorReply.setContentType("text/html"); errorReply.setKeepAliveCounter(0); errorReply.out() << "<html><body><h1>Error</h1><p>bad request</p></body></html>\n"; errorReply.sendReply(400, "Bad Request"); logRequest(j->getRequest(), errorReply, 400); } else if (socket.fail()) log_debug("socket failed"); else { j->getRequest().doPostParse(); j->setWrite(); keepAlive = processRequest(j->getRequest(), socket, j->decrementKeepAliveCounter()); if (keepAlive) { j->setRead(); j->clear(); if (!socket.rdbuf()->in_avail()) { if (queue.getWaitThreadCount() == 0 && !queue.empty()) { // if there is something to do and no threads waiting, we take // the next job just to improve responsiveness. log_debug("put job back into queue"); queue.put(j, true); keepAlive = false; } else { struct pollfd fd; fd.fd = j->getFd(); fd.events = POLLIN; if (::poll(&fd, 1, TntConfig::it().socketReadTimeout) == 0) { log_debug("pass job to poll-thread"); application.getPoller().addIdleJob(j); keepAlive = false; } } } } } } catch (const HttpError& e) { keepAlive = false; state = stateSendError; log_warn("http-Error: " << e.what()); HttpReply errorReply(socket); errorReply.setVersion(1, 0); errorReply.setKeepAliveCounter(0); for (HttpMessage::header_type::const_iterator it = e.header_begin(); it != e.header_end(); ++it) errorReply.setHeader(it->first, it->second); errorReply.out() << e.getBody() << '\n'; errorReply.sendReply(e.getErrcode(), e.getErrmsg()); logRequest(j->getRequest(), errorReply, e.getErrcode()); } } while (keepAlive); } catch (const cxxtools::IOTimeout& e) { application.getPoller().addIdleJob(j); } catch (const std::exception& e) { log_warn("unexpected exception: " << e.what()); } } time(&lastWaitTime); state = stateStopping; cxxtools::MutexLock lock(mutex); workers.erase(this); log_debug("end worker thread " << threadId << " - " << workers.size() << " threads left - " << application.getQueue().getWaitThreadCount() << " waiting threads"); } bool Worker::processRequest(HttpRequest& request, std::iostream& socket, unsigned keepAliveCount) { // log message log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " from client " << request.getPeerIp() << " user-Agent \"" << request.getUserAgent() << "\" user \"" << request.getUsername() << '"'); // create reply-object HttpReply reply(socket); reply.setVersion(request.getMajorVersion(), request.getMinorVersion()); if (request.isMethodHEAD()) reply.setHeadRequest(); reply.setLocale(request.getLocale()); if (request.keepAlive()) reply.setKeepAliveCounter(keepAliveCount); if (TntConfig::it().enableCompression) reply.setAcceptEncoding(request.getEncoding()); // process request try { try { dispatch(request, reply); if (!request.keepAlive() || !reply.keepAlive()) keepAliveCount = 0; if (keepAliveCount > 0) log_debug("keep alive"); else { log_debug("no keep alive request/reply=" << request.keepAlive() << '/' << reply.keepAlive()); } } catch (const HttpError& e) { throw; } catch (const std::exception& e) { throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what()); } catch (...) { log_error("unknown exception"); throw HttpError(HTTP_INTERNAL_SERVER_ERROR, "unknown error"); } } catch (const HttpError& e) { state = stateSendError; log_warn("http-Error: " << e.what()); HttpReply errorReply(socket); errorReply.setVersion(request.getMajorVersion(), request.getMinorVersion()); if (request.keepAlive()) errorReply.setKeepAliveCounter(keepAliveCount); else keepAliveCount = 0; for (HttpMessage::header_type::const_iterator it = e.header_begin(); it != e.header_end(); ++it) errorReply.setHeader(it->first, it->second); errorReply.out() << e.getBody() << '\n'; errorReply.sendReply(e.getErrcode(), e.getErrmsg()); logRequest(request, errorReply, e.getErrcode()); } return keepAliveCount > 0; } void Worker::logRequest(const HttpRequest& request, const HttpReply& reply, unsigned httpReturn) { static cxxtools::atomic_t waitCount = 0; cxxtools::atomicIncrement(waitCount); std::ofstream& accessLog = application.accessLog; if (!accessLog.is_open()) { std::string fname = TntConfig::it().accessLog; if (!fname.empty()) { cxxtools::MutexLock lock(application.accessLogMutex); if (!accessLog.is_open()) { log_debug("access log is not open - open now"); accessLog.open(fname.c_str(), std::ios::out | std::ios::app); if (accessLog.fail()) { std::cerr << "failed to open access log \"" << fname << '"' << std::endl; TntConfig::it().accessLog.clear(); } } } } log_debug("log request to access log with return code " << httpReturn); static const std::string unknown("-"); std::string user = request.getUsername(); if (user.empty()) user = unknown; std::string peerIp = request.getPeerIp(); if (peerIp.empty()) peerIp = unknown; std::string query = request.getQuery(); if (query.empty()) query = unknown; time_t t; ::time(&t); cxxtools::MutexLock lock(application.accessLogMutex); // cache for timestamp of access log static time_t lastLogTime = 0; static char timebuf[40]; if (t != lastLogTime) { struct tm tm; ::localtime_r(&t, &tm); strftime(timebuf, sizeof(timebuf), "%d/%b/%Y:%H:%M:%S %z", &tm); lastLogTime = t; } accessLog << peerIp << " - " << user << " [" << timebuf << "] \"" << request.getMethod_cstr() << ' ' << query << ' ' << "HTTP/" << request.getMajorVersion() << '.' << request.getMinorVersion() << "\" " << httpReturn << ' '; std::string::size_type contentSize = reply.getContentSize(); if (contentSize != 0) accessLog << contentSize; else accessLog << '-'; accessLog << " \"" << request.getHeader(httpheader::referer, "-") << "\" \"" << request.getHeader(httpheader::userAgent, "-") << "\"\n"; if (cxxtools::atomicDecrement(waitCount) == 0) accessLog.flush(); } void Worker::dispatch(HttpRequest& request, HttpReply& reply) { state = stateDispatch; const std::string& url = request.getUrl(); if (!HttpRequest::checkUrl(url)) { log_info("illegal url <" << url << '>'); throw HttpError(HTTP_BAD_REQUEST, "illegal url"); } request.setThreadContext(this); Dispatcher::PosType pos(application.getDispatcher(), request); while (true) { state = stateDispatch; // pos.getNext() throws NotFoundException at end Maptarget ci = pos.getNext(); try { Component* comp = 0; try { if (ci.libname == application.getAppName()) { // if the libname is the app name look first, if the component is // linked directly try { Compident cii = ci; cii.libname = std::string(); comp = &comploader.fetchComp(cii, application.getDispatcher()); } catch (const NotFoundException&) { // if the component is not found in the binary, fetchComp throws // NotFoundException and comp remains 0. // so we can ignore the exceptioni and just continue } } if (comp == 0) comp = &comploader.fetchComp(ci, application.getDispatcher()); } catch (const NotFoundException& e) { log_debug("NotFoundException catched - url " << e.getUrl() << " try next mapping"); continue; } request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url); request.setArgs(ci.getArgs()); std::string appname = application.getAppName().empty() ? ci.libname : application.getAppName(); application.getScopemanager().preCall(request, appname); state = stateProcessingRequest; unsigned http_return; const char* http_msg; std::string msg; try { http_return = comp->topCall(request, reply, request.getQueryParams()); http_msg = HttpReturn::httpMessage(http_return); } catch (const HttpReturn& e) { http_return = e.getReturnCode(); msg = e.getMessage(); http_msg = msg.c_str(); } if (http_return != DECLINED) { if (reply.isDirectMode()) { log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg); state = stateFlush; reply.out().flush(); } else { log_info("request " << request.getMethod_cstr() << ' ' << request.getQuery() << " ready, returncode " << http_return << ' ' << http_msg << " - ContentSize: " << reply.getContentSize()); application.getScopemanager().postCall(request, reply, appname); state = stateSendReply; reply.sendReply(http_return, http_msg); } logRequest(request, reply, http_return); if (reply.out()) log_debug("reply sent"); else { reply.setKeepAliveCounter(0); log_warn("sending failed"); } return; } else log_debug("component " << ci << " returned DECLINED"); } catch (const LibraryNotFound& e) { log_warn("library " << e.getLibname() << " not found"); } } throw NotFoundException(request.getUrl()); } void Worker::timer() { time_t currentTime; time(&currentTime); cxxtools::MutexLock lock(mutex); for (workers_type::iterator it = workers.begin(); it != workers.end(); ++it) { (*it)->healthCheck(currentTime); } } void Worker::healthCheck(time_t currentTime) { if (state == stateProcessingRequest && lastWaitTime != 0 && TntConfig::it().maxRequestTime > 0) { if (static_cast<unsigned>(currentTime - lastWaitTime) > TntConfig::it().maxRequestTime) { log_fatal("requesttime " << TntConfig::it().maxRequestTime << " seconds in thread " << threadId << " exceeded - exit process"); log_info("current state: " << state); ::_exit(111); } } } void Worker::touch() { time(&lastWaitTime); } Scope& Worker::getScope() { return threadScope; } Worker::workers_type::size_type Worker::getCountThreads() { cxxtools::MutexLock lock(mutex); return workers.size(); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "dlg_InsertErrorBars.hxx" #include "dlg_InsertErrorBars.hrc" #include "res_ErrorBar.hxx" #include "ResourceIds.hrc" #include "ResId.hxx" #include "Strings.hrc" #include "chartview/ExplicitValueProvider.hxx" #include "ChartModelHelper.hxx" #include "ObjectIdentifier.hxx" #include "DiagramHelper.hxx" #include "AxisHelper.hxx" #include "ObjectNameProvider.hxx" #include <com/sun/star/chart2/XAxis.hpp> #include <com/sun/star/chart2/XDiagram.hpp> using ::rtl::OUString; using ::com::sun::star::uno::Reference; using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; //............................................................................. namespace chart { //............................................................................. InsertErrorBarsDialog::InsertErrorBarsDialog( Window* pParent, const SfxItemSet& rMyAttrs, const uno::Reference< chart2::XChartDocument > & xChartDocument, ErrorBarResources::tErrorBarType eType /* = ErrorBarResources::ERROR_BAR_Y */ ) : ModalDialog( pParent, SchResId( DLG_DATA_YERRORBAR )), rInAttrs( rMyAttrs ), aBtnOK( this, SchResId( BTN_OK )), aBtnCancel( this, SchResId( BTN_CANCEL )), aBtnHelp( this, SchResId( BTN_HELP )), m_apErrorBarResources( new ErrorBarResources( this, this, rInAttrs, /* bNoneAvailable = */ true, eType )) { FreeResource(); ObjectType objType = eType == ErrorBarResources::ERROR_BAR_Y ? OBJECTTYPE_DATA_ERRORS : OBJECTTYPE_DATA_ERRORS_X; this->SetText( ObjectNameProvider::getName_ObjectForAllSeries(objType) ); m_apErrorBarResources->SetChartDocumentForRangeChoosing( xChartDocument ); } InsertErrorBarsDialog::~InsertErrorBarsDialog() { } void InsertErrorBarsDialog::FillItemSet(SfxItemSet& rOutAttrs) { m_apErrorBarResources->FillItemSet(rOutAttrs); } void InsertErrorBarsDialog::DataChanged( const DataChangedEvent& rDCEvt ) { ModalDialog::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) m_apErrorBarResources->FillValueSets(); } void InsertErrorBarsDialog::SetAxisMinorStepWidthForErrorBarDecimals( double fMinorStepWidth ) { m_apErrorBarResources->SetAxisMinorStepWidthForErrorBarDecimals( fMinorStepWidth ); } double InsertErrorBarsDialog::getAxisMinorStepWidthForErrorBarDecimals( const Reference< frame::XModel >& xChartModel, const Reference< uno::XInterface >& xChartView, const OUString& rSelectedObjectCID ) { double fStepWidth = 0.001; ExplicitValueProvider* pExplicitValueProvider( ExplicitValueProvider::getExplicitValueProvider(xChartView) ); if( pExplicitValueProvider ) { Reference< XAxis > xAxis; Reference< XDiagram > xDiagram( ChartModelHelper::findDiagram( xChartModel ) ); Reference< XDataSeries > xSeries = ObjectIdentifier::getDataSeriesForCID( rSelectedObjectCID, xChartModel ); xAxis = DiagramHelper::getAttachedAxis( xSeries, xDiagram ); if(!xAxis.is()) xAxis = AxisHelper::getAxis( 1/*nDimensionIndex*/, true/*bMainAxis*/, xDiagram ); if(xAxis.is()) { ExplicitScaleData aExplicitScale; ExplicitIncrementData aExplicitIncrement; pExplicitValueProvider->getExplicitValuesForAxis( xAxis,aExplicitScale, aExplicitIncrement ); fStepWidth = aExplicitIncrement.Distance; if( !aExplicitIncrement.SubIncrements.empty() && aExplicitIncrement.SubIncrements[0].IntervalCount>0 ) fStepWidth=fStepWidth/double(aExplicitIncrement.SubIncrements[0].IntervalCount); else fStepWidth/=10; } } return fStepWidth; } //............................................................................. } //namespace chart //............................................................................. /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Set correct objecttype for errorbar.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "dlg_InsertErrorBars.hxx" #include "dlg_InsertErrorBars.hrc" #include "res_ErrorBar.hxx" #include "ResourceIds.hrc" #include "ResId.hxx" #include "Strings.hrc" #include "chartview/ExplicitValueProvider.hxx" #include "ChartModelHelper.hxx" #include "ObjectIdentifier.hxx" #include "DiagramHelper.hxx" #include "AxisHelper.hxx" #include "ObjectNameProvider.hxx" #include <com/sun/star/chart2/XAxis.hpp> #include <com/sun/star/chart2/XDiagram.hpp> using ::rtl::OUString; using ::com::sun::star::uno::Reference; using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; //............................................................................. namespace chart { //............................................................................. InsertErrorBarsDialog::InsertErrorBarsDialog( Window* pParent, const SfxItemSet& rMyAttrs, const uno::Reference< chart2::XChartDocument > & xChartDocument, ErrorBarResources::tErrorBarType eType /* = ErrorBarResources::ERROR_BAR_Y */ ) : ModalDialog( pParent, SchResId( DLG_DATA_YERRORBAR )), rInAttrs( rMyAttrs ), aBtnOK( this, SchResId( BTN_OK )), aBtnCancel( this, SchResId( BTN_CANCEL )), aBtnHelp( this, SchResId( BTN_HELP )), m_apErrorBarResources( new ErrorBarResources( this, this, rInAttrs, /* bNoneAvailable = */ true, eType )) { FreeResource(); ObjectType objType = eType == ErrorBarResources::ERROR_BAR_Y ? OBJECTTYPE_DATA_ERRORS_Y : OBJECTTYPE_DATA_ERRORS_X; this->SetText( ObjectNameProvider::getName_ObjectForAllSeries(objType) ); m_apErrorBarResources->SetChartDocumentForRangeChoosing( xChartDocument ); } InsertErrorBarsDialog::~InsertErrorBarsDialog() { } void InsertErrorBarsDialog::FillItemSet(SfxItemSet& rOutAttrs) { m_apErrorBarResources->FillItemSet(rOutAttrs); } void InsertErrorBarsDialog::DataChanged( const DataChangedEvent& rDCEvt ) { ModalDialog::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) m_apErrorBarResources->FillValueSets(); } void InsertErrorBarsDialog::SetAxisMinorStepWidthForErrorBarDecimals( double fMinorStepWidth ) { m_apErrorBarResources->SetAxisMinorStepWidthForErrorBarDecimals( fMinorStepWidth ); } double InsertErrorBarsDialog::getAxisMinorStepWidthForErrorBarDecimals( const Reference< frame::XModel >& xChartModel, const Reference< uno::XInterface >& xChartView, const OUString& rSelectedObjectCID ) { double fStepWidth = 0.001; ExplicitValueProvider* pExplicitValueProvider( ExplicitValueProvider::getExplicitValueProvider(xChartView) ); if( pExplicitValueProvider ) { Reference< XAxis > xAxis; Reference< XDiagram > xDiagram( ChartModelHelper::findDiagram( xChartModel ) ); Reference< XDataSeries > xSeries = ObjectIdentifier::getDataSeriesForCID( rSelectedObjectCID, xChartModel ); xAxis = DiagramHelper::getAttachedAxis( xSeries, xDiagram ); if(!xAxis.is()) xAxis = AxisHelper::getAxis( 1/*nDimensionIndex*/, true/*bMainAxis*/, xDiagram ); if(xAxis.is()) { ExplicitScaleData aExplicitScale; ExplicitIncrementData aExplicitIncrement; pExplicitValueProvider->getExplicitValuesForAxis( xAxis,aExplicitScale, aExplicitIncrement ); fStepWidth = aExplicitIncrement.Distance; if( !aExplicitIncrement.SubIncrements.empty() && aExplicitIncrement.SubIncrements[0].IntervalCount>0 ) fStepWidth=fStepWidth/double(aExplicitIncrement.SubIncrements[0].IntervalCount); else fStepWidth/=10; } } return fStepWidth; } //............................................................................. } //namespace chart //............................................................................. /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <Windows.h> #include <conio.h> // _getch() #include "Thoth.hpp" //#include "Modules/ThothModules.hpp" #include <Utils/Process.hpp> Thoth::Thoth() { Console::SetTextColor(Console::Color::Info); std::cout << "Thoth" << "\xC4\xC4\xC4\xC2 "; std::cout << '[' << __DATE__ << " : " << __TIME__ << ']' << std::endl; Console::SetTextColor(Console::Color::Cyan | Console::Color::Bright); std::cout << "\t\xC0Wunkolo (Wunkolo@gmail.com)\n"; Console::SetTextColor(Console::Color::Magenta | Console::Color::Bright); std::cout << std::string(Console::GetWidth() - 1, '\xC4') << std::endl; Console::SetTextColor(Console::Color::Info); std::string Path; Path.resize(MAX_PATH + 1, '\x0'); GetModuleFileNameA(nullptr, &Path[0], MAX_PATH); std::cout << "Process Module Path:\n\t" << Path.c_str() << std::endl; std::cout << std::hex << std::uppercase << std::setfill('0'); std::cout << "Thoth Thread ID: 0x" << GetCurrentThreadId() << std::endl; std::cout << "Process Base: 0x" << Util::Process::Base() << std::endl; // Push Commands //PushModule<Research>("research"); //PushModule<Player>("player"); Console::Console::Instance()->PrintLine(); } Thoth::~Thoth() { } void Thoth::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime) { if( _kbhit() ) { Console::Console::Instance()->HandleInput(_getch()); Console::Console::Instance()->PrintLine(); } for( std::pair<std::string, std::shared_ptr<ThothModule>> Command : Commands ) { if( Command.second ) { Command.second->Tick(DeltaTime); } } }<commit_msg>Process info at startup<commit_after>#include <iostream> #include <iomanip> #include <Windows.h> #include <conio.h> // _getch() #include "Thoth.hpp" //#include "Modules/ThothModules.hpp" #include <Utils/Process.hpp> Thoth::Thoth() { Console::SetTextColor(Console::Color::Info); std::cout << "Thoth" << "\xC4\xC4\xC4\xC2 "; std::cout << '[' << __DATE__ << " : " << __TIME__ << ']' << std::endl; Console::SetTextColor(Console::Color::Cyan | Console::Color::Bright); std::cout << "\t\xC0Wunkolo (Wunkolo@gmail.com)\n"; Console::SetTextColor(Console::Color::Magenta | Console::Color::Bright); std::cout << std::string(Console::GetWidth() - 1, '\xC4') << std::endl; Console::SetTextColor(Console::Color::Info); std::string Path; Path.resize(MAX_PATH + 1, '\x0'); GetModuleFileNameA(nullptr, &Path[0], MAX_PATH); std::cout << "Process Module Path:\n\t" << Path.c_str() << std::endl; std::cout << std::hex << std::uppercase << std::setfill('0'); std::cout << "Process Base: 0x" << Util::Process::Base() << std::endl; std::cout << "Thoth Thread ID: 0x" << GetCurrentThreadId() << std::endl; std::cout << "Thoth Base: 0x" << Util::Process::GetModuleBase("Thoth.dll") << std::endl; // Push Commands //PushModule<Research>("research"); //PushModule<Player>("player"); Console::Console::Instance()->PrintLine(); } Thoth::~Thoth() { } void Thoth::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime) { if( _kbhit() ) { Console::Console::Instance()->HandleInput(_getch()); Console::Console::Instance()->PrintLine(); } for( std::pair<std::string, std::shared_ptr<ThothModule>> Command : Commands ) { if( Command.second ) { Command.second->Tick(DeltaTime); } } }<|endoftext|>
<commit_before>// Copyright (c) 2010 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 "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_GetViews GetViews #else #define MAYBE_GetViews DISABLED_GetViews #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViews) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("get_views")) << message_; } <commit_msg>Enable ExtensionApiTest.GetViews on all platforms.<commit_after>// Copyright (c) 2011 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 "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViews) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("get_views")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "base/path_service.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" #if defined(OS_MACOSX) // WebSocket test started timing out - suspect webkit roll from 67965->68051. // http://crbug.com/56596 #define MAYBE_WebSocket DISABLED_WebSocket #else #define MAYBE_WebSocket WebSocket #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; } <commit_msg>Disable ExtensionApiTest.WebSocket<commit_after>// Copyright (c) 2010 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 "base/path_service.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" #if defined(OS_MACOSX) // WebSocket test started timing out - suspect webkit roll from 67965->68051. // http://crbug.com/56596 #define MAYBE_WebSocket DISABLED_WebSocket #else #define MAYBE_WebSocket WebSocket #endif // This test is disabled because of http://crbug.com/57662. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; } <|endoftext|>
<commit_before><commit_msg>Coverity: Assert that GetMutableDictionary returns a non-NULL dictionary.<commit_after><|endoftext|>
<commit_before><commit_msg>Fix shared linux build Split out of reverted change http://src.chromium.org/viewvc/chrome?view=rev&revision=37989<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 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 "chrome/common/extensions/extension_file_util.h" #include "base/file_util.h" #include "base/json/json_value_serializer.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace keys = extension_manifest_keys; #if defined(OS_WIN) // http://crbug.com/106381 #define InstallUninstallGarbageCollect DISABLED_InstallUninstallGarbageCollect #endif TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // Create a source extension. std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); std::string version("1.0"); FilePath src = temp.path().AppendASCII(extension_id); ASSERT_TRUE(file_util::CreateDirectory(src)); // Create a extensions tree. FilePath all_extensions = temp.path().AppendASCII("extensions"); ASSERT_TRUE(file_util::CreateDirectory(all_extensions)); // Install in empty directory. Should create parent directories as needed. FilePath version_1 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_1.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_1)); // Should have moved the source. ASSERT_FALSE(file_util::DirectoryExists(src)); // Install again. Should create a new one with different name. ASSERT_TRUE(file_util::CreateDirectory(src)); FilePath version_2 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_2.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Collect garbage. Should remove first one. std::map<std::string, FilePath> extension_paths; extension_paths[extension_id] = FilePath().AppendASCII(extension_id).Append(version_2.BaseName()); extension_file_util::GarbageCollectExtensions(all_extensions, extension_paths); ASSERT_FALSE(file_util::DirectoryExists(version_1)); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Uninstall. Should remove entire extension subtree. extension_file_util::UninstallExtension(all_extensions, extension_id); ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName())); ASSERT_TRUE(file_util::DirectoryExists(all_extensions)); } TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension != NULL); EXPECT_EQ("The first extension that I made.", extension->description()); } TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_FALSE(extension == NULL); EXPECT_TRUE(error.empty()); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesNoUnderscores \ DISABLED_CheckIllegalFilenamesNoUnderscores #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); src_path = temp.path().AppendASCII("_some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("dddddddddddddddddddddddddddddddd") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str()); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest is not valid JSON. " "Line: 2, column: 16, Syntax error.", error.c_str()); } TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("bad_encoding"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. " "It isn't UTF-8 encoded.", error.c_str()); } #define URL_PREFIX "chrome-extension://extension-id/" TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) { struct TestCase { const char* url; const char* expected_relative_path; } test_cases[] = { { URL_PREFIX "simple.html", "simple.html" }, { URL_PREFIX "directory/to/file.html", "directory/to/file.html" }, { URL_PREFIX "escape%20spaces.html", "escape spaces.html" }, { URL_PREFIX "%C3%9Cber.html", "\xC3\x9C" "ber.html" }, #if defined(OS_WIN) { URL_PREFIX "C%3A/simple.html", "" }, #endif { URL_PREFIX "////simple.html", "simple.html" }, { URL_PREFIX "/simple.html", "simple.html" }, { URL_PREFIX "\\simple.html", "simple.html" }, { URL_PREFIX "\\\\foo\\simple.html", "foo/simple.html" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) { GURL url(test_cases[i].url); #if defined(OS_POSIX) FilePath expected_path(test_cases[i].expected_relative_path); #elif defined(OS_WIN) FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path)); #endif FilePath actual_path = extension_file_util::ExtensionURLToRelativeFilePath(url); EXPECT_FALSE(actual_path.IsAbsolute()) << " For the path " << actual_path.value(); EXPECT_EQ(expected_path.value(), actual_path.value()) << " For the path " << url; } } static scoped_refptr<Extension> LoadExtensionManifest( const std::string& manifest_value, const FilePath& manifest_dir, Extension::Location location, int extra_flags, std::string* error) { JSONStringValueSerializer serializer(manifest_value); scoped_ptr<Value> result(serializer.Deserialize(NULL, error)); if (!result.get()) return NULL; scoped_refptr<Extension> extension = Extension::Create( manifest_dir, location, *static_cast<DictionaryValue*>(result.get()), extra_flags, error); return extension; } TEST(ExtensionFileUtil, ValidateThemeUTF8) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them. std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png"; FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe( non_ascii_file)); file_util::WriteFile(non_ascii_path, "", 0); std::string kManifest = base::StringPrintf( "{ \"name\": \"Test\", \"version\": \"1.0\", " " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }" "}", non_ascii_file.c_str()); std::string error; scoped_refptr<Extension> extension = LoadExtensionManifest( kManifest, temp.path(), Extension::LOAD, 0, &error); ASSERT_TRUE(extension.get()) << error; EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) << error; } // TODO(aa): More tests as motivation allows. Maybe steal some from // ExtensionService? Many of them could probably be tested here without the // MessageLoop shenanigans. <commit_msg>Marking ExtensionFileUtil.CheckIllegalFilenamesOnlyReserved as DISABLED on Windows.<commit_after>// Copyright (c) 2011 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 "chrome/common/extensions/extension_file_util.h" #include "base/file_util.h" #include "base/json/json_value_serializer.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace keys = extension_manifest_keys; #if defined(OS_WIN) // http://crbug.com/106381 #define InstallUninstallGarbageCollect DISABLED_InstallUninstallGarbageCollect #endif TEST(ExtensionFileUtil, InstallUninstallGarbageCollect) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // Create a source extension. std::string extension_id("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); std::string version("1.0"); FilePath src = temp.path().AppendASCII(extension_id); ASSERT_TRUE(file_util::CreateDirectory(src)); // Create a extensions tree. FilePath all_extensions = temp.path().AppendASCII("extensions"); ASSERT_TRUE(file_util::CreateDirectory(all_extensions)); // Install in empty directory. Should create parent directories as needed. FilePath version_1 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_1.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_0") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_1)); // Should have moved the source. ASSERT_FALSE(file_util::DirectoryExists(src)); // Install again. Should create a new one with different name. ASSERT_TRUE(file_util::CreateDirectory(src)); FilePath version_2 = extension_file_util::InstallExtension(src, extension_id, version, all_extensions); ASSERT_EQ(version_2.value(), all_extensions.AppendASCII(extension_id).AppendASCII("1.0_1") .value()); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Collect garbage. Should remove first one. std::map<std::string, FilePath> extension_paths; extension_paths[extension_id] = FilePath().AppendASCII(extension_id).Append(version_2.BaseName()); extension_file_util::GarbageCollectExtensions(all_extensions, extension_paths); ASSERT_FALSE(file_util::DirectoryExists(version_1)); ASSERT_TRUE(file_util::DirectoryExists(version_2)); // Uninstall. Should remove entire extension subtree. extension_file_util::UninstallExtension(all_extensions, extension_id); ASSERT_FALSE(file_util::DirectoryExists(version_2.DirName())); ASSERT_TRUE(file_util::DirectoryExists(all_extensions)); } TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension != NULL); EXPECT_EQ("The first extension that I made.", extension->description()); } TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_FALSE(extension == NULL); EXPECT_TRUE(error.empty()); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesNoUnderscores \ DISABLED_CheckIllegalFilenamesNoUnderscores #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } #if defined(OS_WIN) // http://crbug.com/106381 #define CheckIllegalFilenamesOnlyReserved \ DISABLED_CheckIllegalFilenamesOnlyReserved #endif TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); src_path = temp.path().AppendASCII("_some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("dddddddddddddddddddddddddddddddd") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str()); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") .AppendASCII("1.0"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest is not valid JSON. " "Line: 2, column: 16, Syntax error.", error.c_str()); } TEST(ExtensionFileUtil, FailLoadingNonUTF8Scripts) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("bad_encoding"); std::string error; scoped_refptr<Extension> extension(extension_file_util::LoadExtension( install_dir, Extension::LOAD, Extension::STRICT_ERROR_CHECKS, &error)); ASSERT_TRUE(extension == NULL); ASSERT_STREQ("Could not load file 'bad_encoding.js' for content script. " "It isn't UTF-8 encoded.", error.c_str()); } #define URL_PREFIX "chrome-extension://extension-id/" TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) { struct TestCase { const char* url; const char* expected_relative_path; } test_cases[] = { { URL_PREFIX "simple.html", "simple.html" }, { URL_PREFIX "directory/to/file.html", "directory/to/file.html" }, { URL_PREFIX "escape%20spaces.html", "escape spaces.html" }, { URL_PREFIX "%C3%9Cber.html", "\xC3\x9C" "ber.html" }, #if defined(OS_WIN) { URL_PREFIX "C%3A/simple.html", "" }, #endif { URL_PREFIX "////simple.html", "simple.html" }, { URL_PREFIX "/simple.html", "simple.html" }, { URL_PREFIX "\\simple.html", "simple.html" }, { URL_PREFIX "\\\\foo\\simple.html", "foo/simple.html" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) { GURL url(test_cases[i].url); #if defined(OS_POSIX) FilePath expected_path(test_cases[i].expected_relative_path); #elif defined(OS_WIN) FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path)); #endif FilePath actual_path = extension_file_util::ExtensionURLToRelativeFilePath(url); EXPECT_FALSE(actual_path.IsAbsolute()) << " For the path " << actual_path.value(); EXPECT_EQ(expected_path.value(), actual_path.value()) << " For the path " << url; } } static scoped_refptr<Extension> LoadExtensionManifest( const std::string& manifest_value, const FilePath& manifest_dir, Extension::Location location, int extra_flags, std::string* error) { JSONStringValueSerializer serializer(manifest_value); scoped_ptr<Value> result(serializer.Deserialize(NULL, error)); if (!result.get()) return NULL; scoped_refptr<Extension> extension = Extension::Create( manifest_dir, location, *static_cast<DictionaryValue*>(result.get()), extra_flags, error); return extension; } TEST(ExtensionFileUtil, ValidateThemeUTF8) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); // "aeo" with accents. Use http://0xcc.net/jsescape/ to decode them. std::string non_ascii_file = "\xC3\xA0\xC3\xA8\xC3\xB2.png"; FilePath non_ascii_path = temp.path().Append(FilePath::FromUTF8Unsafe( non_ascii_file)); file_util::WriteFile(non_ascii_path, "", 0); std::string kManifest = base::StringPrintf( "{ \"name\": \"Test\", \"version\": \"1.0\", " " \"theme\": { \"images\": { \"theme_frame\": \"%s\" } }" "}", non_ascii_file.c_str()); std::string error; scoped_refptr<Extension> extension = LoadExtensionManifest( kManifest, temp.path(), Extension::LOAD, 0, &error); ASSERT_TRUE(extension.get()) << error; EXPECT_TRUE(extension_file_util::ValidateExtension(extension, &error)) << error; } // TODO(aa): More tests as motivation allows. Maybe steal some from // ExtensionService? Many of them could probably be tested here without the // MessageLoop shenanigans. <|endoftext|>
<commit_before>// Copyright 2013 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 "chrome/browser/extensions/extension_util.h" #include "base/command_line.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/sync_helper.h" #include "components/variations/variations_associated_data.h" #include "content/public/browser/site_instance.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_util.h" #include "extensions/browser/process_manager.h" #include "extensions/common/extension.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/features/behavior_feature.h" #include "extensions/common/features/feature.h" #include "extensions/common/features/feature_provider.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_handlers/app_isolation_info.h" #include "extensions/common/manifest_handlers/incognito_info.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/grit/extensions_browser_resources.h" #include "ui/base/resource/resource_bundle.h" namespace extensions { namespace util { namespace { const char kSupervisedUserExtensionPermissionIncreaseFieldTrialName[] = "SupervisedUserExtensionPermissionIncrease"; // The entry into the prefs used to flag an extension as installed by custodian. // It is relevant only for supervised users. const char kWasInstalledByCustodianPrefName[] = "was_installed_by_custodian"; // Returns true if |extension| should always be enabled in incognito mode. bool IsWhitelistedForIncognito(const Extension* extension) { const Feature* feature = FeatureProvider::GetBehaviorFeature( behavior_feature::kWhitelistedForIncognito); return feature && feature->IsAvailableToExtension(extension).is_available(); } } // namespace bool IsIncognitoEnabled(const std::string& extension_id, content::BrowserContext* context) { const Extension* extension = ExtensionRegistry::Get(context)-> GetExtensionById(extension_id, ExtensionRegistry::ENABLED); if (extension) { if (!util::CanBeIncognitoEnabled(extension)) return false; // If this is an existing component extension we always allow it to // work in incognito mode. if (extension->location() == Manifest::COMPONENT || extension->location() == Manifest::EXTERNAL_COMPONENT) { return true; } if (IsWhitelistedForIncognito(extension)) return true; } return ExtensionPrefs::Get(context)->IsIncognitoEnabled(extension_id); } void SetIsIncognitoEnabled(const std::string& extension_id, content::BrowserContext* context, bool enabled) { NOTIMPLEMENTED(); } bool CanCrossIncognito(const Extension* extension, content::BrowserContext* context) { // We allow the extension to see events and data from another profile iff it // uses "spanning" behavior and it has incognito access. "split" mode // extensions only see events for a matching profile. CHECK(extension); return IsIncognitoEnabled(extension->id(), context) && !IncognitoInfo::IsSplitMode(extension); } bool CanLoadInIncognito(const Extension* extension, content::BrowserContext* context) { CHECK(extension); if (extension->is_hosted_app()) return true; // Packaged apps and regular extensions need to be enabled specifically for // incognito (and split mode should be set). return IncognitoInfo::IsSplitMode(extension) && IsIncognitoEnabled(extension->id(), context); } bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableExtensionsFileAccessCheck) || ExtensionPrefs::Get(context)->AllowFileAccess(extension_id); } void SetAllowFileAccess(const std::string& extension_id, content::BrowserContext* context, bool allow) { NOTIMPLEMENTED(); } void SetWasInstalledByCustodian(const std::string& extension_id, content::BrowserContext* context, bool installed_by_custodian) { NOTIMPLEMENTED(); } bool WasInstalledByCustodian(const std::string& extension_id, content::BrowserContext* context) { bool installed_by_custodian = false; ExtensionPrefs* prefs = ExtensionPrefs::Get(context); prefs->ReadPrefAsBoolean(extension_id, kWasInstalledByCustodianPrefName, &installed_by_custodian); return installed_by_custodian; } bool IsAppLaunchable(const std::string& extension_id, content::BrowserContext* context) { int reason = ExtensionPrefs::Get(context)->GetDisableReasons(extension_id); return !((reason & Extension::DISABLE_UNSUPPORTED_REQUIREMENT) || (reason & Extension::DISABLE_CORRUPTED)); } bool IsAppLaunchableWithoutEnabling(const std::string& extension_id, content::BrowserContext* context) { return ExtensionRegistry::Get(context)->GetExtensionById( extension_id, ExtensionRegistry::ENABLED) != NULL; } bool ShouldSync(const Extension* extension, content::BrowserContext* context) { return sync_helper::IsSyncable(extension) && !ExtensionPrefs::Get(context)->DoNotSync(extension->id()); } bool IsExtensionIdle(const std::string& extension_id, content::BrowserContext* context) { std::vector<std::string> ids_to_check; ids_to_check.push_back(extension_id); const Extension* extension = ExtensionRegistry::Get(context) ->GetExtensionById(extension_id, ExtensionRegistry::ENABLED); if (extension && extension->is_shared_module()) { // We have to check all the extensions that use this shared module for idle // to tell whether it is really 'idle'. NOTIMPLEMENTED(); } ProcessManager* process_manager = ProcessManager::Get(context); for (std::vector<std::string>::const_iterator i = ids_to_check.begin(); i != ids_to_check.end(); i++) { const std::string id = (*i); ExtensionHost* host = process_manager->GetBackgroundHostForExtension(id); if (host) return false; scoped_refptr<content::SiteInstance> site_instance = process_manager->GetSiteInstanceForURL( Extension::GetBaseURLFromExtensionId(id)); if (site_instance && site_instance->HasProcess()) return false; if (!process_manager->GetRenderFrameHostsForExtension(id).empty()) return false; } return true; } GURL GetSiteForExtensionId(const std::string& extension_id, content::BrowserContext* context) { return content::SiteInstance::GetSiteForURL( context, Extension::GetBaseURLFromExtensionId(extension_id)); } std::unique_ptr<base::DictionaryValue> GetExtensionInfo( const Extension* extension) { DCHECK(extension); std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); dict->SetString("id", extension->id()); dict->SetString("name", extension->name()); // TODO(bridiver) // GURL icon = extensions::ExtensionIconSource::GetIconURL( // extension, // extension_misc::EXTENSION_ICON_SMALLISH, // ExtensionIconSet::MATCH_BIGGER, // false, // Not grayscale. // NULL); // Don't set bool if exists. // dict->SetString("icon", icon.spec()); return dict; } const gfx::ImageSkia& GetDefaultAppIcon() { return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_APP_DEFAULT_ICON); } const gfx::ImageSkia& GetDefaultExtensionIcon() { return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_EXTENSION_DEFAULT_ICON); } bool IsNewBookmarkAppsEnabled() { #if defined(OS_MACOSX) return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNewBookmarkApps); #else return !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableNewBookmarkApps); #endif } bool CanHostedAppsOpenInWindows() { #if defined(OS_MACOSX) return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableHostedAppsInWindows); #else return true; #endif } bool IsExtensionSupervised(const Extension* extension, Profile* profile) { NOTIMPLEMENTED(); return false; } bool NeedCustodianApprovalForPermissionIncrease(const Profile* profile) { NOTIMPLEMENTED(); return false; } } // namespace util } // namespace extensions <commit_msg>Update extension_util.cc to remove kEnableNewBookmarkApps<commit_after>// Copyright 2013 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 "chrome/browser/extensions/extension_util.h" #include "base/command_line.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/sync_helper.h" #include "components/variations/variations_associated_data.h" #include "content/public/browser/site_instance.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_util.h" #include "extensions/browser/process_manager.h" #include "extensions/common/extension.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/features/behavior_feature.h" #include "extensions/common/features/feature.h" #include "extensions/common/features/feature_provider.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_handlers/app_isolation_info.h" #include "extensions/common/manifest_handlers/incognito_info.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/grit/extensions_browser_resources.h" #include "ui/base/resource/resource_bundle.h" namespace extensions { namespace util { namespace { const char kSupervisedUserExtensionPermissionIncreaseFieldTrialName[] = "SupervisedUserExtensionPermissionIncrease"; // The entry into the prefs used to flag an extension as installed by custodian. // It is relevant only for supervised users. const char kWasInstalledByCustodianPrefName[] = "was_installed_by_custodian"; // Returns true if |extension| should always be enabled in incognito mode. bool IsWhitelistedForIncognito(const Extension* extension) { const Feature* feature = FeatureProvider::GetBehaviorFeature( behavior_feature::kWhitelistedForIncognito); return feature && feature->IsAvailableToExtension(extension).is_available(); } } // namespace bool IsIncognitoEnabled(const std::string& extension_id, content::BrowserContext* context) { const Extension* extension = ExtensionRegistry::Get(context)-> GetExtensionById(extension_id, ExtensionRegistry::ENABLED); if (extension) { if (!util::CanBeIncognitoEnabled(extension)) return false; // If this is an existing component extension we always allow it to // work in incognito mode. if (extension->location() == Manifest::COMPONENT || extension->location() == Manifest::EXTERNAL_COMPONENT) { return true; } if (IsWhitelistedForIncognito(extension)) return true; } return ExtensionPrefs::Get(context)->IsIncognitoEnabled(extension_id); } void SetIsIncognitoEnabled(const std::string& extension_id, content::BrowserContext* context, bool enabled) { NOTIMPLEMENTED(); } bool CanCrossIncognito(const Extension* extension, content::BrowserContext* context) { // We allow the extension to see events and data from another profile iff it // uses "spanning" behavior and it has incognito access. "split" mode // extensions only see events for a matching profile. CHECK(extension); return IsIncognitoEnabled(extension->id(), context) && !IncognitoInfo::IsSplitMode(extension); } bool CanLoadInIncognito(const Extension* extension, content::BrowserContext* context) { CHECK(extension); if (extension->is_hosted_app()) return true; // Packaged apps and regular extensions need to be enabled specifically for // incognito (and split mode should be set). return IncognitoInfo::IsSplitMode(extension) && IsIncognitoEnabled(extension->id(), context); } bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableExtensionsFileAccessCheck) || ExtensionPrefs::Get(context)->AllowFileAccess(extension_id); } void SetAllowFileAccess(const std::string& extension_id, content::BrowserContext* context, bool allow) { NOTIMPLEMENTED(); } void SetWasInstalledByCustodian(const std::string& extension_id, content::BrowserContext* context, bool installed_by_custodian) { NOTIMPLEMENTED(); } bool WasInstalledByCustodian(const std::string& extension_id, content::BrowserContext* context) { bool installed_by_custodian = false; ExtensionPrefs* prefs = ExtensionPrefs::Get(context); prefs->ReadPrefAsBoolean(extension_id, kWasInstalledByCustodianPrefName, &installed_by_custodian); return installed_by_custodian; } bool IsAppLaunchable(const std::string& extension_id, content::BrowserContext* context) { int reason = ExtensionPrefs::Get(context)->GetDisableReasons(extension_id); return !((reason & Extension::DISABLE_UNSUPPORTED_REQUIREMENT) || (reason & Extension::DISABLE_CORRUPTED)); } bool IsAppLaunchableWithoutEnabling(const std::string& extension_id, content::BrowserContext* context) { return ExtensionRegistry::Get(context)->GetExtensionById( extension_id, ExtensionRegistry::ENABLED) != NULL; } bool ShouldSync(const Extension* extension, content::BrowserContext* context) { return sync_helper::IsSyncable(extension) && !ExtensionPrefs::Get(context)->DoNotSync(extension->id()); } bool IsExtensionIdle(const std::string& extension_id, content::BrowserContext* context) { std::vector<std::string> ids_to_check; ids_to_check.push_back(extension_id); const Extension* extension = ExtensionRegistry::Get(context) ->GetExtensionById(extension_id, ExtensionRegistry::ENABLED); if (extension && extension->is_shared_module()) { // We have to check all the extensions that use this shared module for idle // to tell whether it is really 'idle'. NOTIMPLEMENTED(); } ProcessManager* process_manager = ProcessManager::Get(context); for (std::vector<std::string>::const_iterator i = ids_to_check.begin(); i != ids_to_check.end(); i++) { const std::string id = (*i); ExtensionHost* host = process_manager->GetBackgroundHostForExtension(id); if (host) return false; scoped_refptr<content::SiteInstance> site_instance = process_manager->GetSiteInstanceForURL( Extension::GetBaseURLFromExtensionId(id)); if (site_instance && site_instance->HasProcess()) return false; if (!process_manager->GetRenderFrameHostsForExtension(id).empty()) return false; } return true; } GURL GetSiteForExtensionId(const std::string& extension_id, content::BrowserContext* context) { return content::SiteInstance::GetSiteForURL( context, Extension::GetBaseURLFromExtensionId(extension_id)); } std::unique_ptr<base::DictionaryValue> GetExtensionInfo( const Extension* extension) { DCHECK(extension); std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); dict->SetString("id", extension->id()); dict->SetString("name", extension->name()); // TODO(bridiver) // GURL icon = extensions::ExtensionIconSource::GetIconURL( // extension, // extension_misc::EXTENSION_ICON_SMALLISH, // ExtensionIconSet::MATCH_BIGGER, // false, // Not grayscale. // NULL); // Don't set bool if exists. // dict->SetString("icon", icon.spec()); return dict; } const gfx::ImageSkia& GetDefaultAppIcon() { return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_APP_DEFAULT_ICON); } const gfx::ImageSkia& GetDefaultExtensionIcon() { return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_EXTENSION_DEFAULT_ICON); } bool IsNewBookmarkAppsEnabled() { #if defined(OS_MACOSX) return base::FeatureList::IsEnabled(features::kBookmarkApps); #else return true; #endif } bool CanHostedAppsOpenInWindows() { #if defined(OS_MACOSX) return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableHostedAppsInWindows); #else return true; #endif } bool IsExtensionSupervised(const Extension* extension, Profile* profile) { NOTIMPLEMENTED(); return false; } bool NeedCustodianApprovalForPermissionIncrease(const Profile* profile) { NOTIMPLEMENTED(); return false; } } // namespace util } // namespace extensions <|endoftext|>
<commit_before>/* * Copyright (c) 2012 by Matthias Noack, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include <gtest/gtest.h> #include "common/test_environment.h" #include "common/test_rpc_server_dir.h" #include "common/test_rpc_server_mrc.h" #include "common/test_rpc_server_osd.h" #include "../generated/xtreemfs/OSDServiceConstants.h" #include "libxtreemfs/client.h" #include "libxtreemfs/file_handle.h" #include "libxtreemfs/options.h" #include "libxtreemfs/volume.h" #include "libxtreemfs/xtreemfs_exception.h" #include "rpc/client.h" #include <vector> #include <algorithm> using namespace std; using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { namespace rpc { class AsyncWriteHandlerTest : public ::testing::Test { protected: enum { BLOCK_SIZE = 1024 * 128 }; virtual void SetUp() { initialize_logger(LEVEL_DEBUG); test_env.options.connect_timeout_s = 15; test_env.options.request_timeout_s = 5; test_env.options.retry_delay_s = 5; test_env.options.max_writeahead = 1024 * 128 * 8; test_env.options.max_writeahead_requests = 8; test_env.options.periodic_xcap_renewal_interval_s = 2; test_env.Start(); // Open a volume volume = test_env.client->OpenVolume( test_env.volume_name_, NULL, // No SSL options. test_env.options); // Open a file. file = volume->OpenFile( test_env.user_credentials, "/test_file", static_cast<xtreemfs::pbrpc::SYSTEM_V_FCNTL>( xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_CREAT | xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_TRUNC | xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_RDWR)); } virtual void TearDown() { //volume->Close(); test_env.Stop(); } TestEnvironment test_env; Volume* volume; FileHandle* file; }; /** A normal async write with nothing special */ TEST_F(AsyncWriteHandlerTest, NormalWrite) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected(blocks); for(int i = 0; i < blocks; ++i) expected[i] = WriteEntry(i, 0, BLOCK_SIZE); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( 2 * test_env.options.request_timeout_s)); EXPECT_TRUE(equal(expected.begin(), expected.end(), test_env.osds[0]->GetReceivedWrites().end() - blocks)); ASSERT_NO_THROW(file->Close()); } /** Let the first write request fail */ TEST_F(AsyncWriteHandlerTest, FirstWriteFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_tail(blocks); for (int i = 0; i < blocks; ++i) expected_tail[i] = WriteEntry(i, 0, BLOCK_SIZE); test_env.osds[0]->AddDropRule(new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new DropNRule(1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the last write request fail */ TEST_F(AsyncWriteHandlerTest, LastWriteFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_front(blocks-1); vector<WriteEntry> expected_tail(1); for (int i = 0; i < blocks-1; ++i) expected_front[i] = WriteEntry(i, 0, BLOCK_SIZE); expected_tail[0] = WriteEntry(blocks-1, 0, BLOCK_SIZE); test_env.osds[0]->AddDropRule(new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new SkipMDropNRule(blocks-1, 1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_front.begin(), expected_front.end(), test_env.osds[0]->GetReceivedWrites().begin())); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the intermediate write request fail */ TEST_F(AsyncWriteHandlerTest, IntermediateWriteFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; size_t middle = blocks / 2; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_front(middle); vector<WriteEntry> expected_tail(blocks - middle); for (int i = 0; i < middle; ++i) expected_front[i] = WriteEntry(i, 0, BLOCK_SIZE); for (int i = middle; i < blocks; ++i) expected_tail[i - middle] = WriteEntry(i, 0, BLOCK_SIZE); test_env.osds[0]->AddDropRule(new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new SkipMDropNRule(middle, 1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_front.begin(), expected_front.end(), test_env.osds[0]->GetReceivedWrites().begin())); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the all writes request fail */ TEST_F(AsyncWriteHandlerTest, AllWritesFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_tail(blocks); for (int i = 0; i < blocks; ++i) expected_tail[i] = WriteEntry(i, 0, BLOCK_SIZE); test_env.osds[0]->AddDropRule(new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new DropNRule(5))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the first write request fail when there are more writes than * writeahead allows */ TEST_F(AsyncWriteHandlerTest, FirstWriteFailLong) { size_t blocks = 2* test_env.options.max_writeahead_requests; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_tail(blocks); for (int i = 0; i < blocks; ++i) expected_tail[i] = WriteEntry(i, 0, BLOCK_SIZE); test_env.osds[0]->AddDropRule(new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new DropNRule(1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** TODO: Maybe check for additional overlapping cases, b * the current implementation of does NOT check for overlap, * but the sequence of retries should match expectations */ /** Let all future requests fail to test the retry count. */ } // namespace rpc } // namespace xtreemfs <commit_msg>client: Modified async_write_handler_test.cpp according to the review for r3056.<commit_after>/* * Copyright (c) 2012 by Matthias Noack, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include <gtest/gtest.h> #include <algorithm> #include <vector> #include "common/test_environment.h" #include "common/test_rpc_server_dir.h" #include "common/test_rpc_server_mrc.h" #include "common/test_rpc_server_osd.h" #include "xtreemfs/OSDServiceConstants.h" #include "libxtreemfs/client.h" #include "libxtreemfs/file_handle.h" #include "libxtreemfs/options.h" #include "libxtreemfs/volume.h" #include "libxtreemfs/xtreemfs_exception.h" #include "rpc/client.h" using namespace std; using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { namespace rpc { class AsyncWriteHandlerTest : public ::testing::Test { protected: enum { BLOCK_SIZE = 1024 * 128 }; virtual void SetUp() { initialize_logger(LEVEL_DEBUG); test_env.options.connect_timeout_s = 15; test_env.options.request_timeout_s = 5; test_env.options.retry_delay_s = 5; test_env.options.max_writeahead = 1024 * 128 * 8; test_env.options.max_writeahead_requests = 8; test_env.options.periodic_xcap_renewal_interval_s = 2; test_env.Start(); // Open a volume volume = test_env.client->OpenVolume( test_env.volume_name_, NULL, // No SSL options. test_env.options); // Open a file. file = volume->OpenFile( test_env.user_credentials, "/test_file", static_cast<xtreemfs::pbrpc::SYSTEM_V_FCNTL>( xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_CREAT | xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_TRUNC | xtreemfs::pbrpc::SYSTEM_V_FCNTL_H_O_RDWR)); } virtual void TearDown() { //volume->Close(); test_env.Stop(); } TestEnvironment test_env; Volume* volume; FileHandle* file; }; /** A normal async write with nothing special */ TEST_F(AsyncWriteHandlerTest, NormalWrite) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected(blocks); for (int i = 0; i < blocks; ++i) { expected[i] = WriteEntry(i, 0, BLOCK_SIZE); } file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( 2 * test_env.options.request_timeout_s)); EXPECT_TRUE(equal(expected.begin(), expected.end(), test_env.osds[0]->GetReceivedWrites().end() - blocks)); ASSERT_NO_THROW(file->Close()); } /** Let the first write request fail. The write should be retried and finally * succeed. */ TEST_F(AsyncWriteHandlerTest, FirstWriteFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_tail(blocks); for (int i = 0; i < blocks; ++i) { expected_tail[i] = WriteEntry(i, 0, BLOCK_SIZE); } test_env.osds[0]->AddDropRule( new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new DropNRule(1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the last write request fail. The write should be retried and finally * succeed. */ TEST_F(AsyncWriteHandlerTest, LastWriteFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_front(blocks - 1); vector<WriteEntry> expected_tail(1); for (int i = 0; i < blocks - 1; ++i) { expected_front[i] = WriteEntry(i, 0, BLOCK_SIZE); } expected_tail[0] = WriteEntry(blocks - 1, 0, BLOCK_SIZE); test_env.osds[0]->AddDropRule( new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new SkipMDropNRule(blocks - 1, 1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_front.begin(), expected_front.end(), test_env.osds[0]->GetReceivedWrites().begin())); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the intermediate write request fail. The write should be retried and * finally succeed. */ TEST_F(AsyncWriteHandlerTest, IntermediateWriteFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; size_t middle = blocks / 2; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_front(middle); vector<WriteEntry> expected_tail(blocks - middle); for (int i = 0; i < middle; ++i) { expected_front[i] = WriteEntry(i, 0, BLOCK_SIZE); } for (int i = middle; i < blocks; ++i) { expected_tail[i - middle] = WriteEntry(i, 0, BLOCK_SIZE); } test_env.osds[0]->AddDropRule( new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new SkipMDropNRule(middle, 1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_front.begin(), expected_front.end(), test_env.osds[0]->GetReceivedWrites().begin())); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the all writes request fail. The write should be retried and finally * succeed. */ TEST_F(AsyncWriteHandlerTest, AllWritesFail) { size_t blocks = 5; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_tail(blocks); for (int i = 0; i < blocks; ++i) { expected_tail[i] = WriteEntry(i, 0, BLOCK_SIZE); } test_env.osds[0]->AddDropRule( new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new DropNRule(blocks))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** Let the first write request fail when there are more writes than * writeahead allows. The write should be retried and finally succeed. */ TEST_F(AsyncWriteHandlerTest, FirstWriteFailLong) { size_t blocks = 2 * test_env.options.max_writeahead_requests; size_t buffer_size = BLOCK_SIZE * blocks; boost::scoped_array<char> write_buf(new char[buffer_size]); vector<WriteEntry> expected_tail(blocks); for (int i = 0; i < blocks; ++i) { expected_tail[i] = WriteEntry(i, 0, BLOCK_SIZE); } test_env.osds[0]->AddDropRule( new ProcIDFilterRule(xtreemfs::pbrpc::PROC_ID_WRITE, new DropNRule(1))); file->Write(test_env.user_credentials, write_buf.get(), buffer_size, 0); boost::this_thread::sleep(boost::posix_time::seconds( test_env.options.connect_timeout_s + 2 * test_env.options.request_timeout_s + 2 * test_env.options.retry_delay_s)); EXPECT_TRUE(equal(expected_tail.begin(), expected_tail.end(), test_env.osds[0]->GetReceivedWrites().end() - expected_tail.size())); ASSERT_NO_THROW(file->Close()); } /** TODO(mno): Maybe let all future requests fail to test the retry count. */ } // namespace rpc } // namespace xtreemfs <|endoftext|>
<commit_before>/* Copyright (C) 2000 by W.C.A. Wijngaards Copyright (C) 2000 by Andrew Zabolotny This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #define CS_SYSDEF_PROVIDE_GETOPT #include "cssysdef.h" #include "cstool/initapp.h" #include "csutil/util.h" #include "ivideo/fontserv.h" #include "iutil/objreg.h" #include "iutil/eventh.h" #include "iutil/comp.h" #include "iutil/plugin.h" #include "iutil/vfs.h" CS_IMPLEMENT_APPLICATION static iObjectRegistry* object_reg; char *programversion = "0.0.1"; char *programname; static struct option long_options[] = { {"first", required_argument, 0, 'f'}, {"glyphs", required_argument, 0, 'g'}, {"size", required_argument, 0, 's'}, {"output", required_argument, 0, 'o'}, {"text", no_argument, 0, 't'}, {"display", no_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {0, no_argument, 0, 0} }; static struct { bool verbose; bool sourcecode; bool display; int fontsize; int first; int glyphs; char *output; } opt = { false, false, false, -1, 0, 256, NULL }; static int lastglyph; static int display_help () { printf ("Crystal Space font conversion/generation utility v%s\n", programversion); printf ("Copyright (C) 2000 by W.C.A. Wijngaards and Andrew Zabolotny\n\n"); printf ("Usage: %s {option/s} [truetype font file] [...]\n\n", programname); printf ("This program allows to convert TTF font files to bitmap format CSF\n"); printf ("which is faster to load although it is non-scalable. By default the\n"); printf ("program will convert all the fonts given on command line to CSF.\n\n"); printf (" -d --display Display font rather than converting it\n"); printf (" -f# --first=# Start conversion at glyph # (default = 0)\n"); printf (" -g# --glyphs=# Convert just # (default = 256) glyphs of the font\n"); printf (" -s# --size=# Set font size # in points\n"); printf (" -o# --output=# Output CSF font to file #\n"); printf (" -t --text Generate text output (C++ code) rather than binary\n"); printf (" -h --help Display this help text\n"); printf (" -v --verbose Comment on what's happening\n"); printf (" -V --version Display program version\n"); return 1; } static bool Display (iFontServer *fs, iFont *font) { int c, l, i; for (c = opt.first; c < lastglyph; c++) { int w, h; uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (!bitmap || !w || !h) continue; printf ("---- Character:%d\n", c); for (l = 0; l < h; l++) { uint8 *line = bitmap + l * ((w + 7) / 8); for (i = 0; i < w; i++) printf ("%s", (line [i / 8] & (0x80 >> (i & 7))) ? "@" : "."); printf ("\n"); } } font->DecRef (); fs->DecRef (); return true; } static bool Convert (const char *fontfile) { if (opt.verbose) printf ("Loading font %s, size = %d\n", fontfile, opt.fontsize); csRef<iFontServer> fs = CS_QUERY_REGISTRY (object_reg, iFontServer); if (!fs) { printf ("Font server plugin has not been loaded.\n"); return false; } csRef<iFont> font = fs->LoadFont (fontfile); if (font == NULL) { printf ("Cannot load font file %s\n", fontfile); return false; } if (opt.fontsize > 0) { font->SetSize (opt.fontsize); int oldsize = opt.fontsize; opt.fontsize = font->GetSize (); if (opt.fontsize != oldsize) printf ("Could not set font size %d, using size %d\n", oldsize, opt.fontsize); } else opt.fontsize = font->GetSize (); // max height of font int maxheight, maxwidth; font->GetMaxSize (maxwidth, maxheight); if (maxwidth > 255) { fprintf (stderr, "Font too large (%dx%d): CSF format supports only widths < 256\n", maxwidth, maxheight); return false; } if (opt.display) return Display (fs, font); char fontname [CS_MAXPATHLEN + 1]; char outfile [CS_MAXPATHLEN + 1]; csSplitPath (fontfile, NULL, 0, fontname, sizeof (fontname)); if (fontname [0] == '*') strcpy (fontname, fontname + 1); char *dot = strchr (fontname, '.'); if (dot) *dot = 0; sprintf (outfile, "%s%d.%s", fontname, opt.fontsize, opt.sourcecode ? "inc" : "csf"); FILE *out = fopen (outfile, opt.sourcecode ? "w" : "wb"); if (!out) { printf ("Could not open output file %s\n", outfile); return false; } int i, c, w, h; if (opt.sourcecode) { /// make a text version fprintf (out, "// %s.%d %dx%d font\n", fontname, opt.fontsize, maxwidth, maxheight); fprintf (out, "// FontDef: { \"%s%d\", %d, %d, %d, %d, font_%s%d, width_%s%d }\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs, fontname, opt.fontsize, fontname, opt.fontsize); fprintf (out, "\n"); } else fprintf (out, "CSF [Font=%s.%d Width=%d Height=%d First=%d Glyphs=%d]\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs); int arrsize = 0; uint8 width [256]; for (c = opt.first; c < lastglyph; c++) { uint8 *bitmap = font->GetGlyphBitmap (c, w, h); width [c] = (bitmap && h) ? w : 0; arrsize += ((width [c] + 7) / 8) * h; } // Character widths go first if (opt.sourcecode) { fprintf (out, "unsigned char width_%s%d [%d] =\n{\n ", fontname, opt.fontsize, opt.glyphs); for (i = opt.first; i < lastglyph; i++) { fprintf (out, "%2d%s", width [i], (i < lastglyph - 1) ? "," : ""); if ((i & 15) == 15) { fprintf (out, "\t// %02x..%02x\n", i - 15, i); if (i < lastglyph - 1) fprintf (out, " "); } } if (opt.glyphs & 15) fprintf (out, "\n"); fprintf (out, "};\n\n"); fprintf (out, "unsigned char font_%s%d [%d] =\n{\n", fontname, opt.fontsize, arrsize); } else fwrite (width + opt.first, opt.glyphs, 1, out); // Output every character in turn for (c = opt.first; c < lastglyph; c++) { // get bitmap uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (opt.verbose) { if (!c) printf ("character "); printf ("%d%s", c, (c < lastglyph - 1) ? "," : "\n"); } int bpc = ((width [c] + 7) / 8) * h; if (bitmap) if (opt.sourcecode) { fprintf (out, " "); for (i = 0; i < bpc; i++) fprintf (out, "0x%02x%s", bitmap [i], (i >= bpc - 1) && (c >= lastglyph - 1) ? "" : ","); fprintf (out, "\t// %02x\n", c); } else if (width [c]) fwrite (bitmap, bpc, 1, out); } fprintf (out, "};\n\n"); fclose (out); font->DecRef (); fs->DecRef (); return true; } int main (int argc, char* argv[]) { #if defined (__EMX__) // Expand wildcards on OS/2+GCC+EMX _wildcard (&argc, &argv); #endif object_reg = csInitializer::CreateEnvironment (argc, argv); if (!object_reg) return -1; if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_VFS, CS_REQUEST_PLUGIN ("crystalspace.font.server.freetype2", iFontServer), CS_REQUEST_END)) { fprintf (stderr, "couldn't init app! (perhaps some plugins are missing?)"); return -1; } programname = argv [0]; int c; while ((c = getopt_long (argc, argv, "f:g:s:o:tdhvV", long_options, NULL)) != EOF) switch (c) { case '?': // unknown option return -1; case 'f': opt.first = atoi (optarg); if ((opt.first < 0) || (opt.first > 255)) { fprintf (stderr, "ERROR: first glyph should be 0..255\n"); return -2; } break; case 'g': opt.glyphs = atoi (optarg); if ((opt.glyphs < 1) || (opt.glyphs > 256)) { fprintf (stderr, "ERROR: glyph count should be 1..256\n"); return -2; } break; case 's': opt.fontsize = atoi (optarg); if ((opt.fontsize < 1) || (opt.fontsize > 1000)) { fprintf (stderr, "ERROR: font size should be 1..1000\n"); return -2; } break; case 'o': opt.output = optarg; break; case 't': opt.sourcecode = true; break; case 'd': opt.display = true; break; case 'h': return display_help (); case 'v': opt.verbose = true; break; case 'V': printf ("%s version %s\n\n", programname, programversion); printf ("This program is distributed in the hope that it will be useful,\n"); printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf ("GNU Library General Public License for more details.\n"); return 0; } /* endswitch */ if (optind >= argc) return display_help (); lastglyph = opt.first + opt.glyphs; if (lastglyph > 256) { fprintf (stderr, "WARNING: Last glyph = %d, limiting to 256\n", lastglyph); lastglyph = 256; opt.glyphs = 256 - opt.first; } // Interpret the non-option arguments as file names for (; optind < argc; ++optind) if (!Convert (argv [optind])) return -2; csInitializer::DestroyApplication (object_reg); return 0; } <commit_msg>Another DecRef() too many.<commit_after>/* Copyright (C) 2000 by W.C.A. Wijngaards Copyright (C) 2000 by Andrew Zabolotny This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #define CS_SYSDEF_PROVIDE_GETOPT #include "cssysdef.h" #include "cstool/initapp.h" #include "csutil/util.h" #include "ivideo/fontserv.h" #include "iutil/objreg.h" #include "iutil/eventh.h" #include "iutil/comp.h" #include "iutil/plugin.h" #include "iutil/vfs.h" CS_IMPLEMENT_APPLICATION static iObjectRegistry* object_reg; char *programversion = "0.0.1"; char *programname; static struct option long_options[] = { {"first", required_argument, 0, 'f'}, {"glyphs", required_argument, 0, 'g'}, {"size", required_argument, 0, 's'}, {"output", required_argument, 0, 'o'}, {"text", no_argument, 0, 't'}, {"display", no_argument, 0, 'd'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {0, no_argument, 0, 0} }; static struct { bool verbose; bool sourcecode; bool display; int fontsize; int first; int glyphs; char *output; } opt = { false, false, false, -1, 0, 256, NULL }; static int lastglyph; static int display_help () { printf ("Crystal Space font conversion/generation utility v%s\n", programversion); printf ("Copyright (C) 2000 by W.C.A. Wijngaards and Andrew Zabolotny\n\n"); printf ("Usage: %s {option/s} [truetype font file] [...]\n\n", programname); printf ("This program allows to convert TTF font files to bitmap format CSF\n"); printf ("which is faster to load although it is non-scalable. By default the\n"); printf ("program will convert all the fonts given on command line to CSF.\n\n"); printf (" -d --display Display font rather than converting it\n"); printf (" -f# --first=# Start conversion at glyph # (default = 0)\n"); printf (" -g# --glyphs=# Convert just # (default = 256) glyphs of the font\n"); printf (" -s# --size=# Set font size # in points\n"); printf (" -o# --output=# Output CSF font to file #\n"); printf (" -t --text Generate text output (C++ code) rather than binary\n"); printf (" -h --help Display this help text\n"); printf (" -v --verbose Comment on what's happening\n"); printf (" -V --version Display program version\n"); return 1; } static bool Display (iFontServer *fs, iFont *font) { int c, l, i; for (c = opt.first; c < lastglyph; c++) { int w, h; uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (!bitmap || !w || !h) continue; printf ("---- Character:%d\n", c); for (l = 0; l < h; l++) { uint8 *line = bitmap + l * ((w + 7) / 8); for (i = 0; i < w; i++) printf ("%s", (line [i / 8] & (0x80 >> (i & 7))) ? "@" : "."); printf ("\n"); } } font->DecRef (); fs->DecRef (); return true; } static bool Convert (const char *fontfile) { if (opt.verbose) printf ("Loading font %s, size = %d\n", fontfile, opt.fontsize); csRef<iFontServer> fs = CS_QUERY_REGISTRY (object_reg, iFontServer); if (!fs) { printf ("Font server plugin has not been loaded.\n"); return false; } csRef<iFont> font = fs->LoadFont (fontfile); if (font == NULL) { printf ("Cannot load font file %s\n", fontfile); return false; } if (opt.fontsize > 0) { font->SetSize (opt.fontsize); int oldsize = opt.fontsize; opt.fontsize = font->GetSize (); if (opt.fontsize != oldsize) printf ("Could not set font size %d, using size %d\n", oldsize, opt.fontsize); } else opt.fontsize = font->GetSize (); // max height of font int maxheight, maxwidth; font->GetMaxSize (maxwidth, maxheight); if (maxwidth > 255) { fprintf (stderr, "Font too large (%dx%d): CSF format supports only widths < 256\n", maxwidth, maxheight); return false; } if (opt.display) return Display (fs, font); char fontname [CS_MAXPATHLEN + 1]; char outfile [CS_MAXPATHLEN + 1]; csSplitPath (fontfile, NULL, 0, fontname, sizeof (fontname)); if (fontname [0] == '*') strcpy (fontname, fontname + 1); char *dot = strchr (fontname, '.'); if (dot) *dot = 0; sprintf (outfile, "%s%d.%s", fontname, opt.fontsize, opt.sourcecode ? "inc" : "csf"); FILE *out = fopen (outfile, opt.sourcecode ? "w" : "wb"); if (!out) { printf ("Could not open output file %s\n", outfile); return false; } int i, c, w, h; if (opt.sourcecode) { /// make a text version fprintf (out, "// %s.%d %dx%d font\n", fontname, opt.fontsize, maxwidth, maxheight); fprintf (out, "// FontDef: { \"%s%d\", %d, %d, %d, %d, font_%s%d, width_%s%d }\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs, fontname, opt.fontsize, fontname, opt.fontsize); fprintf (out, "\n"); } else fprintf (out, "CSF [Font=%s.%d Width=%d Height=%d First=%d Glyphs=%d]\n", fontname, opt.fontsize, maxwidth, maxheight, opt.first, opt.glyphs); int arrsize = 0; uint8 width [256]; for (c = opt.first; c < lastglyph; c++) { uint8 *bitmap = font->GetGlyphBitmap (c, w, h); width [c] = (bitmap && h) ? w : 0; arrsize += ((width [c] + 7) / 8) * h; } // Character widths go first if (opt.sourcecode) { fprintf (out, "unsigned char width_%s%d [%d] =\n{\n ", fontname, opt.fontsize, opt.glyphs); for (i = opt.first; i < lastglyph; i++) { fprintf (out, "%2d%s", width [i], (i < lastglyph - 1) ? "," : ""); if ((i & 15) == 15) { fprintf (out, "\t// %02x..%02x\n", i - 15, i); if (i < lastglyph - 1) fprintf (out, " "); } } if (opt.glyphs & 15) fprintf (out, "\n"); fprintf (out, "};\n\n"); fprintf (out, "unsigned char font_%s%d [%d] =\n{\n", fontname, opt.fontsize, arrsize); } else fwrite (width + opt.first, opt.glyphs, 1, out); // Output every character in turn for (c = opt.first; c < lastglyph; c++) { // get bitmap uint8 *bitmap = font->GetGlyphBitmap (c, w, h); if (opt.verbose) { if (!c) printf ("character "); printf ("%d%s", c, (c < lastglyph - 1) ? "," : "\n"); } int bpc = ((width [c] + 7) / 8) * h; if (bitmap) if (opt.sourcecode) { fprintf (out, " "); for (i = 0; i < bpc; i++) fprintf (out, "0x%02x%s", bitmap [i], (i >= bpc - 1) && (c >= lastglyph - 1) ? "" : ","); fprintf (out, "\t// %02x\n", c); } else if (width [c]) fwrite (bitmap, bpc, 1, out); } fprintf (out, "};\n\n"); fclose (out); return true; } int main (int argc, char* argv[]) { #if defined (__EMX__) // Expand wildcards on OS/2+GCC+EMX _wildcard (&argc, &argv); #endif object_reg = csInitializer::CreateEnvironment (argc, argv); if (!object_reg) return -1; if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_VFS, CS_REQUEST_PLUGIN ("crystalspace.font.server.freetype2", iFontServer), CS_REQUEST_END)) { fprintf (stderr, "couldn't init app! (perhaps some plugins are missing?)"); return -1; } programname = argv [0]; int c; while ((c = getopt_long (argc, argv, "f:g:s:o:tdhvV", long_options, NULL)) != EOF) switch (c) { case '?': // unknown option return -1; case 'f': opt.first = atoi (optarg); if ((opt.first < 0) || (opt.first > 255)) { fprintf (stderr, "ERROR: first glyph should be 0..255\n"); return -2; } break; case 'g': opt.glyphs = atoi (optarg); if ((opt.glyphs < 1) || (opt.glyphs > 256)) { fprintf (stderr, "ERROR: glyph count should be 1..256\n"); return -2; } break; case 's': opt.fontsize = atoi (optarg); if ((opt.fontsize < 1) || (opt.fontsize > 1000)) { fprintf (stderr, "ERROR: font size should be 1..1000\n"); return -2; } break; case 'o': opt.output = optarg; break; case 't': opt.sourcecode = true; break; case 'd': opt.display = true; break; case 'h': return display_help (); case 'v': opt.verbose = true; break; case 'V': printf ("%s version %s\n\n", programname, programversion); printf ("This program is distributed in the hope that it will be useful,\n"); printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf ("GNU Library General Public License for more details.\n"); return 0; } /* endswitch */ if (optind >= argc) return display_help (); lastglyph = opt.first + opt.glyphs; if (lastglyph > 256) { fprintf (stderr, "WARNING: Last glyph = %d, limiting to 256\n", lastglyph); lastglyph = 256; opt.glyphs = 256 - opt.first; } // Interpret the non-option arguments as file names for (; optind < argc; ++optind) if (!Convert (argv [optind])) return -2; csInitializer::DestroyApplication (object_reg); return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "MoveShard.h" #include "Agent.h" #include "Job.h" using namespace arangodb::consensus; MoveShard::MoveShard (Node const& snapshot, Agent* agent, std::string const& jobId, std::string const& creator, std::string const& prefix, std::string const& database, std::string const& collection, std::string const& shard, std::string const& from, std::string const& to) : Job(snapshot, agent, jobId, creator, prefix), _database(database), _collection(collection), _shard(shard), _from(from), _to(to) { JOB_STATUS js = status(); try { if (js == TODO) { start(); } else if (js == NOTFOUND) { if (create()) { start(); } } } catch (std::exception const& e) { LOG_TOPIC(WARN, Logger::AGENCY) << e.what() << __FILE__ << __LINE__; finish("Shards/" + _shard, false, e.what()); } } MoveShard::~MoveShard () {} bool MoveShard::create () { LOG_TOPIC(INFO, Logger::AGENCY) << "Todo: Move shard " + _shard + " from " + _from + " to " << _to; std::string path, now(timepointToString(std::chrono::system_clock::now())); // DBservers std::string planPath = planColPrefix + _database + "/" + _collection + "/shards/" + _shard; std::string curPath = curColPrefix + _database + "/" + _collection + "/" + _shard + "/servers"; Slice current = _snapshot(curPath).slice(); TRI_ASSERT(current.isArray()); TRI_ASSERT(current[0].isString()); _jb = std::make_shared<Builder>(); _jb->openArray(); _jb->openObject(); if (_from == _to) { path = _agencyPrefix + failedPrefix + _jobId; _jb->add("timeFinished", VPackValue(now)); _jb->add("result", VPackValue("Source and destination of moveShard must be different")); } else { path = _agencyPrefix + toDoPrefix + _jobId; } _jb->add(path, VPackValue(VPackValueType::Object)); _jb->add("creator", VPackValue(_creator)); _jb->add("type", VPackValue("moveShard")); _jb->add("database", VPackValue(_database)); _jb->add("collection", VPackValue(_collection)); _jb->add("shard", VPackValue(_shard)); _jb->add("fromServer", VPackValue(_from)); _jb->add("toServer", VPackValue(_to)); _jb->add("isLeader", VPackValue(current[0].copyString() == _from)); _jb->add("jobId", VPackValue(_jobId)); _jb->add("timeCreated", VPackValue(now)); _jb->close(); _jb->close(); _jb->close(); write_ret_t res = transact(_agent, *_jb); if (res.accepted && res.indices.size()==1 && res.indices[0]) { return true; } LOG_TOPIC(INFO, Logger::AGENCY) << "Failed to insert job " + _jobId; return false; } bool MoveShard::start() { // DBservers std::string planPath = planColPrefix + _database + "/" + _collection + "/shards/" + _shard; std::string curPath = curColPrefix + _database + "/" + _collection + "/" + _shard + "/servers"; Slice current = _snapshot(curPath).slice(); // Copy todo to pending Builder todo, pending; // Get todo entry todo.openArray(); if (_jb == nullptr) { try { _snapshot(toDoPrefix + _jobId).toBuilder(todo); } catch (std::exception const&) { LOG_TOPIC(INFO, Logger::AGENCY) << "Failed to get key " + toDoPrefix + _jobId + " from agency snapshot"; return false; } } else { todo.add(_jb->slice()[0].valueAt(0)); } todo.close(); // Enter pending, remove todo, block toserver pending.openArray(); // --- Add pending pending.openObject(); pending.add(_agencyPrefix + pendingPrefix + _jobId, VPackValue(VPackValueType::Object)); pending.add("timeStarted", VPackValue(timepointToString(std::chrono::system_clock::now()))); for (auto const& obj : VPackObjectIterator(todo.slice()[0])) { pending.add(obj.key.copyString(), obj.value); } pending.close(); // --- Delete todo pending.add(_agencyPrefix + toDoPrefix + _jobId, VPackValue(VPackValueType::Object)); pending.add("op", VPackValue("delete")); pending.close(); // --- Block shard pending.add(_agencyPrefix + blockedShardsPrefix + _shard, VPackValue(VPackValueType::Object)); pending.add("jobId", VPackValue(_jobId)); pending.close(); // --- Plan changes pending.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); if (current[0].copyString() == _from) { // Leader pending.add(current[0]); pending.add(VPackValue(_to)); for (size_t i = 1; i < current.length(); ++i) { pending.add(current[i]); } } else { // Follower for (auto const& srv : VPackArrayIterator(current)) { pending.add(srv); } pending.add(VPackValue(_to)); } pending.close(); // --- Increment Plan/Version pending.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); pending.add("op", VPackValue("increment")); pending.close(); pending.close(); // Preconditions // --- Check that Current servers are as we expect pending.openObject(); pending.add(_agencyPrefix + curPath, VPackValue(VPackValueType::Object)); pending.add("old", current); pending.close(); // --- Check if shard is not blocked pending.add(_agencyPrefix + blockedShardsPrefix + _shard, VPackValue(VPackValueType::Object)); pending.add("oldEmpty", VPackValue(true)); pending.close(); pending.close(); pending.close(); // Transact to agency write_ret_t res = transact(_agent, pending); if (res.accepted && res.indices.size()==1 && res.indices[0]) { LOG_TOPIC(INFO, Logger::AGENCY) << "Pending: Move shard " + _shard + " from " + _from + " to " + _to; return true; } LOG_TOPIC(INFO, Logger::AGENCY) << "Start precondition failed for " + _jobId; return false; } JOB_STATUS MoveShard::status () { auto status = exists(); if (status != NOTFOUND) { // Get job details from agency try { _database = _snapshot(pos[status] + _jobId + "/database").getString(); _collection = _snapshot(pos[status] + _jobId + "/collection").getString(); _from = _snapshot(pos[status] + _jobId + "/fromServer").getString(); _to = _snapshot(pos[status] + _jobId + "/toServer").getString(); _shard = _snapshot(pos[status] + _jobId + "/shard").getString(); } catch (std::exception const& e) { std::stringstream err; err << "Failed to find job " << _jobId << " in agency: " << e.what(); LOG_TOPIC(ERR, Logger::AGENCY) << err.str(); finish("Shards/" + _shard, false, err.str()); return FAILED; } } if (status == PENDING) { std::string planPath = planColPrefix + _database + "/" + _collection + "/shards/" + _shard; std::string curPath = curColPrefix + _database + "/" + _collection + "/" + _shard + "/servers"; Slice current = _snapshot(curPath).slice(), plan = _snapshot(curPath).slice(); if (current == plan) { if ((current[0].copyString())[0] == '_') { // Retired leader Builder cyclic; // Cyclic shift _serverId to end cyclic.openArray(); cyclic.openObject(); // --- Plan changes cyclic.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); for (size_t i = 1; i < current.length(); ++i) { cyclic.add(current[i]); } std::string disabledLeader = current[0].copyString(); disabledLeader = disabledLeader.substr(1,disabledLeader.size()-1); cyclic.add(VPackValue(disabledLeader)); cyclic.close(); // --- Plan version cyclic.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); cyclic.add("op", VPackValue("increment")); cyclic.close(); cyclic.close(); cyclic.close(); transact(_agent, cyclic); return PENDING; } else { bool foundFrom = false, foundTo = false; for (auto const& srv : VPackArrayIterator(current)) { std::string srv_str = srv.copyString(); if (srv_str == _from) { foundFrom = true; } if (srv_str == _to) { foundTo = true; } } if (foundFrom && foundTo) { LOG(WARN) << current[0].copyString() << " " << _from; if (current[0].copyString() == _from) { // Leader Builder underscore; // serverId -> _serverId underscore.openArray(); underscore.openObject(); // --- Plan changes underscore.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); underscore.add( VPackValue(std::string("_") + current[0].copyString())); for (size_t i = 1; i < current.length(); ++i) { underscore.add(current[i]); } underscore.close(); // --- Plan version underscore.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); underscore.add("op", VPackValue("increment")); underscore.close(); underscore.close(); underscore.close(); transact(_agent, underscore); } else { Builder remove; remove.openArray(); remove.openObject(); // --- Plan changes remove.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); for (auto const& srv : VPackArrayIterator(current)) { if (srv.copyString() != _from) { remove.add(srv); } } remove.close(); // --- Plan version remove.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); remove.add("op", VPackValue("increment")); remove.close(); remove.close(); remove.close(); transact(_agent, remove); } return PENDING; } else if (foundTo && !foundFrom) { return FINISHED; } } if (finish("Shards/" + _shard)) { return FINISHED; } } } return status; } <commit_msg>move-shard slightly changed order of actions<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "MoveShard.h" #include "Agent.h" #include "Job.h" using namespace arangodb::consensus; MoveShard::MoveShard (Node const& snapshot, Agent* agent, std::string const& jobId, std::string const& creator, std::string const& prefix, std::string const& database, std::string const& collection, std::string const& shard, std::string const& from, std::string const& to) : Job(snapshot, agent, jobId, creator, prefix), _database(database), _collection(collection), _shard(shard), _from(from), _to(to) { JOB_STATUS js = status(); try { if (js == TODO) { start(); } else if (js == NOTFOUND) { if (create()) { start(); } } } catch (std::exception const& e) { LOG_TOPIC(WARN, Logger::AGENCY) << e.what() << __FILE__ << __LINE__; finish("Shards/" + _shard, false, e.what()); } } MoveShard::~MoveShard () {} bool MoveShard::create () { LOG_TOPIC(INFO, Logger::AGENCY) << "Todo: Move shard " + _shard + " from " + _from + " to " << _to; std::string path, now(timepointToString(std::chrono::system_clock::now())); // DBservers std::string planPath = planColPrefix + _database + "/" + _collection + "/shards/" + _shard; std::string curPath = curColPrefix + _database + "/" + _collection + "/" + _shard + "/servers"; Slice current = _snapshot(curPath).slice(); TRI_ASSERT(current.isArray()); TRI_ASSERT(current[0].isString()); _jb = std::make_shared<Builder>(); _jb->openArray(); _jb->openObject(); if (_from == _to) { path = _agencyPrefix + failedPrefix + _jobId; _jb->add("timeFinished", VPackValue(now)); _jb->add("result", VPackValue("Source and destination of moveShard must be different")); } else { path = _agencyPrefix + toDoPrefix + _jobId; } _jb->add(path, VPackValue(VPackValueType::Object)); _jb->add("creator", VPackValue(_creator)); _jb->add("type", VPackValue("moveShard")); _jb->add("database", VPackValue(_database)); _jb->add("collection", VPackValue(_collection)); _jb->add("shard", VPackValue(_shard)); _jb->add("fromServer", VPackValue(_from)); _jb->add("toServer", VPackValue(_to)); _jb->add("isLeader", VPackValue(current[0].copyString() == _from)); _jb->add("jobId", VPackValue(_jobId)); _jb->add("timeCreated", VPackValue(now)); _jb->close(); _jb->close(); _jb->close(); write_ret_t res = transact(_agent, *_jb); if (res.accepted && res.indices.size()==1 && res.indices[0]) { return true; } LOG_TOPIC(INFO, Logger::AGENCY) << "Failed to insert job " + _jobId; return false; } bool MoveShard::start() { // DBservers std::string planPath = planColPrefix + _database + "/" + _collection + "/shards/" + _shard; std::string curPath = curColPrefix + _database + "/" + _collection + "/" + _shard + "/servers"; Slice current = _snapshot(curPath).slice(); // Copy todo to pending Builder todo, pending; // Get todo entry todo.openArray(); if (_jb == nullptr) { try { _snapshot(toDoPrefix + _jobId).toBuilder(todo); } catch (std::exception const&) { LOG_TOPIC(INFO, Logger::AGENCY) << "Failed to get key " + toDoPrefix + _jobId + " from agency snapshot"; return false; } } else { todo.add(_jb->slice()[0].valueAt(0)); } todo.close(); // Enter pending, remove todo, block toserver pending.openArray(); // --- Add pending pending.openObject(); pending.add(_agencyPrefix + pendingPrefix + _jobId, VPackValue(VPackValueType::Object)); pending.add("timeStarted", VPackValue(timepointToString(std::chrono::system_clock::now()))); for (auto const& obj : VPackObjectIterator(todo.slice()[0])) { pending.add(obj.key.copyString(), obj.value); } pending.close(); // --- Delete todo pending.add(_agencyPrefix + toDoPrefix + _jobId, VPackValue(VPackValueType::Object)); pending.add("op", VPackValue("delete")); pending.close(); // --- Block shard pending.add(_agencyPrefix + blockedShardsPrefix + _shard, VPackValue(VPackValueType::Object)); pending.add("jobId", VPackValue(_jobId)); pending.close(); // --- Plan changes pending.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); if (current[0].copyString() == _from) { // Leader pending.add(current[0]); pending.add(VPackValue(_to)); for (size_t i = 1; i < current.length(); ++i) { pending.add(current[i]); } } else { // Follower for (auto const& srv : VPackArrayIterator(current)) { pending.add(srv); } pending.add(VPackValue(_to)); } pending.close(); // --- Increment Plan/Version pending.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); pending.add("op", VPackValue("increment")); pending.close(); pending.close(); // Preconditions // --- Check that Current servers are as we expect pending.openObject(); pending.add(_agencyPrefix + curPath, VPackValue(VPackValueType::Object)); pending.add("old", current); pending.close(); // --- Check if shard is not blocked pending.add(_agencyPrefix + blockedShardsPrefix + _shard, VPackValue(VPackValueType::Object)); pending.add("oldEmpty", VPackValue(true)); pending.close(); pending.close(); pending.close(); // Transact to agency write_ret_t res = transact(_agent, pending); if (res.accepted && res.indices.size()==1 && res.indices[0]) { LOG_TOPIC(INFO, Logger::AGENCY) << "Pending: Move shard " + _shard + " from " + _from + " to " + _to; return true; } LOG_TOPIC(INFO, Logger::AGENCY) << "Start precondition failed for " + _jobId; return false; } JOB_STATUS MoveShard::status () { auto status = exists(); if (status != NOTFOUND) { // Get job details from agency try { _database = _snapshot(pos[status] + _jobId + "/database").getString(); _collection = _snapshot(pos[status] + _jobId + "/collection").getString(); _from = _snapshot(pos[status] + _jobId + "/fromServer").getString(); _to = _snapshot(pos[status] + _jobId + "/toServer").getString(); _shard = _snapshot(pos[status] + _jobId + "/shard").getString(); } catch (std::exception const& e) { std::stringstream err; err << "Failed to find job " << _jobId << " in agency: " << e.what(); LOG_TOPIC(ERR, Logger::AGENCY) << err.str(); finish("Shards/" + _shard, false, err.str()); return FAILED; } } if (status == PENDING) { std::string planPath = planColPrefix + _database + "/" + _collection + "/shards/" + _shard; std::string curPath = curColPrefix + _database + "/" + _collection + "/" + _shard + "/servers"; Slice current = _snapshot(curPath).slice(), plan = _snapshot(curPath).slice(); if (current == plan) { if ((current[0].copyString())[0] == '_') { // Retired leader Builder cyclic; // Cyclic shift _serverId to end cyclic.openArray(); cyclic.openObject(); // --- Plan changes cyclic.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); for (size_t i = 1; i < current.length(); ++i) { cyclic.add(current[i]); } std::string disabledLeader = current[0].copyString(); disabledLeader = disabledLeader.substr(1,disabledLeader.size()-1); cyclic.add(VPackValue(disabledLeader)); cyclic.close(); // --- Plan version cyclic.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); cyclic.add("op", VPackValue("increment")); cyclic.close(); cyclic.close(); cyclic.close(); transact(_agent, cyclic); return PENDING; } else { bool foundFrom = false, foundTo = false; for (auto const& srv : VPackArrayIterator(current)) { std::string srv_str = srv.copyString(); if (srv_str == _from) { foundFrom = true; } if (srv_str == _to) { foundTo = true; } } if (foundFrom && foundTo) { if (current[0].copyString() == _from) { // Leader Builder underscore; // serverId -> _serverId underscore.openArray(); underscore.openObject(); // --- Plan changes underscore.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); underscore.add( VPackValue(std::string("_") + current[0].copyString())); for (size_t i = 1; i < current.length(); ++i) { underscore.add(current[i]); } underscore.close(); // --- Plan version underscore.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); underscore.add("op", VPackValue("increment")); underscore.close(); underscore.close(); underscore.close(); transact(_agent, underscore); } else { Builder remove; remove.openArray(); remove.openObject(); // --- Plan changes remove.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array)); for (auto const& srv : VPackArrayIterator(current)) { if (srv.copyString() != _from) { remove.add(srv); } } remove.close(); // --- Plan version remove.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object)); remove.add("op", VPackValue("increment")); remove.close(); remove.close(); remove.close(); transact(_agent, remove); } return PENDING; } else if (foundTo && !foundFrom) { return FINISHED; } } if (finish("Shards/" + _shard)) { return FINISHED; } } } return status; } <|endoftext|>
<commit_before>#include "ffi.h" /////////////// void FFI::InitializeStaticFunctions(Handle<Object> target) { Local<Object> o = Object::New(); // atoi and abs here for testing purposes o->Set(String::New("atoi"), Pointer::WrapPointer((unsigned char *)atoi)); // Windows has multiple `abs` signatures, so we need to manually disambiguate int (*absPtr)(int)(abs); o->Set(String::New("abs"), Pointer::WrapPointer((unsigned char *)absPtr)); // dl functions used by the DynamicLibrary JS class o->Set(String::New("dlopen"), Pointer::WrapPointer((unsigned char *)dlopen)); o->Set(String::New("dlclose"), Pointer::WrapPointer((unsigned char *)dlclose)); o->Set(String::New("dlsym"), Pointer::WrapPointer((unsigned char *)dlsym)); o->Set(String::New("dlerror"), Pointer::WrapPointer((unsigned char *)dlerror)); target->Set(String::NewSymbol("StaticFunctions"), o); } /////////////// void FFI::InitializeBindings(Handle<Object> target) { Local<Object> o = Object::New(); target->Set(String::New("free"), FunctionTemplate::New(Free)->GetFunction()); target->Set(String::New("prepCif"), FunctionTemplate::New(FFIPrepCif)->GetFunction()); target->Set(String::New("strtoul"), FunctionTemplate::New(Strtoul)->GetFunction()); target->Set(String::New("POINTER_SIZE"), Integer::New(sizeof(unsigned char *))); target->Set(String::New("FFI_TYPE_SIZE"), Integer::New(sizeof(ffi_type))); bool hasObjc = false; #if __OBJC__ || __OBJC2__ hasObjc = true; #endif target->Set(String::New("HAS_OBJC"), Boolean::New(hasObjc), static_cast<PropertyAttribute>(ReadOnly|DontDelete)); Local<Object> smap = Object::New(); smap->Set(String::New("byte"), Integer::New(sizeof(unsigned char))); smap->Set(String::New("int8"), Integer::New(sizeof(int8_t))); smap->Set(String::New("uint8"), Integer::New(sizeof(uint8_t))); smap->Set(String::New("int16"), Integer::New(sizeof(int16_t))); smap->Set(String::New("uint16"), Integer::New(sizeof(uint16_t))); smap->Set(String::New("int32"), Integer::New(sizeof(int32_t))); smap->Set(String::New("uint32"), Integer::New(sizeof(uint32_t))); smap->Set(String::New("int64"), Integer::New(sizeof(int64_t))); smap->Set(String::New("uint64"), Integer::New(sizeof(uint64_t))); smap->Set(String::New("char"), Integer::New(sizeof(char))); smap->Set(String::New("uchar"), Integer::New(sizeof(unsigned char))); smap->Set(String::New("short"), Integer::New(sizeof(short))); smap->Set(String::New("ushort"), Integer::New(sizeof(unsigned short))); smap->Set(String::New("int"), Integer::New(sizeof(int))); smap->Set(String::New("uint"), Integer::New(sizeof(unsigned int))); smap->Set(String::New("long"), Integer::New(sizeof(long))); smap->Set(String::New("ulong"), Integer::New(sizeof(unsigned long))); smap->Set(String::New("longlong"), Integer::New(sizeof(long long))); smap->Set(String::New("ulonglong"), Integer::New(sizeof(unsigned long long))); smap->Set(String::New("float"), Integer::New(sizeof(float))); smap->Set(String::New("double"), Integer::New(sizeof(double))); smap->Set(String::New("pointer"), Integer::New(sizeof(unsigned char *))); smap->Set(String::New("string"), Integer::New(sizeof(char *))); smap->Set(String::New("size_t"), Integer::New(sizeof(size_t))); // Size of a Persistent handle to a JS object smap->Set(String::New("Object"), Integer::New(sizeof(Persistent<Object>))); Local<Object> ftmap = Object::New(); ftmap->Set(String::New("void"), Pointer::WrapPointer((unsigned char *)&ffi_type_void)); ftmap->Set(String::New("byte"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint8)); ftmap->Set(String::New("int8"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint8)); ftmap->Set(String::New("uint8"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint8)); ftmap->Set(String::New("uint16"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint16)); ftmap->Set(String::New("int16"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint16)); ftmap->Set(String::New("uint32"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint32)); ftmap->Set(String::New("int32"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint32)); ftmap->Set(String::New("uint64"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint64)); ftmap->Set(String::New("int64"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint64)); ftmap->Set(String::New("uchar"), Pointer::WrapPointer((unsigned char *)&ffi_type_uchar)); ftmap->Set(String::New("char"), Pointer::WrapPointer((unsigned char *)&ffi_type_schar)); ftmap->Set(String::New("ushort"), Pointer::WrapPointer((unsigned char *)&ffi_type_ushort)); ftmap->Set(String::New("short"), Pointer::WrapPointer((unsigned char *)&ffi_type_sshort)); ftmap->Set(String::New("uint"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint)); ftmap->Set(String::New("int"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint)); ftmap->Set(String::New("float"), Pointer::WrapPointer((unsigned char *)&ffi_type_float)); ftmap->Set(String::New("double"), Pointer::WrapPointer((unsigned char *)&ffi_type_double)); ftmap->Set(String::New("pointer"), Pointer::WrapPointer((unsigned char *)&ffi_type_pointer)); ftmap->Set(String::New("string"), Pointer::WrapPointer((unsigned char *)&ffi_type_pointer)); ftmap->Set(String::New("size_t"), Pointer::WrapPointer((unsigned char *)&ffi_type_pointer)); // libffi is weird when it comes to long data types (defaults to 64-bit), so we emulate here, since // some platforms have 32-bit longs and some platforms have 64-bit longs. if (sizeof(long) == 4) { ftmap->Set(String::New("ulong"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint32)); ftmap->Set(String::New("long"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint32)); } else if (sizeof(long) == 8) { ftmap->Set(String::New("ulong"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint64)); ftmap->Set(String::New("long"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint64)); } // Let libffi handle "long long" ftmap->Set(String::New("ulonglong"),Pointer::WrapPointer((unsigned char *)&ffi_type_ulong)); ftmap->Set(String::New("longlong"), Pointer::WrapPointer((unsigned char *)&ffi_type_slong)); target->Set(String::New("FFI_TYPES"), ftmap); target->Set(String::New("TYPE_SIZE_MAP"), smap); } Handle<Value> FFI::Free(const Arguments &args) { HandleScope scope; Pointer *p = ObjectWrap::Unwrap<Pointer>(args[0]->ToObject()); free(p->GetPointer()); return Undefined(); } /** * Hard-coded `stftoul` binding, for the benchmarks. */ Handle<Value> FFI::Strtoul(const Arguments &args) { HandleScope scope; Pointer *middle = ObjectWrap::Unwrap<Pointer>(args[1]->ToObject()); char buf[128]; args[0]->ToString()->WriteUtf8(buf); unsigned long val = strtoul(buf, (char **)middle->GetPointer(), args[2]->Int32Value()); return scope.Close(Integer::NewFromUnsigned(val)); } /** * Function that creates and returns an `ffi_cif` pointer from the given return * value type and argument types. */ Handle<Value> FFI::FFIPrepCif(const Arguments& args) { HandleScope scope; unsigned int nargs; Pointer *rtype, *atypes, *cif; ffi_status status; if (args.Length() != 3) { return THROW_ERROR_EXCEPTION("prepCif() requires 3 arguments!"); } nargs = args[0]->Uint32Value(); rtype = ObjectWrap::Unwrap<Pointer>(args[1]->ToObject()); atypes = ObjectWrap::Unwrap<Pointer>(args[2]->ToObject()); cif = new Pointer(NULL); cif->Alloc(sizeof(ffi_cif)); status = ffi_prep_cif( (ffi_cif *)cif->GetPointer(), FFI_DEFAULT_ABI, nargs, (ffi_type *)rtype->GetPointer(), (ffi_type **)atypes->GetPointer()); if (status != FFI_OK) { delete cif; return THROW_ERROR_EXCEPTION("ffi_prep_cif() returned error."); } return scope.Close(Pointer::WrapInstance(cif)); } /////////////// extern "C" { static void init(Handle<Object> target) { HandleScope scope; Pointer::Initialize(target); FFI::InitializeBindings(target); FFI::InitializeStaticFunctions(target); CallbackInfo::Initialize(target); ForeignCaller::Initialize(target); } NODE_MODULE(ffi_bindings, init); } <commit_msg>Remove unused variable.<commit_after>#include "ffi.h" /////////////// void FFI::InitializeStaticFunctions(Handle<Object> target) { Local<Object> o = Object::New(); // atoi and abs here for testing purposes o->Set(String::New("atoi"), Pointer::WrapPointer((unsigned char *)atoi)); // Windows has multiple `abs` signatures, so we need to manually disambiguate int (*absPtr)(int)(abs); o->Set(String::New("abs"), Pointer::WrapPointer((unsigned char *)absPtr)); // dl functions used by the DynamicLibrary JS class o->Set(String::New("dlopen"), Pointer::WrapPointer((unsigned char *)dlopen)); o->Set(String::New("dlclose"), Pointer::WrapPointer((unsigned char *)dlclose)); o->Set(String::New("dlsym"), Pointer::WrapPointer((unsigned char *)dlsym)); o->Set(String::New("dlerror"), Pointer::WrapPointer((unsigned char *)dlerror)); target->Set(String::NewSymbol("StaticFunctions"), o); } /////////////// void FFI::InitializeBindings(Handle<Object> target) { target->Set(String::New("free"), FunctionTemplate::New(Free)->GetFunction()); target->Set(String::New("prepCif"), FunctionTemplate::New(FFIPrepCif)->GetFunction()); target->Set(String::New("strtoul"), FunctionTemplate::New(Strtoul)->GetFunction()); target->Set(String::New("POINTER_SIZE"), Integer::New(sizeof(unsigned char *))); target->Set(String::New("FFI_TYPE_SIZE"), Integer::New(sizeof(ffi_type))); bool hasObjc = false; #if __OBJC__ || __OBJC2__ hasObjc = true; #endif target->Set(String::New("HAS_OBJC"), Boolean::New(hasObjc), static_cast<PropertyAttribute>(ReadOnly|DontDelete)); Local<Object> smap = Object::New(); smap->Set(String::New("byte"), Integer::New(sizeof(unsigned char))); smap->Set(String::New("int8"), Integer::New(sizeof(int8_t))); smap->Set(String::New("uint8"), Integer::New(sizeof(uint8_t))); smap->Set(String::New("int16"), Integer::New(sizeof(int16_t))); smap->Set(String::New("uint16"), Integer::New(sizeof(uint16_t))); smap->Set(String::New("int32"), Integer::New(sizeof(int32_t))); smap->Set(String::New("uint32"), Integer::New(sizeof(uint32_t))); smap->Set(String::New("int64"), Integer::New(sizeof(int64_t))); smap->Set(String::New("uint64"), Integer::New(sizeof(uint64_t))); smap->Set(String::New("char"), Integer::New(sizeof(char))); smap->Set(String::New("uchar"), Integer::New(sizeof(unsigned char))); smap->Set(String::New("short"), Integer::New(sizeof(short))); smap->Set(String::New("ushort"), Integer::New(sizeof(unsigned short))); smap->Set(String::New("int"), Integer::New(sizeof(int))); smap->Set(String::New("uint"), Integer::New(sizeof(unsigned int))); smap->Set(String::New("long"), Integer::New(sizeof(long))); smap->Set(String::New("ulong"), Integer::New(sizeof(unsigned long))); smap->Set(String::New("longlong"), Integer::New(sizeof(long long))); smap->Set(String::New("ulonglong"), Integer::New(sizeof(unsigned long long))); smap->Set(String::New("float"), Integer::New(sizeof(float))); smap->Set(String::New("double"), Integer::New(sizeof(double))); smap->Set(String::New("pointer"), Integer::New(sizeof(unsigned char *))); smap->Set(String::New("string"), Integer::New(sizeof(char *))); smap->Set(String::New("size_t"), Integer::New(sizeof(size_t))); // Size of a Persistent handle to a JS object smap->Set(String::New("Object"), Integer::New(sizeof(Persistent<Object>))); Local<Object> ftmap = Object::New(); ftmap->Set(String::New("void"), Pointer::WrapPointer((unsigned char *)&ffi_type_void)); ftmap->Set(String::New("byte"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint8)); ftmap->Set(String::New("int8"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint8)); ftmap->Set(String::New("uint8"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint8)); ftmap->Set(String::New("uint16"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint16)); ftmap->Set(String::New("int16"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint16)); ftmap->Set(String::New("uint32"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint32)); ftmap->Set(String::New("int32"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint32)); ftmap->Set(String::New("uint64"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint64)); ftmap->Set(String::New("int64"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint64)); ftmap->Set(String::New("uchar"), Pointer::WrapPointer((unsigned char *)&ffi_type_uchar)); ftmap->Set(String::New("char"), Pointer::WrapPointer((unsigned char *)&ffi_type_schar)); ftmap->Set(String::New("ushort"), Pointer::WrapPointer((unsigned char *)&ffi_type_ushort)); ftmap->Set(String::New("short"), Pointer::WrapPointer((unsigned char *)&ffi_type_sshort)); ftmap->Set(String::New("uint"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint)); ftmap->Set(String::New("int"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint)); ftmap->Set(String::New("float"), Pointer::WrapPointer((unsigned char *)&ffi_type_float)); ftmap->Set(String::New("double"), Pointer::WrapPointer((unsigned char *)&ffi_type_double)); ftmap->Set(String::New("pointer"), Pointer::WrapPointer((unsigned char *)&ffi_type_pointer)); ftmap->Set(String::New("string"), Pointer::WrapPointer((unsigned char *)&ffi_type_pointer)); ftmap->Set(String::New("size_t"), Pointer::WrapPointer((unsigned char *)&ffi_type_pointer)); // libffi is weird when it comes to long data types (defaults to 64-bit), so we emulate here, since // some platforms have 32-bit longs and some platforms have 64-bit longs. if (sizeof(long) == 4) { ftmap->Set(String::New("ulong"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint32)); ftmap->Set(String::New("long"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint32)); } else if (sizeof(long) == 8) { ftmap->Set(String::New("ulong"), Pointer::WrapPointer((unsigned char *)&ffi_type_uint64)); ftmap->Set(String::New("long"), Pointer::WrapPointer((unsigned char *)&ffi_type_sint64)); } // Let libffi handle "long long" ftmap->Set(String::New("ulonglong"),Pointer::WrapPointer((unsigned char *)&ffi_type_ulong)); ftmap->Set(String::New("longlong"), Pointer::WrapPointer((unsigned char *)&ffi_type_slong)); target->Set(String::New("FFI_TYPES"), ftmap); target->Set(String::New("TYPE_SIZE_MAP"), smap); } Handle<Value> FFI::Free(const Arguments &args) { HandleScope scope; Pointer *p = ObjectWrap::Unwrap<Pointer>(args[0]->ToObject()); free(p->GetPointer()); return Undefined(); } /** * Hard-coded `stftoul` binding, for the benchmarks. */ Handle<Value> FFI::Strtoul(const Arguments &args) { HandleScope scope; Pointer *middle = ObjectWrap::Unwrap<Pointer>(args[1]->ToObject()); char buf[128]; args[0]->ToString()->WriteUtf8(buf); unsigned long val = strtoul(buf, (char **)middle->GetPointer(), args[2]->Int32Value()); return scope.Close(Integer::NewFromUnsigned(val)); } /** * Function that creates and returns an `ffi_cif` pointer from the given return * value type and argument types. */ Handle<Value> FFI::FFIPrepCif(const Arguments& args) { HandleScope scope; unsigned int nargs; Pointer *rtype, *atypes, *cif; ffi_status status; if (args.Length() != 3) { return THROW_ERROR_EXCEPTION("prepCif() requires 3 arguments!"); } nargs = args[0]->Uint32Value(); rtype = ObjectWrap::Unwrap<Pointer>(args[1]->ToObject()); atypes = ObjectWrap::Unwrap<Pointer>(args[2]->ToObject()); cif = new Pointer(NULL); cif->Alloc(sizeof(ffi_cif)); status = ffi_prep_cif( (ffi_cif *)cif->GetPointer(), FFI_DEFAULT_ABI, nargs, (ffi_type *)rtype->GetPointer(), (ffi_type **)atypes->GetPointer()); if (status != FFI_OK) { delete cif; return THROW_ERROR_EXCEPTION("ffi_prep_cif() returned error."); } return scope.Close(Pointer::WrapInstance(cif)); } /////////////// extern "C" { static void init(Handle<Object> target) { HandleScope scope; Pointer::Initialize(target); FFI::InitializeBindings(target); FFI::InitializeStaticFunctions(target); CallbackInfo::Initialize(target); ForeignCaller::Initialize(target); } NODE_MODULE(ffi_bindings, init); } <|endoftext|>
<commit_before>/* * Copyright 2017-2018 Baidu 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_openrasp.h" } #include <sstream> #include <fstream> #include "openrasp_v8.h" #include "openrasp_ini.h" #ifdef HAVE_OPENRASP_REMOTE_MANAGER #include "agent/openrasp_agent_manager.h" #endif namespace openrasp { openrasp_v8_process_globals process_globals; } // namespace openrasp using namespace openrasp; ZEND_DECLARE_MODULE_GLOBALS(openrasp_v8) PHP_GINIT_FUNCTION(openrasp_v8) { <<<<<<< HEAD #ifdef ZTS new (openrasp_v8_globals) _zend_openrasp_v8_globals; #endif ======= if (!init_isolate(TSRMLS_C)) { return 0; } v8::Isolate *isolate = OPENRASP_V8_G(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handlescope(isolate); v8::Local<v8::Context> context = OPENRASP_V8_G(context).Get(isolate); v8::Context::Scope context_scope(context); v8::TryCatch try_catch; v8::Local<v8::Function> check = OPENRASP_V8_G(check).Get(isolate); v8::Local<v8::Value> type = V8STRING_N(c_type).ToLocalChecked(); v8::Local<v8::Value> params = zval_to_v8val(z_params, isolate TSRMLS_CC); v8::Local<v8::Object> request_context = OPENRASP_V8_G(request_context).Get(isolate); v8::Local<v8::Value> argv[]{type, params, request_context}; v8::Local<v8::Value> rst; { TimeoutTask *task = new TimeoutTask(isolate, openrasp_ini.timeout_ms); std::lock_guard<std::timed_mutex> lock(task->GetMtx()); process_globals.v8_platform->CallOnBackgroundThread(task, v8::Platform::kShortRunningTask); bool avoidwarning = check->Call(context, check, 3, argv).ToLocal(&rst); } if (rst.IsEmpty()) { if (try_catch.Message().IsEmpty()) { v8::Local<v8::Function> console_log = context->Global() ->Get(context, V8STRING_I("console").ToLocalChecked()) .ToLocalChecked() .As<v8::Object>() ->Get(context, V8STRING_I("log").ToLocalChecked()) .ToLocalChecked() .As<v8::Function>(); v8::Local<v8::Object> message = v8::Object::New(isolate); message->Set(V8STRING_N("message").ToLocalChecked(), V8STRING_N("Javascript plugin execution timeout.").ToLocalChecked()); message->Set(V8STRING_N("type").ToLocalChecked(), type); message->Set(V8STRING_N("params").ToLocalChecked(), params); message->Set(V8STRING_N("context").ToLocalChecked(), request_context); bool avoidwarning = console_log->Call(context, console_log, 1, reinterpret_cast<v8::Local<v8::Value> *>(&message)).IsEmpty(); } else { std::stringstream stream; v8error_to_stream(isolate, try_catch, stream); std::string error = stream.str(); plugin_info(error.c_str(), error.length() TSRMLS_CC); } return 0; } if (!rst->IsArray()) { return 0; } v8::Local<v8::String> key_action = OPENRASP_V8_G(key_action).Get(isolate); v8::Local<v8::String> key_message = OPENRASP_V8_G(key_message).Get(isolate); v8::Local<v8::String> key_name = OPENRASP_V8_G(key_name).Get(isolate); v8::Local<v8::String> key_confidence = OPENRASP_V8_G(key_confidence).Get(isolate); v8::Local<v8::String> key_algorithm = OPENRASP_V8_G(key_algorithm).Get(isolate); v8::Local<v8::Array> arr = rst.As<v8::Array>(); int len = arr->Length(); bool is_block = false; for (int i = 0; i < len; i++) { v8::Local<v8::Object> item = arr->Get(i).As<v8::Object>(); v8::Local<v8::Value> v8_action = item->Get(key_action); if (!v8_action->IsString()) { continue; } int action_hash = v8_action->ToString()->GetIdentityHash(); if (OPENRASP_V8_G(action_hash_ignore) == action_hash) { continue; } is_block = is_block || OPENRASP_V8_G(action_hash_block) == action_hash; v8::Local<v8::Value> v8_message = item->Get(key_message); v8::Local<v8::Value> v8_name = item->Get(key_name); v8::Local<v8::Value> v8_confidence = item->Get(key_confidence); v8::Local<v8::Value> v8_algorithm = item->Get(key_algorithm); v8::String::Utf8Value utf_action(v8_action); v8::String::Utf8Value utf_message(v8_message); v8::String::Utf8Value utf_name(v8_name); v8::String::Utf8Value utf_algorithm(v8_algorithm); zval z_type, z_action, z_message, z_name, z_confidence, z_algorithm; INIT_ZVAL(z_type); INIT_ZVAL(z_action); INIT_ZVAL(z_message); INIT_ZVAL(z_name); INIT_ZVAL(z_confidence); INIT_ZVAL(z_algorithm); ZVAL_STRING(&z_type, c_type, 0); ZVAL_STRINGL(&z_action, *utf_action, utf_action.length(), 0); ZVAL_STRINGL(&z_message, *utf_message, utf_message.length(), 0); ZVAL_STRINGL(&z_name, *utf_name, utf_name.length(), 0); ZVAL_LONG(&z_confidence, v8_confidence->Int32Value()); ZVAL_STRINGL(&z_algorithm, *utf_algorithm, utf_algorithm.length(), 0); zval result; INIT_ZVAL(result); ALLOC_HASHTABLE(Z_ARRVAL(result)); // 设置 zend hash 的析构函数为空 // 便于用共享 v8 产生的字符串,减少内存分配 zend_hash_init(Z_ARRVAL(result), 0, 0, 0, 0); Z_TYPE(result) = IS_ARRAY; add_assoc_zval(&result, "attack_type", &z_type); add_assoc_zval(&result, "attack_params", z_params); add_assoc_zval(&result, "intercept_state", &z_action); add_assoc_zval(&result, "plugin_message", &z_message); add_assoc_zval(&result, "plugin_name", &z_name); add_assoc_zval(&result, "plugin_confidence", &z_confidence); add_assoc_zval(&result, "plugin_algorithm", &z_algorithm); alarm_info(&result TSRMLS_CC); zval_dtor(&result); } return is_block ? 1 : 0; >>>>>>> master } PHP_GSHUTDOWN_FUNCTION(openrasp_v8) { if (openrasp_v8_globals->isolate) { openrasp_v8_globals->isolate->Dispose(); openrasp_v8_globals->isolate = nullptr; } #ifdef ZTS openrasp_v8_globals->~_zend_openrasp_v8_globals(); #endif } PHP_MINIT_FUNCTION(openrasp_v8) { ZEND_INIT_MODULE_GLOBALS(openrasp_v8, PHP_GINIT(openrasp_v8), PHP_GSHUTDOWN(openrasp_v8)); // It can be called multiple times, // but intern code initializes v8 only once v8::V8::Initialize(); #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { return SUCCESS; } #endif load_plugins(); if (!process_globals.snapshot_blob) { Platform::Initialize(); Snapshot *snapshot = new Snapshot(process_globals.plugin_config, process_globals.plugin_src_list); Platform::Shutdown(); if (!snapshot->IsOk()) { delete snapshot; } else { process_globals.snapshot_blob = snapshot; } } return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(openrasp_v8) { <<<<<<< HEAD ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_v8, PHP_GSHUTDOWN(openrasp_v8)); ======= if (process_globals.is_initialized && !OPENRASP_V8_G(is_isolate_initialized)) { if (!process_globals.v8_platform) { #ifdef ZTS process_globals.v8_platform = v8::platform::CreateDefaultPlatform(); #else process_globals.v8_platform = v8::platform::CreateDefaultPlatform(1); #endif v8::V8::InitializePlatform(process_globals.v8_platform); } OPENRASP_V8_G(create_params).array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); OPENRASP_V8_G(create_params).snapshot_blob = &process_globals.snapshot_blob; OPENRASP_V8_G(create_params).external_references = external_references; v8::Isolate *isolate = v8::Isolate::New(OPENRASP_V8_G(create_params)); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); v8::Local<v8::String> key_action = V8STRING_I("action").ToLocalChecked(); v8::Local<v8::String> key_message = V8STRING_I("message").ToLocalChecked(); v8::Local<v8::String> key_name = V8STRING_I("name").ToLocalChecked(); v8::Local<v8::String> key_confidence = V8STRING_I("confidence").ToLocalChecked(); v8::Local<v8::String> key_algorithm = V8STRING_I("algorithm").ToLocalChecked(); v8::Local<v8::Object> RASP = context->Global() ->Get(context, V8STRING_I("RASP").ToLocalChecked()) .ToLocalChecked() .As<v8::Object>(); v8::Local<v8::Function> check = RASP->Get(context, V8STRING_I("check").ToLocalChecked()) .ToLocalChecked() .As<v8::Function>(); OPENRASP_V8_G(isolate) = isolate; OPENRASP_V8_G(context).Reset(isolate, context); OPENRASP_V8_G(key_action).Reset(isolate, key_action); OPENRASP_V8_G(key_message).Reset(isolate, key_message); OPENRASP_V8_G(key_name).Reset(isolate, key_name); OPENRASP_V8_G(key_confidence).Reset(isolate, key_confidence); OPENRASP_V8_G(key_algorithm).Reset(isolate, key_algorithm); OPENRASP_V8_G(RASP).Reset(isolate, RASP); OPENRASP_V8_G(check).Reset(isolate, check); OPENRASP_V8_G(request_context).Reset(isolate, RequestContext::New(isolate)); OPENRASP_V8_G(action_hash_ignore) = V8STRING_N("ignore").ToLocalChecked()->GetIdentityHash(); OPENRASP_V8_G(action_hash_log) = V8STRING_N("log").ToLocalChecked()->GetIdentityHash(); OPENRASP_V8_G(action_hash_block) = V8STRING_N("block").ToLocalChecked()->GetIdentityHash(); >>>>>>> master // Disposing v8 is permanent, it cannot be reinitialized, // it should generally not be necessary to dispose v8 before exiting a process, // so skip this step for module graceful reload // v8::V8::Dispose(); Platform::Shutdown(); delete process_globals.snapshot_blob; process_globals.snapshot_blob = nullptr; return SUCCESS; } PHP_RINIT_FUNCTION(openrasp_v8) { #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { uint64_t timestamp = oam->get_plugin_update_timestamp(); if (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp)) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock && (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp))) { std::string filename = std::string(openrasp_ini.root_dir) + DEFAULT_SLASH + std::string("snapshot.dat"); Snapshot *blob = new Snapshot(filename, timestamp); if (!blob->IsOk()) { delete blob; } else { delete process_globals.snapshot_blob; process_globals.snapshot_blob = blob; } } } } #endif if (process_globals.snapshot_blob) { if (!OPENRASP_V8_G(isolate) || OPENRASP_V8_G(isolate)->IsExpired(process_globals.snapshot_blob->timestamp)) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock) { if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->Dispose(); } Platform::Initialize(); OPENRASP_V8_G(isolate) = Isolate::New(process_globals.snapshot_blob); } } } if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->GetData()->request_context.Reset(); } return SUCCESS; } <commit_msg>[PHP5]commit unsaved file<commit_after>/* * Copyright 2017-2018 Baidu 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_openrasp.h" } #include <sstream> #include <fstream> #include "openrasp_v8.h" #include "openrasp_ini.h" #ifdef HAVE_OPENRASP_REMOTE_MANAGER #include "agent/openrasp_agent_manager.h" #endif namespace openrasp { openrasp_v8_process_globals process_globals; } // namespace openrasp using namespace openrasp; ZEND_DECLARE_MODULE_GLOBALS(openrasp_v8) PHP_GINIT_FUNCTION(openrasp_v8) { #ifdef ZTS new (openrasp_v8_globals) _zend_openrasp_v8_globals; #endif } PHP_GSHUTDOWN_FUNCTION(openrasp_v8) { if (openrasp_v8_globals->isolate) { openrasp_v8_globals->isolate->Dispose(); openrasp_v8_globals->isolate = nullptr; } #ifdef ZTS openrasp_v8_globals->~_zend_openrasp_v8_globals(); #endif } PHP_MINIT_FUNCTION(openrasp_v8) { ZEND_INIT_MODULE_GLOBALS(openrasp_v8, PHP_GINIT(openrasp_v8), PHP_GSHUTDOWN(openrasp_v8)); // It can be called multiple times, // but intern code initializes v8 only once v8::V8::Initialize(); #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { return SUCCESS; } #endif load_plugins(); if (!process_globals.snapshot_blob) { Platform::Initialize(); Snapshot *snapshot = new Snapshot(process_globals.plugin_config, process_globals.plugin_src_list); Platform::Shutdown(); if (!snapshot->IsOk()) { delete snapshot; } else { process_globals.snapshot_blob = snapshot; } } return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(openrasp_v8) { ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_v8, PHP_GSHUTDOWN(openrasp_v8)); // Disposing v8 is permanent, it cannot be reinitialized, // it should generally not be necessary to dispose v8 before exiting a process, // so skip this step for module graceful reload // v8::V8::Dispose(); Platform::Shutdown(); delete process_globals.snapshot_blob; process_globals.snapshot_blob = nullptr; return SUCCESS; } PHP_RINIT_FUNCTION(openrasp_v8) { #ifdef HAVE_OPENRASP_REMOTE_MANAGER if (openrasp_ini.remote_management_enable && oam != nullptr) { uint64_t timestamp = oam->get_plugin_update_timestamp(); if (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp)) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock && (!process_globals.snapshot_blob || process_globals.snapshot_blob->IsExpired(timestamp))) { std::string filename = std::string(openrasp_ini.root_dir) + DEFAULT_SLASH + std::string("snapshot.dat"); Snapshot *blob = new Snapshot(filename, timestamp); if (!blob->IsOk()) { delete blob; } else { delete process_globals.snapshot_blob; process_globals.snapshot_blob = blob; } } } } #endif if (process_globals.snapshot_blob) { if (!OPENRASP_V8_G(isolate) || OPENRASP_V8_G(isolate)->IsExpired(process_globals.snapshot_blob->timestamp)) { std::unique_lock<std::mutex> lock(process_globals.mtx, std::try_to_lock); if (lock) { if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->Dispose(); } Platform::Initialize(); OPENRASP_V8_G(isolate) = Isolate::New(process_globals.snapshot_blob); } } } if (OPENRASP_V8_G(isolate)) { OPENRASP_V8_G(isolate)->GetData()->request_context.Reset(); } return SUCCESS; } <|endoftext|>
<commit_before>#include "descartes_planner/ladder_graph_dag_search.h" namespace descartes_planner { DAGSearch::DAGSearch(const LadderGraph &graph) : graph_(graph) { // On creating an object, let's allocate everything we need solution_.resize(graph.size()); for (size_t i = 0; i < graph.size(); ++i) { const auto n_vertices = graph.rungSize(i); solution_[i].distance.resize(n_vertices); solution_[i].predecessor.resize(n_vertices); } } double DAGSearch::run() { // Cost to the first rung should be set to zero std::fill(solution_.front().distance.begin(), solution_.front().distance.end(), 0.0); // Other rows initialize to zero for (size_t i = 1; i < solution_.size(); ++i) { std::fill(solution_[i].distance.begin(), solution_[i].distance.end(), std::numeric_limits<double>::max()); } // Now we iterate over the graph in 'topological' order for (size_t rung = 0; rung < solution_.size() - 1; ++rung) { const auto n_vertices = graph_.rungSize(rung); const auto next_rung = rung + 1; // For each vertex in the out edge list for (size_t index = 0; index < n_vertices; ++index) { const auto u_cost = distance(rung, index); const auto& edges = graph_.getEdges(rung)[index]; // for each out edge for (const auto& edge : edges) { auto dv = u_cost + edge.cost; // new cost if (dv < distance(next_rung, edge.idx)) { distance(next_rung, edge.idx) = dv; predecessor(next_rung, edge.idx) = index; // the predecessor's rung is implied to be the current rung } } } // vertex for loop } // rung for loop return *std::min_element(solution_.back().distance.begin(), solution_.back().distance.end()); } std::vector<DAGSearch::predecessor_t> DAGSearch::shortestPath() const { auto min_it = std::min_element(solution_.back().distance.begin(), solution_.back().distance.end()); auto min_idx = std::distance(solution_.back().distance.begin(), min_it); assert(min_idx >= 0); std::vector<predecessor_t> path (solution_.size()); size_type current_rung = path.size() - 1; size_type current_index = min_idx; for (unsigned i = 0; i < path.size(); ++i) { auto count = path.size() - 1 - i; assert(current_rung == count); path[count] = current_index; current_index = predecessor(current_rung, current_index); current_rung -= 1; } return path; } } // namespace descartes_planner <commit_msg>Use size_type in main loop of search.<commit_after>#include "descartes_planner/ladder_graph_dag_search.h" namespace descartes_planner { DAGSearch::DAGSearch(const LadderGraph &graph) : graph_(graph) { // On creating an object, let's allocate everything we need solution_.resize(graph.size()); for (size_t i = 0; i < graph.size(); ++i) { const auto n_vertices = graph.rungSize(i); solution_[i].distance.resize(n_vertices); solution_[i].predecessor.resize(n_vertices); } } double DAGSearch::run() { // Cost to the first rung should be set to zero std::fill(solution_.front().distance.begin(), solution_.front().distance.end(), 0.0); // Other rows initialize to zero for (size_type i = 1; i < solution_.size(); ++i) { std::fill(solution_[i].distance.begin(), solution_[i].distance.end(), std::numeric_limits<double>::max()); } // Now we iterate over the graph in 'topological' order for (size_type rung = 0; rung < solution_.size() - 1; ++rung) { const auto n_vertices = graph_.rungSize(rung); const auto next_rung = rung + 1; // For each vertex in the out edge list for (size_t index = 0; index < n_vertices; ++index) { const auto u_cost = distance(rung, index); const auto& edges = graph_.getEdges(rung)[index]; // for each out edge for (const auto& edge : edges) { auto dv = u_cost + edge.cost; // new cost if (dv < distance(next_rung, edge.idx)) { distance(next_rung, edge.idx) = dv; predecessor(next_rung, edge.idx) = index; // the predecessor's rung is implied to be the current rung } } } // vertex for loop } // rung for loop return *std::min_element(solution_.back().distance.begin(), solution_.back().distance.end()); } std::vector<DAGSearch::predecessor_t> DAGSearch::shortestPath() const { auto min_it = std::min_element(solution_.back().distance.begin(), solution_.back().distance.end()); auto min_idx = std::distance(solution_.back().distance.begin(), min_it); assert(min_idx >= 0); std::vector<predecessor_t> path (solution_.size()); size_type current_rung = path.size() - 1; size_type current_index = min_idx; for (unsigned i = 0; i < path.size(); ++i) { auto count = path.size() - 1 - i; assert(current_rung == count); path[count] = current_index; current_index = predecessor(current_rung, current_index); current_rung -= 1; } return path; } } // namespace descartes_planner <|endoftext|>
<commit_before>#include <QString> #include "kernel.h" #include "ilwis.h" #include "geometries.h" #include "ilwisdata.h" #include "coordinatesystem.h" #include "georeference.h" #include "georefimplementation.h" #include "factory.h" #include "abstractfactory.h" #include "georefimplementationfactory.h" using namespace Ilwis; GeoReference::GeoReference() { } GeoReference::GeoReference(const Resource& resource) : IlwisObject(resource) { } GeoReference::~GeoReference() { // if ( coordinateSystem().isValid()) // qDebug() << "use count " << name() << " : " << mastercatalog()->usecount(coordinateSystem()->id()); } GeoReference *GeoReference::create(const QString& type,const Resource& resource) { GeoReference *georef = new GeoReference(resource); GeoRefImplementationFactory *grfFac = kernel()->factory<GeoRefImplementationFactory>("ilwis::georefimplementationfactory"); GeoRefImplementation *impl = grfFac->create(type); if ( !impl) { ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1,type); return 0; } georef->impl(impl); return georef; } Coordinate GeoReference::pixel2Coord(const Pixeld &pixel) const { return _georefImpl->pixel2Coord(pixel); } Pixeld GeoReference::coord2Pixel(const Coordinate &crd) const { // for performance reasons no isValid check here, haas tobe checked before hand return _georefImpl->coord2Pixel(crd); } double GeoReference::pixelSize() const { // for performance reasons no isValid check here, haas tobe checked before hand return _georefImpl->pixelSize(); } bool GeoReference::compute() { if ( isValid()) return _georefImpl->compute(); return false; } ICoordinateSystem GeoReference::coordinateSystem() const { if ( isValid()) return _georefImpl->coordinateSystem(); return ICoordinateSystem(); } void GeoReference::coordinateSystem(const ICoordinateSystem& csy) { if ( isValid()) _georefImpl->coordinateSystem(csy); } Size<> GeoReference::size() const { if ( isValid()) return _georefImpl->size(); return Size<>(); } void GeoReference::size(const Size<> &sz) { // size must always be positive or undefined if ( isValid() && sz.xsize() > 0 && sz.ysize() > 0) _georefImpl->size(sz); } bool GeoReference::centerOfPixel() const { if ( isValid()) return _georefImpl->centerOfPixel(); return false; } void GeoReference::centerOfPixel(bool yesno) { if ( isValid()) _georefImpl->centerOfPixel(yesno); } bool GeoReference::isCompatible(const IGeoReference &georefOther) const { if (!georefOther.isValid()) return false; if (georefOther->id() == id()) return true; if ( coordinateSystem() != georefOther->coordinateSystem()) return false; if ( isValid()) return _georefImpl->isCompatible(georefOther); return false; } void GeoReference::adapter(GeoRefAdapter *adapt) { _adapter.reset(adapt); } const QScopedPointer<Ilwis::GeoRefAdapter> &GeoReference::adapter() const { return _adapter; } Envelope GeoReference::pixel2Coord(const BoundingBox &box) const { if ( !box.isValid()) { ERROR2(ERR_INVALID_PROPERTY_FOR_2,"size", "box"); return Envelope(); } Coordinate c1 = pixel2Coord(box.min_corner()); Coordinate c2 = pixel2Coord(box.max_corner()); return Envelope(c1,c2); } BoundingBox GeoReference::coord2Pixel(const Envelope &box) const { if ( !box.isValid()) { ERROR2(ERR_INVALID_PROPERTY_FOR_2,"size", "box"); return BoundingBox(); } Pixel p1 = coord2Pixel(box.min_corner()); Pixel p2 = coord2Pixel(box.max_corner()); return BoundingBox(p1,p2); } bool GeoReference::isValid() const { return !_georefImpl.isNull(); } void GeoReference::impl(GeoRefImplementation *impl) { _georefImpl.reset(impl); } IlwisTypes GeoReference::ilwisType() const { return itGEOREF; } <commit_msg>Submit the next pixel to pixel2coord for getting the correct bottom-right coordinate<commit_after>#include <QString> #include "kernel.h" #include "ilwis.h" #include "geometries.h" #include "ilwisdata.h" #include "coordinatesystem.h" #include "georeference.h" #include "georefimplementation.h" #include "factory.h" #include "abstractfactory.h" #include "georefimplementationfactory.h" using namespace Ilwis; GeoReference::GeoReference() { } GeoReference::GeoReference(const Resource& resource) : IlwisObject(resource) { } GeoReference::~GeoReference() { // if ( coordinateSystem().isValid()) // qDebug() << "use count " << name() << " : " << mastercatalog()->usecount(coordinateSystem()->id()); } GeoReference *GeoReference::create(const QString& type,const Resource& resource) { GeoReference *georef = new GeoReference(resource); GeoRefImplementationFactory *grfFac = kernel()->factory<GeoRefImplementationFactory>("ilwis::georefimplementationfactory"); GeoRefImplementation *impl = grfFac->create(type); if ( !impl) { ERROR1(ERR_COULDNT_CREATE_OBJECT_FOR_1,type); return 0; } georef->impl(impl); return georef; } Coordinate GeoReference::pixel2Coord(const Pixeld &pixel) const { return _georefImpl->pixel2Coord(pixel); } Pixeld GeoReference::coord2Pixel(const Coordinate &crd) const { // for performance reasons no isValid check here, haas tobe checked before hand return _georefImpl->coord2Pixel(crd); } double GeoReference::pixelSize() const { // for performance reasons no isValid check here, haas tobe checked before hand return _georefImpl->pixelSize(); } bool GeoReference::compute() { if ( isValid()) return _georefImpl->compute(); return false; } ICoordinateSystem GeoReference::coordinateSystem() const { if ( isValid()) return _georefImpl->coordinateSystem(); return ICoordinateSystem(); } void GeoReference::coordinateSystem(const ICoordinateSystem& csy) { if ( isValid()) _georefImpl->coordinateSystem(csy); } Size<> GeoReference::size() const { if ( isValid()) return _georefImpl->size(); return Size<>(); } void GeoReference::size(const Size<> &sz) { // size must always be positive or undefined if ( isValid() && sz.xsize() > 0 && sz.ysize() > 0) _georefImpl->size(sz); } bool GeoReference::centerOfPixel() const { if ( isValid()) return _georefImpl->centerOfPixel(); return false; } void GeoReference::centerOfPixel(bool yesno) { if ( isValid()) _georefImpl->centerOfPixel(yesno); } bool GeoReference::isCompatible(const IGeoReference &georefOther) const { if (!georefOther.isValid()) return false; if (georefOther->id() == id()) return true; if ( coordinateSystem() != georefOther->coordinateSystem()) return false; if ( isValid()) return _georefImpl->isCompatible(georefOther); return false; } void GeoReference::adapter(GeoRefAdapter *adapt) { _adapter.reset(adapt); } const QScopedPointer<Ilwis::GeoRefAdapter> &GeoReference::adapter() const { return _adapter; } Envelope GeoReference::pixel2Coord(const BoundingBox &box) const { if ( !box.isValid()) { ERROR2(ERR_INVALID_PROPERTY_FOR_2,"size", "box"); return Envelope(); } Coordinate c1 = pixel2Coord(box.min_corner()); Coordinate c2 = pixel2Coord(box.max_corner() + Pixel(1,1)); return Envelope(c1,c2); } BoundingBox GeoReference::coord2Pixel(const Envelope &box) const { if ( !box.isValid()) { ERROR2(ERR_INVALID_PROPERTY_FOR_2,"size", "box"); return BoundingBox(); } Pixel p1 = coord2Pixel(box.min_corner()); Pixel p2 = coord2Pixel(box.max_corner()); return BoundingBox(p1,p2); } bool GeoReference::isValid() const { return !_georefImpl.isNull(); } void GeoReference::impl(GeoRefImplementation *impl) { _georefImpl.reset(impl); } IlwisTypes GeoReference::ilwisType() const { return itGEOREF; } <|endoftext|>
<commit_before>/* * SelectionVariable.cpp * MWorksCore * * Created by David Cox on 3/1/06. * Copyright 2006 MIT. All rights reserved. * */ #include "SelectionVariable.h" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/case_conv.hpp> #include "VariableReference.h" #include "VariableProperties.h" #include "VariableRegistry.h" #include "SequentialSelection.h" #include "RandomWORSelection.h" #include "RandomWithReplacementSelection.h" #include "ComponentRegistry.h" #include "ExpressionVariable.h" using boost::algorithm::to_lower_copy; BEGIN_NAMESPACE_MW SelectionVariable::SelectionVariable(VariableProperties *props, shared_ptr<Selection> _selection) : Selectable(), Variable(props), selected_index(NO_SELECTION) { if (_selection) { attachSelection(_selection); } } Datum SelectionVariable::getTentativeSelection(int index) { if (!selection) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Internal error: selection variable has no selection attached"); return Datum(0L); } const std::vector<int>& tenativeSelections = selection->getTentativeSelections(); if (tenativeSelections.size() == 0) { // Issue an error message only if the experiment is running. Otherwise, all selection variable indexing // expressions will produce load-time errors (since ParsedExpressionVariable's constructors evaluate the // expression to test for validity). if (StateSystem::instance()->isRunning()) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Selection variable has no tentative selections available. Returning 0."); } return Datum(0L); } if ((index < 0) || (index >= tenativeSelections.size())) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Selection variable index (%d) is out of bounds. Returning 0.", index); return Datum(0L); } return values[tenativeSelections[index]]; } void SelectionVariable::nextValue() { if (selection != NULL) { try { selected_index = selection->draw(); } catch (std::exception &e) { merror(M_PARADIGM_MESSAGE_DOMAIN, "%s", e.what()); return; } // announce your new value so that the event stream contains // all information about what happened in the experiment announce(); performNotifications(values[selected_index]); } else { merror(M_PARADIGM_MESSAGE_DOMAIN, "Attempt to advance a selection variable with a NULL selection"); } } Datum SelectionVariable::getValue() { if (selected_index == NO_SELECTION) { nextValue(); } if (selected_index == NO_SELECTION) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Attempt to select a value from a selection variable with no values defined"); return Datum(0L); } return values[selected_index]; } Variable *SelectionVariable::clone(){ // This isn't quite right, but we can run with it for now return new VariableReference(this); } shared_ptr<mw::Component> SelectionVariableFactory::createObject(std::map<std::string, std::string> parameters, ComponentRegistry *reg) { REQUIRE_ATTRIBUTES(parameters, "tag", "values", "sampling_method", "nsamples", "selection"); std::string full_name(""); std::string description(""); GenericDataType type = M_INTEGER; WhenType editable = M_ALWAYS; // when can we edit the variable bool viewable = true; // can the user see this variable bool persistant = false; // save the variable from run to run WhenType logging = M_WHEN_CHANGED; // when does this variable get logged Datum defaultValue(0L); // the default value Datum object. std::string groups(""); string tag(parameters.find("tag")->second); if(parameters.find("full_name") != parameters.end()) { full_name = parameters.find("full_name")->second; } if(parameters.find("description") != parameters.end()) { description = parameters.find("description")->second; } string type_lower = to_lower_copy(parameters.find("type")->second); if(type_lower == "integer") { type = M_INTEGER; defaultValue = 0L; } else if(type_lower == "float" || type_lower == "double") { type = M_FLOAT; defaultValue = 0.0; } else if(type_lower == "string") { type = M_STRING; defaultValue = ""; } else if(type_lower == "boolean") { type = M_BOOLEAN; defaultValue = false; } else if(type_lower == "selection"){ type = M_UNDEFINED; defaultValue = 0L; } else { throw InvalidAttributeException(parameters["reference_id"], "type", parameters.find("type")->second); } // TODO...when changed? if(parameters.find("editable") != parameters.end()){ string editable_lower = to_lower_copy(parameters.find("editable")->second); if(editable_lower == "never") { editable = M_NEVER; } else if(editable_lower == "when_idle") { editable = M_WHEN_IDLE; } else if(editable_lower == "always") { editable = M_ALWAYS; } else if(editable_lower == "at_startup") { editable = M_AT_STARTUP; } else if(editable_lower == "every_trial") { editable = M_EVERY_TRIAL; } else if(editable_lower == "when_changed") { editable = M_WHEN_CHANGED; } else { throw InvalidAttributeException(parameters["reference_id"], "editable", parameters.find("editable")->second); } } else { editable = M_NEVER; } if(parameters.find("viewable") != parameters.end()){ try { viewable = reg->getBoolean(parameters.find("viewable")->second); } catch (boost::bad_lexical_cast &) { throw InvalidAttributeException(parameters["reference_id"], "viewable", parameters.find("viewable")->second); } } else { viewable = true; } if(parameters.find("persistant") != parameters.end()){ try { persistant = boost::lexical_cast<bool>(parameters.find("persistant")->second); } catch (boost::bad_lexical_cast &) { throw InvalidAttributeException(parameters["reference_id"], "persistant", parameters.find("persistant")->second); } } else { persistant = false; } if(parameters.find("logging") != parameters.end()){ string logging_lower = to_lower_copy(parameters.find("logging")->second); if(logging_lower == "never") { logging = M_NEVER; } else if(logging_lower == "when_idle") { logging = M_WHEN_IDLE; } else if(logging_lower == "always") { logging = M_ALWAYS; } else if(logging_lower == "at_startup") { logging = M_AT_STARTUP; } else if(logging_lower == "every_trial") { logging = M_EVERY_TRIAL; } else if(logging_lower == "when_changed") { logging = M_WHEN_CHANGED; } else { throw InvalidAttributeException(parameters["reference_id"], "logging", parameters.find("logging")->second); } } else { logging = M_ALWAYS; } /* switch(type) { case M_INTEGER: case M_FLOAT: case M_BOOLEAN: try { defaultValue = Datum(type, boost::lexical_cast<float>(parameters.find("default_value")->second)); } catch (bad_lexical_cast &) { throw InvalidAttributeException("default_value", parameters.find("default_value")->second); } break; case M_STRING: defaultValue = Datum(parameters.find("default_value")->second); break; default: throw InvalidAttributeException("default_value", parameters.find("default_value")->second); break; }*/ if(parameters.find("groups") != parameters.end()) { groups = parameters.find("groups")->second; } // TODO when the variable properties get fixed, we can get rid of this nonsense VariableProperties props(&defaultValue, tag, full_name, description, M_ALWAYS, M_WHEN_CHANGED, true, false, M_INTEGER_INFINITE, std::string("")); boost::shared_ptr<SelectionVariable>selectionVar; selectionVar = global_variable_registry->createSelectionVariable(&props); // get the values std::vector<stx::AnyScalar> values; ParsedExpressionVariable::evaluateExpressionList(parameters["values"], values); // get the sampling method std::map<std::string, std::string>::const_iterator samplingMethodElement = parameters.find("sampling_method"); if(samplingMethodElement == parameters.end()) { throw; } // get the number of samples unsigned int numSamples = 0; try { numSamples = boost::lexical_cast< unsigned int >( parameters.find("nsamples")->second ); } catch (boost::bad_lexical_cast &) { throw InvalidAttributeException(parameters["reference_id"], "nsamples", parameters.find("nsamples")->second); } // if it's cycles, multiply by the number of elements in the possible values if(to_lower_copy(parameters.find("sampling_method")->second) == "cycles") { numSamples *= values.size(); } else if(to_lower_copy(parameters.find("sampling_method")->second) == "samples") { // do nothing } else { throw InvalidAttributeException(parameters["reference_id"], "sampling_method", parameters.find("sampling_method")->second); } bool autoreset_behavior = false; string autoreset_value = parameters["autoreset"]; if(!autoreset_value.empty()){ boost::algorithm::to_lower(autoreset_value); if(autoreset_value == "yes" || autoreset_value == "1" || autoreset_value == "true"){ autoreset_behavior = true; } } // get the selection type shared_ptr<Selection> selection; if(to_lower_copy(parameters.find("selection")->second) == "sequential_ascending") { selection = shared_ptr<SequentialSelection>(new SequentialSelection(numSamples, true, autoreset_behavior)); } else if(to_lower_copy(parameters.find("selection")->second) == "sequential_descending") { selection = shared_ptr<SequentialSelection>(new SequentialSelection(numSamples, false, autoreset_behavior)); } else if(to_lower_copy(parameters.find("selection")->second) == "random_without_replacement") { selection = shared_ptr<RandomWORSelection>(new RandomWORSelection(numSamples, autoreset_behavior)); } else if(to_lower_copy(parameters.find("selection")->second) == "random_with_replacement") { selection = shared_ptr<RandomWithReplacementSelection>(new RandomWithReplacementSelection(numSamples, autoreset_behavior)); } else { throw InvalidAttributeException(parameters["reference_id"], "selection", parameters.find("selection")->second); } selectionVar->attachSelection(selection); for(std::vector<stx::AnyScalar>::const_iterator i = values.begin(); i != values.end(); ++i) { selectionVar->addValue(Datum(*i)); } return selectionVar; } END_NAMESPACE_MW <commit_msg>Fixed a broken selection variable unit test<commit_after>/* * SelectionVariable.cpp * MWorksCore * * Created by David Cox on 3/1/06. * Copyright 2006 MIT. All rights reserved. * */ #include "SelectionVariable.h" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/case_conv.hpp> #include "VariableReference.h" #include "VariableProperties.h" #include "VariableRegistry.h" #include "SequentialSelection.h" #include "RandomWORSelection.h" #include "RandomWithReplacementSelection.h" #include "ComponentRegistry.h" #include "ExpressionVariable.h" using boost::algorithm::to_lower_copy; BEGIN_NAMESPACE_MW SelectionVariable::SelectionVariable(VariableProperties *props, shared_ptr<Selection> _selection) : Selectable(), Variable(props), selected_index(NO_SELECTION) { if (_selection) { attachSelection(_selection); } } Datum SelectionVariable::getTentativeSelection(int index) { if (!selection) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Internal error: selection variable has no selection attached"); return Datum(0L); } const std::vector<int>& tenativeSelections = selection->getTentativeSelections(); if (tenativeSelections.size() == 0) { // Issue an error message only if the experiment is running. Otherwise, all selection variable indexing // expressions will produce load-time errors (since ParsedExpressionVariable's constructors evaluate the // expression to test for validity). if (StateSystem::instance(false) && StateSystem::instance()->isRunning()) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Selection variable has no tentative selections available. Returning 0."); } return Datum(0L); } if ((index < 0) || (index >= tenativeSelections.size())) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Selection variable index (%d) is out of bounds. Returning 0.", index); return Datum(0L); } return values[tenativeSelections[index]]; } void SelectionVariable::nextValue() { if (selection != NULL) { try { selected_index = selection->draw(); } catch (std::exception &e) { merror(M_PARADIGM_MESSAGE_DOMAIN, "%s", e.what()); return; } // announce your new value so that the event stream contains // all information about what happened in the experiment announce(); performNotifications(values[selected_index]); } else { merror(M_PARADIGM_MESSAGE_DOMAIN, "Attempt to advance a selection variable with a NULL selection"); } } Datum SelectionVariable::getValue() { if (selected_index == NO_SELECTION) { nextValue(); } if (selected_index == NO_SELECTION) { merror(M_PARADIGM_MESSAGE_DOMAIN, "Attempt to select a value from a selection variable with no values defined"); return Datum(0L); } return values[selected_index]; } Variable *SelectionVariable::clone(){ // This isn't quite right, but we can run with it for now return new VariableReference(this); } shared_ptr<mw::Component> SelectionVariableFactory::createObject(std::map<std::string, std::string> parameters, ComponentRegistry *reg) { REQUIRE_ATTRIBUTES(parameters, "tag", "values", "sampling_method", "nsamples", "selection"); std::string full_name(""); std::string description(""); GenericDataType type = M_INTEGER; WhenType editable = M_ALWAYS; // when can we edit the variable bool viewable = true; // can the user see this variable bool persistant = false; // save the variable from run to run WhenType logging = M_WHEN_CHANGED; // when does this variable get logged Datum defaultValue(0L); // the default value Datum object. std::string groups(""); string tag(parameters.find("tag")->second); if(parameters.find("full_name") != parameters.end()) { full_name = parameters.find("full_name")->second; } if(parameters.find("description") != parameters.end()) { description = parameters.find("description")->second; } string type_lower = to_lower_copy(parameters.find("type")->second); if(type_lower == "integer") { type = M_INTEGER; defaultValue = 0L; } else if(type_lower == "float" || type_lower == "double") { type = M_FLOAT; defaultValue = 0.0; } else if(type_lower == "string") { type = M_STRING; defaultValue = ""; } else if(type_lower == "boolean") { type = M_BOOLEAN; defaultValue = false; } else if(type_lower == "selection"){ type = M_UNDEFINED; defaultValue = 0L; } else { throw InvalidAttributeException(parameters["reference_id"], "type", parameters.find("type")->second); } // TODO...when changed? if(parameters.find("editable") != parameters.end()){ string editable_lower = to_lower_copy(parameters.find("editable")->second); if(editable_lower == "never") { editable = M_NEVER; } else if(editable_lower == "when_idle") { editable = M_WHEN_IDLE; } else if(editable_lower == "always") { editable = M_ALWAYS; } else if(editable_lower == "at_startup") { editable = M_AT_STARTUP; } else if(editable_lower == "every_trial") { editable = M_EVERY_TRIAL; } else if(editable_lower == "when_changed") { editable = M_WHEN_CHANGED; } else { throw InvalidAttributeException(parameters["reference_id"], "editable", parameters.find("editable")->second); } } else { editable = M_NEVER; } if(parameters.find("viewable") != parameters.end()){ try { viewable = reg->getBoolean(parameters.find("viewable")->second); } catch (boost::bad_lexical_cast &) { throw InvalidAttributeException(parameters["reference_id"], "viewable", parameters.find("viewable")->second); } } else { viewable = true; } if(parameters.find("persistant") != parameters.end()){ try { persistant = boost::lexical_cast<bool>(parameters.find("persistant")->second); } catch (boost::bad_lexical_cast &) { throw InvalidAttributeException(parameters["reference_id"], "persistant", parameters.find("persistant")->second); } } else { persistant = false; } if(parameters.find("logging") != parameters.end()){ string logging_lower = to_lower_copy(parameters.find("logging")->second); if(logging_lower == "never") { logging = M_NEVER; } else if(logging_lower == "when_idle") { logging = M_WHEN_IDLE; } else if(logging_lower == "always") { logging = M_ALWAYS; } else if(logging_lower == "at_startup") { logging = M_AT_STARTUP; } else if(logging_lower == "every_trial") { logging = M_EVERY_TRIAL; } else if(logging_lower == "when_changed") { logging = M_WHEN_CHANGED; } else { throw InvalidAttributeException(parameters["reference_id"], "logging", parameters.find("logging")->second); } } else { logging = M_ALWAYS; } /* switch(type) { case M_INTEGER: case M_FLOAT: case M_BOOLEAN: try { defaultValue = Datum(type, boost::lexical_cast<float>(parameters.find("default_value")->second)); } catch (bad_lexical_cast &) { throw InvalidAttributeException("default_value", parameters.find("default_value")->second); } break; case M_STRING: defaultValue = Datum(parameters.find("default_value")->second); break; default: throw InvalidAttributeException("default_value", parameters.find("default_value")->second); break; }*/ if(parameters.find("groups") != parameters.end()) { groups = parameters.find("groups")->second; } // TODO when the variable properties get fixed, we can get rid of this nonsense VariableProperties props(&defaultValue, tag, full_name, description, M_ALWAYS, M_WHEN_CHANGED, true, false, M_INTEGER_INFINITE, std::string("")); boost::shared_ptr<SelectionVariable>selectionVar; selectionVar = global_variable_registry->createSelectionVariable(&props); // get the values std::vector<stx::AnyScalar> values; ParsedExpressionVariable::evaluateExpressionList(parameters["values"], values); // get the sampling method std::map<std::string, std::string>::const_iterator samplingMethodElement = parameters.find("sampling_method"); if(samplingMethodElement == parameters.end()) { throw; } // get the number of samples unsigned int numSamples = 0; try { numSamples = boost::lexical_cast< unsigned int >( parameters.find("nsamples")->second ); } catch (boost::bad_lexical_cast &) { throw InvalidAttributeException(parameters["reference_id"], "nsamples", parameters.find("nsamples")->second); } // if it's cycles, multiply by the number of elements in the possible values if(to_lower_copy(parameters.find("sampling_method")->second) == "cycles") { numSamples *= values.size(); } else if(to_lower_copy(parameters.find("sampling_method")->second) == "samples") { // do nothing } else { throw InvalidAttributeException(parameters["reference_id"], "sampling_method", parameters.find("sampling_method")->second); } bool autoreset_behavior = false; string autoreset_value = parameters["autoreset"]; if(!autoreset_value.empty()){ boost::algorithm::to_lower(autoreset_value); if(autoreset_value == "yes" || autoreset_value == "1" || autoreset_value == "true"){ autoreset_behavior = true; } } // get the selection type shared_ptr<Selection> selection; if(to_lower_copy(parameters.find("selection")->second) == "sequential_ascending") { selection = shared_ptr<SequentialSelection>(new SequentialSelection(numSamples, true, autoreset_behavior)); } else if(to_lower_copy(parameters.find("selection")->second) == "sequential_descending") { selection = shared_ptr<SequentialSelection>(new SequentialSelection(numSamples, false, autoreset_behavior)); } else if(to_lower_copy(parameters.find("selection")->second) == "random_without_replacement") { selection = shared_ptr<RandomWORSelection>(new RandomWORSelection(numSamples, autoreset_behavior)); } else if(to_lower_copy(parameters.find("selection")->second) == "random_with_replacement") { selection = shared_ptr<RandomWithReplacementSelection>(new RandomWithReplacementSelection(numSamples, autoreset_behavior)); } else { throw InvalidAttributeException(parameters["reference_id"], "selection", parameters.find("selection")->second); } selectionVar->attachSelection(selection); for(std::vector<stx::AnyScalar>::const_iterator i = values.begin(); i != values.end(); ++i) { selectionVar->addValue(Datum(*i)); } return selectionVar; } END_NAMESPACE_MW <|endoftext|>
<commit_before>/** * @file ReactorFactory.cpp */ // Copyright 2006 California Institute of Technology #include "cantera/zeroD/ReactorFactory.h" #include "cantera/zeroD/Reservoir.h" #include "cantera/zeroD/Reactor.h" #include "cantera/zeroD/FlowReactor.h" #include "cantera/zeroD/ConstPressureReactor.h" using namespace std; namespace Cantera { ReactorFactory* ReactorFactory::s_factory = 0; mutex_t ReactorFactory::reactor_mutex; static int ntypes = 4; static string _types[] = {"Reservoir", "Reactor", "ConstPressureReactor", "FlowReactor" }; // these constants are defined in ReactorBase.h static int _itypes[] = {ReservoirType, ReactorType, FlowReactorType, ConstPressureReactorType }; /** * This method returns a new instance of a subclass of ThermoPhase */ ReactorBase* ReactorFactory::newReactor(string reactorType) { int ir=-1; for (int n = 0; n < ntypes; n++) { if (reactorType == _types[n]) { ir = _itypes[n]; } } return newReactor(ir); } ReactorBase* ReactorFactory::newReactor(int ir) { switch (ir) { case ReservoirType: return new Reservoir(); case ReactorType: return new Reactor(); case FlowReactorType: return new FlowReactor(); case ConstPressureReactorType: return new ConstPressureReactor(); default: throw Cantera::CanteraError("ReactorFactory::newReactor", "unknown reactor type!"); } return 0; } } <commit_msg>Fixed correspondence of reactor type string names to integer constants<commit_after>/** * @file ReactorFactory.cpp */ // Copyright 2006 California Institute of Technology #include "cantera/zeroD/ReactorFactory.h" #include "cantera/zeroD/Reservoir.h" #include "cantera/zeroD/Reactor.h" #include "cantera/zeroD/FlowReactor.h" #include "cantera/zeroD/ConstPressureReactor.h" using namespace std; namespace Cantera { ReactorFactory* ReactorFactory::s_factory = 0; mutex_t ReactorFactory::reactor_mutex; static int ntypes = 4; static string _types[] = {"Reservoir", "Reactor", "ConstPressureReactor", "FlowReactor" }; // these constants are defined in ReactorBase.h static int _itypes[] = {ReservoirType, ReactorType, ConstPressureReactorType, FlowReactorType }; /** * This method returns a new instance of a subclass of ThermoPhase */ ReactorBase* ReactorFactory::newReactor(string reactorType) { int ir=-1; for (int n = 0; n < ntypes; n++) { if (reactorType == _types[n]) { ir = _itypes[n]; } } return newReactor(ir); } ReactorBase* ReactorFactory::newReactor(int ir) { switch (ir) { case ReservoirType: return new Reservoir(); case ReactorType: return new Reactor(); case FlowReactorType: return new FlowReactor(); case ConstPressureReactorType: return new ConstPressureReactor(); default: throw Cantera::CanteraError("ReactorFactory::newReactor", "unknown reactor type!"); } return 0; } } <|endoftext|>
<commit_before> /** * @file /home/ryan/programming/atl/test/test_parser.cpp * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu> * Created on Dec 16, 2014 */ #include <gtest/gtest.h> #include "../atl.hpp" #include "../helpers.hpp" #include "../debug.hpp" #include <iostream> #include <vector> using namespace atl; using namespace std; struct ParserTest : public ::testing::Test { Atl atl; }; TEST_F(ParserTest, Atoms) { ASSERT_EQ(unwrap<Fixnum>(atl.parse.string_("2")).value, 2); ASSERT_EQ(unwrap<String>(atl.parse.string_("\"Hello, world!\"")).value, "Hello, world!"); } TEST_F(ParserTest, SimpleIntList) { auto parsed = atl.parse.string_("(1 2 3)"); auto ast = flat_iterator::range(parsed); auto expected = vector<Any>{ wrap(1), wrap(2), wrap(3) }; for(auto& vv : zip(ast, expected)) { #ifdef DEBUGGING cout << "parsed: " << printer::any(*get<0>(vv)) << "\nexpected: " << printer::any(*get<1>(vv)) << endl; #endif ASSERT_EQ(*get<0>(vv), *get<1>(vv)); } } TEST_F(ParserTest, NestedIntList) { auto parsed = atl.parse.string_("(1 2 (4 5) 3)"); auto ast = flat_iterator::range(parsed); auto begin = unwrap<Ast>(parsed).value; auto expected = vector<Any>{ wrap(1), wrap(2), begin[3], Any(tag<Any>::value, begin + 7), // the pointer to the end of '(4 5) wrap(4), wrap(5), wrap(3) }; for(auto& vv : zip(ast, expected)) { #ifdef DEBUGGING cout << "parsed: " << printer::any(*get<0>(vv)) << "\nexpected: " << printer::any(*get<1>(vv)) << endl; #endif ASSERT_EQ(*get<0>(vv), *get<1>(vv)); } } TEST_F(ParserTest, TestQuote) { auto parsed = atl.parse.string_("'(2 3)"); auto ast = flat_iterator::range(parsed); auto begin = unwrap<Ast>(parsed).value; vector<Any> expected = vector<Any>{ Any(tag<Quote>::value), begin[2], // the (pointer to point to end of) quoted list Any(tag<Any>::value, begin + 6), // end of quoted list wrap(2), wrap(3) }; for(auto& vv : zip(ast, expected)) { #ifdef DEBUGGING cout << "parsed: " << printer::any(*get<0>(vv)) << "\nexpected: " << printer::any(*get<1>(vv)) << endl; #endif ASSERT_EQ(*get<0>(vv), *get<1>(vv)); } } TEST_F(ParserTest, TestLambda) { // I'm making '[[:delim:]]\[[:delim:]]' a reserved symbol for lambda, make sure it's parsed correctly. auto parsed = atl.parse.string_("(\\ (a b) (c d e))"); tag_t linkable = tag<Lambda>::value; ASSERT_EQ(unwrap<Ast>(parsed)[0]._tag, linkable); parsed = atl.parse.string_("(\\a b\\)"); linkable = tag<Symbol>::value; ASSERT_EQ(unwrap<Ast>(parsed)[0]._tag, linkable); ASSERT_EQ(unwrap<Ast>(parsed)[1]._tag, linkable); } TEST_F(ParserTest, TestLet) { auto parsed = atl.parse.string_("(let (a b) (a 1 2))"); tag_t let_tag = tag<Let>::value; ASSERT_EQ(unwrap<Ast>(parsed)[0]._tag, let_tag); } <commit_msg>Test stream parsing<commit_after> /** * @file /home/ryan/programming/atl/test/test_parser.cpp * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu> * Created on Dec 16, 2014 */ #include <gtest/gtest.h> #include "../atl.hpp" #include "../helpers.hpp" #include "../debug.hpp" #include <iostream> #include <vector> #include <sstream> using namespace atl; using namespace std; struct ParserTest : public ::testing::Test { Atl atl; }; TEST_F(ParserTest, Atoms) { ASSERT_EQ(unwrap<Fixnum>(atl.parse.string_("2")).value, 2); ASSERT_EQ(unwrap<String>(atl.parse.string_("\"Hello, world!\"")).value, "Hello, world!"); } TEST_F(ParserTest, SimpleIntList) { auto parsed = atl.parse.string_("(1 2 3)"); auto ast = flat_iterator::range(parsed); auto expected = vector<Any>{ wrap(1), wrap(2), wrap(3) }; for(auto& vv : zip(ast, expected)) { #ifdef DEBUGGING cout << "parsed: " << printer::any(*get<0>(vv)) << "\nexpected: " << printer::any(*get<1>(vv)) << endl; #endif ASSERT_EQ(*get<0>(vv), *get<1>(vv)); } } TEST_F(ParserTest, NestedIntList) { auto parsed = atl.parse.string_("(1 2 (4 5) 3)"); auto ast = flat_iterator::range(parsed); auto begin = unwrap<Ast>(parsed).value; auto expected = vector<Any>{ wrap(1), wrap(2), begin[3], Any(tag<Any>::value, begin + 7), // the pointer to the end of '(4 5) wrap(4), wrap(5), wrap(3) }; for(auto& vv : zip(ast, expected)) { #ifdef DEBUGGING cout << "parsed: " << printer::any(*get<0>(vv)) << "\nexpected: " << printer::any(*get<1>(vv)) << endl; #endif ASSERT_EQ(*get<0>(vv), *get<1>(vv)); } } TEST_F(ParserTest, TestQuote) { auto parsed = atl.parse.string_("'(2 3)"); auto ast = flat_iterator::range(parsed); auto begin = unwrap<Ast>(parsed).value; vector<Any> expected = vector<Any>{ Any(tag<Quote>::value), begin[2], // the (pointer to point to end of) quoted list Any(tag<Any>::value, begin + 6), // end of quoted list wrap(2), wrap(3) }; for(auto& vv : zip(ast, expected)) { #ifdef DEBUGGING cout << "parsed: " << printer::any(*get<0>(vv)) << "\nexpected: " << printer::any(*get<1>(vv)) << endl; #endif ASSERT_EQ(*get<0>(vv), *get<1>(vv)); } } TEST_F(ParserTest, TestLambda) { // I'm making '[[:delim:]]\[[:delim:]]' a reserved symbol for lambda, make sure it's parsed correctly. auto parsed = atl.parse.string_("(\\ (a b) (c d e))"); tag_t linkable = tag<Lambda>::value; ASSERT_EQ(unwrap<Ast>(parsed)[0]._tag, linkable); parsed = atl.parse.string_("(\\a b\\)"); linkable = tag<Symbol>::value; ASSERT_EQ(unwrap<Ast>(parsed)[0]._tag, linkable); ASSERT_EQ(unwrap<Ast>(parsed)[1]._tag, linkable); } TEST_F(ParserTest, TestLet) { auto parsed = atl.parse.string_("(let (a b) (a 1 2))"); tag_t let_tag = tag<Let>::value; ASSERT_EQ(unwrap<Ast>(parsed)[0]._tag, let_tag); } TEST_F(ParserTest, test_stream_parsing) { string contents = "(a b c)"; stringstream as_stream(contents); auto a = unwrap<Ast>(atl.parse.string_(contents)); auto b = unwrap<Ast>(atl.parse.stream(as_stream)); for(auto& vv : zip(a, b)) ASSERT_EQ(unwrap<Symbol>(*get<0>(vv)).name, unwrap<Symbol>(*get<1>(vv)).name); } <|endoftext|>
<commit_before><commit_msg>prefer OUStringBuffer to concatenating OUString in a loop<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/renderer/atom_sandboxed_renderer_client.h" #include <string> #include "atom/common/api/api_messages.h" #include "atom/common/api/atom_bindings.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/v8_value_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/options_switches.h" #include "atom/renderer/api/atom_api_renderer_ipc.h" #include "atom/renderer/atom_render_view_observer.h" #include "base/command_line.h" #include "chrome/renderer/printing/print_web_view_helper.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_observer.h" #include "ipc/ipc_message_macros.h" #include "native_mate/converter.h" #include "native_mate/dictionary.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebView.h" #include "atom/common/node_includes.h" #include "atom_natives.h" // NOLINT: This file is generated with js2c namespace atom { namespace { const std::string kIpcKey = "ipcNative"; const std::string kModuleCacheKey = "native-module-cache"; v8::Local<v8::Object> GetModuleCache(v8::Isolate* isolate) { mate::Dictionary global(isolate, isolate->GetCurrentContext()->Global()); v8::Local<v8::Value> cache; if (!global.GetHidden(kModuleCacheKey, &cache)) { cache = v8::Object::New(isolate); global.SetHidden(kModuleCacheKey, cache); } return cache->ToObject(); } // adapted from node.cc v8::Local<v8::Value> GetBinding(v8::Isolate* isolate, v8::Local<v8::String> key, mate::Arguments* margs) { v8::Local<v8::Object> exports; std::string module_key = mate::V8ToString(key); mate::Dictionary cache(isolate, GetModuleCache(isolate)); if (cache.Get(module_key.c_str(), &exports)) { return exports; } auto mod = node::get_builtin_module(module_key.c_str()); if (!mod) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_key.c_str()); margs->ThrowError(errmsg); return exports; } exports = v8::Object::New(isolate); DCHECK_EQ(mod->nm_register_func, nullptr); DCHECK_NE(mod->nm_context_register_func, nullptr); mod->nm_context_register_func(exports, v8::Null(isolate), isolate->GetCurrentContext(), mod->nm_priv); cache.Set(module_key.c_str(), exports); return exports; } base::CommandLine::StringVector GetArgv() { return base::CommandLine::ForCurrentProcess()->argv(); } void InitializeBindings(v8::Local<v8::Object> binding, v8::Local<v8::Context> context) { auto isolate = context->GetIsolate(); mate::Dictionary b(isolate, binding); b.SetMethod("get", GetBinding); b.SetMethod("crash", AtomBindings::Crash); b.SetMethod("hang", AtomBindings::Hang); b.SetMethod("getArgv", GetArgv); b.SetMethod("getProcessMemoryInfo", &AtomBindings::GetProcessMemoryInfo); b.SetMethod("getSystemMemoryInfo", &AtomBindings::GetSystemMemoryInfo); } class AtomSandboxedRenderViewObserver : public AtomRenderViewObserver { public: AtomSandboxedRenderViewObserver(content::RenderView* render_view, AtomSandboxedRendererClient* renderer_client) : AtomRenderViewObserver(render_view, nullptr), v8_converter_(new atom::V8ValueConverter), renderer_client_(renderer_client) { v8_converter_->SetDisableNode(true); } protected: void EmitIPCEvent(blink::WebFrame* frame, const base::string16& channel, const base::ListValue& args) override { if (!frame || frame->isWebRemoteFrame()) return; auto isolate = blink::mainThreadIsolate(); v8::HandleScope handle_scope(isolate); auto context = frame->mainWorldScriptContext(); v8::Context::Scope context_scope(context); v8::Local<v8::Value> argv[] = { mate::ConvertToV8(isolate, channel), v8_converter_->ToV8Value(&args, context) }; renderer_client_->InvokeIpcCallback( context, "onMessage", std::vector<v8::Local<v8::Value>>(argv, argv + 2)); } private: std::unique_ptr<atom::V8ValueConverter> v8_converter_; AtomSandboxedRendererClient* renderer_client_; DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRenderViewObserver); }; } // namespace AtomSandboxedRendererClient::AtomSandboxedRendererClient() { } AtomSandboxedRendererClient::~AtomSandboxedRendererClient() { } void AtomSandboxedRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { RendererClientBase::RenderFrameCreated(render_frame); } void AtomSandboxedRendererClient::RenderViewCreated( content::RenderView* render_view) { new AtomSandboxedRenderViewObserver(render_view, this); RendererClientBase::RenderViewCreated(render_view); } void AtomSandboxedRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string preload_script = command_line->GetSwitchValueASCII( switches::kPreloadScript); if (preload_script.empty()) return; auto isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); // Wrap the bundle into a function that receives the binding object and the // preload script path as arguments. std::string preload_bundle_native(node::preload_bundle_data, node::preload_bundle_data + sizeof(node::preload_bundle_data)); std::stringstream ss; ss << "(function(binding, preloadPath, require) {\n"; ss << preload_bundle_native << "\n"; ss << "})"; std::string preload_wrapper = ss.str(); // Compile the wrapper and run it to get the function object auto script = v8::Script::Compile( mate::ConvertToV8(isolate, preload_wrapper)->ToString()); auto func = v8::Handle<v8::Function>::Cast( script->Run(context).ToLocalChecked()); // Create and initialize the binding object auto binding = v8::Object::New(isolate); InitializeBindings(binding, context); AddRenderBindings(isolate, binding); v8::Local<v8::Value> args[] = { binding, mate::ConvertToV8(isolate, preload_script) }; // Execute the function with proper arguments ignore_result(func->Call(context, v8::Null(isolate), 2, args)); } void AtomSandboxedRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { auto isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); InvokeIpcCallback(context, "onExit", std::vector<v8::Local<v8::Value>>()); } void AtomSandboxedRendererClient::InvokeIpcCallback( v8::Handle<v8::Context> context, const std::string& callback_name, std::vector<v8::Handle<v8::Value>> args) { auto isolate = context->GetIsolate(); auto binding_key = mate::ConvertToV8(isolate, kIpcKey)->ToString(); auto private_binding_key = v8::Private::ForApi(isolate, binding_key); auto global_object = context->Global(); v8::Local<v8::Value> value; if (!global_object->GetPrivate(context, private_binding_key).ToLocal(&value)) return; if (value.IsEmpty() || !value->IsObject()) return; auto binding = value->ToObject(); auto callback_key = mate::ConvertToV8(isolate, callback_name)->ToString(); auto callback_value = binding->Get(callback_key); DCHECK(callback_value->IsFunction()); // set by sandboxed_renderer/init.js auto callback = v8::Handle<v8::Function>::Cast(callback_value); ignore_result(callback->Call(context, binding, args.size(), &args[0])); } } // namespace atom <commit_msg>Fixed invalid empty vector subscript access<commit_after>// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/renderer/atom_sandboxed_renderer_client.h" #include <string> #include "atom/common/api/api_messages.h" #include "atom/common/api/atom_bindings.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/v8_value_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/options_switches.h" #include "atom/renderer/api/atom_api_renderer_ipc.h" #include "atom/renderer/atom_render_view_observer.h" #include "base/command_line.h" #include "chrome/renderer/printing/print_web_view_helper.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_observer.h" #include "ipc/ipc_message_macros.h" #include "native_mate/converter.h" #include "native_mate/dictionary.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebView.h" #include "atom/common/node_includes.h" #include "atom_natives.h" // NOLINT: This file is generated with js2c namespace atom { namespace { const std::string kIpcKey = "ipcNative"; const std::string kModuleCacheKey = "native-module-cache"; v8::Local<v8::Object> GetModuleCache(v8::Isolate* isolate) { mate::Dictionary global(isolate, isolate->GetCurrentContext()->Global()); v8::Local<v8::Value> cache; if (!global.GetHidden(kModuleCacheKey, &cache)) { cache = v8::Object::New(isolate); global.SetHidden(kModuleCacheKey, cache); } return cache->ToObject(); } // adapted from node.cc v8::Local<v8::Value> GetBinding(v8::Isolate* isolate, v8::Local<v8::String> key, mate::Arguments* margs) { v8::Local<v8::Object> exports; std::string module_key = mate::V8ToString(key); mate::Dictionary cache(isolate, GetModuleCache(isolate)); if (cache.Get(module_key.c_str(), &exports)) { return exports; } auto mod = node::get_builtin_module(module_key.c_str()); if (!mod) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_key.c_str()); margs->ThrowError(errmsg); return exports; } exports = v8::Object::New(isolate); DCHECK_EQ(mod->nm_register_func, nullptr); DCHECK_NE(mod->nm_context_register_func, nullptr); mod->nm_context_register_func(exports, v8::Null(isolate), isolate->GetCurrentContext(), mod->nm_priv); cache.Set(module_key.c_str(), exports); return exports; } base::CommandLine::StringVector GetArgv() { return base::CommandLine::ForCurrentProcess()->argv(); } void InitializeBindings(v8::Local<v8::Object> binding, v8::Local<v8::Context> context) { auto isolate = context->GetIsolate(); mate::Dictionary b(isolate, binding); b.SetMethod("get", GetBinding); b.SetMethod("crash", AtomBindings::Crash); b.SetMethod("hang", AtomBindings::Hang); b.SetMethod("getArgv", GetArgv); b.SetMethod("getProcessMemoryInfo", &AtomBindings::GetProcessMemoryInfo); b.SetMethod("getSystemMemoryInfo", &AtomBindings::GetSystemMemoryInfo); } class AtomSandboxedRenderViewObserver : public AtomRenderViewObserver { public: AtomSandboxedRenderViewObserver(content::RenderView* render_view, AtomSandboxedRendererClient* renderer_client) : AtomRenderViewObserver(render_view, nullptr), v8_converter_(new atom::V8ValueConverter), renderer_client_(renderer_client) { v8_converter_->SetDisableNode(true); } protected: void EmitIPCEvent(blink::WebFrame* frame, const base::string16& channel, const base::ListValue& args) override { if (!frame || frame->isWebRemoteFrame()) return; auto isolate = blink::mainThreadIsolate(); v8::HandleScope handle_scope(isolate); auto context = frame->mainWorldScriptContext(); v8::Context::Scope context_scope(context); v8::Local<v8::Value> argv[] = { mate::ConvertToV8(isolate, channel), v8_converter_->ToV8Value(&args, context) }; renderer_client_->InvokeIpcCallback( context, "onMessage", std::vector<v8::Local<v8::Value>>(argv, argv + 2)); } private: std::unique_ptr<atom::V8ValueConverter> v8_converter_; AtomSandboxedRendererClient* renderer_client_; DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRenderViewObserver); }; } // namespace AtomSandboxedRendererClient::AtomSandboxedRendererClient() { } AtomSandboxedRendererClient::~AtomSandboxedRendererClient() { } void AtomSandboxedRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { RendererClientBase::RenderFrameCreated(render_frame); } void AtomSandboxedRendererClient::RenderViewCreated( content::RenderView* render_view) { new AtomSandboxedRenderViewObserver(render_view, this); RendererClientBase::RenderViewCreated(render_view); } void AtomSandboxedRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string preload_script = command_line->GetSwitchValueASCII( switches::kPreloadScript); if (preload_script.empty()) return; auto isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); // Wrap the bundle into a function that receives the binding object and the // preload script path as arguments. std::string preload_bundle_native(node::preload_bundle_data, node::preload_bundle_data + sizeof(node::preload_bundle_data)); std::stringstream ss; ss << "(function(binding, preloadPath, require) {\n"; ss << preload_bundle_native << "\n"; ss << "})"; std::string preload_wrapper = ss.str(); // Compile the wrapper and run it to get the function object auto script = v8::Script::Compile( mate::ConvertToV8(isolate, preload_wrapper)->ToString()); auto func = v8::Handle<v8::Function>::Cast( script->Run(context).ToLocalChecked()); // Create and initialize the binding object auto binding = v8::Object::New(isolate); InitializeBindings(binding, context); AddRenderBindings(isolate, binding); v8::Local<v8::Value> args[] = { binding, mate::ConvertToV8(isolate, preload_script) }; // Execute the function with proper arguments ignore_result(func->Call(context, v8::Null(isolate), 2, args)); } void AtomSandboxedRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { auto isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context); InvokeIpcCallback(context, "onExit", std::vector<v8::Local<v8::Value>>()); } void AtomSandboxedRendererClient::InvokeIpcCallback( v8::Handle<v8::Context> context, const std::string& callback_name, std::vector<v8::Handle<v8::Value>> args) { auto isolate = context->GetIsolate(); auto binding_key = mate::ConvertToV8(isolate, kIpcKey)->ToString(); auto private_binding_key = v8::Private::ForApi(isolate, binding_key); auto global_object = context->Global(); v8::Local<v8::Value> value; if (!global_object->GetPrivate(context, private_binding_key).ToLocal(&value)) return; if (value.IsEmpty() || !value->IsObject()) return; auto binding = value->ToObject(); auto callback_key = mate::ConvertToV8(isolate, callback_name)->ToString(); auto callback_value = binding->Get(callback_key); DCHECK(callback_value->IsFunction()); // set by sandboxed_renderer/init.js auto callback = v8::Handle<v8::Function>::Cast(callback_value); ignore_result(callback->Call(context, binding, args.size(), args.data())); } } // namespace atom <|endoftext|>
<commit_before>#include <functional> #include "test_helpers.hxx" using namespace std; using namespace pqxx; // Test program for libpqxx. Verify abort behaviour of RobustTransaction. // // The program will attempt to add an entry to a table called "pqxxevents", // with a key column called "year"--and then abort the change. namespace { // Let's take a boring year that is not going to be in the "pqxxevents" table const long BoringYear = 1977; // Count events and specifically events occurring in Boring Year, leaving the // former count in the result pair's first member, and the latter in second. pair<int, int> count_events(connection_base &C, string table) { nontransaction tx{C}; const string CountQuery = "SELECT count(*) FROM " + table; int all_years, boring_year; row R; R = tx.exec1(CountQuery); R.front().to(all_years); R = tx.exec1(CountQuery + " WHERE year=" + to_string(BoringYear)); R.front().to(boring_year); return make_pair(all_years, boring_year); }; struct deliberate_error : exception { }; void test_018(transaction_base &T) { connection_base &C(T.conn()); T.abort(); { work T2(C); test::create_pqxxevents(T2); T2.commit(); } const string Table = "pqxxevents"; const pair<int,int> Before = perform(bind(count_events, ref(C), Table)); PQXX_CHECK_EQUAL( Before.second, 0, "Already have event for " + to_string(BoringYear) + ", cannot run."); { quiet_errorhandler d(C); PQXX_CHECK_THROWS( perform( [&C, Table]() { robusttransaction<serializable> tx{C}; tx.exec0( "INSERT INTO " + Table + " VALUES (" + to_string(BoringYear) + ", '" + tx.esc("yawn") + "')"); throw deliberate_error(); }), deliberate_error, "Not getting expected exception from failing transactor."); } const pair<int,int> After = perform(bind(count_events, ref(C), Table)); PQXX_CHECK_EQUAL(After.first, Before.first, "Event count changed."); PQXX_CHECK_EQUAL( After.second, Before.second, "Event count for " + to_string(BoringYear) + " changed."); } } // namespace PQXX_REGISTER_TEST_T(test_018, nontransaction) <commit_msg>Fix compile warning.<commit_after>#include <functional> #include "test_helpers.hxx" using namespace std; using namespace pqxx; // Test program for libpqxx. Verify abort behaviour of RobustTransaction. // // The program will attempt to add an entry to a table called "pqxxevents", // with a key column called "year"--and then abort the change. namespace { // Let's take a boring year that is not going to be in the "pqxxevents" table const long BoringYear = 1977; // Count events and specifically events occurring in Boring Year, leaving the // former count in the result pair's first member, and the latter in second. pair<int, int> count_events(connection_base &C, string table) { nontransaction tx{C}; const string CountQuery = "SELECT count(*) FROM " + table; int all_years, boring_year; row R; R = tx.exec1(CountQuery); R.front().to(all_years); R = tx.exec1(CountQuery + " WHERE year=" + to_string(BoringYear)); R.front().to(boring_year); return make_pair(all_years, boring_year); } struct deliberate_error : exception { }; void test_018(transaction_base &T) { connection_base &C(T.conn()); T.abort(); { work T2(C); test::create_pqxxevents(T2); T2.commit(); } const string Table = "pqxxevents"; const pair<int,int> Before = perform(bind(count_events, ref(C), Table)); PQXX_CHECK_EQUAL( Before.second, 0, "Already have event for " + to_string(BoringYear) + ", cannot run."); { quiet_errorhandler d(C); PQXX_CHECK_THROWS( perform( [&C, Table]() { robusttransaction<serializable> tx{C}; tx.exec0( "INSERT INTO " + Table + " VALUES (" + to_string(BoringYear) + ", '" + tx.esc("yawn") + "')"); throw deliberate_error(); }), deliberate_error, "Not getting expected exception from failing transactor."); } const pair<int,int> After = perform(bind(count_events, ref(C), Table)); PQXX_CHECK_EQUAL(After.first, Before.first, "Event count changed."); PQXX_CHECK_EQUAL( After.second, Before.second, "Event count for " + to_string(BoringYear) + " changed."); } } // namespace PQXX_REGISTER_TEST_T(test_018, nontransaction) <|endoftext|>
<commit_before>// Copyright 2020 The TensorFlow Runtime Authors // // 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. // This file defines dispatch functions for CPU implementation of TF ops. #include "../kernels/batch_norm.h" #include "../kernels/conv2d.h" #include "../kernels/max_pooling.h" #include "../kernels/zero_padding.h" #include "tfrt/common/compat/eigen/eigen_dtype.h" #include "tfrt/core_runtime/op_attrs.h" #include "tfrt/core_runtime/op_utils.h" #include "tfrt/cpu/core_runtime/cpu_op_registry.h" namespace tfrt { namespace compat { static AsyncValueRef<DenseHostTensor> TfPadOp( const DenseHostTensor& input, const DenseHostTensor& padding, const TensorMetadata& output_md, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); auto output = DenseHostTensor::CreateUninitialized(output_md, host); if (!output) { return EmitErrorAsync(exec_ctx, "out of memory allocating tensor"); } DHTIndexableView<int32_t, 2> padding_view(&padding); const auto& padding_shape = padding_view.FixedShape(); const FixedRankShape<2> expected_padding_shape({4, 2}); if (padding_shape != expected_padding_shape) { return EmitErrorAsync(exec_ctx, "padding shape shoulsd be (4, 2)"); } AsyncValueRef<Chain> chain; switch (input.dtype()) { default: chain = EmitErrorAsync(exec_ctx, "unsupported dtype for TfPadOp"); break; #define DTYPE_NUMERIC(ENUM) \ case DType::ENUM: \ chain = TfPadImpl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, padding_view[{1, 0}], padding_view[{1, 1}], \ padding_view[{2, 0}], padding_view[{2, 1}], output.getPointer(), \ exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } return ForwardValue(output.getValue(), std::move(chain)); } static AsyncValueRef<DenseHostTensor> TfMaxPoolOp( const DenseHostTensor& input, const OpAttrsRef& attrs, const TensorMetadata& output_md, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); auto output = DenseHostTensor::CreateUninitialized(output_md, host); if (!output) { return EmitErrorAsync(exec_ctx, "out of memory allocating tensor"); } auto padding = attrs.GetStringAsserting("padding"); auto strides = attrs.GetArrayOptional<Index>("strides"); auto ksize = attrs.GetArrayOptional<Index>("ksize"); auto data_format = attrs.GetStringOptional("data_format"); if (strides.size() != 4) { return EmitErrorAsync(exec_ctx, "strides should have 4 elements"); } if (ksize.size() != 4) { return EmitErrorAsync(exec_ctx, "ksize should have 4 elements"); } if (data_format.has_value() && data_format.getValue().str() != "NHWC") { return EmitErrorAsync(exec_ctx, "only channel last order is supported"); } std::array<Index, 2> strides_t{strides[1], strides[2]}; std::array<Index, 2> ksize_t{ksize[1], ksize[2]}; AsyncValueRef<Chain> chain; switch (input.dtype()) { default: chain = EmitErrorAsync(exec_ctx, "unsupported dtype for TfMaxPoolOp"); break; #define DTYPE_FLOAT(ENUM) \ case DType::ENUM: \ chain = MaxPoolImpl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, output.getPointer(), padding, strides_t, ksize_t, exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } return ForwardValue(output.getValue(), std::move(chain)); } static AsyncValueRef<DenseHostTensor> TfConv2DOp( const DenseHostTensor& input, const DenseHostTensor& filter, const OpAttrsRef& attrs, const TensorMetadata& output_md, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); auto output = DenseHostTensor::CreateUninitialized(output_md, host); if (!output) { return EmitErrorAsync(exec_ctx, "out of memory allocating tensor"); } auto padding = attrs.GetStringAsserting("padding"); auto strides = attrs.GetArrayOptional<Index>("strides"); auto data_format = attrs.GetStringOptional("data_format"); if (data_format.has_value() && data_format.getValue().str() != "NHWC") { return EmitErrorAsync(exec_ctx, "only channel last order is supported"); } if (strides.size() != 4) { return EmitErrorAsync(exec_ctx, "strides should have 4 elements"); } std::array<Index, 2> strides_t{strides[1], strides[2]}; AsyncValueRef<Chain> chain; using OutputKernel = llvm::Expected<Eigen::NoOpOutputKernel>; auto output_kernel = [](Conv2DParams) -> OutputKernel { return Eigen::NoOpOutputKernel(); }; switch (input.dtype()) { default: chain = EmitErrorAsync(exec_ctx, "unsupported dtype for TfConv2DOp"); break; #define DTYPE_NUMERIC(ENUM) \ case DType::ENUM: \ chain = internal::Conv2DImpl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, filter, output.getPointer(), padding, strides_t, \ std::move(output_kernel), exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } return ForwardValue(output.getValue(), std::move(chain)); } static std::array<AsyncValueRef<DenseHostTensor>, 6> TfFusedBatchNormV3Op( const DenseHostTensor& input, const DenseHostTensor& scale, const DenseHostTensor& bias, const DenseHostTensor& mean, const DenseHostTensor& variance, const OpAttrsRef& attrs, const TensorMetadata& output_md0, const TensorMetadata& output_md1, const TensorMetadata& output_md2, const TensorMetadata& output_md3, const TensorMetadata& output_md4, const TensorMetadata& output_md5, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); std::array<AsyncValueRef<DenseHostTensor>, 6> results; auto result = MakeUnconstructedAsyncValueRef<DenseHostTensor>(); for (int i = 0; i < 6; ++i) { results[i] = result.CopyRef(); } auto output = DenseHostTensor::CreateUninitialized(output_md0, host); if (!output) { result.SetError(absl::InternalError("out of memory allocating tensor")); return results; } if (output_md1.IsValid() || output_md2.IsValid() || output_md3.IsValid() || output_md4.IsValid() || output_md5.IsValid()) { result.SetError(absl::InternalError( "TfFusedBatchNormV3Op only supports one valid output")); return results; } float epsilon; if (!attrs.Get("epsilon", &epsilon)) { result.SetError(absl::InternalError("missing epsilon attribute")); return results; } auto data_format = attrs.GetStringOptional("data_format"); if (data_format.has_value() && data_format.getValue().str() != "NHWC") { result.SetError( absl::InternalError("only channel last order is supported")); return results; } AsyncValueRef<Chain> chain; switch (input.dtype()) { default: chain = EmitErrorAsync( exec_ctx, absl::InternalError("unsupported dtype for TfFusedBatchNormV3Op")); break; #define DTYPE_FLOAT(ENUM) \ case DType::ENUM: \ chain = FusedBatchNormV3Impl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, scale, bias, mean, variance, output.getPointer(), epsilon, \ exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } result = ForwardValue(output.getValue(), std::move(chain)); for (int i = 0; i < 6; ++i) { results[i] = result.CopyRef(); } return results; } } // namespace compat void RegisterEigenTFOps(CpuOpRegistry* op_registry) { op_registry->AddOp("tf.Pad", TFRT_CPU_OP(compat::TfPadOp), CpuOpFlags::NoSideEffects); op_registry->AddOp("tf.MaxPool", TFRT_CPU_OP(compat::TfMaxPoolOp), CpuOpFlags::NoSideEffects, {"padding", "explicit_paddings", "data_format", "strides", "dilations", "ksize"}); op_registry->AddOp( "tf.Conv2D", TFRT_CPU_OP(compat::TfConv2DOp), CpuOpFlags::NoSideEffects, {"padding", "explicit_paddings", "data_format", "strides", "dilations"}); op_registry->AddOp("tf.FusedBatchNormV3", TFRT_CPU_OP(compat::TfFusedBatchNormV3Op), CpuOpFlags::NoSideEffects, {"data_format", "epsilon"}); } } // namespace tfrt <commit_msg>Replace deprecated llvm::Optional methods<commit_after>// Copyright 2020 The TensorFlow Runtime Authors // // 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. // This file defines dispatch functions for CPU implementation of TF ops. #include "../kernels/batch_norm.h" #include "../kernels/conv2d.h" #include "../kernels/max_pooling.h" #include "../kernels/zero_padding.h" #include "tfrt/common/compat/eigen/eigen_dtype.h" #include "tfrt/core_runtime/op_attrs.h" #include "tfrt/core_runtime/op_utils.h" #include "tfrt/cpu/core_runtime/cpu_op_registry.h" namespace tfrt { namespace compat { static AsyncValueRef<DenseHostTensor> TfPadOp( const DenseHostTensor& input, const DenseHostTensor& padding, const TensorMetadata& output_md, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); auto output = DenseHostTensor::CreateUninitialized(output_md, host); if (!output) { return EmitErrorAsync(exec_ctx, "out of memory allocating tensor"); } DHTIndexableView<int32_t, 2> padding_view(&padding); const auto& padding_shape = padding_view.FixedShape(); const FixedRankShape<2> expected_padding_shape({4, 2}); if (padding_shape != expected_padding_shape) { return EmitErrorAsync(exec_ctx, "padding shape shoulsd be (4, 2)"); } AsyncValueRef<Chain> chain; switch (input.dtype()) { default: chain = EmitErrorAsync(exec_ctx, "unsupported dtype for TfPadOp"); break; #define DTYPE_NUMERIC(ENUM) \ case DType::ENUM: \ chain = TfPadImpl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, padding_view[{1, 0}], padding_view[{1, 1}], \ padding_view[{2, 0}], padding_view[{2, 1}], output.getPointer(), \ exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } return ForwardValue(*output, std::move(chain)); } static AsyncValueRef<DenseHostTensor> TfMaxPoolOp( const DenseHostTensor& input, const OpAttrsRef& attrs, const TensorMetadata& output_md, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); auto output = DenseHostTensor::CreateUninitialized(output_md, host); if (!output) { return EmitErrorAsync(exec_ctx, "out of memory allocating tensor"); } auto padding = attrs.GetStringAsserting("padding"); auto strides = attrs.GetArrayOptional<Index>("strides"); auto ksize = attrs.GetArrayOptional<Index>("ksize"); auto data_format = attrs.GetStringOptional("data_format"); if (strides.size() != 4) { return EmitErrorAsync(exec_ctx, "strides should have 4 elements"); } if (ksize.size() != 4) { return EmitErrorAsync(exec_ctx, "ksize should have 4 elements"); } if (data_format.has_value() && data_format->str() != "NHWC") { return EmitErrorAsync(exec_ctx, "only channel last order is supported"); } std::array<Index, 2> strides_t{strides[1], strides[2]}; std::array<Index, 2> ksize_t{ksize[1], ksize[2]}; AsyncValueRef<Chain> chain; switch (input.dtype()) { default: chain = EmitErrorAsync(exec_ctx, "unsupported dtype for TfMaxPoolOp"); break; #define DTYPE_FLOAT(ENUM) \ case DType::ENUM: \ chain = MaxPoolImpl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, output.getPointer(), padding, strides_t, ksize_t, exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } return ForwardValue(*output, std::move(chain)); } static AsyncValueRef<DenseHostTensor> TfConv2DOp( const DenseHostTensor& input, const DenseHostTensor& filter, const OpAttrsRef& attrs, const TensorMetadata& output_md, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); auto output = DenseHostTensor::CreateUninitialized(output_md, host); if (!output) { return EmitErrorAsync(exec_ctx, "out of memory allocating tensor"); } auto padding = attrs.GetStringAsserting("padding"); auto strides = attrs.GetArrayOptional<Index>("strides"); auto data_format = attrs.GetStringOptional("data_format"); if (data_format.has_value() && data_format->str() != "NHWC") { return EmitErrorAsync(exec_ctx, "only channel last order is supported"); } if (strides.size() != 4) { return EmitErrorAsync(exec_ctx, "strides should have 4 elements"); } std::array<Index, 2> strides_t{strides[1], strides[2]}; AsyncValueRef<Chain> chain; using OutputKernel = llvm::Expected<Eigen::NoOpOutputKernel>; auto output_kernel = [](Conv2DParams) -> OutputKernel { return Eigen::NoOpOutputKernel(); }; switch (input.dtype()) { default: chain = EmitErrorAsync(exec_ctx, "unsupported dtype for TfConv2DOp"); break; #define DTYPE_NUMERIC(ENUM) \ case DType::ENUM: \ chain = internal::Conv2DImpl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, filter, output.getPointer(), padding, strides_t, \ std::move(output_kernel), exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } return ForwardValue(*output, std::move(chain)); } static std::array<AsyncValueRef<DenseHostTensor>, 6> TfFusedBatchNormV3Op( const DenseHostTensor& input, const DenseHostTensor& scale, const DenseHostTensor& bias, const DenseHostTensor& mean, const DenseHostTensor& variance, const OpAttrsRef& attrs, const TensorMetadata& output_md0, const TensorMetadata& output_md1, const TensorMetadata& output_md2, const TensorMetadata& output_md3, const TensorMetadata& output_md4, const TensorMetadata& output_md5, const ExecutionContext& exec_ctx) { HostContext* host = exec_ctx.host(); std::array<AsyncValueRef<DenseHostTensor>, 6> results; auto result = MakeUnconstructedAsyncValueRef<DenseHostTensor>(); for (int i = 0; i < 6; ++i) { results[i] = result.CopyRef(); } auto output = DenseHostTensor::CreateUninitialized(output_md0, host); if (!output) { result.SetError(absl::InternalError("out of memory allocating tensor")); return results; } if (output_md1.IsValid() || output_md2.IsValid() || output_md3.IsValid() || output_md4.IsValid() || output_md5.IsValid()) { result.SetError(absl::InternalError( "TfFusedBatchNormV3Op only supports one valid output")); return results; } float epsilon; if (!attrs.Get("epsilon", &epsilon)) { result.SetError(absl::InternalError("missing epsilon attribute")); return results; } auto data_format = attrs.GetStringOptional("data_format"); if (data_format.has_value() && data_format->str() != "NHWC") { result.SetError( absl::InternalError("only channel last order is supported")); return results; } AsyncValueRef<Chain> chain; switch (input.dtype()) { default: chain = EmitErrorAsync( exec_ctx, absl::InternalError("unsupported dtype for TfFusedBatchNormV3Op")); break; #define DTYPE_FLOAT(ENUM) \ case DType::ENUM: \ chain = FusedBatchNormV3Impl<EigenTypeForDTypeKind<DType::ENUM>>( \ input, scale, bias, mean, variance, output.getPointer(), epsilon, \ exec_ctx); \ break; #include "tfrt/dtype/dtype.def" // NOLINT } result = ForwardValue(*output, std::move(chain)); for (int i = 0; i < 6; ++i) { results[i] = result.CopyRef(); } return results; } } // namespace compat void RegisterEigenTFOps(CpuOpRegistry* op_registry) { op_registry->AddOp("tf.Pad", TFRT_CPU_OP(compat::TfPadOp), CpuOpFlags::NoSideEffects); op_registry->AddOp("tf.MaxPool", TFRT_CPU_OP(compat::TfMaxPoolOp), CpuOpFlags::NoSideEffects, {"padding", "explicit_paddings", "data_format", "strides", "dilations", "ksize"}); op_registry->AddOp( "tf.Conv2D", TFRT_CPU_OP(compat::TfConv2DOp), CpuOpFlags::NoSideEffects, {"padding", "explicit_paddings", "data_format", "strides", "dilations"}); op_registry->AddOp("tf.FusedBatchNormV3", TFRT_CPU_OP(compat::TfFusedBatchNormV3Op), CpuOpFlags::NoSideEffects, {"data_format", "epsilon"}); } } // namespace tfrt <|endoftext|>
<commit_before>#include "Bitmap.hpp" #include <zlib.h> Bitmap::Bitmap(AVFrame *frame) { pix_fmt = static_cast<PixelFormat>(frame->format); width = frame->width; height = frame->height; avpicture_alloc(&picture, pix_fmt, frame->width, frame->height); av_image_copy(picture.data, picture.linesize, const_cast<const uint8_t**>(frame->data), frame->linesize, pix_fmt, width, height); } Bitmap::~Bitmap() { avpicture_free(&picture); } #define WS 8 #define WS2 64 inline static double window_average(uint8_t data[], int linesize, int w_i, int w_j){ uint32_t avg = 0; for( int i = 0; i < WS; i++ ) { for( int j = 0; j < WS; j++ ) { avg += data[linesize*(w_i*WS + i) + w_j*WS + i]; } } return (double)(avg) / WS2; } double Bitmap::SSIM(Bitmap &other) { // FIXME: this should be resized if( width != other.width || height != other.height ) { throw "The bitmaps currently have to be of the same size"; } double coef_1 = 6.5025; // (0.01 * 255)^2 double coef_2 = 58.5225; // (0.03 * 255)^2 int w_width = width / WS; int w_height = height / WS; int linesize = picture.linesize[0]; uint8_t *data_this = picture.data[0]; uint8_t *data_other = other.picture.data[0]; double ssim = 0; for( int w_i = 0; w_i < w_height; w_i++ ) { for( int w_j = 0; w_j < w_width; w_j++ ) { int w_offset = linesize * w_i * WS + w_j * WS; int x = 0, xx = 0, y = 0, yy = 0, xy = 0; for( int i = 0; i < WS; i++ ) { int l_offset = w_offset + linesize*i; for( int j = 0; j < WS; j++ ) { int cur_this = data_this [l_offset + j]; int cur_other = data_other[l_offset + j]; x += cur_this; xx += cur_this * cur_this; y += cur_other; yy += cur_other * cur_other; xy += cur_this * cur_other; } } double avg_this = (double) x / WS2; double avg_other = (double) y / WS2; double var_this = (double) (xx - x*x) / WS2; double var_other = (double) (yy - y*y) / WS2; double covar = (double) (xy - x*y) / WS2; ssim += (2 * avg_this * avg_other + coef_1) * (2 * covar + coef_2) / (avg_this * avg_this + avg_other * avg_other + coef_1) / (var_this + var_other + coef_2); } } return ssim / w_height / w_width; } uint32_t Bitmap::CRC32(bool include_chroma) { uint32_t crc = crc32(0, Z_NULL, 0); crc = crc32(crc, picture.data[0], picture.linesize[0] * height); if( include_chroma ) { crc = crc32(crc, picture.data[1], width * height / 4); crc = crc32(crc, picture.data[2], width * height / 4); } return crc; } <commit_msg>Remove an unused function.<commit_after>#include "Bitmap.hpp" #include <zlib.h> Bitmap::Bitmap(AVFrame *frame) { pix_fmt = static_cast<PixelFormat>(frame->format); width = frame->width; height = frame->height; avpicture_alloc(&picture, pix_fmt, frame->width, frame->height); av_image_copy(picture.data, picture.linesize, const_cast<const uint8_t**>(frame->data), frame->linesize, pix_fmt, width, height); } Bitmap::~Bitmap() { avpicture_free(&picture); } #define WS 8 #define WS2 64 double Bitmap::SSIM(Bitmap &other) { // FIXME: this should be resized if( width != other.width || height != other.height ) { throw "The bitmaps currently have to be of the same size"; } double coef_1 = 6.5025; // (0.01 * 255)^2 double coef_2 = 58.5225; // (0.03 * 255)^2 int w_width = width / WS; int w_height = height / WS; int linesize = picture.linesize[0]; uint8_t *data_this = picture.data[0]; uint8_t *data_other = other.picture.data[0]; double ssim = 0; for( int w_i = 0; w_i < w_height; w_i++ ) { for( int w_j = 0; w_j < w_width; w_j++ ) { int w_offset = linesize * w_i * WS + w_j * WS; int x = 0, xx = 0, y = 0, yy = 0, xy = 0; for( int i = 0; i < WS; i++ ) { int l_offset = w_offset + linesize*i; for( int j = 0; j < WS; j++ ) { int cur_this = data_this [l_offset + j]; int cur_other = data_other[l_offset + j]; x += cur_this; xx += cur_this * cur_this; y += cur_other; yy += cur_other * cur_other; xy += cur_this * cur_other; } } double avg_this = (double) x / WS2; double avg_other = (double) y / WS2; double var_this = (double) (xx - x*x) / WS2; double var_other = (double) (yy - y*y) / WS2; double covar = (double) (xy - x*y) / WS2; ssim += (2 * avg_this * avg_other + coef_1) * (2 * covar + coef_2) / (avg_this * avg_this + avg_other * avg_other + coef_1) / (var_this + var_other + coef_2); } } return ssim / w_height / w_width; } uint32_t Bitmap::CRC32(bool include_chroma) { uint32_t crc = crc32(0, Z_NULL, 0); crc = crc32(crc, picture.data[0], picture.linesize[0] * height); if( include_chroma ) { crc = crc32(crc, picture.data[1], width * height / 4); crc = crc32(crc, picture.data[2], width * height / 4); } return crc; } <|endoftext|>
<commit_before>#include <cstdint> #include <utility> #include "Buddha.h" Buddha::Buddha(const Params & p, const std::size_t thread_vector_size) : thread_vector_size_(thread_vector_size) { x_size_ = p.width; y_size_ = p.width; radius_ = p.radius; num_threads_ = p.num_threads; max_iterations_ = p.max_iterations; if (max_iterations_ > thread_vector_size) throw MaxIterationsTooBigException(); } Buddha::Params Buddha::get_empty_params() { Params p; p.num_threads = -1; return p; } void Buddha::run() { uint64_t part_size = x_size_ * y_size_ / num_threads_; for (std::size_t i = 0; i < num_threads_; ++i) threads_.emplace_back(&Buddha::worker, this, i * part_size, (i+1) * part_size); for (auto & t : threads_) t.join(); } std::pair<uint64_t, uint64_t> Buddha::lin2car(uint64_t pos) const { return std::make_pair(pos % x_size_, pos / x_size_); } uint64_t Buddha::car2lin(uint64_t x, uint64_t y) const { return y * x_size_ + x; } Buddha::complex_type Buddha::car2complex(uint64_t x, uint64_t y) const { floating_type re = radius_ * ( 2. / x_size_ * x - 1); floating_type im = radius_ * ( 2. / y_size_ * x - 1); return complex_type(re, im); } Buddha::complex_type Buddha::lin2complex(uint64_t pos) const { auto pair = lin2car(pos); return car2complex(pair.first, pair.second); } uint64_t Buddha::complex2lin(Buddha::complex_type c) const { auto pair = complex2car(c); return car2lin(pair.first, pair.second); } <commit_msg>Implemented complex2car.<commit_after>#include <cstdint> #include <utility> #include "Buddha.h" Buddha::Buddha(const Params & p, const std::size_t thread_vector_size) : thread_vector_size_(thread_vector_size) { x_size_ = p.width; y_size_ = p.width; radius_ = p.radius; num_threads_ = p.num_threads; max_iterations_ = p.max_iterations; if (max_iterations_ > thread_vector_size) throw MaxIterationsTooBigException(); } Buddha::Params Buddha::get_empty_params() { Params p; p.num_threads = -1; return p; } void Buddha::run() { uint64_t part_size = x_size_ * y_size_ / num_threads_; for (std::size_t i = 0; i < num_threads_; ++i) threads_.emplace_back(&Buddha::worker, this, i * part_size, (i+1) * part_size); for (auto & t : threads_) t.join(); } std::pair<uint64_t, uint64_t> Buddha::lin2car(uint64_t pos) const { return std::make_pair(pos % x_size_, pos / x_size_); } uint64_t Buddha::car2lin(uint64_t x, uint64_t y) const { return y * x_size_ + x; } Buddha::complex_type Buddha::car2complex(uint64_t x, uint64_t y) const { floating_type re = radius_ * ( 2. / x_size_ * x - 1); floating_type im = radius_ * ( 2. / y_size_ * x - 1); return complex_type(re, im); } std::pair<uint64_t, uint64_t> Buddha::complex2car( Buddha::complex_type c) const { uint64_t x = (uint64_t)(x_size_ * (c.real() / radius_ + 1) / 2.); uint64_t y = (uint64_t)(y_size_ * (c.imag() / radius_ + 1) / 2.); return std::make_pair(x, y); } Buddha::complex_type Buddha::lin2complex(uint64_t pos) const { auto pair = lin2car(pos); return car2complex(pair.first, pair.second); } uint64_t Buddha::complex2lin(Buddha::complex_type c) const { auto pair = complex2car(c); return car2lin(pair.first, pair.second); } <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "content/browser/file_system/file_system_dispatcher_host.h" #include <string> #include <vector> #include "base/file_path.h" #include "base/platform_file.h" #include "base/threading/thread.h" #include "base/time.h" #include "content/common/file_system_messages.h" #include "googleurl/src/gurl.h" #include "ipc/ipc_platform_file.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #include "webkit/fileapi/file_system_callback_dispatcher.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_operation.h" #include "webkit/fileapi/file_system_operation.h" #include "webkit/fileapi/file_system_quota_util.h" #include "webkit/fileapi/file_system_util.h" using content::BrowserThread; using fileapi::FileSystemCallbackDispatcher; using fileapi::FileSystemFileUtil; using fileapi::FileSystemOperation; using fileapi::FileSystemOperationContext; class BrowserFileSystemCallbackDispatcher : public FileSystemCallbackDispatcher { public: BrowserFileSystemCallbackDispatcher( FileSystemDispatcherHost* dispatcher_host, int request_id) : dispatcher_host_(dispatcher_host), request_id_(request_id) { DCHECK(dispatcher_host_); } virtual ~BrowserFileSystemCallbackDispatcher() { dispatcher_host_->UnregisterOperation(request_id_); } virtual void DidSucceed() { dispatcher_host_->Send(new FileSystemMsg_DidSucceed(request_id_)); } virtual void DidReadMetadata( const base::PlatformFileInfo& info, const FilePath& platform_path) { dispatcher_host_->Send(new FileSystemMsg_DidReadMetadata( request_id_, info, platform_path)); } virtual void DidReadDirectory( const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more) { dispatcher_host_->Send(new FileSystemMsg_DidReadDirectory( request_id_, entries, has_more)); } virtual void DidOpenFileSystem(const std::string& name, const GURL& root) { dispatcher_host_->Send( new FileSystemMsg_OpenComplete( request_id_, root.is_valid(), name, root)); } virtual void DidFail(base::PlatformFileError error_code) { dispatcher_host_->Send(new FileSystemMsg_DidFail(request_id_, error_code)); } virtual void DidWrite(int64 bytes, bool complete) { dispatcher_host_->Send(new FileSystemMsg_DidWrite( request_id_, bytes, complete)); } virtual void DidOpenFile( base::PlatformFile file, base::ProcessHandle peer_handle) { IPC::PlatformFileForTransit file_for_transit = file != base::kInvalidPlatformFileValue ? IPC::GetFileHandleForProcess(file, peer_handle, true) : IPC::InvalidPlatformFileForTransit(); dispatcher_host_->Send(new FileSystemMsg_DidOpenFile( request_id_, file_for_transit)); } private: scoped_refptr<FileSystemDispatcherHost> dispatcher_host_; int request_id_; }; FileSystemDispatcherHost::FileSystemDispatcherHost( net::URLRequestContextGetter* request_context_getter, fileapi::FileSystemContext* file_system_context) : context_(file_system_context), request_context_getter_(request_context_getter), request_context_(NULL) { DCHECK(context_); DCHECK(request_context_getter_); } FileSystemDispatcherHost::FileSystemDispatcherHost( net::URLRequestContext* request_context, fileapi::FileSystemContext* file_system_context) : context_(file_system_context), request_context_(request_context) { DCHECK(context_); DCHECK(request_context_); } FileSystemDispatcherHost::~FileSystemDispatcherHost() { } void FileSystemDispatcherHost::OnChannelConnected(int32 peer_pid) { BrowserMessageFilter::OnChannelConnected(peer_pid); if (request_context_getter_.get()) { DCHECK(!request_context_); request_context_ = request_context_getter_->GetURLRequestContext(); request_context_getter_ = NULL; DCHECK(request_context_); } } void FileSystemDispatcherHost::OverrideThreadForMessage( const IPC::Message& message, BrowserThread::ID* thread) { if (message.type() == FileSystemHostMsg_SyncGetPlatformPath::ID) *thread = BrowserThread::FILE; } bool FileSystemDispatcherHost::OnMessageReceived( const IPC::Message& message, bool* message_was_ok) { *message_was_ok = true; bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(FileSystemDispatcherHost, message, *message_was_ok) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Open, OnOpen) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Move, OnMove) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Copy, OnCopy) IPC_MESSAGE_HANDLER(FileSystemMsg_Remove, OnRemove) IPC_MESSAGE_HANDLER(FileSystemHostMsg_ReadMetadata, OnReadMetadata) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Create, OnCreate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Exists, OnExists) IPC_MESSAGE_HANDLER(FileSystemHostMsg_ReadDirectory, OnReadDirectory) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Write, OnWrite) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Truncate, OnTruncate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_TouchFile, OnTouchFile) IPC_MESSAGE_HANDLER(FileSystemHostMsg_CancelWrite, OnCancel) IPC_MESSAGE_HANDLER(FileSystemHostMsg_OpenFile, OnOpenFile) IPC_MESSAGE_HANDLER(FileSystemHostMsg_WillUpdate, OnWillUpdate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_DidUpdate, OnDidUpdate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_SyncGetPlatformPath, OnSyncGetPlatformPath) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP_EX() return handled; } void FileSystemDispatcherHost::OnOpen( int request_id, const GURL& origin_url, fileapi::FileSystemType type, int64 requested_size, bool create) { GetNewOperation(request_id)->OpenFileSystem(origin_url, type, create); } void FileSystemDispatcherHost::OnMove( int request_id, const GURL& src_path, const GURL& dest_path) { GetNewOperation(request_id)->Move(src_path, dest_path); } void FileSystemDispatcherHost::OnCopy( int request_id, const GURL& src_path, const GURL& dest_path) { GetNewOperation(request_id)->Copy(src_path, dest_path); } void FileSystemDispatcherHost::OnRemove( int request_id, const GURL& path, bool recursive) { GetNewOperation(request_id)->Remove(path, recursive); } void FileSystemDispatcherHost::OnReadMetadata( int request_id, const GURL& path) { GetNewOperation(request_id)->GetMetadata(path); } void FileSystemDispatcherHost::OnCreate( int request_id, const GURL& path, bool exclusive, bool is_directory, bool recursive) { if (is_directory) GetNewOperation(request_id)->CreateDirectory(path, exclusive, recursive); else GetNewOperation(request_id)->CreateFile(path, exclusive); } void FileSystemDispatcherHost::OnExists( int request_id, const GURL& path, bool is_directory) { if (is_directory) GetNewOperation(request_id)->DirectoryExists(path); else GetNewOperation(request_id)->FileExists(path); } void FileSystemDispatcherHost::OnReadDirectory( int request_id, const GURL& path) { GetNewOperation(request_id)->ReadDirectory(path); } void FileSystemDispatcherHost::OnWrite( int request_id, const GURL& path, const GURL& blob_url, int64 offset) { if (!request_context_) { // We can't write w/o a request context, trying to do so will crash. NOTREACHED(); return; } GetNewOperation(request_id)->Write( request_context_, path, blob_url, offset); } void FileSystemDispatcherHost::OnTruncate( int request_id, const GURL& path, int64 length) { GetNewOperation(request_id)->Truncate(path, length); } void FileSystemDispatcherHost::OnTouchFile( int request_id, const GURL& path, const base::Time& last_access_time, const base::Time& last_modified_time) { GetNewOperation(request_id)->TouchFile( path, last_access_time, last_modified_time); } void FileSystemDispatcherHost::OnCancel( int request_id, int request_id_to_cancel) { FileSystemOperation* write = operations_.Lookup( request_id_to_cancel); if (write) { // The cancel will eventually send both the write failure and the cancel // success. write->Cancel(GetNewOperation(request_id)); } else { // The write already finished; report that we failed to stop it. Send(new FileSystemMsg_DidFail( request_id, base::PLATFORM_FILE_ERROR_INVALID_OPERATION)); } } void FileSystemDispatcherHost::OnOpenFile( int request_id, const GURL& path, int file_flags) { GetNewOperation(request_id)->OpenFile(path, file_flags, peer_handle()); } void FileSystemDispatcherHost::OnWillUpdate(const GURL& path) { GURL origin_url; fileapi::FileSystemType type; if (!CrackFileSystemURL(path, &origin_url, &type, NULL)) return; fileapi::FileSystemQuotaUtil* quota_util = context_->GetQuotaUtil(type); if (!quota_util) return; quota_util->proxy()->StartUpdateOrigin(origin_url, type); } void FileSystemDispatcherHost::OnDidUpdate(const GURL& path, int64 delta) { GURL origin_url; fileapi::FileSystemType type; if (!CrackFileSystemURL(path, &origin_url, &type, NULL)) return; fileapi::FileSystemQuotaUtil* quota_util = context_->GetQuotaUtil(type); if (!quota_util) return; quota_util->proxy()->UpdateOriginUsage( context_->quota_manager_proxy(), origin_url, type, delta); quota_util->proxy()->EndUpdateOrigin(origin_url, type); } void FileSystemDispatcherHost::OnSyncGetPlatformPath( const GURL& path, FilePath* platform_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); DCHECK(platform_path); *platform_path = FilePath(); FileSystemOperation* operation = new FileSystemOperation( NULL, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), context_); operation->SyncGetPlatformPath(path, platform_path); } FileSystemOperation* FileSystemDispatcherHost::GetNewOperation( int request_id) { BrowserFileSystemCallbackDispatcher* dispatcher = new BrowserFileSystemCallbackDispatcher(this, request_id); FileSystemOperation* operation = new FileSystemOperation( dispatcher, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), context_); operations_.AddWithID(operation, request_id); return operation; } void FileSystemDispatcherHost::UnregisterOperation(int request_id) { DCHECK(operations_.Lookup(request_id)); operations_.Remove(request_id); } <commit_msg>Add UserMetrics for OpenFileSystem<commit_after>// Copyright (c) 2011 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 "content/browser/file_system/file_system_dispatcher_host.h" #include <string> #include <vector> #include "base/file_path.h" #include "base/platform_file.h" #include "base/threading/thread.h" #include "base/time.h" #include "content/browser/user_metrics.h" #include "content/common/file_system_messages.h" #include "googleurl/src/gurl.h" #include "ipc/ipc_platform_file.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #include "webkit/fileapi/file_system_callback_dispatcher.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_operation.h" #include "webkit/fileapi/file_system_operation.h" #include "webkit/fileapi/file_system_quota_util.h" #include "webkit/fileapi/file_system_util.h" using content::BrowserThread; using fileapi::FileSystemCallbackDispatcher; using fileapi::FileSystemFileUtil; using fileapi::FileSystemOperation; using fileapi::FileSystemOperationContext; class BrowserFileSystemCallbackDispatcher : public FileSystemCallbackDispatcher { public: BrowserFileSystemCallbackDispatcher( FileSystemDispatcherHost* dispatcher_host, int request_id) : dispatcher_host_(dispatcher_host), request_id_(request_id) { DCHECK(dispatcher_host_); } virtual ~BrowserFileSystemCallbackDispatcher() { dispatcher_host_->UnregisterOperation(request_id_); } virtual void DidSucceed() { dispatcher_host_->Send(new FileSystemMsg_DidSucceed(request_id_)); } virtual void DidReadMetadata( const base::PlatformFileInfo& info, const FilePath& platform_path) { dispatcher_host_->Send(new FileSystemMsg_DidReadMetadata( request_id_, info, platform_path)); } virtual void DidReadDirectory( const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more) { dispatcher_host_->Send(new FileSystemMsg_DidReadDirectory( request_id_, entries, has_more)); } virtual void DidOpenFileSystem(const std::string& name, const GURL& root) { dispatcher_host_->Send( new FileSystemMsg_OpenComplete( request_id_, root.is_valid(), name, root)); } virtual void DidFail(base::PlatformFileError error_code) { dispatcher_host_->Send(new FileSystemMsg_DidFail(request_id_, error_code)); } virtual void DidWrite(int64 bytes, bool complete) { dispatcher_host_->Send(new FileSystemMsg_DidWrite( request_id_, bytes, complete)); } virtual void DidOpenFile( base::PlatformFile file, base::ProcessHandle peer_handle) { IPC::PlatformFileForTransit file_for_transit = file != base::kInvalidPlatformFileValue ? IPC::GetFileHandleForProcess(file, peer_handle, true) : IPC::InvalidPlatformFileForTransit(); dispatcher_host_->Send(new FileSystemMsg_DidOpenFile( request_id_, file_for_transit)); } private: scoped_refptr<FileSystemDispatcherHost> dispatcher_host_; int request_id_; }; FileSystemDispatcherHost::FileSystemDispatcherHost( net::URLRequestContextGetter* request_context_getter, fileapi::FileSystemContext* file_system_context) : context_(file_system_context), request_context_getter_(request_context_getter), request_context_(NULL) { DCHECK(context_); DCHECK(request_context_getter_); } FileSystemDispatcherHost::FileSystemDispatcherHost( net::URLRequestContext* request_context, fileapi::FileSystemContext* file_system_context) : context_(file_system_context), request_context_(request_context) { DCHECK(context_); DCHECK(request_context_); } FileSystemDispatcherHost::~FileSystemDispatcherHost() { } void FileSystemDispatcherHost::OnChannelConnected(int32 peer_pid) { BrowserMessageFilter::OnChannelConnected(peer_pid); if (request_context_getter_.get()) { DCHECK(!request_context_); request_context_ = request_context_getter_->GetURLRequestContext(); request_context_getter_ = NULL; DCHECK(request_context_); } } void FileSystemDispatcherHost::OverrideThreadForMessage( const IPC::Message& message, BrowserThread::ID* thread) { if (message.type() == FileSystemHostMsg_SyncGetPlatformPath::ID) *thread = BrowserThread::FILE; } bool FileSystemDispatcherHost::OnMessageReceived( const IPC::Message& message, bool* message_was_ok) { *message_was_ok = true; bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(FileSystemDispatcherHost, message, *message_was_ok) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Open, OnOpen) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Move, OnMove) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Copy, OnCopy) IPC_MESSAGE_HANDLER(FileSystemMsg_Remove, OnRemove) IPC_MESSAGE_HANDLER(FileSystemHostMsg_ReadMetadata, OnReadMetadata) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Create, OnCreate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Exists, OnExists) IPC_MESSAGE_HANDLER(FileSystemHostMsg_ReadDirectory, OnReadDirectory) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Write, OnWrite) IPC_MESSAGE_HANDLER(FileSystemHostMsg_Truncate, OnTruncate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_TouchFile, OnTouchFile) IPC_MESSAGE_HANDLER(FileSystemHostMsg_CancelWrite, OnCancel) IPC_MESSAGE_HANDLER(FileSystemHostMsg_OpenFile, OnOpenFile) IPC_MESSAGE_HANDLER(FileSystemHostMsg_WillUpdate, OnWillUpdate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_DidUpdate, OnDidUpdate) IPC_MESSAGE_HANDLER(FileSystemHostMsg_SyncGetPlatformPath, OnSyncGetPlatformPath) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP_EX() return handled; } void FileSystemDispatcherHost::OnOpen( int request_id, const GURL& origin_url, fileapi::FileSystemType type, int64 requested_size, bool create) { if (type == fileapi::kFileSystemTypeTemporary) { UserMetrics::RecordAction(UserMetricsAction("OpenFileSystemTemporary")); } else if (type == fileapi::kFileSystemTypePersistent) { UserMetrics::RecordAction(UserMetricsAction("OpenFileSystemPersistent")); } GetNewOperation(request_id)->OpenFileSystem(origin_url, type, create); } void FileSystemDispatcherHost::OnMove( int request_id, const GURL& src_path, const GURL& dest_path) { GetNewOperation(request_id)->Move(src_path, dest_path); } void FileSystemDispatcherHost::OnCopy( int request_id, const GURL& src_path, const GURL& dest_path) { GetNewOperation(request_id)->Copy(src_path, dest_path); } void FileSystemDispatcherHost::OnRemove( int request_id, const GURL& path, bool recursive) { GetNewOperation(request_id)->Remove(path, recursive); } void FileSystemDispatcherHost::OnReadMetadata( int request_id, const GURL& path) { GetNewOperation(request_id)->GetMetadata(path); } void FileSystemDispatcherHost::OnCreate( int request_id, const GURL& path, bool exclusive, bool is_directory, bool recursive) { if (is_directory) GetNewOperation(request_id)->CreateDirectory(path, exclusive, recursive); else GetNewOperation(request_id)->CreateFile(path, exclusive); } void FileSystemDispatcherHost::OnExists( int request_id, const GURL& path, bool is_directory) { if (is_directory) GetNewOperation(request_id)->DirectoryExists(path); else GetNewOperation(request_id)->FileExists(path); } void FileSystemDispatcherHost::OnReadDirectory( int request_id, const GURL& path) { GetNewOperation(request_id)->ReadDirectory(path); } void FileSystemDispatcherHost::OnWrite( int request_id, const GURL& path, const GURL& blob_url, int64 offset) { if (!request_context_) { // We can't write w/o a request context, trying to do so will crash. NOTREACHED(); return; } GetNewOperation(request_id)->Write( request_context_, path, blob_url, offset); } void FileSystemDispatcherHost::OnTruncate( int request_id, const GURL& path, int64 length) { GetNewOperation(request_id)->Truncate(path, length); } void FileSystemDispatcherHost::OnTouchFile( int request_id, const GURL& path, const base::Time& last_access_time, const base::Time& last_modified_time) { GetNewOperation(request_id)->TouchFile( path, last_access_time, last_modified_time); } void FileSystemDispatcherHost::OnCancel( int request_id, int request_id_to_cancel) { FileSystemOperation* write = operations_.Lookup( request_id_to_cancel); if (write) { // The cancel will eventually send both the write failure and the cancel // success. write->Cancel(GetNewOperation(request_id)); } else { // The write already finished; report that we failed to stop it. Send(new FileSystemMsg_DidFail( request_id, base::PLATFORM_FILE_ERROR_INVALID_OPERATION)); } } void FileSystemDispatcherHost::OnOpenFile( int request_id, const GURL& path, int file_flags) { GetNewOperation(request_id)->OpenFile(path, file_flags, peer_handle()); } void FileSystemDispatcherHost::OnWillUpdate(const GURL& path) { GURL origin_url; fileapi::FileSystemType type; if (!CrackFileSystemURL(path, &origin_url, &type, NULL)) return; fileapi::FileSystemQuotaUtil* quota_util = context_->GetQuotaUtil(type); if (!quota_util) return; quota_util->proxy()->StartUpdateOrigin(origin_url, type); } void FileSystemDispatcherHost::OnDidUpdate(const GURL& path, int64 delta) { GURL origin_url; fileapi::FileSystemType type; if (!CrackFileSystemURL(path, &origin_url, &type, NULL)) return; fileapi::FileSystemQuotaUtil* quota_util = context_->GetQuotaUtil(type); if (!quota_util) return; quota_util->proxy()->UpdateOriginUsage( context_->quota_manager_proxy(), origin_url, type, delta); quota_util->proxy()->EndUpdateOrigin(origin_url, type); } void FileSystemDispatcherHost::OnSyncGetPlatformPath( const GURL& path, FilePath* platform_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); DCHECK(platform_path); *platform_path = FilePath(); FileSystemOperation* operation = new FileSystemOperation( NULL, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), context_); operation->SyncGetPlatformPath(path, platform_path); } FileSystemOperation* FileSystemDispatcherHost::GetNewOperation( int request_id) { BrowserFileSystemCallbackDispatcher* dispatcher = new BrowserFileSystemCallbackDispatcher(this, request_id); FileSystemOperation* operation = new FileSystemOperation( dispatcher, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), context_); operations_.AddWithID(operation, request_id); return operation; } void FileSystemDispatcherHost::UnregisterOperation(int request_id) { DCHECK(operations_.Lookup(request_id)); operations_.Remove(request_id); } <|endoftext|>
<commit_before>#include <cmath> #include <vector> #include "drake/systems/plants/collision/DrakeCollision.h" #include "drake/systems/plants/collision/Model.h" #include "gtest/gtest.h" using Eigen::Isometry3d; using Eigen::Vector3d; using Eigen::AngleAxisd; namespace DrakeCollision { namespace { /* * Three bodies (cube (1 m edges) and two spheres (0.5 m radii) arranged like *this * * ***** * ** ** * * 3 * --+-- * ** ** | * ***** | * | * ^ 2 m * y | | * | | * +---+---+ ***** | * | | | ** * | * | +---+----> * 2 * --+-- * | 1 | x ** ** * +-------+ ***** * | | * +------ 2 m ---------+ * | | * */ TEST(ModelTest, closestPointsAllToAll) { // Set up the geometry. Isometry3d T_body1_to_world, T_body2_to_world, T_body3_to_world, T_elem2_to_body; T_body1_to_world.setIdentity(); T_body2_to_world.setIdentity(); T_body3_to_world.setIdentity(); T_body2_to_world.translation() << 1, 0, 0; T_elem2_to_body.setIdentity(); T_elem2_to_body.translation() << 1, 0, 0; T_body3_to_world.translation() << 2, 2, 0; // rotate 90 degrees in z T_body3_to_world.linear() = AngleAxisd(M_PI_2,Vector3d::UnitZ()).toRotationMatrix(); // Numerical precision tolerance to perform floating point comparisons. const double tolerance = 1.0e-6; DrakeShapes::Box geometry_1(Vector3d(1, 1, 1)); DrakeShapes::Sphere geometry_2(0.5); DrakeShapes::Sphere geometry_3(0.5); Element element_1(geometry_1); Element element_2(geometry_2, T_elem2_to_body); Element element_3(geometry_3); // Populate the model. std::shared_ptr<Model> model = newModel(); ElementId id1 = model->addElement(element_1); ElementId id2 = model->addElement(element_2); ElementId id3 = model->addElement(element_3); model->updateElementWorldTransform(id1, T_body1_to_world); model->updateElementWorldTransform(id2, T_body2_to_world); model->updateElementWorldTransform(id3, T_body3_to_world); // Compute the closest points. const std::vector<ElementId> ids_to_check = {id1, id2, id3}; std::vector<PointPair> points; model->closestPointsAllToAll(ids_to_check, true, points); ASSERT_EQ(3, points.size()); // Check the closest point between object 1 and object 2. // TODO(david-german-tri): Migrate this test to use Eigen matchers once // they are available. EXPECT_EQ(id1, points[0].getIdA()); EXPECT_EQ(id2, points[0].getIdB()); EXPECT_NEAR(1.0, points[0].getDistance(), tolerance); // Normal is on body B. // Points are in the local frame of the body. EXPECT_TRUE(points[0].getNormal().isApprox(Vector3d(-1, 0, 0))); EXPECT_TRUE(points[0].getPtA().isApprox(Vector3d(0.5, 0, 0))); EXPECT_TRUE(points[0].getPtB().isApprox(Vector3d(0.5, 0, 0))); // Check the closest point between object 1 and object 3. EXPECT_EQ(id1, points[1].getIdA()); EXPECT_EQ(id3, points[1].getIdB()); EXPECT_NEAR(1.6213203435596428, points[1].getDistance(), tolerance); // Normal is on body B. // Points are in the local frame of the body. EXPECT_TRUE(points[1].getNormal().isApprox( Vector3d(-sqrt(2) / 2, -sqrt(2) / 2, 0))); EXPECT_TRUE(points[1].getPtA().isApprox( Vector3d(0.5, 0.5, 0))); EXPECT_TRUE(points[1].getPtB().isApprox( Vector3d(-sqrt(2) / 4, sqrt(2) / 4, 0))); // Check the closest point between object 2 and object 3. EXPECT_EQ(id2, points[2].getIdA()); EXPECT_EQ(id3, points[2].getIdB()); EXPECT_NEAR(1.0, points[2].getDistance(), tolerance); // Normal is on body B. // Points are in the local frame of the body. EXPECT_TRUE(points[2].getNormal().isApprox(Vector3d(0, -1, 0))); EXPECT_TRUE(points[2].getPtA().isApprox(Vector3d(1, 0.5, 0))); EXPECT_TRUE(points[2].getPtB().isApprox(Vector3d(-0.5, 0, 0))); } } // namespace } // namespace DrakeCollision <commit_msg>Comments on reference frame's<commit_after>#include <cmath> #include <vector> #include "drake/systems/plants/collision/DrakeCollision.h" #include "drake/systems/plants/collision/Model.h" #include "gtest/gtest.h" using Eigen::Isometry3d; using Eigen::Vector3d; using Eigen::AngleAxisd; namespace DrakeCollision { namespace { /* * Three bodies (cube (1 m edges) and two spheres (0.5 m radii) arranged like *this * * ***** * ** ** * * 3 * --+-- * ** ** | * ***** | * | * ^ 2 m * y | | * | | * +---+---+ ***** | * | | | ** * | * | +---+----> * 2 * --+-- * | 1 | x ** ** * +-------+ ***** * | | * +------ 2 m ---------+ * | | * */ TEST(ModelTest, closestPointsAllToAll) { // Set up the geometry. Isometry3d T_body1_to_world, T_body2_to_world, T_body3_to_world, T_elem2_to_body; T_body1_to_world.setIdentity(); T_body2_to_world.setIdentity(); T_body3_to_world.setIdentity(); T_body2_to_world.translation() << 1, 0, 0; T_elem2_to_body.setIdentity(); T_elem2_to_body.translation() << 1, 0, 0; T_body3_to_world.translation() << 2, 2, 0; // rotate 90 degrees in z T_body3_to_world.linear() = AngleAxisd(M_PI_2,Vector3d::UnitZ()).toRotationMatrix(); // Numerical precision tolerance to perform floating point comparisons. const double tolerance = 1.0e-6; DrakeShapes::Box geometry_1(Vector3d(1, 1, 1)); DrakeShapes::Sphere geometry_2(0.5); DrakeShapes::Sphere geometry_3(0.5); Element element_1(geometry_1); Element element_2(geometry_2, T_elem2_to_body); Element element_3(geometry_3); // Populate the model. std::shared_ptr<Model> model = newModel(); ElementId id1 = model->addElement(element_1); ElementId id2 = model->addElement(element_2); ElementId id3 = model->addElement(element_3); model->updateElementWorldTransform(id1, T_body1_to_world); model->updateElementWorldTransform(id2, T_body2_to_world); model->updateElementWorldTransform(id3, T_body3_to_world); // Compute the closest points. const std::vector<ElementId> ids_to_check = {id1, id2, id3}; std::vector<PointPair> points; model->closestPointsAllToAll(ids_to_check, true, points); ASSERT_EQ(3, points.size()); // Check the closest point between object 1 and object 2. // TODO(david-german-tri): Migrate this test to use Eigen matchers once // they are available. EXPECT_EQ(id1, points[0].getIdA()); EXPECT_EQ(id2, points[0].getIdB()); EXPECT_NEAR(1.0, points[0].getDistance(), tolerance); // Normal is on body B expressed in the world's frame. // Points are in the local frame of the body. EXPECT_TRUE(points[0].getNormal().isApprox(Vector3d(-1, 0, 0))); EXPECT_TRUE(points[0].getPtA().isApprox(Vector3d(0.5, 0, 0))); EXPECT_TRUE(points[0].getPtB().isApprox(Vector3d(0.5, 0, 0))); // Check the closest point between object 1 and object 3. EXPECT_EQ(id1, points[1].getIdA()); EXPECT_EQ(id3, points[1].getIdB()); EXPECT_NEAR(1.6213203435596428, points[1].getDistance(), tolerance); // Normal is on body B expressed in the world's frame. // Points are in the local frame of the body. EXPECT_TRUE(points[1].getNormal().isApprox( Vector3d(-sqrt(2) / 2, -sqrt(2) / 2, 0))); EXPECT_TRUE(points[1].getPtA().isApprox( Vector3d(0.5, 0.5, 0))); // Notice the y component is positive given that the body's frame is rotated // 90 degrees around the z axis. // Therefore x_body = y_world, y_body=-x_world and z_body=z_world EXPECT_TRUE(points[1].getPtB().isApprox( Vector3d(-sqrt(2) / 4, sqrt(2) / 4, 0))); // Check the closest point between object 2 and object 3. EXPECT_EQ(id2, points[2].getIdA()); EXPECT_EQ(id3, points[2].getIdB()); EXPECT_NEAR(1.0, points[2].getDistance(), tolerance); // Normal is on body B expressed in the world's frame. // Points are in the local frame of the body. EXPECT_TRUE(points[2].getNormal().isApprox(Vector3d(0, -1, 0))); EXPECT_TRUE(points[2].getPtA().isApprox(Vector3d(1, 0.5, 0))); EXPECT_TRUE(points[2].getPtB().isApprox(Vector3d(-0.5, 0, 0))); } } // namespace } // namespace DrakeCollision <|endoftext|>
<commit_before>#include <include/base/cef_bind.h> #include <brick/window/edit_account_window.h> #include <error.h> #include "brick/helper.h" #include "brick/notification.h" #include "brick/platform_util.h" #include "app_message_delegate.h" #include "brick/v8_handler.h" #include "include/wrapper/cef_closure_task.h" namespace { const char kNameSpace[] = "AppEx"; const char kMessageLoginName[] = "Login"; const char kMessageNavigateName[] = "Navigate"; const char kMessageBrowseName[] = "Browse"; const char kMessageChangeTooltipName[] = "ChangeTooltip"; const char kMessageSetIndicatorName[] = "SetIndicator"; const char kMessageIndicatorBadgeName[] = "IndicatorBadgee"; const char kMessageShowNotificationName[] = "ShowNotification"; const char kMessageAddAccountName[] = "AddAccount"; const char kCurrentPortalId[] = "current_portal"; const char kIndicatorOnlineName[] = "online"; const char kIndicatorOfflineName[] = "offline"; const char kIndicatorFlashName[] = "flash"; const char kIndicatorFlashImportantName[] = "flash_important"; } // namespace AppMessageDelegate::AppMessageDelegate() : ProcessMessageDelegate (kNameSpace) { } bool AppMessageDelegate::OnProcessMessageReceived( CefRefPtr<ClientHandler> handler, CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) { std::string message_name = message->GetName(); CefRefPtr<CefListValue> request_args = message->GetArgumentList(); int32 callbackId = -1; int32 error = NO_ERROR; CefRefPtr<CefProcessMessage> response = CefProcessMessage::Create("invokeCallback"); CefRefPtr<CefListValue> response_args = response->GetArgumentList(); // V8 extension messages are handled here. These messages come from the // render process thread (in cef_app.cpp), and have the following format: // name - the name of the native function to call // argument0 - the id of this message. This id is passed back to the // render process in order to execute callbacks // argument1 - argumentN - the arguments for the function // // If we have any arguments, the first is the callbackId if (request_args->GetSize() > 0 && request_args->GetType(0) != VTYPE_NULL) { callbackId = request_args->GetInt(0); if (callbackId != -1) response_args->SetInt(0, callbackId); } message_name = message_name.substr(strlen(kNameSpace)); if (message_name == kMessageLoginName) { // Parameters: // 0: int32 - callback id if (request_args->GetSize() != 1) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { CefRefPtr<Account> account = ClientHandler::GetInstance()->GetAccountManager()->GetCurrentAccount(); Account::AuthResult auth_result = account->Auth(); if (auth_result.success) { SetCookies(CefCookieManager::GetGlobalManager(), account->GetBaseUrl(), auth_result.cookies, account->IsSecure()); response_args->SetBool(2, true); } else { response_args->SetBool(2, false); response_args->SetInt(3, auth_result.error_code); response_args->SetString(4, auth_result.http_error); } } } else if (message_name == kMessageNavigateName) { // Parameters: // 0: int32 - callback id // 1: string - url if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string url = request_args->GetString(1); if (url == kCurrentPortalId) { url = ClientHandler::GetInstance()->GetAccountManager()->GetCurrentAccount()->GetBaseUrl(); } if ( url.find("https://") == 0 || url.find("http://") == 0 ) { browser->GetMainFrame()->LoadURL(url); } else { LOG(WARNING) << "Trying to navigate to the forbidden url: " << url; error = ERR_INVALID_URL; } } } else if (message_name == kMessageBrowseName) { // Parameters: // 0: int32 - callback id // 1: string - url if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string url = request_args->GetString(1); if ( url.find("https://") == 0 || url.find("http://") == 0 ) { // Currently allow only web urls opening... platform_util::OpenExternal(url); } else { LOG(WARNING) << "Trying to browse forbidden url: " << url; error = ERR_INVALID_URL; } } } else if (message_name == kMessageChangeTooltipName) { // Parameters: // 0: int32 - callback id // 1: string - text if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string text = request_args->GetString(1); ClientHandler::GetInstance()->GetStatusIconHandle()->SetTooltip( text.c_str() ); } } else if (message_name == kMessageSetIndicatorName) { // Parameters: // 0: int32 - callback id // 1: string - status from StatusIcon::Icon if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string status = request_args->GetString(1); if (status == kIndicatorOnlineName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::ONLINE); } else if (status == kIndicatorOfflineName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::OFFLINE); } else if (status == kIndicatorFlashName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::FLASH); } else if (status == kIndicatorFlashImportantName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::FLASH_IMPORTANT); } } } else if (message_name == kMessageIndicatorBadgeName) { // Parameters: // 0: int32 - callback id // 1: int - count // 2: bool - important if ( request_args->GetSize() != 3 || request_args->GetType(1) != VTYPE_INT || request_args->GetType(2) != VTYPE_BOOL ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetBadge( request_args->GetInt(1), request_args->GetBool(2) ); } } else if (message_name == kMessageShowNotificationName) { // Parameters: // 0: int32 - callback id // 1: string - title // 2: string - text // 3: string - icon path // 4: int - duration if ( request_args->GetSize() != 5 || request_args->GetType(1) != VTYPE_STRING || request_args->GetType(2) != VTYPE_STRING || request_args->GetType(3) != VTYPE_STRING || request_args->GetType(4) != VTYPE_INT ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string icon_url = request_args->GetString(3); if ( icon_url.find("https://") == 0 || icon_url.find("http://") == 0 ) { Notification::Notify( request_args->GetString(1), request_args->GetString(2), icon_url, request_args->GetInt(4) ); } else { LOG(WARNING) << "Trying to show forbidden icon: " << icon_url; error = ERR_INVALID_URL; } }; } else if (message_name == kMessageAddAccountName) { // Parameters: // 0: int32 - callback id // 1: bool - switch after add if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_BOOL ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { EditAccountWindow *window(new EditAccountWindow); window->Init(CefRefPtr<Account> (new Account), request_args->GetBool(1)); window->Show(); }; } else { return false; } if (callbackId != -1) { response_args->SetInt(1, error); // Send response browser->SendProcessMessage(PID_RENDERER, response); } return true; } void AppMessageDelegate::CreateProcessMessageDelegates(ClientHandler::ProcessMessageDelegateSet& delegates) { delegates.insert(new AppMessageDelegate); } void AppMessageDelegate::SetCookies(CefRefPtr<CefCookieManager> manager, const CefString &url, HttpClient::cookie_map cookies, bool is_secure) { if (!CefCurrentlyOn(TID_IO)) { // Execute on the IO thread. CefPostTask(TID_IO, base::Bind(&AppMessageDelegate::SetCookies, manager, url, cookies, is_secure)); return; } for (HttpClient::cookie_map::iterator value=cookies.begin(); value != cookies.end(); ++value) { CefCookie cookie; CefString(&cookie.name) = value->first; CefString(&cookie.value) = value->second; cookie.secure = is_secure; cookie.httponly = true; manager->SetCookie(url, cookie); } } CefString AppMessageDelegate::ParseAuthSessid(std::string body) { std::string sessId; size_t pos = body.find("sessionId: '") + sizeof("sessionId: '"); sessId = body.substr( pos - 1, body.find("'", pos + 1) - pos + 1 ); CefString result; result.FromASCII(sessId.c_str()); return result; }<commit_msg>Разрешаем показывать нотификацию без иконки<commit_after>#include <include/base/cef_bind.h> #include <brick/window/edit_account_window.h> #include <error.h> #include "brick/helper.h" #include "brick/notification.h" #include "brick/platform_util.h" #include "app_message_delegate.h" #include "brick/v8_handler.h" #include "include/wrapper/cef_closure_task.h" namespace { const char kNameSpace[] = "AppEx"; const char kMessageLoginName[] = "Login"; const char kMessageNavigateName[] = "Navigate"; const char kMessageBrowseName[] = "Browse"; const char kMessageChangeTooltipName[] = "ChangeTooltip"; const char kMessageSetIndicatorName[] = "SetIndicator"; const char kMessageIndicatorBadgeName[] = "IndicatorBadgee"; const char kMessageShowNotificationName[] = "ShowNotification"; const char kMessageAddAccountName[] = "AddAccount"; const char kCurrentPortalId[] = "current_portal"; const char kIndicatorOnlineName[] = "online"; const char kIndicatorOfflineName[] = "offline"; const char kIndicatorFlashName[] = "flash"; const char kIndicatorFlashImportantName[] = "flash_important"; } // namespace AppMessageDelegate::AppMessageDelegate() : ProcessMessageDelegate (kNameSpace) { } bool AppMessageDelegate::OnProcessMessageReceived( CefRefPtr<ClientHandler> handler, CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) { std::string message_name = message->GetName(); CefRefPtr<CefListValue> request_args = message->GetArgumentList(); int32 callbackId = -1; int32 error = NO_ERROR; CefRefPtr<CefProcessMessage> response = CefProcessMessage::Create("invokeCallback"); CefRefPtr<CefListValue> response_args = response->GetArgumentList(); // V8 extension messages are handled here. These messages come from the // render process thread (in cef_app.cpp), and have the following format: // name - the name of the native function to call // argument0 - the id of this message. This id is passed back to the // render process in order to execute callbacks // argument1 - argumentN - the arguments for the function // // If we have any arguments, the first is the callbackId if (request_args->GetSize() > 0 && request_args->GetType(0) != VTYPE_NULL) { callbackId = request_args->GetInt(0); if (callbackId != -1) response_args->SetInt(0, callbackId); } message_name = message_name.substr(strlen(kNameSpace)); if (message_name == kMessageLoginName) { // Parameters: // 0: int32 - callback id if (request_args->GetSize() != 1) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { CefRefPtr<Account> account = ClientHandler::GetInstance()->GetAccountManager()->GetCurrentAccount(); Account::AuthResult auth_result = account->Auth(); if (auth_result.success) { SetCookies(CefCookieManager::GetGlobalManager(), account->GetBaseUrl(), auth_result.cookies, account->IsSecure()); response_args->SetBool(2, true); } else { response_args->SetBool(2, false); response_args->SetInt(3, auth_result.error_code); response_args->SetString(4, auth_result.http_error); } } } else if (message_name == kMessageNavigateName) { // Parameters: // 0: int32 - callback id // 1: string - url if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string url = request_args->GetString(1); if (url == kCurrentPortalId) { url = ClientHandler::GetInstance()->GetAccountManager()->GetCurrentAccount()->GetBaseUrl(); } if ( url.find("https://") == 0 || url.find("http://") == 0 ) { browser->GetMainFrame()->LoadURL(url); } else { LOG(WARNING) << "Trying to navigate to the forbidden url: " << url; error = ERR_INVALID_URL; } } } else if (message_name == kMessageBrowseName) { // Parameters: // 0: int32 - callback id // 1: string - url if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string url = request_args->GetString(1); if ( url.find("https://") == 0 || url.find("http://") == 0 ) { // Currently allow only web urls opening... platform_util::OpenExternal(url); } else { LOG(WARNING) << "Trying to browse forbidden url: " << url; error = ERR_INVALID_URL; } } } else if (message_name == kMessageChangeTooltipName) { // Parameters: // 0: int32 - callback id // 1: string - text if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string text = request_args->GetString(1); ClientHandler::GetInstance()->GetStatusIconHandle()->SetTooltip( text.c_str() ); } } else if (message_name == kMessageSetIndicatorName) { // Parameters: // 0: int32 - callback id // 1: string - status from StatusIcon::Icon if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_STRING ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string status = request_args->GetString(1); if (status == kIndicatorOnlineName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::ONLINE); } else if (status == kIndicatorOfflineName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::OFFLINE); } else if (status == kIndicatorFlashName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::FLASH); } else if (status == kIndicatorFlashImportantName) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetIcon(StatusIcon::Icon::FLASH_IMPORTANT); } } } else if (message_name == kMessageIndicatorBadgeName) { // Parameters: // 0: int32 - callback id // 1: int - count // 2: bool - important if ( request_args->GetSize() != 3 || request_args->GetType(1) != VTYPE_INT || request_args->GetType(2) != VTYPE_BOOL ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { ClientHandler::GetInstance()->GetStatusIconHandle()->SetBadge( request_args->GetInt(1), request_args->GetBool(2) ); } } else if (message_name == kMessageShowNotificationName) { // Parameters: // 0: int32 - callback id // 1: string - title // 2: string - text // 3: string - icon path // 4: int - duration if ( request_args->GetSize() != 5 || request_args->GetType(1) != VTYPE_STRING || request_args->GetType(2) != VTYPE_STRING || request_args->GetType(3) != VTYPE_STRING || request_args->GetType(4) != VTYPE_INT ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { std::string icon_url = request_args->GetString(3); if ( icon_url.empty() || icon_url.find("https://") == 0 || icon_url.find("http://") == 0 ) { Notification::Notify( request_args->GetString(1), request_args->GetString(2), icon_url, request_args->GetInt(4) ); } else { LOG(WARNING) << "Trying to show forbidden icon: " << icon_url; error = ERR_INVALID_URL; } }; } else if (message_name == kMessageAddAccountName) { // Parameters: // 0: int32 - callback id // 1: bool - switch after add if ( request_args->GetSize() != 2 || request_args->GetType(1) != VTYPE_BOOL ) { error = ERR_INVALID_PARAMS; } if (error == NO_ERROR) { EditAccountWindow *window(new EditAccountWindow); window->Init(CefRefPtr<Account> (new Account), request_args->GetBool(1)); window->Show(); }; } else { return false; } if (callbackId != -1) { response_args->SetInt(1, error); // Send response browser->SendProcessMessage(PID_RENDERER, response); } return true; } void AppMessageDelegate::CreateProcessMessageDelegates(ClientHandler::ProcessMessageDelegateSet& delegates) { delegates.insert(new AppMessageDelegate); } void AppMessageDelegate::SetCookies(CefRefPtr<CefCookieManager> manager, const CefString &url, HttpClient::cookie_map cookies, bool is_secure) { if (!CefCurrentlyOn(TID_IO)) { // Execute on the IO thread. CefPostTask(TID_IO, base::Bind(&AppMessageDelegate::SetCookies, manager, url, cookies, is_secure)); return; } for (HttpClient::cookie_map::iterator value=cookies.begin(); value != cookies.end(); ++value) { CefCookie cookie; CefString(&cookie.name) = value->first; CefString(&cookie.value) = value->second; cookie.secure = is_secure; cookie.httponly = true; manager->SetCookie(url, cookie); } } CefString AppMessageDelegate::ParseAuthSessid(std::string body) { std::string sessId; size_t pos = body.find("sessionId: '") + sizeof("sessionId: '"); sessId = body.substr( pos - 1, body.find("'", pos + 1) - pos + 1 ); CefString result; result.FromASCII(sessId.c_str()); return result; }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #if defined OS2 #define INCL_DOS #define INCL_DOSMISC #endif #include "bridges/cpp_uno/shared/vtablefactory.hxx" #include "guardedarray.hxx" #include "bridges/cpp_uno/shared/vtables.hxx" #include "osl/thread.h" #include "osl/security.hxx" #include "osl/file.hxx" #include "osl/diagnose.h" #include "osl/mutex.hxx" #include "rtl/alloc.h" #include "rtl/ustring.hxx" #include "sal/types.h" #include "typelib/typedescription.hxx" #include <hash_map> #include <new> #include <vector> #if defined SAL_UNX #include <unistd.h> #include <string.h> #include <sys/mman.h> #elif defined SAL_W32 #define WIN32_LEAN_AND_MEAN #ifdef _MSC_VER #pragma warning(push,1) // disable warnings within system headers #endif #include <windows.h> #ifdef _MSC_VER #pragma warning(pop) #endif #elif defined SAL_OS2 #define INCL_DOS #define INCL_DOSMISC #include <os2.h> #else #error Unsupported platform #endif using bridges::cpp_uno::shared::VtableFactory; namespace { extern "C" void * SAL_CALL allocExec(rtl_arena_type *, sal_Size * size) { sal_Size pagesize; #if defined SAL_UNX #if defined FREEBSD || defined NETBSD || defined OPENBSD pagesize = getpagesize(); #else pagesize = sysconf(_SC_PAGESIZE); #endif #elif defined SAL_W32 SYSTEM_INFO info; GetSystemInfo(&info); pagesize = info.dwPageSize; #elif defined(SAL_OS2) ULONG ulPageSize; DosQuerySysInfo(QSV_PAGE_SIZE, QSV_PAGE_SIZE, &ulPageSize, sizeof(ULONG)); pagesize = (sal_Size)ulPageSize; #else #error Unsupported platform #endif sal_Size n = (*size + (pagesize - 1)) & ~(pagesize - 1); void * p; #if defined SAL_UNX p = mmap( 0, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (p == MAP_FAILED) { p = 0; } else if (mprotect (static_cast<char*>(p), n, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) { munmap (static_cast<char*>(p), n); p = 0; } #elif defined SAL_W32 p = VirtualAlloc(0, n, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #elif defined(SAL_OS2) p = 0; DosAllocMem( &p, n, PAG_COMMIT | PAG_READ | PAG_WRITE | OBJ_ANY); #endif if (p != 0) { *size = n; } return p; } extern "C" void SAL_CALL freeExec( rtl_arena_type *, void * address, sal_Size size) { #if defined SAL_UNX munmap(static_cast< char * >(address), size); #elif defined SAL_W32 (void) size; // unused VirtualFree(address, 0, MEM_RELEASE); #elif defined(SAL_OS2) (void) DosFreeMem( address); #endif } } class VtableFactory::GuardedBlocks: public std::vector< Block > { public: GuardedBlocks(VtableFactory const & factory): m_factory(factory), m_guarded(true) {} ~GuardedBlocks(); void unguard() { m_guarded = false; } private: GuardedBlocks(GuardedBlocks &); // not implemented void operator =(GuardedBlocks); // not implemented VtableFactory const & m_factory; bool m_guarded; }; VtableFactory::GuardedBlocks::~GuardedBlocks() { if (m_guarded) { for (iterator i(begin()); i != end(); ++i) { m_factory.freeBlock(*i); } } } class VtableFactory::BaseOffset { public: BaseOffset(typelib_InterfaceTypeDescription * type) { calculate(type, 0); } sal_Int32 getFunctionOffset(rtl::OUString const & name) const { return m_map.find(name)->second; } private: sal_Int32 calculate( typelib_InterfaceTypeDescription * type, sal_Int32 offset); typedef std::hash_map< rtl::OUString, sal_Int32, rtl::OUStringHash > Map; Map m_map; }; sal_Int32 VtableFactory::BaseOffset::calculate( typelib_InterfaceTypeDescription * type, sal_Int32 offset) { rtl::OUString name(type->aBase.pTypeName); if (m_map.find(name) == m_map.end()) { for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) { offset = calculate(type->ppBaseTypes[i], offset); } m_map.insert(Map::value_type(name, offset)); typelib_typedescription_complete( reinterpret_cast< typelib_TypeDescription ** >(&type)); offset += bridges::cpp_uno::shared::getLocalFunctions(type); } return offset; } VtableFactory::VtableFactory(): m_arena( rtl_arena_create( "bridges::cpp_uno::shared::VtableFactory", sizeof (void *), // to satisfy alignment requirements 0, reinterpret_cast< rtl_arena_type * >(-1), allocExec, freeExec, 0)) { if (m_arena == 0) { throw std::bad_alloc(); } } VtableFactory::~VtableFactory() { { osl::MutexGuard guard(m_mutex); for (Map::iterator i(m_map.begin()); i != m_map.end(); ++i) { for (sal_Int32 j = 0; j < i->second.count; ++j) { freeBlock(i->second.blocks[j]); } delete[] i->second.blocks; } } rtl_arena_destroy(m_arena); } VtableFactory::Vtables VtableFactory::getVtables( typelib_InterfaceTypeDescription * type) { rtl::OUString name(type->aBase.pTypeName); osl::MutexGuard guard(m_mutex); Map::iterator i(m_map.find(name)); if (i == m_map.end()) { GuardedBlocks blocks(*this); createVtables(blocks, BaseOffset(type), type, true); Vtables vtables; OSL_ASSERT(blocks.size() <= SAL_MAX_INT32); vtables.count = static_cast< sal_Int32 >(blocks.size()); bridges::cpp_uno::shared::GuardedArray< Block > guardedBlocks( new Block[vtables.count]); vtables.blocks = guardedBlocks.get(); for (sal_Int32 j = 0; j < vtables.count; ++j) { vtables.blocks[j] = blocks[j]; } i = m_map.insert(Map::value_type(name, vtables)).first; guardedBlocks.release(); blocks.unguard(); } return i->second; } #ifdef USE_DOUBLE_MMAP bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const { sal_Size size = getBlockSize(slotCount); sal_Size pagesize = sysconf(_SC_PAGESIZE); block.size = (size + (pagesize - 1)) & ~(pagesize - 1); block.start = block.exec = NULL; block.fd = -1; osl::Security aSecurity; rtl::OUString strDirectory; rtl::OUString strURLDirectory; if (aSecurity.getHomeDir(strURLDirectory)) osl::File::getSystemPathFromFileURL(strURLDirectory, strDirectory); for (int i = strDirectory.getLength() == 0 ? 1 : 0; i < 2; ++i) { if (!strDirectory.getLength()) strDirectory = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/tmp" )); strDirectory += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/.execoooXXXXXX" )); rtl::OString aTmpName = rtl::OUStringToOString(strDirectory, osl_getThreadTextEncoding()); char *tmpfname = new char[aTmpName.getLength()+1]; strncpy(tmpfname, aTmpName.getStr(), aTmpName.getLength()+1); if ((block.fd = mkstemp(tmpfname)) == -1) perror("creation of executable memory area failed"); if (block.fd == -1) { delete[] tmpfname; break; } unlink(tmpfname); delete[] tmpfname; if (ftruncate(block.fd, block.size) == -1) { perror("truncation of executable memory area failed"); close(block.fd); block.fd = -1; break; } block.start = mmap(NULL, block.size, PROT_READ | PROT_WRITE, MAP_SHARED, block.fd, 0); if (block.start== MAP_FAILED) { block.start = 0; } block.exec = mmap(NULL, block.size, PROT_READ | PROT_EXEC, MAP_SHARED, block.fd, 0); if (block.exec == MAP_FAILED) { block.exec = 0; } //All good if (block.start && block.exec && block.fd != -1) break; freeBlock(block); strDirectory = rtl::OUString(); } if (!block.start || !block.exec || block.fd == -1) { //Fall back to non-doublemmaped allocation block.fd = -1; block.start = block.exec = rtl_arena_alloc(m_arena, &block.size); } return (block.start != 0 && block.exec != 0); } void VtableFactory::freeBlock(Block const & block) const { //if the double-map failed we were allocated on the arena if (block.fd == -1 && block.start == block.exec && block.start != NULL) rtl_arena_free(m_arena, block.start, block.size); else { if (block.start) munmap(block.start, block.size); if (block.exec) munmap(block.exec, block.size); if (block.fd != -1) close(block.fd); } } #else bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const { block.size = getBlockSize(slotCount); block.start = rtl_arena_alloc(m_arena, &block.size); return block.start != 0; } void VtableFactory::freeBlock(Block const & block) const { rtl_arena_free(m_arena, block.start, block.size); } #endif void VtableFactory::createVtables( GuardedBlocks & blocks, BaseOffset const & baseOffset, typelib_InterfaceTypeDescription * type, bool includePrimary) const { if (includePrimary) { sal_Int32 slotCount = bridges::cpp_uno::shared::getPrimaryFunctions(type); Block block; if (!createBlock(block, slotCount)) { throw std::bad_alloc(); } try { Slot * slots = initializeBlock(block.start, slotCount); unsigned char * codeBegin = reinterpret_cast< unsigned char * >(slots); unsigned char * code = codeBegin; sal_Int32 vtableOffset = blocks.size() * sizeof (Slot *); for (typelib_InterfaceTypeDescription const * type2 = type; type2 != 0; type2 = type2->pBaseTypeDescription) { code = addLocalFunctions( &slots, code, #ifdef USE_DOUBLE_MMAP sal_IntPtr(block.exec) - sal_IntPtr(block.start), #endif type2, baseOffset.getFunctionOffset(type2->aBase.pTypeName), bridges::cpp_uno::shared::getLocalFunctions(type2), vtableOffset); } flushCode(codeBegin, code); #ifdef USE_DOUBLE_MMAP //Finished generating block, swap writable pointer with executable //pointer ::std::swap(block.start, block.exec); #endif blocks.push_back(block); } catch (...) { freeBlock(block); throw; } } for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) { createVtables(blocks, baseOffset, type->ppBaseTypes[i], i != 0); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>use errno to get the correct error message if mkstemp() fails<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #if defined OS2 #define INCL_DOS #define INCL_DOSMISC #endif #include "bridges/cpp_uno/shared/vtablefactory.hxx" #include "guardedarray.hxx" #include "bridges/cpp_uno/shared/vtables.hxx" #include "osl/thread.h" #include "osl/security.hxx" #include "osl/file.hxx" #include "osl/diagnose.h" #include "osl/mutex.hxx" #include "rtl/alloc.h" #include "rtl/ustring.hxx" #include "sal/types.h" #include "typelib/typedescription.hxx" #include <hash_map> #include <new> #include <vector> #if defined SAL_UNX #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/mman.h> #elif defined SAL_W32 #define WIN32_LEAN_AND_MEAN #ifdef _MSC_VER #pragma warning(push,1) // disable warnings within system headers #endif #include <windows.h> #ifdef _MSC_VER #pragma warning(pop) #endif #elif defined SAL_OS2 #define INCL_DOS #define INCL_DOSMISC #include <os2.h> #else #error Unsupported platform #endif using bridges::cpp_uno::shared::VtableFactory; namespace { extern "C" void * SAL_CALL allocExec(rtl_arena_type *, sal_Size * size) { sal_Size pagesize; #if defined SAL_UNX #if defined FREEBSD || defined NETBSD || defined OPENBSD pagesize = getpagesize(); #else pagesize = sysconf(_SC_PAGESIZE); #endif #elif defined SAL_W32 SYSTEM_INFO info; GetSystemInfo(&info); pagesize = info.dwPageSize; #elif defined(SAL_OS2) ULONG ulPageSize; DosQuerySysInfo(QSV_PAGE_SIZE, QSV_PAGE_SIZE, &ulPageSize, sizeof(ULONG)); pagesize = (sal_Size)ulPageSize; #else #error Unsupported platform #endif sal_Size n = (*size + (pagesize - 1)) & ~(pagesize - 1); void * p; #if defined SAL_UNX p = mmap( 0, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (p == MAP_FAILED) { p = 0; } else if (mprotect (static_cast<char*>(p), n, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) { munmap (static_cast<char*>(p), n); p = 0; } #elif defined SAL_W32 p = VirtualAlloc(0, n, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #elif defined(SAL_OS2) p = 0; DosAllocMem( &p, n, PAG_COMMIT | PAG_READ | PAG_WRITE | OBJ_ANY); #endif if (p != 0) { *size = n; } return p; } extern "C" void SAL_CALL freeExec( rtl_arena_type *, void * address, sal_Size size) { #if defined SAL_UNX munmap(static_cast< char * >(address), size); #elif defined SAL_W32 (void) size; // unused VirtualFree(address, 0, MEM_RELEASE); #elif defined(SAL_OS2) (void) DosFreeMem( address); #endif } } class VtableFactory::GuardedBlocks: public std::vector< Block > { public: GuardedBlocks(VtableFactory const & factory): m_factory(factory), m_guarded(true) {} ~GuardedBlocks(); void unguard() { m_guarded = false; } private: GuardedBlocks(GuardedBlocks &); // not implemented void operator =(GuardedBlocks); // not implemented VtableFactory const & m_factory; bool m_guarded; }; VtableFactory::GuardedBlocks::~GuardedBlocks() { if (m_guarded) { for (iterator i(begin()); i != end(); ++i) { m_factory.freeBlock(*i); } } } class VtableFactory::BaseOffset { public: BaseOffset(typelib_InterfaceTypeDescription * type) { calculate(type, 0); } sal_Int32 getFunctionOffset(rtl::OUString const & name) const { return m_map.find(name)->second; } private: sal_Int32 calculate( typelib_InterfaceTypeDescription * type, sal_Int32 offset); typedef std::hash_map< rtl::OUString, sal_Int32, rtl::OUStringHash > Map; Map m_map; }; sal_Int32 VtableFactory::BaseOffset::calculate( typelib_InterfaceTypeDescription * type, sal_Int32 offset) { rtl::OUString name(type->aBase.pTypeName); if (m_map.find(name) == m_map.end()) { for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) { offset = calculate(type->ppBaseTypes[i], offset); } m_map.insert(Map::value_type(name, offset)); typelib_typedescription_complete( reinterpret_cast< typelib_TypeDescription ** >(&type)); offset += bridges::cpp_uno::shared::getLocalFunctions(type); } return offset; } VtableFactory::VtableFactory(): m_arena( rtl_arena_create( "bridges::cpp_uno::shared::VtableFactory", sizeof (void *), // to satisfy alignment requirements 0, reinterpret_cast< rtl_arena_type * >(-1), allocExec, freeExec, 0)) { if (m_arena == 0) { throw std::bad_alloc(); } } VtableFactory::~VtableFactory() { { osl::MutexGuard guard(m_mutex); for (Map::iterator i(m_map.begin()); i != m_map.end(); ++i) { for (sal_Int32 j = 0; j < i->second.count; ++j) { freeBlock(i->second.blocks[j]); } delete[] i->second.blocks; } } rtl_arena_destroy(m_arena); } VtableFactory::Vtables VtableFactory::getVtables( typelib_InterfaceTypeDescription * type) { rtl::OUString name(type->aBase.pTypeName); osl::MutexGuard guard(m_mutex); Map::iterator i(m_map.find(name)); if (i == m_map.end()) { GuardedBlocks blocks(*this); createVtables(blocks, BaseOffset(type), type, true); Vtables vtables; OSL_ASSERT(blocks.size() <= SAL_MAX_INT32); vtables.count = static_cast< sal_Int32 >(blocks.size()); bridges::cpp_uno::shared::GuardedArray< Block > guardedBlocks( new Block[vtables.count]); vtables.blocks = guardedBlocks.get(); for (sal_Int32 j = 0; j < vtables.count; ++j) { vtables.blocks[j] = blocks[j]; } i = m_map.insert(Map::value_type(name, vtables)).first; guardedBlocks.release(); blocks.unguard(); } return i->second; } #ifdef USE_DOUBLE_MMAP bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const { sal_Size size = getBlockSize(slotCount); sal_Size pagesize = sysconf(_SC_PAGESIZE); block.size = (size + (pagesize - 1)) & ~(pagesize - 1); block.start = block.exec = NULL; block.fd = -1; osl::Security aSecurity; rtl::OUString strDirectory; rtl::OUString strURLDirectory; if (aSecurity.getHomeDir(strURLDirectory)) osl::File::getSystemPathFromFileURL(strURLDirectory, strDirectory); for (int i = strDirectory.getLength() == 0 ? 1 : 0; i < 2; ++i) { if (!strDirectory.getLength()) strDirectory = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/tmp" )); strDirectory += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/.execoooXXXXXX" )); rtl::OString aTmpName = rtl::OUStringToOString(strDirectory, osl_getThreadTextEncoding()); char *tmpfname = new char[aTmpName.getLength()+1]; strncpy(tmpfname, aTmpName.getStr(), aTmpName.getLength()+1); if ((block.fd = mkstemp(tmpfname)) == -1) fprintf(stderr, "mkstemp(\"%s\") failed: %s\n", tmpfname, strerror(errno)); if (block.fd == -1) { delete[] tmpfname; break; } unlink(tmpfname); delete[] tmpfname; if (ftruncate(block.fd, block.size) == -1) { perror("truncation of executable memory area failed"); close(block.fd); block.fd = -1; break; } block.start = mmap(NULL, block.size, PROT_READ | PROT_WRITE, MAP_SHARED, block.fd, 0); if (block.start== MAP_FAILED) { block.start = 0; } block.exec = mmap(NULL, block.size, PROT_READ | PROT_EXEC, MAP_SHARED, block.fd, 0); if (block.exec == MAP_FAILED) { block.exec = 0; } //All good if (block.start && block.exec && block.fd != -1) break; freeBlock(block); strDirectory = rtl::OUString(); } if (!block.start || !block.exec || block.fd == -1) { //Fall back to non-doublemmaped allocation block.fd = -1; block.start = block.exec = rtl_arena_alloc(m_arena, &block.size); } return (block.start != 0 && block.exec != 0); } void VtableFactory::freeBlock(Block const & block) const { //if the double-map failed we were allocated on the arena if (block.fd == -1 && block.start == block.exec && block.start != NULL) rtl_arena_free(m_arena, block.start, block.size); else { if (block.start) munmap(block.start, block.size); if (block.exec) munmap(block.exec, block.size); if (block.fd != -1) close(block.fd); } } #else bool VtableFactory::createBlock(Block &block, sal_Int32 slotCount) const { block.size = getBlockSize(slotCount); block.start = rtl_arena_alloc(m_arena, &block.size); return block.start != 0; } void VtableFactory::freeBlock(Block const & block) const { rtl_arena_free(m_arena, block.start, block.size); } #endif void VtableFactory::createVtables( GuardedBlocks & blocks, BaseOffset const & baseOffset, typelib_InterfaceTypeDescription * type, bool includePrimary) const { if (includePrimary) { sal_Int32 slotCount = bridges::cpp_uno::shared::getPrimaryFunctions(type); Block block; if (!createBlock(block, slotCount)) { throw std::bad_alloc(); } try { Slot * slots = initializeBlock(block.start, slotCount); unsigned char * codeBegin = reinterpret_cast< unsigned char * >(slots); unsigned char * code = codeBegin; sal_Int32 vtableOffset = blocks.size() * sizeof (Slot *); for (typelib_InterfaceTypeDescription const * type2 = type; type2 != 0; type2 = type2->pBaseTypeDescription) { code = addLocalFunctions( &slots, code, #ifdef USE_DOUBLE_MMAP sal_IntPtr(block.exec) - sal_IntPtr(block.start), #endif type2, baseOffset.getFunctionOffset(type2->aBase.pTypeName), bridges::cpp_uno::shared::getLocalFunctions(type2), vtableOffset); } flushCode(codeBegin, code); #ifdef USE_DOUBLE_MMAP //Finished generating block, swap writable pointer with executable //pointer ::std::swap(block.start, block.exec); #endif blocks.push_back(block); } catch (...) { freeBlock(block); throw; } } for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) { createVtables(blocks, baseOffset, type->ppBaseTypes[i], i != 0); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before> #include <binder/ProcessState.h> #include <cutils/properties.h> #include <utils/SystemClock.h> #include <fcntl.h> #include <time.h> #include "libpreview.h" #include "SimpleH264Encoder.h" using android::Mutex; libpreview::Client *libpreviewClient; SimpleH264Encoder *simpleH264Encoder; Mutex simpleH264EncoderLock; int fd; void libpreview_FrameCallback(void *userData, void *frame, libpreview::FrameFormat format, size_t width, size_t height, libpreview::FrameOwner owner) { (void) userData; Mutex::Autolock autolock(simpleH264EncoderLock); if (simpleH264Encoder == nullptr) { libpreviewClient->releaseFrame(owner); return; } SimpleH264Encoder::InputFrame inputFrame; SimpleH264Encoder::InputFrameInfo inputFrameInfo; #ifdef ANDROID inputFrameInfo.captureTimeMs = android::elapsedRealtime(); #else timespec now; clock_gettime(CLOCK_MONOTONIC, &now); inputFrameInfo.captureTimeMs = (int64_t)now.tv_sec * 1e3 + (int64_t)now.tv_nsec / 1e6; #endif if (!simpleH264Encoder->getInputFrame(inputFrame)) { printf("Unable to get input frame\n"); return; } switch (format) { case libpreview::FRAMEFORMAT_YVU420SP: if (inputFrame.format != libpreview::FRAMEFORMAT_YVU420SP) { printf("Unsupported encoder format: %d\n", inputFrame.format); return; } // Copy Y plane memcpy(inputFrame.data, frame, width * height); // Copy UV plane while converting from YVU420SemiPlaner to YUV420SemiPlaner { uint8_t *s = static_cast<uint8_t *>(frame) + width * height; uint8_t *d = static_cast<uint8_t *>(inputFrame.data) + width * height; uint8_t *dEnd = d + width * height / 2; for (; d < dEnd; s += 2, d += 2) { d[0] = s[1]; d[1] = s[0]; } } break; case libpreview::FRAMEFORMAT_YUV420SP: if (inputFrame.format != format) { printf("Unsupported encoder format: %d\n", inputFrame.format); return; } memcpy(inputFrame.data, frame, inputFrame.size); break; case libpreview::FRAMEFORMAT_YUV420SP_VENUS: if (inputFrame.format != format) { printf("Unsupported encoder format: %d\n", inputFrame.format); return; } switch (inputFrame.format) { case libpreview::FRAMEFORMAT_YUV420SP_VENUS: memcpy(inputFrame.data, frame, inputFrame.size); break; case libpreview::FRAMEFORMAT_YUV420SP: // Copy Y plane memcpy(inputFrame.data, frame, width * height); // Pack and copy UV plane memcpy( static_cast<uint8_t *>(inputFrame.data) + width * height, static_cast<uint8_t *>(frame) + libpreview::VENUS_C_PLANE_OFFSET(width, height), width * height / 2 ); break; default: break; } break; default: printf("Unsupported format: %d\n", format); return; } simpleH264Encoder->nextFrame(inputFrame, inputFrameInfo); libpreviewClient->releaseFrame(owner); } void libpreview_AbandonedCallback(void *userData) { (void) userData; printf("libpreview_AbandonedCallback\n"); exit(1); } void frameOutCallback(SimpleH264Encoder::EncodedFrameInfo& info) { printf("Frame %lld size=%8d keyframe=%d\n", info.input.captureTimeMs, info.encodedFrameLength, info.keyFrame); TEMP_FAILURE_RETRY( write( fd, info.encodedFrame, info.encodedFrameLength ) ); } int main(int argc, char **argv) { (void) argc; (void) argv; #ifdef ANDROID android::sp<android::ProcessState> ps = android::ProcessState::self(); ps->startThreadPool(); #endif libpreviewClient = libpreview::open(libpreview_FrameCallback, libpreview_AbandonedCallback, 0); if (!libpreviewClient) { printf("Unable to open libpreview\n"); return 1; } size_t width; size_t height; libpreviewClient->getSize(width, height); int vbr = property_get_int32("ro.silk.camera.vbr", 1024); int fps = property_get_int32("ro.silk.camera.fps", 24); for (int i = 0; i < 5; i++) { char filename[32]; snprintf(filename, sizeof(filename) - 1, "/data/vid_%d.h264", i); fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0440); if (fd < 0) { printf("Unable to open output file: %s\n", filename); } printf("Output file: %s\n", filename); { Mutex::Autolock autolock(simpleH264EncoderLock); simpleH264Encoder = SimpleH264Encoder::Create( width, height, vbr, fps, frameOutCallback, nullptr ); } printf("Encoder started\n"); if (simpleH264Encoder == nullptr) { printf("Unable to create a SimpleH264Encoder\n"); return 1; } // Fiddle with the bitrate while recording just because we can for (int j = 0; j < 10; j++) { int bitRateK = 1000 * (j+1) / 10; simpleH264Encoder->setBitRate(bitRateK); printf(". (bitrate=%dk)\n", bitRateK); sleep(1); } simpleH264Encoder->stop(); { Mutex::Autolock autolock(simpleH264EncoderLock); delete simpleH264Encoder; simpleH264Encoder = nullptr; } close(fd); printf("Encoder stopped\n"); sleep(1); // Take a breath... } printf("Releasing libpreview\n"); libpreviewClient->release(); return 0; } <commit_msg>Compute/display bitrate<commit_after> #include <binder/ProcessState.h> #include <cutils/properties.h> #include <utils/SystemClock.h> #include <fcntl.h> #include <time.h> #include <vector> #include "libpreview.h" #include "SimpleH264Encoder.h" using android::Mutex; libpreview::Client *libpreviewClient; SimpleH264Encoder *simpleH264Encoder; Mutex simpleH264EncoderLock; int fd; std::vector<int> outputFrameSize; void libpreview_FrameCallback(void *userData, void *frame, libpreview::FrameFormat format, size_t width, size_t height, libpreview::FrameOwner owner) { (void) userData; Mutex::Autolock autolock(simpleH264EncoderLock); if (simpleH264Encoder == nullptr) { libpreviewClient->releaseFrame(owner); return; } SimpleH264Encoder::InputFrame inputFrame; SimpleH264Encoder::InputFrameInfo inputFrameInfo; #ifdef ANDROID inputFrameInfo.captureTimeMs = android::elapsedRealtime(); #else timespec now; clock_gettime(CLOCK_MONOTONIC, &now); inputFrameInfo.captureTimeMs = (int64_t)now.tv_sec * 1e3 + (int64_t)now.tv_nsec / 1e6; #endif if (!simpleH264Encoder->getInputFrame(inputFrame)) { printf("Unable to get input frame\n"); return; } switch (format) { case libpreview::FRAMEFORMAT_YVU420SP: if (inputFrame.format != libpreview::FRAMEFORMAT_YVU420SP) { printf("Unsupported encoder format: %d\n", inputFrame.format); return; } // Copy Y plane memcpy(inputFrame.data, frame, width * height); // Copy UV plane while converting from YVU420SemiPlaner to YUV420SemiPlaner { uint8_t *s = static_cast<uint8_t *>(frame) + width * height; uint8_t *d = static_cast<uint8_t *>(inputFrame.data) + width * height; uint8_t *dEnd = d + width * height / 2; for (; d < dEnd; s += 2, d += 2) { d[0] = s[1]; d[1] = s[0]; } } break; case libpreview::FRAMEFORMAT_YUV420SP: if (inputFrame.format != format) { printf("Unsupported encoder format: %d\n", inputFrame.format); return; } memcpy(inputFrame.data, frame, inputFrame.size); break; case libpreview::FRAMEFORMAT_YUV420SP_VENUS: if (inputFrame.format != format) { printf("Unsupported encoder format: %d\n", inputFrame.format); return; } switch (inputFrame.format) { case libpreview::FRAMEFORMAT_YUV420SP_VENUS: memcpy(inputFrame.data, frame, inputFrame.size); break; case libpreview::FRAMEFORMAT_YUV420SP: // Copy Y plane memcpy(inputFrame.data, frame, width * height); // Pack and copy UV plane memcpy( static_cast<uint8_t *>(inputFrame.data) + width * height, static_cast<uint8_t *>(frame) + libpreview::VENUS_C_PLANE_OFFSET(width, height), width * height / 2 ); break; default: break; } break; default: printf("Unsupported format: %d\n", format); return; } simpleH264Encoder->nextFrame(inputFrame, inputFrameInfo); libpreviewClient->releaseFrame(owner); } void libpreview_AbandonedCallback(void *userData) { (void) userData; printf("libpreview_AbandonedCallback\n"); exit(1); } void frameOutCallback(SimpleH264Encoder::EncodedFrameInfo& info) { outputFrameSize.erase(outputFrameSize.begin()); outputFrameSize.push_back(info.encodedFrameLength); int64_t bitrate = 0; for (auto i = 0; i < outputFrameSize.size(); i++) { bitrate += outputFrameSize[i] * 8; } printf("Frame %lld size=%8d keyframe=%d (bitrate: %lld)\n", info.input.captureTimeMs, info.encodedFrameLength, info.keyFrame, bitrate ); TEMP_FAILURE_RETRY( write( fd, info.encodedFrame, info.encodedFrameLength ) ); } int main(int argc, char **argv) { (void) argc; (void) argv; #ifdef ANDROID android::sp<android::ProcessState> ps = android::ProcessState::self(); ps->startThreadPool(); #endif libpreviewClient = libpreview::open(libpreview_FrameCallback, libpreview_AbandonedCallback, 0); if (!libpreviewClient) { printf("Unable to open libpreview\n"); return 1; } size_t width; size_t height; libpreviewClient->getSize(width, height); int vbr = property_get_int32("ro.silk.camera.vbr", 1024); int fps = property_get_int32("ro.silk.camera.fps", 24); outputFrameSize.resize(fps); for (auto i = 0; i < fps; i++) { outputFrameSize.push_back(0); } for (auto i = 0; i < 1; i++) { char filename[32]; snprintf(filename, sizeof(filename) - 1, "/data/vid_%d.h264", i); fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0440); if (fd < 0) { printf("Unable to open output file: %s\n", filename); } printf("Output file: %s\n", filename); { Mutex::Autolock autolock(simpleH264EncoderLock); simpleH264Encoder = SimpleH264Encoder::Create( width, height, vbr, fps, frameOutCallback, nullptr ); } printf("Encoder started\n"); if (simpleH264Encoder == nullptr) { printf("Unable to create a SimpleH264Encoder\n"); return 1; } // Fiddle with the bitrate while recording just because we can for (int j = 0; j < 10; j++) { int bitRateK = 1000 * (j+1) / 10; simpleH264Encoder->setBitRate(bitRateK); printf(". (bitrate=%dk)\n", bitRateK); sleep(1); } simpleH264Encoder->stop(); { Mutex::Autolock autolock(simpleH264EncoderLock); delete simpleH264Encoder; simpleH264Encoder = nullptr; } close(fd); printf("Encoder stopped\n"); sleep(1); // Take a breath... } printf("Releasing libpreview\n"); libpreviewClient->release(); return 0; } <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- /// \file es/storage.hpp /// \brief The entity/component data store // // Copyright 2013-2014, nocte@hippie.nu Released under the MIT License. //--------------------------------------------------------------------------- #pragma once #include <algorithm> #include <bitset> #include <cassert> #include <cstdint> #include <functional> #include <stdexcept> #include <string> #include <typeinfo> #include <type_traits> #include <vector> #include <unordered_map> #include "component.hpp" #include "entity.hpp" #include "traits.hpp" namespace es { /** A storage ties entities and components together. * Storage associates two other bits of data with every entity: * - A 64-bit mask that keeps track of which components are defined * - A vector of bytes, holding the actual data * * The vector of bytes tries to pack the component data as tightly as * possible. It is really fast for plain old datatypes, but it also * handles nontrivial types safely. It packs a virtual table and a * pointer to some heap space in the vector, and calls the constructor * and destructor as needed. */ class storage { // It is assumed the first few components will be accessed the // most often. We keep a cache of the first 12. static const uint32_t cache_size = 12; static const uint32_t cache_mask = (1 << cache_size) - 1; /** This data gets associated with every entity. */ struct elem { /** Bitmask to keep track of which components are held in \a data. */ std::bitset<64> components; /** Set to true if any data has changed. */ bool dirty; /** Component data for this entity. */ std::vector<char> data; elem() : dirty(true) {} }; typedef component::placeholder placeholder; /** Data types that do not have a flat memory layout are kept in the ** elem::data buffer in a placeholder object. */ template <typename t> class holder : public placeholder { public: holder () { } holder (t&& init) : held_(std::move(init)) { } holder (const t& init) : held_(init) { } const t& held() const { return held_; } t& held() { return held_; } placeholder* clone() const { return new holder<t>(held_); } void serialize(std::vector<char>& buffer) const { es::serialize(held(), buffer); } buffer_t::const_iterator deserialize(buffer_t::const_iterator first, buffer_t::const_iterator last) { return es::deserialize(held(), first, last); } void move_to (buffer_t::iterator pos) { auto ptr (reinterpret_cast<holder<t>*>(&*pos)); auto tmp (new (ptr) holder<t>(std::move(held_))); assert(tmp == ptr); (void)tmp; } private: t held_; }; typedef std::unordered_map<uint32_t, elem> stor_impl; public: typedef uint8_t component_id; typedef stor_impl::iterator iterator; typedef stor_impl::const_iterator const_iterator; public: std::function<void(iterator)> on_new_entity; std::function<void(iterator)> on_deleted_entity; public: storage(); ~storage(); template <typename type> component_id register_component (std::string&& name) { size_t size; if (is_flat<type>::value) { size = sizeof(type); components_.emplace_back(std::move(name), size, typeid(type), nullptr); } else { flat_mask_.set(components_.size()); size = sizeof(holder<type>); components_.emplace_back(std::move(name), size, typeid(type), std::unique_ptr<placeholder>(new holder<type>())); } if (components_.size() < cache_size) { size_t i (component_offsets_.size()); component_offsets_.resize(i * 2); for (size_t j (i); j != i * 2; ++j) component_offsets_[j] = component_offsets_[j-i] + size; } return components_.size() - 1; } component_id find_component (const std::string& name) const; const component& operator[] (component_id id) const { return components_[id]; } const std::vector<component>& components() const { return components_; } public: entity new_entity(); /** Get an entity with a given ID, or create it if it didn't exist yet. */ iterator make (uint32_t id); /** Create a whole bunch of empty entities in one go. * @param count The number of entities to create * @return The range of entities created */ std::pair<entity, entity> new_entities (size_t count); entity clone_entity (iterator f); iterator find (entity en); const_iterator find (entity en) const; size_t size() const; bool delete_entity (entity en); void delete_entity (iterator f); void remove_component_from_entity (iterator en, component_id c); bool exists (entity en) const { return entities_.count(en) != 0; } bool entity_has_component (iterator en, component_id c) const; template <typename type> void set (entity en, component_id c_id, type&& val) { set<type>(find(en), c_id, std::forward<type>(val)); } template <typename type> void set (iterator en, component_id c_id, type&& val) { assert(c_id < components_.size()); const component& c (components_[c_id]); assert(c.is_of_type<type>()); elem& e (en->second); size_t off (offset(e, c_id)); if (!e.components[c_id]) { if (e.data.size() < off) e.data.resize(off + c.size()); else e.data.insert(e.data.begin() + off, c.size(), 0); } if (is_flat<type>::value) { assert(e.data.size() >= off + sizeof(type)); new (&*e.data.begin() + off) type (val); } else { assert(e.data.size() >= off + sizeof(holder<type>)); auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off)); if (e.components[c_id]) ptr->~holder(); auto tmp (new (ptr) holder<type>(std::move(val))); assert(tmp == ptr); (void)tmp; } e.components.set(c_id); e.dirty = true; } template <typename type> const type& get (entity en, component_id c_id) const { return get<type>(find(en), c_id); } template <typename type> const type& get (const_iterator en, component_id c_id) const { auto& e (en->second); if (!e.components[c_id]) throw std::logic_error("entity does not have component"); return get<type>(e, c_id); } template <typename type> type& get (entity en, component_id c_id) { return get<type>(find(en), c_id); } template <typename type> type& get (iterator en, component_id c_id) { auto& e (en->second); if (!e.components[c_id]) throw std::logic_error("entity does not have component"); return get<type>(e, c_id); } /** Call a function for every entity that has a given component. * The callee can then query and change the value of the component through * a var_ref object, or remove the entity. * @param c The component to look for. * @param func The function to call. This function will be passed an * iterator to the current entity, and a var_ref corresponding * to the component value in this entity. */ template <typename t> void for_each (component_id c, std::function<bool(iterator, t&)> func) { std::bitset<64> mask; mask.set(c); for (auto i (begin()); i != end(); ) { auto next (std::next(i)); elem& e (i->second); if ((e.components & mask) == mask) e.dirty |= func(i, get<t>(e, c)); i = next; } } template <typename t1, typename t2> void for_each (component_id c1, component_id c2, std::function<bool(iterator, t1&, t2&)> func) { std::bitset<64> mask; mask.set(c1); mask.set(c2); for (auto i (begin()); i != end(); ) { auto next (std::next(i)); elem& e (i->second); if ((e.components & mask) == mask) e.dirty |= func(i, get<t1>(e, c1), get<t2>(e, c2)); i = next; } } template <typename t1, typename t2, typename t3> void for_each (component_id c1, component_id c2, component_id c3, std::function<bool(iterator, t1&, t2&, t3&)> func) { std::bitset<64> mask; mask.set(c1); mask.set(c2); mask.set(c3); for (auto i (begin()); i != end(); ) { auto next (std::next(i)); elem& e (i->second); if ((e.components & mask) == mask) { e.dirty |= func(i, get<t1>(e, c1), get<t2>(e, c2), get<t3>(e, c3)); } i = next; } } bool check_dirty (iterator en); bool check_dirty_and_clear (iterator en); void serialize (const_iterator en, std::vector<char>& buffer) const; void deserialize (iterator en, const std::vector<char>& buffer); iterator begin() { return entities_.begin(); } iterator end() { return entities_.end(); } const_iterator begin() const { return entities_.begin(); } const_iterator end() const { return entities_.end(); } const_iterator cbegin() const { return entities_.cbegin(); } const_iterator cend() const { return entities_.cend(); } private: template <typename type> const type& get (const elem& e, component_id c_id) const { assert(components_[c_id].is_of_type<type>()); auto data_ptr (&*e.data.begin() + offset(e, c_id)); if (is_flat<type>::value) return *reinterpret_cast<const type*>(data_ptr); auto obj_ptr (reinterpret_cast<const holder<type>*>(data_ptr)); return obj_ptr->held(); } template <typename type> type& get (elem& e, component_id c_id) { assert(components_[c_id].is_of_type<type>()); auto data_ptr (&*e.data.begin() + offset(e, c_id)); if (is_flat<type>::value) return *reinterpret_cast<type*>(data_ptr); auto obj_ptr (reinterpret_cast<holder<type>*>(data_ptr)); return obj_ptr->held(); } size_t offset (const elem& e, component_id c) const; void call_destructors (iterator i) const; private: /** Keeps track of entity IDs to give out. */ uint32_t next_id_; /** The list of registered components. */ std::vector<component> components_; /** Mapping entity IDs to their data. */ std::unordered_map<uint32_t, elem> entities_; /** A lookup table for the data offsets of components. * The index is the bitmask as used in elem::components. */ std::vector<size_t> component_offsets_; /** A bitmask to quickly determine whether a certain combination of ** components has a flat memory layout or not. */ std::bitset<64> flat_mask_; }; } // namespace es <commit_msg>Fix compile error when passing a reference type to set()<commit_after>//--------------------------------------------------------------------------- /// \file es/storage.hpp /// \brief The entity/component data store // // Copyright 2013-2014, nocte@hippie.nu Released under the MIT License. //--------------------------------------------------------------------------- #pragma once #include <algorithm> #include <bitset> #include <cassert> #include <cstdint> #include <functional> #include <stdexcept> #include <string> #include <typeinfo> #include <type_traits> #include <vector> #include <unordered_map> #include "component.hpp" #include "entity.hpp" #include "traits.hpp" namespace es { /** A storage ties entities and components together. * Storage associates two other bits of data with every entity: * - A 64-bit mask that keeps track of which components are defined * - A vector of bytes, holding the actual data * * The vector of bytes tries to pack the component data as tightly as * possible. It is really fast for plain old datatypes, but it also * handles nontrivial types safely. It packs a virtual table and a * pointer to some heap space in the vector, and calls the constructor * and destructor as needed. */ class storage { // It is assumed the first few components will be accessed the // most often. We keep a cache of the first 12. static const uint32_t cache_size = 12; static const uint32_t cache_mask = (1 << cache_size) - 1; /** This data gets associated with every entity. */ struct elem { /** Bitmask to keep track of which components are held in \a data. */ std::bitset<64> components; /** Set to true if any data has changed. */ bool dirty; /** Component data for this entity. */ std::vector<char> data; elem() : dirty(true) {} }; typedef component::placeholder placeholder; /** Data types that do not have a flat memory layout are kept in the ** elem::data buffer in a placeholder object. */ template <typename t> class holder : public placeholder { public: holder () { } holder (t&& init) : held_(std::move(init)) { } holder (const t& init) : held_(init) { } const t& held() const { return held_; } t& held() { return held_; } placeholder* clone() const { return new holder<t>(held_); } void serialize(std::vector<char>& buffer) const { es::serialize(held(), buffer); } buffer_t::const_iterator deserialize(buffer_t::const_iterator first, buffer_t::const_iterator last) { return es::deserialize(held(), first, last); } void move_to (buffer_t::iterator pos) { auto ptr (reinterpret_cast<holder<t>*>(&*pos)); auto tmp (new (ptr) holder<t>(std::move(held_))); assert(tmp == ptr); (void)tmp; } private: t held_; }; typedef std::unordered_map<uint32_t, elem> stor_impl; public: typedef uint8_t component_id; typedef stor_impl::iterator iterator; typedef stor_impl::const_iterator const_iterator; public: std::function<void(iterator)> on_new_entity; std::function<void(iterator)> on_deleted_entity; public: storage(); ~storage(); template <typename type> component_id register_component (std::string&& name) { size_t size; if (is_flat<type>::value) { size = sizeof(type); components_.emplace_back(std::move(name), size, typeid(type), nullptr); } else { flat_mask_.set(components_.size()); size = sizeof(holder<type>); components_.emplace_back(std::move(name), size, typeid(type), std::unique_ptr<placeholder>(new holder<type>())); } if (components_.size() < cache_size) { size_t i (component_offsets_.size()); component_offsets_.resize(i * 2); for (size_t j (i); j != i * 2; ++j) component_offsets_[j] = component_offsets_[j-i] + size; } return components_.size() - 1; } component_id find_component (const std::string& name) const; const component& operator[] (component_id id) const { return components_[id]; } const std::vector<component>& components() const { return components_; } public: entity new_entity(); /** Get an entity with a given ID, or create it if it didn't exist yet. */ iterator make (uint32_t id); /** Create a whole bunch of empty entities in one go. * @param count The number of entities to create * @return The range of entities created */ std::pair<entity, entity> new_entities (size_t count); entity clone_entity (iterator f); iterator find (entity en); const_iterator find (entity en) const; size_t size() const; bool delete_entity (entity en); void delete_entity (iterator f); void remove_component_from_entity (iterator en, component_id c); bool exists (entity en) const { return entities_.count(en) != 0; } bool entity_has_component (iterator en, component_id c) const; template <typename value_type> void set (entity en, component_id c_id, value_type&& val) { set<value_type>(find(en), c_id, std::forward<value_type>(val)); } template <typename value_type> void set (iterator en, component_id c_id, value_type&& val) { typedef typename std::remove_reference<value_type>::type type; assert(c_id < components_.size()); const component& c (components_[c_id]); assert(c.is_of_type<type>()); elem& e (en->second); size_t off (offset(e, c_id)); if (!e.components[c_id]) { if (e.data.size() < off) e.data.resize(off + c.size()); else e.data.insert(e.data.begin() + off, c.size(), 0); } if (is_flat<type>::value) { assert(e.data.size() >= off + sizeof(type)); new (&*e.data.begin() + off) type (val); } else { assert(e.data.size() >= off + sizeof(holder<type>)); auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off)); if (e.components[c_id]) ptr->~holder(); auto tmp (new (ptr) holder<type>(std::move(val))); assert(tmp == ptr); (void)tmp; } e.components.set(c_id); e.dirty = true; } template <typename type> const type& get (entity en, component_id c_id) const { return get<type>(find(en), c_id); } template <typename type> const type& get (const_iterator en, component_id c_id) const { auto& e (en->second); if (!e.components[c_id]) throw std::logic_error("entity does not have component"); return get<type>(e, c_id); } template <typename type> type& get (entity en, component_id c_id) { return get<type>(find(en), c_id); } template <typename type> type& get (iterator en, component_id c_id) { auto& e (en->second); if (!e.components[c_id]) throw std::logic_error("entity does not have component"); return get<type>(e, c_id); } /** Call a function for every entity that has a given component. * The callee can then query and change the value of the component through * a var_ref object, or remove the entity. * @param c The component to look for. * @param func The function to call. This function will be passed an * iterator to the current entity, and a var_ref corresponding * to the component value in this entity. */ template <typename t> void for_each (component_id c, std::function<bool(iterator, t&)> func) { std::bitset<64> mask; mask.set(c); for (auto i (begin()); i != end(); ) { auto next (std::next(i)); elem& e (i->second); if ((e.components & mask) == mask) e.dirty |= func(i, get<t>(e, c)); i = next; } } template <typename t1, typename t2> void for_each (component_id c1, component_id c2, std::function<bool(iterator, t1&, t2&)> func) { std::bitset<64> mask; mask.set(c1); mask.set(c2); for (auto i (begin()); i != end(); ) { auto next (std::next(i)); elem& e (i->second); if ((e.components & mask) == mask) e.dirty |= func(i, get<t1>(e, c1), get<t2>(e, c2)); i = next; } } template <typename t1, typename t2, typename t3> void for_each (component_id c1, component_id c2, component_id c3, std::function<bool(iterator, t1&, t2&, t3&)> func) { std::bitset<64> mask; mask.set(c1); mask.set(c2); mask.set(c3); for (auto i (begin()); i != end(); ) { auto next (std::next(i)); elem& e (i->second); if ((e.components & mask) == mask) { e.dirty |= func(i, get<t1>(e, c1), get<t2>(e, c2), get<t3>(e, c3)); } i = next; } } bool check_dirty (iterator en); bool check_dirty_and_clear (iterator en); void serialize (const_iterator en, std::vector<char>& buffer) const; void deserialize (iterator en, const std::vector<char>& buffer); iterator begin() { return entities_.begin(); } iterator end() { return entities_.end(); } const_iterator begin() const { return entities_.begin(); } const_iterator end() const { return entities_.end(); } const_iterator cbegin() const { return entities_.cbegin(); } const_iterator cend() const { return entities_.cend(); } private: template <typename type> const type& get (const elem& e, component_id c_id) const { assert(components_[c_id].is_of_type<type>()); auto data_ptr (&*e.data.begin() + offset(e, c_id)); if (is_flat<type>::value) return *reinterpret_cast<const type*>(data_ptr); auto obj_ptr (reinterpret_cast<const holder<type>*>(data_ptr)); return obj_ptr->held(); } template <typename type> type& get (elem& e, component_id c_id) { assert(components_[c_id].is_of_type<type>()); auto data_ptr (&*e.data.begin() + offset(e, c_id)); if (is_flat<type>::value) return *reinterpret_cast<type*>(data_ptr); auto obj_ptr (reinterpret_cast<holder<type>*>(data_ptr)); return obj_ptr->held(); } size_t offset (const elem& e, component_id c) const; void call_destructors (iterator i) const; private: /** Keeps track of entity IDs to give out. */ uint32_t next_id_; /** The list of registered components. */ std::vector<component> components_; /** Mapping entity IDs to their data. */ std::unordered_map<uint32_t, elem> entities_; /** A lookup table for the data offsets of components. * The index is the bitmask as used in elem::components. */ std::vector<size_t> component_offsets_; /** A bitmask to quickly determine whether a certain combination of ** components has a flat memory layout or not. */ std::bitset<64> flat_mask_; }; } // namespace es <|endoftext|>
<commit_before>#include "utils.hpp" struct tpool : densitas::core::thread_pool { tpool(int max_threads) : densitas::core::thread_pool(max_threads) {} std::size_t get_max_threads() { return max_threads_; } std::list<std::pair<std::shared_ptr<std::atomic_bool>, std::thread>>& get_threads() { return threads_; } }; template<typename... Args> struct functor { bool called; functor() : called(false) {} void operator()(Args...) { called = true; } }; COLLECTION(thread_pool) { TEST(test_construct) { tpool tp(42); assert_equal(42u, tp.get_max_threads(), SPOT); assert_equal(0, tp.get_threads().size(), SPOT); } TEST(test_construct_with_weird_param) { tpool tp(-3); assert_equal(1u, tp.get_max_threads(), SPOT); } TEST(test_launch_new_without_args) { functor<> func; { tpool tp(3); tp.launch_new(std::ref(func)); assert_equal(1, tp.get_threads().size(), SPOT); } assert_true(func.called, SPOT); } TEST(test_launch_new_with_some_args) { functor<int, double> func; { tpool tp(5); tp.launch_new(std::ref(func), 1, 5.); assert_equal(1, tp.get_threads().size(), SPOT); } assert_true(func.called, SPOT); } TEST(test_launch_many) { functor<int, double> func; { tpool tp(4); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(std::ref(func), 1, 5.); } assert_true(func.called, SPOT); } struct cond_var_mock { bool called; cond_var_mock() : called{false} {} void notify_one() { called = true; } }; COLLECTION(functor_runner) { struct fixture { std::shared_ptr<std::atomic_bool> done_; cond_var_mock cond_var_; densitas::core::functor_runner<cond_var_mock> runner_; bool called_; fixture() : done_(std::make_shared<std::atomic_bool>(false)), cond_var_{}, runner_{done_, cond_var_}, called_{false} {} virtual ~fixture() UNITTEST_NOEXCEPT_FALSE { assert_true(called_, SPOT); assert_true(*done_, SPOT); assert_true(cond_var_.called, SPOT); } }; TEST_FIXTURE(fixture, test_with_no_args) { runner_([this](){ called_ = true; }); } TEST_FIXTURE(fixture, test_with_multiple_args) { runner_([this](int, double){ called_ = true; }, 42, 1.3); } } struct cv : densitas::core::condition_variable { bool get_flag() { return flag_; } }; COLLECTION(condition_variable) { TEST(test_constructor) { cv cond_var; assert_false(cond_var.get_flag(), SPOT); } TEST(test_notify_one) { cv cond_var; cond_var.notify_one(); assert_true(cond_var.get_flag(), SPOT); } TEST(test_notify_one_and_wait) { cv cond_var; cond_var.notify_one(); cond_var.wait(); assert_false(cond_var.get_flag(), SPOT); } TEST(test_notify_one_and_wait_in_separate_threads) { cv cond_var; std::thread([&cond_var]() { std::this_thread::sleep_for(std::chrono::milliseconds(20)); cond_var.notify_one(); }).detach(); cond_var.wait(); assert_false(cond_var.get_flag(), SPOT); } } } <commit_msg>code cleanup<commit_after>#include "utils.hpp" struct tpool : densitas::core::thread_pool { tpool(int max_threads) : densitas::core::thread_pool(max_threads) {} std::size_t get_max_threads() { return max_threads_; } std::list<std::pair<std::shared_ptr<std::atomic_bool>, std::thread>>& get_threads() { return threads_; } }; template<typename... Args> struct functor { bool called; functor() : called(false) {} void operator()(Args...) { called = true; } }; COLLECTION(thread_pool) { TEST(test_construct) { tpool tp(42); assert_equal(42u, tp.get_max_threads(), SPOT); assert_equal(0, tp.get_threads().size(), SPOT); } TEST(test_construct_with_weird_param) { tpool tp(-3); assert_equal(1u, tp.get_max_threads(), SPOT); } TEST(test_launch_new_without_args) { functor<> func; { tpool tp(3); tp.launch_new(std::ref(func)); assert_equal(1, tp.get_threads().size(), SPOT); } assert_true(func.called, SPOT); } TEST(test_launch_new_with_some_args) { functor<int, double> func; { tpool tp(5); tp.launch_new(std::ref(func), 1, 5.); assert_equal(1, tp.get_threads().size(), SPOT); } assert_true(func.called, SPOT); } TEST(test_launch_many) { functor<int, double> func; { tpool tp(4); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(functor<>()); tp.launch_new(std::ref(func), 1, 5.); } assert_true(func.called, SPOT); } struct cond_var_mock { bool called; cond_var_mock() : called{false} {} void notify_one() { called = true; } }; COLLECTION(functor_runner) { struct fixture { std::shared_ptr<std::atomic_bool> done_; cond_var_mock cond_var_; densitas::core::functor_runner<cond_var_mock> runner_; bool called_; fixture() : done_(std::make_shared<std::atomic_bool>(false)), cond_var_{}, runner_{done_, cond_var_}, called_{false} {} virtual ~fixture() UNITTEST_NOEXCEPT_FALSE { assert_true(called_, SPOT); assert_true(*done_, SPOT); assert_true(cond_var_.called, SPOT); } }; TEST_FIXTURE(fixture, test_with_no_args) { runner_([this](){ called_ = true; }); } TEST_FIXTURE(fixture, test_with_multiple_args) { runner_([this](int, double){ called_ = true; }, 42, 1.3); } } struct cv : densitas::core::condition_variable { bool get_flag() { return flag_; } }; COLLECTION(condition_variable) { TEST(test_constructor) { cv cond_var; assert_false(cond_var.get_flag(), SPOT); } TEST(test_notify_one) { cv cond_var; cond_var.notify_one(); assert_true(cond_var.get_flag(), SPOT); } TEST(test_notify_one_and_wait) { cv cond_var; cond_var.notify_one(); cond_var.wait(); assert_false(cond_var.get_flag(), SPOT); } TEST(test_notify_one_and_wait_in_separate_threads) { cv cond_var; std::thread([&cond_var]() { std::this_thread::sleep_for(std::chrono::milliseconds(20)); cond_var.notify_one(); }).detach(); cond_var.wait(); assert_false(cond_var.get_flag(), SPOT); } } } <|endoftext|>
<commit_before>/// /// \author John Farrier /// /// \copyright Copyright 2014 John Farrier /// /// 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 <celero/Archive.h> #include <celero/Celero.h> #include <celero/Console.h> #include <celero/Benchmark.h> #include <celero/TestVector.h> #include <celero/Utilities.h> #include <celero/Executor.h> #include <celero/Print.h> #include <celero/ResultTable.h> #include <celero/JUnit.h> #include <celero/CommandLine.h> #include <celero/Distribution.h> #include <celero/Callbacks.h> #include <iostream> #include <fstream> #include <cmath> using namespace celero; std::shared_ptr<celero::Benchmark> celero::RegisterTest(const char* groupName, const char* benchmarkName, const uint64_t samples, const uint64_t calls, std::shared_ptr<celero::Factory> experimentFactory, const double target) { auto bm = celero::TestVector::Instance()[groupName]; if(bm == nullptr) { bm = std::make_shared<Benchmark>(groupName); celero::TestVector::Instance().push_back(bm); } auto p = std::make_shared<Experiment>(bm); p->setIsBaselineCase(false); p->setName(benchmarkName); p->setSamples(samples); p->setCalls(calls); p->setFactory(experimentFactory); p->setBaselineTarget(target); bm->addExperiment(p); return bm; } std::shared_ptr<celero::Benchmark> celero::RegisterBaseline(const char* groupName, const char* benchmarkName, const uint64_t samples, const uint64_t calls, std::shared_ptr<celero::Factory> experimentFactory) { auto bm = celero::TestVector::Instance()[groupName]; if(bm == nullptr) { bm = std::make_shared<Benchmark>(groupName); celero::TestVector::Instance().push_back(bm); } auto p = std::make_shared<Experiment>(bm); p->setIsBaselineCase(true); p->setName(benchmarkName); p->setSamples(samples); p->setCalls(calls); p->setFactory(experimentFactory); p->setBaselineTarget(1.0); bm->setBaseline(p); return bm; } void celero::Run(int argc, char** argv) { cmdline::parser args; args.add("list", 'l', "Prints a list of all available benchmarks."); args.add<std::string>("group", 'g', "Runs a specific group of benchmarks.", false, ""); args.add<std::string>("outputTable", 't', "Saves a results table to the named file.", false, ""); args.add<std::string>("junit", 'j', "Saves a JUnit XML-formatted file to the named file.", false, ""); args.add<std::string>("archive", 'a', "Saves or updates a result archive file.", false, ""); args.add<uint64_t>("distribution", 'd', "Builds a file to help characterize the distribution of measurements and exits.", false, 0); args.parse_check(argc, argv); if(args.exist("list")) { TestVector& tests = celero::TestVector::Instance(); std::cout << "Avaliable tests:" << std::endl; for(unsigned int i = 0; i < tests.size(); i++) { auto bm = celero::TestVector::Instance()[i]; std::cout << " " << bm->getName() << std::endl; } return; } // Initial output print::GreenBar(""); std::cout << std::fixed; celero::console::SetConsoleColor(celero::console::ConsoleColor_Green_Bold); std::cout << "[ CELERO ]" << std::endl; celero::console::SetConsoleColor(celero::console::ConsoleColor_Default); celero::print::GreenBar(""); celero::timer::CachePerformanceFrequency(); // Shall we build a distribution? auto intArgument = args.get<uint64_t>("distribution"); if(intArgument > 0) { RunDistribution(intArgument); } // Has a result output file been specified? auto argument = args.get<std::string>("outputTable"); if(argument.empty() == false) { celero::ResultTable::Instance().setFileName(argument); celero::AddExperimentResultCompleteFunction( [](std::shared_ptr<celero::Result> p) { celero::ResultTable::Instance().add(p); }); } // Has a result output file been specified? argument = args.get<std::string>("archive"); if(argument.empty() == false) { celero::Archive::Instance().setFileName(argument); celero::AddExperimentResultCompleteFunction( [](std::shared_ptr<celero::Result> p) { celero::Archive::Instance().add(p); }); } // Has a JUnit output file been specified? argument = args.get<std::string>("junit"); if(argument.empty() == false) { celero::JUnit::Instance().setFileName(argument); celero::AddExperimentResultCompleteFunction( [](std::shared_ptr<celero::Result> p) { celero::JUnit::Instance().add(p); }); } std::string finalOutput; // Has a run group been specified? argument = args.get<std::string>("group"); if(argument.empty() == false) { executor::Run(argument); } else { executor::RunAll(); } // Final output. print::StageBanner(finalOutput); } <commit_msg>Sort tests alphabetically<commit_after>/// /// \author John Farrier /// /// \copyright Copyright 2014 John Farrier /// /// 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 <celero/Archive.h> #include <celero/Celero.h> #include <celero/Console.h> #include <celero/Benchmark.h> #include <celero/TestVector.h> #include <celero/Utilities.h> #include <celero/Executor.h> #include <celero/Print.h> #include <celero/ResultTable.h> #include <celero/JUnit.h> #include <celero/CommandLine.h> #include <celero/Distribution.h> #include <celero/Callbacks.h> #include <iostream> #include <fstream> #include <cmath> using namespace celero; std::shared_ptr<celero::Benchmark> celero::RegisterTest(const char* groupName, const char* benchmarkName, const uint64_t samples, const uint64_t calls, std::shared_ptr<celero::Factory> experimentFactory, const double target) { auto bm = celero::TestVector::Instance()[groupName]; if(bm == nullptr) { bm = std::make_shared<Benchmark>(groupName); celero::TestVector::Instance().push_back(bm); } auto p = std::make_shared<Experiment>(bm); p->setIsBaselineCase(false); p->setName(benchmarkName); p->setSamples(samples); p->setCalls(calls); p->setFactory(experimentFactory); p->setBaselineTarget(target); bm->addExperiment(p); return bm; } std::shared_ptr<celero::Benchmark> celero::RegisterBaseline(const char* groupName, const char* benchmarkName, const uint64_t samples, const uint64_t calls, std::shared_ptr<celero::Factory> experimentFactory) { auto bm = celero::TestVector::Instance()[groupName]; if(bm == nullptr) { bm = std::make_shared<Benchmark>(groupName); celero::TestVector::Instance().push_back(bm); } auto p = std::make_shared<Experiment>(bm); p->setIsBaselineCase(true); p->setName(benchmarkName); p->setSamples(samples); p->setCalls(calls); p->setFactory(experimentFactory); p->setBaselineTarget(1.0); bm->setBaseline(p); return bm; } void celero::Run(int argc, char** argv) { cmdline::parser args; args.add("list", 'l', "Prints a list of all available benchmarks."); args.add<std::string>("group", 'g', "Runs a specific group of benchmarks.", false, ""); args.add<std::string>("outputTable", 't', "Saves a results table to the named file.", false, ""); args.add<std::string>("junit", 'j', "Saves a JUnit XML-formatted file to the named file.", false, ""); args.add<std::string>("archive", 'a', "Saves or updates a result archive file.", false, ""); args.add<uint64_t>("distribution", 'd', "Builds a file to help characterize the distribution of measurements and exits.", false, 0); args.parse_check(argc, argv); if(args.exist("list")) { TestVector& tests = celero::TestVector::Instance(); std::cout << "Avaliable tests:" << std::endl; std::vector<std::string> test_names; for(unsigned int i = 0; i < tests.size(); i++) { auto bm = celero::TestVector::Instance()[i]; test_names.push_back(bm->getName()); } std::sort(test_names.begin(), test_names.end()); for(auto test_name: test_names) std::cout << " " << test_name << std::endl; return; } // Initial output print::GreenBar(""); std::cout << std::fixed; celero::console::SetConsoleColor(celero::console::ConsoleColor_Green_Bold); std::cout << "[ CELERO ]" << std::endl; celero::console::SetConsoleColor(celero::console::ConsoleColor_Default); celero::print::GreenBar(""); celero::timer::CachePerformanceFrequency(); // Shall we build a distribution? auto intArgument = args.get<uint64_t>("distribution"); if(intArgument > 0) { RunDistribution(intArgument); } // Has a result output file been specified? auto argument = args.get<std::string>("outputTable"); if(argument.empty() == false) { celero::ResultTable::Instance().setFileName(argument); celero::AddExperimentResultCompleteFunction( [](std::shared_ptr<celero::Result> p) { celero::ResultTable::Instance().add(p); }); } // Has a result output file been specified? argument = args.get<std::string>("archive"); if(argument.empty() == false) { celero::Archive::Instance().setFileName(argument); celero::AddExperimentResultCompleteFunction( [](std::shared_ptr<celero::Result> p) { celero::Archive::Instance().add(p); }); } // Has a JUnit output file been specified? argument = args.get<std::string>("junit"); if(argument.empty() == false) { celero::JUnit::Instance().setFileName(argument); celero::AddExperimentResultCompleteFunction( [](std::shared_ptr<celero::Result> p) { celero::JUnit::Instance().add(p); }); } std::string finalOutput; // Has a run group been specified? argument = args.get<std::string>("group"); if(argument.empty() == false) { executor::Run(argument); } else { executor::RunAll(); } // Final output. print::StageBanner(finalOutput); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (C) 2017 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "authenticator.hh" #include "authenticated_user.hh" #include "authenticator.hh" #include "authorizer.hh" #include "password_authenticator.hh" #include "default_authorizer.hh" #include "permission.hh" #include "db/config.hh" #include "utils/class_registrator.hh" namespace auth { class service; static const sstring PACKAGE_NAME("com.scylladb.auth."); static const sstring& transitional_authenticator_name() { static const sstring name = PACKAGE_NAME + "TransitionalAuthenticator"; return name; } static const sstring& transitional_authorizer_name() { static const sstring name = PACKAGE_NAME + "TransitionalAuthorizer"; return name; } class transitional_authenticator : public authenticator { std::unique_ptr<authenticator> _authenticator; public: static const sstring PASSWORD_AUTHENTICATOR_NAME; transitional_authenticator(cql3::query_processor& qp, ::service::migration_manager& mm) : transitional_authenticator(std::make_unique<password_authenticator>(qp, mm)) {} transitional_authenticator(std::unique_ptr<authenticator> a) : _authenticator(std::move(a)) {} future<> start() override { return _authenticator->start(); } future<> stop() override { return _authenticator->stop(); } const sstring& qualified_java_name() const override { return transitional_authenticator_name(); } bool require_authentication() const override { return true; } option_set supported_options() const override { return _authenticator->supported_options(); } option_set alterable_options() const override { return _authenticator->alterable_options(); } future<::shared_ptr<authenticated_user>> authenticate(const credentials_map& credentials) const override { auto i = credentials.find(authenticator::USERNAME_KEY); if ((i == credentials.end() || i->second.empty()) && (!credentials.count(PASSWORD_KEY) || credentials.at(PASSWORD_KEY).empty())) { // return anon user return make_ready_future<::shared_ptr<authenticated_user>>(::make_shared<authenticated_user>()); } return make_ready_future().then([this, &credentials] { return _authenticator->authenticate(credentials); }).handle_exception([](auto ep) { try { std::rethrow_exception(ep); } catch (exceptions::authentication_exception&) { // return anon user return make_ready_future<::shared_ptr<authenticated_user>>(::make_shared<authenticated_user>()); } }); } future<> create(sstring username, const option_map& options) override { return _authenticator->create(username, options); } future<> alter(sstring username, const option_map& options) override { return _authenticator->alter(username, options); } future<> drop(sstring username) override { return _authenticator->drop(username); } const resource_set& protected_resources() const override { return _authenticator->protected_resources(); } ::shared_ptr<sasl_challenge> new_sasl_challenge() const override { class sasl_wrapper : public sasl_challenge { public: sasl_wrapper(::shared_ptr<sasl_challenge> sasl) : _sasl(std::move(sasl)) {} bytes evaluate_response(bytes_view client_response) override { try { return _sasl->evaluate_response(client_response); } catch (exceptions::authentication_exception&) { _complete = true; return {}; } } bool is_complete() const { return _complete || _sasl->is_complete(); } future<::shared_ptr<authenticated_user>> get_authenticated_user() const { return _sasl->get_authenticated_user(); } private: ::shared_ptr<sasl_challenge> _sasl; bool _complete = false; }; return ::make_shared<sasl_wrapper>(_authenticator->new_sasl_challenge()); } }; class transitional_authorizer : public authorizer { std::unique_ptr<authorizer> _authorizer; public: transitional_authorizer(cql3::query_processor& qp, ::service::migration_manager& mm) : transitional_authorizer(std::make_unique<default_authorizer>(qp, mm)) {} transitional_authorizer(std::unique_ptr<authorizer> a) : _authorizer(std::move(a)) {} ~transitional_authorizer() {} future<> start() override { return _authorizer->start(); } future<> stop() override { return _authorizer->stop(); } const sstring& qualified_java_name() const override { return transitional_authorizer_name(); } future<permission_set> authorize(service& ser, ::shared_ptr<authenticated_user> user, resource resource) const override { return is_super_user(ser, *user).then([](bool s) { static const permission_set transitional_permissions = permission_set::of<permission::CREATE, permission::ALTER, permission::DROP, permission::SELECT, permission::MODIFY>(); return make_ready_future<permission_set>(s ? permissions::ALL : transitional_permissions); }); } future<> grant(::shared_ptr<authenticated_user> user, permission_set ps, resource r, sstring s) override { return _authorizer->grant(std::move(user), std::move(ps), std::move(r), std::move(s)); } future<> revoke(::shared_ptr<authenticated_user> user, permission_set ps, resource r, sstring s) override { return _authorizer->revoke(std::move(user), std::move(ps), std::move(r), std::move(s)); } future<std::vector<permission_details>> list(service& ser, ::shared_ptr<authenticated_user> user, permission_set ps, optional<resource> r, optional<sstring> s) const override { return _authorizer->list(ser, std::move(user), std::move(ps), std::move(r), std::move(s)); } future<> revoke_all(sstring s) override { return _authorizer->revoke_all(std::move(s)); } future<> revoke_all(resource r) override { return _authorizer->revoke_all(std::move(r)); } const resource_set& protected_resources() override { return _authorizer->protected_resources(); } future<> validate_configuration() const override { return _authorizer->validate_configuration(); } }; } // // To ensure correct initialization order, we unfortunately need to use string literals. // static const class_registrator< auth::authenticator, auth::transitional_authenticator, cql3::query_processor&, ::service::migration_manager&> transitional_authenticator_reg(auth::PACKAGE_NAME + "TransitionalAuthenticator"); static const class_registrator< auth::authorizer, auth::transitional_authorizer, cql3::query_processor&, ::service::migration_manager&> transitional_authorizer_reg(auth::PACKAGE_NAME + "TransitionalAuthorizer"); <commit_msg>auth: Fix transitional auth for non-valid credentials<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (C) 2017 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "authenticator.hh" #include "authenticated_user.hh" #include "authenticator.hh" #include "authorizer.hh" #include "password_authenticator.hh" #include "default_authorizer.hh" #include "permission.hh" #include "db/config.hh" #include "utils/class_registrator.hh" namespace auth { class service; static const sstring PACKAGE_NAME("com.scylladb.auth."); static const sstring& transitional_authenticator_name() { static const sstring name = PACKAGE_NAME + "TransitionalAuthenticator"; return name; } static const sstring& transitional_authorizer_name() { static const sstring name = PACKAGE_NAME + "TransitionalAuthorizer"; return name; } class transitional_authenticator : public authenticator { std::unique_ptr<authenticator> _authenticator; public: static const sstring PASSWORD_AUTHENTICATOR_NAME; transitional_authenticator(cql3::query_processor& qp, ::service::migration_manager& mm) : transitional_authenticator(std::make_unique<password_authenticator>(qp, mm)) {} transitional_authenticator(std::unique_ptr<authenticator> a) : _authenticator(std::move(a)) {} future<> start() override { return _authenticator->start(); } future<> stop() override { return _authenticator->stop(); } const sstring& qualified_java_name() const override { return transitional_authenticator_name(); } bool require_authentication() const override { return true; } option_set supported_options() const override { return _authenticator->supported_options(); } option_set alterable_options() const override { return _authenticator->alterable_options(); } future<::shared_ptr<authenticated_user>> authenticate(const credentials_map& credentials) const override { auto i = credentials.find(authenticator::USERNAME_KEY); if ((i == credentials.end() || i->second.empty()) && (!credentials.count(PASSWORD_KEY) || credentials.at(PASSWORD_KEY).empty())) { // return anon user return make_ready_future<::shared_ptr<authenticated_user>>(::make_shared<authenticated_user>()); } return make_ready_future().then([this, &credentials] { return _authenticator->authenticate(credentials); }).handle_exception([](auto ep) { try { std::rethrow_exception(ep); } catch (exceptions::authentication_exception&) { // return anon user return make_ready_future<::shared_ptr<authenticated_user>>(::make_shared<authenticated_user>()); } }); } future<> create(sstring username, const option_map& options) override { return _authenticator->create(username, options); } future<> alter(sstring username, const option_map& options) override { return _authenticator->alter(username, options); } future<> drop(sstring username) override { return _authenticator->drop(username); } const resource_set& protected_resources() const override { return _authenticator->protected_resources(); } ::shared_ptr<sasl_challenge> new_sasl_challenge() const override { class sasl_wrapper : public sasl_challenge { public: sasl_wrapper(::shared_ptr<sasl_challenge> sasl) : _sasl(std::move(sasl)) {} bytes evaluate_response(bytes_view client_response) override { try { return _sasl->evaluate_response(client_response); } catch (exceptions::authentication_exception&) { _complete = true; return {}; } } bool is_complete() const { return _complete || _sasl->is_complete(); } future<::shared_ptr<authenticated_user>> get_authenticated_user() const { return futurize_apply([this] { return _sasl->get_authenticated_user().handle_exception([](auto ep) { try { std::rethrow_exception(ep); } catch (exceptions::authentication_exception&) { // return anon user return make_ready_future<::shared_ptr<authenticated_user>>(::make_shared<authenticated_user>()); } }); }); } private: ::shared_ptr<sasl_challenge> _sasl; bool _complete = false; }; return ::make_shared<sasl_wrapper>(_authenticator->new_sasl_challenge()); } }; class transitional_authorizer : public authorizer { std::unique_ptr<authorizer> _authorizer; public: transitional_authorizer(cql3::query_processor& qp, ::service::migration_manager& mm) : transitional_authorizer(std::make_unique<default_authorizer>(qp, mm)) {} transitional_authorizer(std::unique_ptr<authorizer> a) : _authorizer(std::move(a)) {} ~transitional_authorizer() {} future<> start() override { return _authorizer->start(); } future<> stop() override { return _authorizer->stop(); } const sstring& qualified_java_name() const override { return transitional_authorizer_name(); } future<permission_set> authorize(service& ser, ::shared_ptr<authenticated_user> user, resource resource) const override { return is_super_user(ser, *user).then([](bool s) { static const permission_set transitional_permissions = permission_set::of<permission::CREATE, permission::ALTER, permission::DROP, permission::SELECT, permission::MODIFY>(); return make_ready_future<permission_set>(s ? permissions::ALL : transitional_permissions); }); } future<> grant(::shared_ptr<authenticated_user> user, permission_set ps, resource r, sstring s) override { return _authorizer->grant(std::move(user), std::move(ps), std::move(r), std::move(s)); } future<> revoke(::shared_ptr<authenticated_user> user, permission_set ps, resource r, sstring s) override { return _authorizer->revoke(std::move(user), std::move(ps), std::move(r), std::move(s)); } future<std::vector<permission_details>> list(service& ser, ::shared_ptr<authenticated_user> user, permission_set ps, optional<resource> r, optional<sstring> s) const override { return _authorizer->list(ser, std::move(user), std::move(ps), std::move(r), std::move(s)); } future<> revoke_all(sstring s) override { return _authorizer->revoke_all(std::move(s)); } future<> revoke_all(resource r) override { return _authorizer->revoke_all(std::move(r)); } const resource_set& protected_resources() override { return _authorizer->protected_resources(); } future<> validate_configuration() const override { return _authorizer->validate_configuration(); } }; } // // To ensure correct initialization order, we unfortunately need to use string literals. // static const class_registrator< auth::authenticator, auth::transitional_authenticator, cql3::query_processor&, ::service::migration_manager&> transitional_authenticator_reg(auth::PACKAGE_NAME + "TransitionalAuthenticator"); static const class_registrator< auth::authorizer, auth::transitional_authorizer, cql3::query_processor&, ::service::migration_manager&> transitional_authorizer_reg(auth::PACKAGE_NAME + "TransitionalAuthorizer"); <|endoftext|>