text
stringlengths
54
60.6k
<commit_before>/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usServiceReference.h" #include "usServiceReferencePrivate.h" #include "usServiceRegistrationPrivate.h" #include "usModule.h" #include "usModulePrivate.h" US_BEGIN_NAMESPACE typedef ServiceRegistrationPrivate::MutexType MutexType; typedef MutexLock<MutexType> MutexLocker; ServiceReference::ServiceReference() : d(new ServiceReferencePrivate(0)) { } ServiceReference::ServiceReference(const ServiceReference& ref) : d(ref.d) { d->ref.Ref(); } ServiceReference::ServiceReference(ServiceRegistrationPrivate* reg) : d(new ServiceReferencePrivate(reg)) { } ServiceReference::operator bool() const { return GetModule() != 0; } ServiceReference& ServiceReference::operator=(int null) { if (null == 0) { if (!d->ref.Deref()) delete d; d = new ServiceReferencePrivate(0); } return *this; } ServiceReference::~ServiceReference() { if (!d->ref.Deref()) delete d; } Any ServiceReference::GetProperty(const std::string& key) const { MutexLocker lock(d->registration->propsLock); ServiceProperties::const_iterator iter = d->registration->properties.find(key); if (iter != d->registration->properties.end()) return iter->second; return Any(); } void ServiceReference::GetPropertyKeys(std::vector<std::string>& keys) const { MutexLocker lock(d->registration->propsLock); ServiceProperties::const_iterator iterEnd = d->registration->properties.end(); for (ServiceProperties::const_iterator iter = d->registration->properties.begin(); iter != iterEnd; ++iter) { keys.push_back(iter->first); } } Module* ServiceReference::GetModule() const { if (d->registration == 0 || d->registration->module == 0) { return 0; } return d->registration->module->q; } void ServiceReference::GetUsingModules(std::vector<Module*>& modules) const { MutexLocker lock(d->registration->propsLock); ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); for (ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); iter != end; ++iter) { modules.push_back(iter->first); } } bool ServiceReference::operator<(const ServiceReference& reference) const { int r1 = 0; int r2 = 0; Any anyR1 = GetProperty(ServiceConstants::SERVICE_RANKING()); Any anyR2 = reference.GetProperty(ServiceConstants::SERVICE_RANKING()); if (anyR1.Type() == typeid(int)) r1 = any_cast<int>(anyR1); if (anyR2.Type() == typeid(int)) r2 = any_cast<int>(anyR2); if (r1 != r2) { // use ranking if ranking differs return r1 < r2; } else { long int id1 = any_cast<long int>(GetProperty(ServiceConstants::SERVICE_ID())); long int id2 = any_cast<long int>(reference.GetProperty(ServiceConstants::SERVICE_ID())); // otherwise compare using IDs, // is less than if it has a higher ID. return id2 < id1; } } bool ServiceReference::operator==(const ServiceReference& reference) const { return d->registration == reference.d->registration; } ServiceReference& ServiceReference::operator=(const ServiceReference& reference) { ServiceReferencePrivate* curr_d = d; d = reference.d; d->ref.Ref(); if (!curr_d->ref.Deref()) delete curr_d; return *this; } std::size_t ServiceReference::Hash() const { using namespace US_HASH_FUNCTION_NAMESPACE; return US_HASH_FUNCTION(ServiceRegistrationPrivate*, this->d->registration); } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const ServiceReference& serviceRef) { os << "Reference for service object registered from " << serviceRef.GetModule()->GetName() << " " << serviceRef.GetModule()->GetVersion() << " ("; std::vector<std::string> keys; serviceRef.GetPropertyKeys(keys); int keySize = keys.size(); for(int i = 0; i < keySize; ++i) { os << keys[i] << "=" << serviceRef.GetProperty(keys[i]); if (i < keySize-1) os << ","; } os << ")"; return os; } <commit_msg>Fixed size_t / int issue in usServiceReference<commit_after>/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usServiceReference.h" #include "usServiceReferencePrivate.h" #include "usServiceRegistrationPrivate.h" #include "usModule.h" #include "usModulePrivate.h" US_BEGIN_NAMESPACE typedef ServiceRegistrationPrivate::MutexType MutexType; typedef MutexLock<MutexType> MutexLocker; ServiceReference::ServiceReference() : d(new ServiceReferencePrivate(0)) { } ServiceReference::ServiceReference(const ServiceReference& ref) : d(ref.d) { d->ref.Ref(); } ServiceReference::ServiceReference(ServiceRegistrationPrivate* reg) : d(new ServiceReferencePrivate(reg)) { } ServiceReference::operator bool() const { return GetModule() != 0; } ServiceReference& ServiceReference::operator=(int null) { if (null == 0) { if (!d->ref.Deref()) delete d; d = new ServiceReferencePrivate(0); } return *this; } ServiceReference::~ServiceReference() { if (!d->ref.Deref()) delete d; } Any ServiceReference::GetProperty(const std::string& key) const { MutexLocker lock(d->registration->propsLock); ServiceProperties::const_iterator iter = d->registration->properties.find(key); if (iter != d->registration->properties.end()) return iter->second; return Any(); } void ServiceReference::GetPropertyKeys(std::vector<std::string>& keys) const { MutexLocker lock(d->registration->propsLock); ServiceProperties::const_iterator iterEnd = d->registration->properties.end(); for (ServiceProperties::const_iterator iter = d->registration->properties.begin(); iter != iterEnd; ++iter) { keys.push_back(iter->first); } } Module* ServiceReference::GetModule() const { if (d->registration == 0 || d->registration->module == 0) { return 0; } return d->registration->module->q; } void ServiceReference::GetUsingModules(std::vector<Module*>& modules) const { MutexLocker lock(d->registration->propsLock); ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); for (ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); iter != end; ++iter) { modules.push_back(iter->first); } } bool ServiceReference::operator<(const ServiceReference& reference) const { int r1 = 0; int r2 = 0; Any anyR1 = GetProperty(ServiceConstants::SERVICE_RANKING()); Any anyR2 = reference.GetProperty(ServiceConstants::SERVICE_RANKING()); if (anyR1.Type() == typeid(int)) r1 = any_cast<int>(anyR1); if (anyR2.Type() == typeid(int)) r2 = any_cast<int>(anyR2); if (r1 != r2) { // use ranking if ranking differs return r1 < r2; } else { long int id1 = any_cast<long int>(GetProperty(ServiceConstants::SERVICE_ID())); long int id2 = any_cast<long int>(reference.GetProperty(ServiceConstants::SERVICE_ID())); // otherwise compare using IDs, // is less than if it has a higher ID. return id2 < id1; } } bool ServiceReference::operator==(const ServiceReference& reference) const { return d->registration == reference.d->registration; } ServiceReference& ServiceReference::operator=(const ServiceReference& reference) { ServiceReferencePrivate* curr_d = d; d = reference.d; d->ref.Ref(); if (!curr_d->ref.Deref()) delete curr_d; return *this; } std::size_t ServiceReference::Hash() const { using namespace US_HASH_FUNCTION_NAMESPACE; return US_HASH_FUNCTION(ServiceRegistrationPrivate*, this->d->registration); } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const ServiceReference& serviceRef) { os << "Reference for service object registered from " << serviceRef.GetModule()->GetName() << " " << serviceRef.GetModule()->GetVersion() << " ("; std::vector<std::string> keys; serviceRef.GetPropertyKeys(keys); size_t keySize = keys.size(); for(size_t i = 0; i < keySize; ++i) { os << keys[i] << "=" << serviceRef.GetProperty(keys[i]); if (i < keySize-1) os << ","; } os << ")"; return os; } <|endoftext|>
<commit_before>/** * @file Event.hpp * @author Denis Kotov * @date 10 Jun 2017 * @brief Contains abstract class for Pack Buffer * @copyright MIT License. Open source: */ #ifndef ICC_EVENT_HPP #define ICC_EVENT_HPP #include <vector> #include <map> #include <tuple> #include <utility> #include <algorithm> #include "IComponent.hpp" template <typename _T> class Event; template <typename _R, typename ... _Args> class Event<_R(_Args...)> { public: using tCallback = _R(IComponent::*)(_Args...); using tUncheckedObjectAndCallbacks = std::pair<IComponent *, tCallback>; using tUncheckedListCallbacks = std::vector<tUncheckedObjectAndCallbacks>; using tCheckedObjectAndCallbacks = std::pair<std::weak_ptr<IComponent>, tCallback>; using tCheckedListCallbacks = std::vector<tCheckedObjectAndCallbacks>; public: Event() = default; Event(Event const&) = default; Event(Event &&) = default; public: /** * Unsafe function for connect Event to object _listener with _callback * User should be confident that _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void connect(_R(_Component::*_callback)(_Args...), _Component * _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if (_listener) { unchecked_listeners_.emplace_back( static_cast<IComponent*>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback)); } } /** * Safe function for connect Event to object _listener with _callback * User can check if _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void connect(_R(_Component::*_callback)(_Args...), std::shared_ptr<_Component> _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if(_listener) { checked_listeners_.emplace_back( static_cast<std::shared_ptr<IComponent>>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback) ); } } /** * Unsafe function for disconnect Event from object _listener with _callback * User should be confident that _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void disconnect(_R(_Component::*_callback)(_Args...), _Component * _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if (_listener) { std::pair<IComponent *, tCallback> removedCallback = { static_cast<IComponent*>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback) }; auto erase = std::remove(unchecked_listeners_.begin(), unchecked_listeners_.end(), removedCallback); unchecked_listeners_.erase(erase, unchecked_listeners_.end()); } } /** * Safe function for disconnect Event from object _listener with _callback * User can check if _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void disconnect(_R(_Component::*_callback)(_Args...), std::shared_ptr<_Component> _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if(_listener) { std::pair<std::weak_ptr<IComponent>, tCallback> removedCallback = { static_cast<std::shared_ptr<IComponent>>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback) }; auto erase = std::remove_if(checked_listeners_.begin(), checked_listeners_.end(), [=](const std::pair<std::weak_ptr<IComponent>, tCallback> & rad) { bool result = false; if (auto _observer = rad.first.lock()) { result = (_callback == static_cast<void(_Component::*)(_Args...)>(rad.second)); } else { result = true; } return result; }); checked_listeners_.erase(erase, checked_listeners_.end()); } } /** * Method for calling Event * @param _args Parameters for calling Event */ void operator()(_Args... _args) { for (auto & listener : unchecked_listeners_) { (listener.first)->push([=]() mutable { ((listener.first)->*(listener.second))(std::forward<_Args>(_args)...); }); } for (auto & listener : checked_listeners_) { if (auto _observer = listener.first.lock()) { _observer->push([=]() mutable { ((_observer.get())->*(listener.second))(std::forward<_Args>(_args)...); }); } else { // TODO(redra): Delete it } } } /** * Method for calling const Event * @param _args Parameters for calling const Event */ void operator()(_Args... _args) const { for (auto & listener : unchecked_listeners_) { (listener.first)->push([=]() mutable { ((listener.first)->*(listener.second))(std::forward<_Args>(_args)...); }); } for (auto & listener : checked_listeners_) { if (auto _observer = listener.first.lock()) { _observer->push([=]() mutable { ((_observer.get())->*(listener.second))(std::forward<_Args>(_args)...); }); } else { // TODO(redra): Delete it } } } /** * Convertion function is used to convert Event to std::function * @return std::function object */ operator std::function<_R(_Args...)>() { return [event = *this](_Args... _args) mutable { for (auto & listener : event.unchecked_listeners_) { (listener.first)->push([=]() mutable { ((listener.first)->*(listener.second))(std::forward<_Args>(_args)...); }); } for (auto & listener : event.checked_listeners_) { if (auto _observer = listener.first.lock()) { _observer->push([=]() mutable { ((_observer.get())->*(listener.second))(std::forward<_Args>(_args)...); }); } else { // TODO(redra): Delete it } } return _R(); }; } private: tUncheckedListCallbacks unchecked_listeners_; tCheckedListCallbacks checked_listeners_; }; #endif //ICC_EVENT_HPP <commit_msg>Removed unsafe listeners in operator std::function<...><commit_after>/** * @file Event.hpp * @author Denis Kotov * @date 10 Jun 2017 * @brief Contains abstract class for Pack Buffer * @copyright MIT License. Open source: */ #ifndef ICC_EVENT_HPP #define ICC_EVENT_HPP #include <vector> #include <map> #include <tuple> #include <utility> #include <algorithm> #include "IComponent.hpp" template <typename _T> class Event; template <typename _R, typename ... _Args> class Event<_R(_Args...)> { public: using tCallback = _R(IComponent::*)(_Args...); using tUncheckedObjectAndCallbacks = std::pair<IComponent *, tCallback>; using tUncheckedListCallbacks = std::vector<tUncheckedObjectAndCallbacks>; using tCheckedObjectAndCallbacks = std::pair<std::weak_ptr<IComponent>, tCallback>; using tCheckedListCallbacks = std::vector<tCheckedObjectAndCallbacks>; public: Event() = default; Event(Event const&) = default; Event(Event &&) = default; public: /** * Unsafe function for connect Event to object _listener with _callback * User should be confident that _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void connect(_R(_Component::*_callback)(_Args...), _Component * _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if (_listener) { unchecked_listeners_.emplace_back( static_cast<IComponent*>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback)); } } /** * Safe function for connect Event to object _listener with _callback * User can check if _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void connect(_R(_Component::*_callback)(_Args...), std::shared_ptr<_Component> _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if(_listener) { checked_listeners_.emplace_back( static_cast<std::shared_ptr<IComponent>>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback) ); } } /** * Unsafe function for disconnect Event from object _listener with _callback * User should be confident that _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void disconnect(_R(_Component::*_callback)(_Args...), _Component * _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if (_listener) { std::pair<IComponent *, tCallback> removedCallback = { static_cast<IComponent*>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback) }; auto erase = std::remove(unchecked_listeners_.begin(), unchecked_listeners_.end(), removedCallback); unchecked_listeners_.erase(erase, unchecked_listeners_.end()); } } /** * Safe function for disconnect Event from object _listener with _callback * User can check if _listener is exist at moment of calling callback * @tparam _Component Type of object that listen Event * @param _callback method in object that listen Event * @param _listener Object that listen Event */ template <typename _Component> void disconnect(_R(_Component::*_callback)(_Args...), std::shared_ptr<_Component> _listener) { static_assert(std::is_base_of<IComponent, _Component>::value, "_listener is not derived from IComponent"); if(_listener) { std::pair<std::weak_ptr<IComponent>, tCallback> removedCallback = { static_cast<std::shared_ptr<IComponent>>(_listener), static_cast<_R(IComponent::*)(_Args...)>(_callback) }; auto erase = std::remove_if(checked_listeners_.begin(), checked_listeners_.end(), [=](const std::pair<std::weak_ptr<IComponent>, tCallback> & rad) { bool result = false; if (auto _observer = rad.first.lock()) { result = (_callback == static_cast<void(_Component::*)(_Args...)>(rad.second)); } else { result = true; } return result; }); checked_listeners_.erase(erase, checked_listeners_.end()); } } /** * Method for calling Event * @param _args Parameters for calling Event */ void operator()(_Args... _args) { for (auto & listener : unchecked_listeners_) { (listener.first)->push([=]() mutable { ((listener.first)->*(listener.second))(std::forward<_Args>(_args)...); }); } for (auto & listener : checked_listeners_) { if (auto _observer = listener.first.lock()) { _observer->push([=]() mutable { ((_observer.get())->*(listener.second))(std::forward<_Args>(_args)...); }); } else { // TODO(redra): Delete it } } } /** * Method for calling const Event * @param _args Parameters for calling const Event */ void operator()(_Args... _args) const { for (auto & listener : unchecked_listeners_) { (listener.first)->push([=]() mutable { ((listener.first)->*(listener.second))(std::forward<_Args>(_args)...); }); } for (auto & listener : checked_listeners_) { if (auto _observer = listener.first.lock()) { _observer->push([=]() mutable { ((_observer.get())->*(listener.second))(std::forward<_Args>(_args)...); }); } else { // TODO(redra): Delete it } } } /** * Convertion function is used to convert Event to std::function * @return std::function object */ operator std::function<_R(_Args...)>() { return [event = *this](_Args... _args) mutable { for (auto & listener : event.checked_listeners_) { if (auto _observer = listener.first.lock()) { _observer->push([=]() mutable { ((_observer.get())->*(listener.second))(std::forward<_Args>(_args)...); }); } else { // TODO(redra): Delete it } } return _R(); }; } private: tUncheckedListCallbacks unchecked_listeners_; tCheckedListCallbacks checked_listeners_; }; #endif //ICC_EVENT_HPP <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 Intel 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. // // ======================================================================== // #include "AMRVolume.h" // ospray #include "ospray/common/Model.h" #include "ospray/common/Data.h" #include "ospray/transferFunction/TransferFunction.h" #include "ospcommon/tasking/parallel_for.h" // ispc exports #include "AMRVolume_ispc.h" #include "finest_ispc.h" #include "current_ispc.h" #include "octant_ispc.h" // stl #include <set> #include <map> namespace ospray { namespace amr { AMRVolume::AMRVolume() { ispcEquivalent = ispc::AMRVolume_create(this); } std::string AMRVolume::toString() const { return "ospray::AMRVolume"; } /*! Copy voxels into the volume at the given index (non-zero return value indicates success). */ int AMRVolume::setRegion(const void *source, const vec3i &index, const vec3i &count) { FATAL("'setRegion()' doesn't make sense for AMR volumes; " "they can only be set from existing data"); } //! Allocate storage and populate the volume. void AMRVolume::commit() { updateEditableParameters(); // Make the voxel value range visible to the application. if (findParam("voxelRange") == nullptr) set("voxelRange", voxelRange); else voxelRange = getParam2f("voxelRange", voxelRange); auto methodStringFromEnv = getEnvVar<std::string>("OSPRAY_AMR_METHOD"); std::string methodString = "current"; if (methodStringFromEnv.first) methodString = methodStringFromEnv.second; else methodString = getParamString("amrMethod","current"); if (methodString == "finest" || methodString == "finestLevel") ispc::AMR_install_finest(getIE()); else if (methodString == "current" || methodString == "currentLevel") ispc::AMR_install_current(getIE()); else if (methodString == "octant") ispc::AMR_install_octant(getIE()); if (data != nullptr) //TODO: support data updates return; brickInfoData = getParamData("brickInfo"); assert(brickInfoData); assert(brickInfoData->data); brickDataData = getParamData("brickData"); assert(brickDataData); assert(brickDataData->data); assert(data == nullptr); data = new AMRData(*brickInfoData,*brickDataData); assert(accel == nullptr); accel = new AMRAccel(*data); Ref<TransferFunction> xf = (TransferFunction*)getParamObject("transferFunction"); assert(xf); float finestLevelCellWidth = data->brick[0]->cellWidth; box3i rootLevelBox = empty; for (int i=0;i<data->numBricks;i++) { if (data->brick[i]->level == 0) rootLevelBox.extend(data->brick[i]->box); finestLevelCellWidth = min(finestLevelCellWidth,data->brick[i]->cellWidth); } vec3i rootGridDims = rootLevelBox.size()+vec3i(1); ospLogF(1) << "found root level dimensions of " << rootGridDims; // finding coarset cell size: float coarsestCellWidth = 0.f; for (int i=0;i<data->numBricks;i++) coarsestCellWidth = max(coarsestCellWidth,data->brick[i]->cellWidth); ospLogF(1) << "coarsest cell width is " << coarsestCellWidth << std::endl; float samplingStep = 0.1f*coarsestCellWidth; auto rateFromString = getEnvVar<std::string>("OSPRAY_AMR_SAMPLING_STEP"); if (rateFromString.first) samplingStep = atof(rateFromString.second.c_str()); box3f worldBounds = accel->worldBounds; ispc::AMRVolume_set(getIE(), xf->getIE(), (ispc::box3f&)worldBounds, samplingStep); ispc::AMRVolume_setAMR(getIE(), accel->node.size(), &accel->node[0], accel->leaf.size(), &accel->leaf[0], accel->level.size(), &accel->level[0], (ispc::box3f &)worldBounds); ospcommon::tasking::parallel_for(accel->leaf.size(),[&](int leafID) { ispc::AMRVolume_computeValueRangeOfLeaf(getIE(), leafID); }); } OSP_REGISTER_VOLUME(AMRVolume, AMRVolume); OSP_REGISTER_VOLUME(AMRVolume, amr_volume); } // ::ospray::amr } // ::ospray<commit_msg>build fix - file rename not caught locally<commit_after>// ======================================================================== // // Copyright 2009-2017 Intel 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. // // ======================================================================== // #include "AMRVolume.h" // ospray #include "ospray/common/Model.h" #include "ospray/common/Data.h" #include "ospray/transferFunction/TransferFunction.h" #include "ospcommon/tasking/parallel_for.h" // ispc exports #include "AMRVolume_ispc.h" #include "method_finest_ispc.h" #include "method_current_ispc.h" #include "method_octant_ispc.h" // stl #include <set> #include <map> namespace ospray { namespace amr { AMRVolume::AMRVolume() { ispcEquivalent = ispc::AMRVolume_create(this); } std::string AMRVolume::toString() const { return "ospray::AMRVolume"; } /*! Copy voxels into the volume at the given index (non-zero return value indicates success). */ int AMRVolume::setRegion(const void *source, const vec3i &index, const vec3i &count) { FATAL("'setRegion()' doesn't make sense for AMR volumes; " "they can only be set from existing data"); } //! Allocate storage and populate the volume. void AMRVolume::commit() { updateEditableParameters(); // Make the voxel value range visible to the application. if (findParam("voxelRange") == nullptr) set("voxelRange", voxelRange); else voxelRange = getParam2f("voxelRange", voxelRange); auto methodStringFromEnv = getEnvVar<std::string>("OSPRAY_AMR_METHOD"); std::string methodString = "current"; if (methodStringFromEnv.first) methodString = methodStringFromEnv.second; else methodString = getParamString("amrMethod","current"); if (methodString == "finest" || methodString == "finestLevel") ispc::AMR_install_finest(getIE()); else if (methodString == "current" || methodString == "currentLevel") ispc::AMR_install_current(getIE()); else if (methodString == "octant") ispc::AMR_install_octant(getIE()); if (data != nullptr) //TODO: support data updates return; brickInfoData = getParamData("brickInfo"); assert(brickInfoData); assert(brickInfoData->data); brickDataData = getParamData("brickData"); assert(brickDataData); assert(brickDataData->data); assert(data == nullptr); data = new AMRData(*brickInfoData,*brickDataData); assert(accel == nullptr); accel = new AMRAccel(*data); Ref<TransferFunction> xf = (TransferFunction*)getParamObject("transferFunction"); assert(xf); float finestLevelCellWidth = data->brick[0]->cellWidth; box3i rootLevelBox = empty; for (int i=0;i<data->numBricks;i++) { if (data->brick[i]->level == 0) rootLevelBox.extend(data->brick[i]->box); finestLevelCellWidth = min(finestLevelCellWidth,data->brick[i]->cellWidth); } vec3i rootGridDims = rootLevelBox.size()+vec3i(1); ospLogF(1) << "found root level dimensions of " << rootGridDims; // finding coarset cell size: float coarsestCellWidth = 0.f; for (int i=0;i<data->numBricks;i++) coarsestCellWidth = max(coarsestCellWidth,data->brick[i]->cellWidth); ospLogF(1) << "coarsest cell width is " << coarsestCellWidth << std::endl; float samplingStep = 0.1f*coarsestCellWidth; auto rateFromString = getEnvVar<std::string>("OSPRAY_AMR_SAMPLING_STEP"); if (rateFromString.first) samplingStep = atof(rateFromString.second.c_str()); box3f worldBounds = accel->worldBounds; ispc::AMRVolume_set(getIE(), xf->getIE(), (ispc::box3f&)worldBounds, samplingStep); ispc::AMRVolume_setAMR(getIE(), accel->node.size(), &accel->node[0], accel->leaf.size(), &accel->leaf[0], accel->level.size(), &accel->level[0], (ispc::box3f &)worldBounds); ospcommon::tasking::parallel_for(accel->leaf.size(),[&](int leafID) { ispc::AMRVolume_computeValueRangeOfLeaf(getIE(), leafID); }); } OSP_REGISTER_VOLUME(AMRVolume, AMRVolume); OSP_REGISTER_VOLUME(AMRVolume, amr_volume); } // ::ospray::amr } // ::ospray<|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // // Arion // // Extract metadata and create beautiful thumbnails of your images. // // ------------ // main.cpp // ------------ // // Copyright (c) 2015 Paul Filitchkin, Snapwire // // 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 organization 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 HOLDER 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. // //------------------------------------------------------------------------------ // Local #include "models/operation.hpp" #include "models/resize.hpp" #include "models/read_meta.hpp" #include "utils/utils.hpp" #include "arion.hpp" // Boost #include <boost/exception/info.hpp> #include <boost/exception/error_info.hpp> #include <boost/exception/all.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/lexical_cast.hpp> // Stdlib #include <iostream> #include <string> using namespace boost::program_options; using namespace std; #define ARION_VERSION "0.3.1" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void showHelp(options_description& desc) { cerr << desc << endl; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { try { positional_options_description p; p.add("input", 1); string description = "Arion v"; description += ARION_VERSION; description += "\n\n Arguments"; options_description desc(description); desc.add_options() ("help", "Produce this help message") ("version", "Print version") ("input", value< string >(), "The input operations to execute in JSON"); variables_map vm; store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm); notify(vm); string inputJson; if (vm.count("help")) { showHelp(desc); return 1; } if (vm.count("version")) { cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl; return 0; } if (vm.count("input")) { inputJson = vm["input"].as<string>(); } else { cout << "You must provide the input operations to execute" << endl << endl; showHelp(desc); return 1; } Arion arion; if (!arion.setup(inputJson)) { cout << arion.getJson(); exit(-1); } bool result = arion.run(); cout << arion.getJson(); if (result) { exit(0); } else { exit(-1); } } catch (std::exception& e) { Utils::exitWithError(e.what()); } return 0; } <commit_msg>version update<commit_after>//------------------------------------------------------------------------------ // // Arion // // Extract metadata and create beautiful thumbnails of your images. // // ------------ // main.cpp // ------------ // // Copyright (c) 2015 Paul Filitchkin, Snapwire // // 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 organization 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 HOLDER 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. // //------------------------------------------------------------------------------ // Local #include "models/operation.hpp" #include "models/resize.hpp" #include "models/read_meta.hpp" #include "utils/utils.hpp" #include "arion.hpp" // Boost #include <boost/exception/info.hpp> #include <boost/exception/error_info.hpp> #include <boost/exception/all.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/lexical_cast.hpp> // Stdlib #include <iostream> #include <string> using namespace boost::program_options; using namespace std; #define ARION_VERSION "0.3.2" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void showHelp(options_description& desc) { cerr << desc << endl; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { try { positional_options_description p; p.add("input", 1); string description = "Arion v"; description += ARION_VERSION; description += "\n\n Arguments"; options_description desc(description); desc.add_options() ("help", "Produce this help message") ("version", "Print version") ("input", value< string >(), "The input operations to execute in JSON"); variables_map vm; store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm); notify(vm); string inputJson; if (vm.count("help")) { showHelp(desc); return 1; } if (vm.count("version")) { cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl; return 0; } if (vm.count("input")) { inputJson = vm["input"].as<string>(); } else { cout << "You must provide the input operations to execute" << endl << endl; showHelp(desc); return 1; } Arion arion; if (!arion.setup(inputJson)) { cout << arion.getJson(); exit(-1); } bool result = arion.run(); cout << arion.getJson(); if (result) { exit(0); } else { exit(-1); } } catch (std::exception& e) { Utils::exitWithError(e.what()); } return 0; } <|endoftext|>
<commit_before>#include "vmainwindow.h" #include <QApplication> #include <QTranslator> #include <QDebug> #include <QLibraryInfo> #include <QFile> #include <QTextCodec> #include <QFileInfo> #include <QStringList> #include <QDir> #include "utils/vutils.h" #include "vsingleinstanceguard.h" #include "vconfigmanager.h" VConfigManager *g_config; #if defined(QT_NO_DEBUG) QFile g_logFile; #endif void VLogger(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toUtf8(); QString header; switch (type) { case QtDebugMsg: header = "Debug:"; break; case QtInfoMsg: header = "Info:"; break; case QtWarningMsg: header = "Warning:"; break; case QtCriticalMsg: header = "Critical:"; break; case QtFatalMsg: header = "Fatal:"; } #if defined(QT_NO_DEBUG) Q_UNUSED(context); QTextStream stream(&g_logFile); #if defined(Q_OS_WIN) stream << header << localMsg << "\r\n"; #else stream << header << localMsg << "\n"; #endif if (type == QtFatalMsg) { g_logFile.close(); abort(); } #else std::string fileStr = QFileInfo(context.file).fileName().toStdString(); const char *file = fileStr.c_str(); switch (type) { case QtDebugMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtInfoMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtWarningMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtCriticalMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtFatalMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); abort(); } fflush(stderr); #endif } int main(int argc, char *argv[]) { VSingleInstanceGuard guard; bool canRun = guard.tryRun(); #if defined(QT_NO_DEBUG) if (canRun) { g_logFile.setFileName(VConfigManager::getLogFilePath()); g_logFile.open(QIODevice::WriteOnly); } #endif if (canRun) { qInstallMessageHandler(VLogger); } QTextCodec *codec = QTextCodec::codecForName("UTF8"); if (codec) { QTextCodec::setCodecForLocale(codec); } QApplication app(argc, argv); // The file path passed via command line arguments. QStringList filePaths = VUtils::filterFilePathsToOpen(app.arguments().mid(1)); qDebug() << "command line arguments" << app.arguments(); qDebug() << "files to open from arguments" << filePaths; if (!canRun) { // Ask another instance to open files passed in. if (!filePaths.isEmpty()) { guard.openExternalFiles(filePaths); } else { guard.showInstance(); } return 0; } VConfigManager vconfig; vconfig.initialize(); g_config = &vconfig; QString locale = VUtils::getLocale(); // Set default locale. if (locale == "zh_CN") { QLocale::setDefault(QLocale(QLocale::Chinese, QLocale::China)); } // load translation for Qt QTranslator qtTranslator; if (!qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qtTranslator.load("qt_" + locale, "translations"); } app.installTranslator(&qtTranslator); // load translation for vnote QTranslator translator; if (translator.load("vnote_" + locale, ":/translations")) { app.installTranslator(&translator); } VMainWindow w(&guard); QString style = VUtils::readFileFromDisk(":/resources/vnote.qss"); if (!style.isEmpty()) { VUtils::processStyle(style, w.getPalette()); app.setStyleSheet(style); } w.show(); w.openStartupPages(); w.openFiles(filePaths); w.promptNewNotebookIfEmpty(); return app.exec(); } <commit_msg>add openssl version check<commit_after>#include "vmainwindow.h" #include <QApplication> #include <QTranslator> #include <QDebug> #include <QLibraryInfo> #include <QFile> #include <QTextCodec> #include <QFileInfo> #include <QStringList> #include <QDir> #include <QSslSocket> #include "utils/vutils.h" #include "vsingleinstanceguard.h" #include "vconfigmanager.h" VConfigManager *g_config; #if defined(QT_NO_DEBUG) QFile g_logFile; #endif void VLogger(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toUtf8(); QString header; switch (type) { case QtDebugMsg: header = "Debug:"; break; case QtInfoMsg: header = "Info:"; break; case QtWarningMsg: header = "Warning:"; break; case QtCriticalMsg: header = "Critical:"; break; case QtFatalMsg: header = "Fatal:"; } #if defined(QT_NO_DEBUG) Q_UNUSED(context); QTextStream stream(&g_logFile); #if defined(Q_OS_WIN) stream << header << localMsg << "\r\n"; #else stream << header << localMsg << "\n"; #endif if (type == QtFatalMsg) { g_logFile.close(); abort(); } #else std::string fileStr = QFileInfo(context.file).fileName().toStdString(); const char *file = fileStr.c_str(); switch (type) { case QtDebugMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtInfoMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtWarningMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtCriticalMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); break; case QtFatalMsg: fprintf(stderr, "%s(%s:%u) %s\n", header.toStdString().c_str(), file, context.line, localMsg.constData()); abort(); } fflush(stderr); #endif } int main(int argc, char *argv[]) { VSingleInstanceGuard guard; bool canRun = guard.tryRun(); #if defined(QT_NO_DEBUG) if (canRun) { g_logFile.setFileName(VConfigManager::getLogFilePath()); g_logFile.open(QIODevice::WriteOnly); } #endif if (canRun) { qInstallMessageHandler(VLogger); } QTextCodec *codec = QTextCodec::codecForName("UTF8"); if (codec) { QTextCodec::setCodecForLocale(codec); } QApplication app(argc, argv); // Check the openSSL. qDebug() << "openSSL" << QSslSocket::sslLibraryBuildVersionString() << QSslSocket::sslLibraryVersionNumber(); // The file path passed via command line arguments. QStringList filePaths = VUtils::filterFilePathsToOpen(app.arguments().mid(1)); qDebug() << "command line arguments" << app.arguments(); qDebug() << "files to open from arguments" << filePaths; if (!canRun) { // Ask another instance to open files passed in. if (!filePaths.isEmpty()) { guard.openExternalFiles(filePaths); } else { guard.showInstance(); } return 0; } VConfigManager vconfig; vconfig.initialize(); g_config = &vconfig; QString locale = VUtils::getLocale(); // Set default locale. if (locale == "zh_CN") { QLocale::setDefault(QLocale(QLocale::Chinese, QLocale::China)); } // load translation for Qt QTranslator qtTranslator; if (!qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qtTranslator.load("qt_" + locale, "translations"); } app.installTranslator(&qtTranslator); // load translation for vnote QTranslator translator; if (translator.load("vnote_" + locale, ":/translations")) { app.installTranslator(&translator); } VMainWindow w(&guard); QString style = VUtils::readFileFromDisk(":/resources/vnote.qss"); if (!style.isEmpty()) { VUtils::processStyle(style, w.getPalette()); app.setStyleSheet(style); } w.show(); w.openStartupPages(); w.openFiles(filePaths); w.promptNewNotebookIfEmpty(); return app.exec(); } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); // Display formatting cout << std::fixed; // use fixed format for nice formatting // cout << std::scientific; cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; size_t n = 12; // 12 qubits size_t N = std::pow(2, n); vector<size_t> dims; // local dimensions for (size_t i = 0; i < n; i++) dims.push_back(2); cout << "n = " << n << " qubits, matrix size " << N << " x " << N << "." << endl; // TIMING Timer t, total; // start the timer, automatic tic() in the constructor // Matrix initialization cout << endl << "Matrix initialization timing." << endl; cmat randcmat = cmat::Random(N, N); t.toc(); // read the time cout << "Took " << t.seconds() << " seconds." << endl; // Matrix product cout << endl << "Matrix product timing." << endl; t.tic(); // reset the chronometer cmat prodmat; prodmat = randcmat * randcmat; // need this (otherwise lazy evaluation) t.toc(); // read the time cout << "Took " << t.seconds() << " seconds." << endl; // ptrace SLOW SLOW SLOW cout << endl << "ptrace timing." << endl; vector<size_t> subsys_ptrace = { 0 }; cout << "Subsytem(s): "; internal::_disp_container(subsys_ptrace); cout << endl; t.tic(); ptrace(randcmat, subsys_ptrace, dims); t.toc(); cout << "Took " << t.seconds() << " seconds." << endl; // ptranspose cout << endl << "ptranspose timing." << endl; vector<size_t> subsys_ptranspose; // partially transpose all subsystems for (size_t i = 0; i < n; i++) subsys_ptranspose.push_back(i); cout << "Subsytem(s): "; internal::_disp_container(subsys_ptranspose); cout << endl; t.tic(); ptranspose(randcmat, subsys_ptranspose, dims); t.toc(); cout << "Took " << t.seconds() << " seconds." << endl; // syspermute cout << endl << "syspermute timing." << endl; vector<size_t> perm; // left-shift all subsystems by 1 for (size_t i = 0; i < n; i++) perm.push_back((i + 1) % n); cout << "Subsytem(s): "; internal::_disp_container(perm); cout << endl; t.tic(); syspermute(randcmat, perm, dims); t.toc(); cout << "Took " << t.seconds() << " seconds." << endl; total.toc(); // read the total running time cout << endl << "Total time: " << total.seconds() << " seconds." << endl; // END TIMING cout << "Exiting qpp..." << endl; } <commit_msg>commit<commit_after>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); // Display formatting cout << std::fixed; // use fixed format for nice formatting // cout << std::scientific; cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; size_t n = 12; // 12 qubits size_t N = std::pow(2, n); vector<size_t> dims; // local dimensions for (size_t i = 0; i < n; i++) dims.push_back(2); cout << "n = " << n << " qubits, matrix size " << N << " x " << N << "." << endl; // TIMING Timer t, total; // start the timer, automatic tic() in the constructor // Matrix initialization cout << endl << "Matrix initialization timing." << endl; cmat randcmat = cmat::Random(N, N); t.toc(); // read the time cout << "Took " << t.seconds() << " seconds." << endl; // Matrix product cout << endl << "Matrix product timing." << endl; t.tic(); // reset the chronometer cmat prodmat; prodmat = randcmat * randcmat; // need this (otherwise lazy evaluation) t.toc(); // read the time cout << "Took " << t.seconds() << " seconds." << endl; // ptrace SLOW SLOW SLOW cout << endl << "ptrace timing." << endl; vector<size_t> subsys_ptrace = { 0 }; cout << "Subsytem(s): ["; internal::_disp_container(subsys_ptrace); cout<<"]"<<endl; t.tic(); ptrace(randcmat, subsys_ptrace, dims); t.toc(); cout << "Took " << t.seconds() << " seconds." << endl; // ptranspose cout << endl << "ptranspose timing." << endl; vector<size_t> subsys_ptranspose; // partially transpose all subsystems for (size_t i = 0; i < n; i++) subsys_ptranspose.push_back(i); cout << "Subsytem(s): ["; internal::_disp_container(subsys_ptranspose); cout<<"]"<<endl; t.tic(); ptranspose(randcmat, subsys_ptranspose, dims); t.toc(); cout << "Took " << t.seconds() << " seconds." << endl; // syspermute cout << endl << "syspermute timing." << endl; vector<size_t> perm; // left-shift all subsystems by 1 for (size_t i = 0; i < n; i++) perm.push_back((i + 1) % n); cout << "Subsytem(s): ["; internal::_disp_container(perm); cout<<"]"<<endl; t.tic(); syspermute(randcmat, perm, dims); t.toc(); cout << "Took " << t.seconds() << " seconds." << endl; total.toc(); // read the total running time cout << endl << "Total time: " << total.seconds() << " seconds." << endl; // END TIMING cout << "Exiting qpp..." << endl; } <|endoftext|>
<commit_before>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO MEDIUM PRIORITY There is some flicker still when refreshing Report // tabs on Windows. // TODO MEDIUM PRIORITY Do proper "make package" instructions using CPack to // make RPM and .deb packages. // TODO MEDIUM PRIORITY Within "make install" and/or "make package" for // Linux, include installation of icon and association of file extension with // application so that .dcm files can be opened by double-clicking and so that // application icon appears along with other applications' icons as usual for // Gnome, KDE etc.. // TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of ComboBox and TextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO Facilitate automatic checking for updates from user's // machine, or else provide an easy way for users to sign up to a mailing // list that keeps them informed about updates. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(dcm::App); <commit_msg>Updated a TODO.<commit_after>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO MEDIUM PRIORITY There is some flicker still when refreshing Report // tabs on Windows. // TODO MEDIUM PRIORITY Do proper "make package" instructions using CPack to // make RPM and .deb packages. // TODO MEDIUM PRIORITY Within "make install" and/or "make package" for // Linux, include installation of icon and association of file extension with // application so that .dcm files can be opened by double-clicking and so that // application icon appears along with other applications' icons as usual for // Gnome, KDE etc.. // TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of ComboBox and TextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO LOW PRIORITY Facilitate automatic checking for updates from user's // machine. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(dcm::App); <|endoftext|>
<commit_before>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include <cmath> #include "qpp.h" #include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: check that everything works for expressions in ALL FILES!!!! // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping // TODO: use a Singleton Engine class (with static members) to get rid of qpp.cpp // TODO: look at unaryExpr for functors!!!! // TODO: test that everything works with GenProducts! // TODO: implement selfadjoint eigensolver // TODO: re-write everything so it works only for matrices (not expressions) using namespace std; using namespace qpp; using namespace qpp::types; int myfunc(const cplx &z) { return std::abs(z); } template<typename Derived> void printFirstRow(const Derived& x) { cout << x.row(0) << endl; } //int main(int argc, char **argv) int main() { _init(); std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; // MATLAB interface testing cmat randu = rand_unitary(3); cout << endl; displn(randu); saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w"); cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu"); cout << endl; displn(randu - res); // functor testing auto lambda = [](const cplx& z)->int { return abs(z);}; cmat mat1(3, 3); mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii; cout << endl; displn(mat1); cout << endl; displn(fun<cmat, int>(mat1 * mat1, lambda)); cout << endl; displn(fun<cmat>(mat1 * mat1, myfunc)); // other functions cout << endl; cmat mat11 = mat1 * mat1; displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1))); mat11 = cmat::Random(3, 3); mat11 = mat11 + adjoint(mat11); cmat mat2(2, 2); mat2 << 1, ct::ii, -ct::ii, 1; // eigenvalue test cout << endl << hevals<cmat>(mat11) << endl; displn( mat11 * hevects(mat11).col(0) - (hevals(mat11)(0)) * hevects(mat11).col(0)); cout << endl << mat11 << endl << endl; printFirstRow(mat11); cout << endl; displn(transpose(mat11)); cout << typeid(transpose(mat11)).name() << endl<<endl; //displn(transpose(mat11 * mat11)); //cout << typeid(transpose(mat11*mat11)).name() << endl; cout << endl << "Exiting qpp..." << endl; } <commit_msg>commit<commit_after>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include <cmath> #include "qpp.h" #include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: check that everything works for expressions in ALL FILES!!!! // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping // TODO: use a Singleton Engine class (with static members) to get rid of qpp.cpp // TODO: look at unaryExpr for functors!!!! // TODO: test that everything works with GenProducts! // TODO: implement selfadjoint eigensolver // TODO: re-write everything so it works only for matrices (not expressions) using namespace std; using namespace qpp; using namespace qpp::types; int myfunc(const cplx &z) { return std::abs(z); } template<typename Derived> void printFirstRow(const Derived& x) { cout << x.row(0) << endl; } //int main(int argc, char **argv) int main() { _init(); std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; // MATLAB interface testing cmat randu = rand_unitary(3); cout << endl; displn(randu); saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w"); cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu"); cout << endl; displn(randu - res); // functor testing auto lambda = [](const cplx& z)->int { return abs(z);}; cmat mat1(3, 3); mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii; cout << endl; displn(mat1); cout << endl; displn(fun<cmat, int>(mat1 * mat1, lambda)); cout << endl; displn(fun<cmat>(mat1 * mat1, myfunc)); // other functions cout << endl; cmat mat11 = mat1 * mat1; displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1))); mat11 = cmat::Random(3, 3); mat11 = mat11 + adjoint(mat11); cmat mat2(2, 2); mat2 << 1, ct::ii, -ct::ii, 1; // eigenvalue test cout << endl << hevals<cmat>(mat11) << endl; displn( mat11 * hevects(mat11).col(0) - (hevals(mat11)(0)) * hevects(mat11).col(0)); cout << endl << mat11 << endl << endl; printFirstRow(mat11); cout << endl; displn(transpose(mat11)); cout << typeid(transpose(mat11)).name() << endl<<endl; displn(transpose(mat11 * mat11)); cout << typeid(transpose(mat11*mat11)).name() << endl; cout << endl << "Exiting qpp..." << endl; } <|endoftext|>
<commit_before>#include <fstream> #include <vector> #include <locale.h> #include "LogEntryFilter.h" #include "LogEntryRootFilter.h" #include "LogEntryMessageFilter.h" #include "LogEntryTimeFilter.h" #include "FileUtils.hpp" #include "CommandLineUtils.hpp" #include "LogEntryParser.h" #include "Rearranger.h" #include "LogEntryFilterFactory.h" #include "alphanum.hpp" using namespace std; #ifdef _WIN32 #define kPathSeparator '\\' #else #define kPathSeparator '/' #endif void sortFiles(vector<string> &files); int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); int ret = 0; if (argc == 1 || cmdOptionExists(argv, argv + argc, "--help")) { cout << "LogUtil: A handy tool to merge/filter log files.\ngit: https://github.com/yhd4711499/LogUtil.git\n\n"; cout << "usage :\tlogutil"; cout << "\t[-d] [-f] [-o] [-r] [-start] [-end]\n\n"; cout << "\t-d\tmerge all files under the directory.\n"; cout << "\t-f\tsort the log file.\n"; cout << "\t-o\toutput file. [<file_or_dirname>_ALL.log] will be used if not set.\n\t\tor [std] to print output to stdout.\n"; cout << "\t-r\tfilter rules.\n"; cout << "\nAdvanced usage:\n\n"; cout << "\t-start/end\tshow logs between [start , end), \"YYYY-mm-dd hh:MM:SS.SSS\" .\n\n"; cout << "examples :\n"; cout << "\tlogutil ~/LogDir\n"; cout << "\tlogutil ~/LogDir -o std\n"; cout << "\tlogutil -d ~/LogDir\n"; cout << "\tlogutil -d ~/LogDir -start 2016-06-18\n"; cout << "\tlogutil -d ~/LogDir -start 2016-06-18 -end 2016-06-19\n"; cout << "\tlogutil -d ~/LogDir -r ~/block_rules.json\n"; cout << "\tlogutil -d ~/LogDir -o ~/Log_ALL.log\n"; cout << "\tlogutil -f ~/LogDir/log.log -o ~/Log_ALL.log\n"; return 0; } vector<string> files; char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr; if (argc == 2) { if (isFile(argv[1])) { filename = argv[1]; } else { dirname = argv[1]; } } else { dirname = getCmdOption(argv, argv + argc, "-d"); filename = getCmdOption(argv, argv + argc, "-f"); } if (filename) { files.push_back(filename); } if (dirname) { ret = listFiles(dirname, files); if (ret != 0) { cerr << "Failed to visit dir : " << dirname << endl; return ret; } } if (files.size() > 1) { sortFiles(files); } char *filterRultFile = getCmdOption(argv, argv + argc, "-r"); char *startTime = getCmdOption(argv, argv + argc, "-start"); char *endTime = getCmdOption(argv, argv + argc, "-end"); outputFilename = getCmdOption(argv, argv + argc, "-o"); if (!strncmp(outputFilename, "std", 3)) { outputFilename = NULL; } else if (!outputFilename) { if (filename) { string folderName, filenameWoDir; splitFilename(string(filename), folderName, filenameWoDir); string newFilename(folderName + kPathSeparator + "All_" + filenameWoDir); outputFilename = new char[newFilename.length() + 1]; strcpy(outputFilename, newFilename.c_str()); } else if (dirname) { string newFilename(string(dirname) + kPathSeparator + "All.log"); outputFilename = new char[newFilename.length() + 1]; strcpy(outputFilename, newFilename.c_str()); } } LogEntryFilterFactory::registerCreator("root", LogEntryRootFilter::creator); LogEntryFilterFactory::registerCreator("log", LogEntryMessageFilter::creator); LogEntryFilterFactory::registerCreator("time", LogEntryTimeFilter::creator); LogEntryParser parser; if (filterRultFile) { auto fileRuleStream = fstream(filterRultFile); json fileRuleJson; fileRuleStream >> fileRuleJson; parser.addFilter(LogEntryFilterFactory::create(fileRuleJson)); } if (startTime || endTime) { string start = startTime ? (string) startTime : ""; string end = endTime ? (string) endTime : ""; LogEntryTimeFilter *filter = new LogEntryTimeFilter( LogEntryTimeFilter::getDate(start), LogEntryTimeFilter::getTime(start), LogEntryTimeFilter::getDate(end), LogEntryTimeFilter::getTime(end), true); parser.addFilter(filter); } vector<LogEntry *> entries; for (string file : files) { try { parser.parseFile(file, entries); } catch (runtime_error &error) { cerr << "Failed to parse file : " << file << ". error: " << error.what() << endl; } catch (...) { cerr << "Failed to parse file : " << file << endl; } } Rearranger rearranger; rearranger.sort(entries); int index = 1; for (LogEntry *entry : entries) { entry->line.orderedIndex = index; index += entry->line.lines.size(); } if (outputFilename) { ofstream os(outputFilename); for (LogEntry *entry : entries) { os << *entry; } printf("All done. File saved to %s\n", outputFilename); } else { for (LogEntry *entry : entries) { cout << *entry; } } return 0; } void sortFiles(vector<string> &files) { /* * A little tricky here: files must be sorted in natural order on filename. * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files. * * For example. * * We'ev two logs files: * * 9.log ([2000-1-1 00:00:00,000] A) * 10.log ([2000-1-1 00:00:00,000] B) * * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000]. * * After sorting by ascii comparing on filename: * 10.log * 9.log * * Then we first parse [B] from 10.log and then [A] from 9.log: * * [2000-1-1 00:00:00,000] B * [2000-1-1 00:00:00,000] A * * So the sorting order of files must be the same as generating. * */ sort(files.begin(), files.end(), [](string &lhs, string &rhs) { return doj::alphanum_comp(lhs, rhs) < 0; }); }<commit_msg>- : bug (null pointer)<commit_after>#include <fstream> #include <vector> #include <locale.h> #include "LogEntryFilter.h" #include "LogEntryRootFilter.h" #include "LogEntryMessageFilter.h" #include "LogEntryTimeFilter.h" #include "FileUtils.hpp" #include "CommandLineUtils.hpp" #include "LogEntryParser.h" #include "Rearranger.h" #include "LogEntryFilterFactory.h" #include "alphanum.hpp" using namespace std; #ifdef _WIN32 #define kPathSeparator '\\' #else #define kPathSeparator '/' #endif void sortFiles(vector<string> &files); int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); int ret = 0; if (argc == 1 || cmdOptionExists(argv, argv + argc, "--help")) { cout << "LogUtil: A handy tool to merge/filter log files.\ngit: https://github.com/yhd4711499/LogUtil.git\n\n"; cout << "usage :\tlogutil"; cout << "\t[-d] [-f] [-o] [-r] [-start] [-end]\n\n"; cout << "\t-d\tmerge all files under the directory.\n"; cout << "\t-f\tsort the log file.\n"; cout << "\t-o\toutput file. [<file_or_dirname>_ALL.log] will be used if not set.\n\t\tor [std] to print output to stdout.\n"; cout << "\t-r\tfilter rules.\n"; cout << "\nAdvanced usage:\n\n"; cout << "\t-start/end\tshow logs between [start , end), \"YYYY-mm-dd hh:MM:SS.SSS\" .\n\n"; cout << "examples :\n"; cout << "\tlogutil ~/LogDir\n"; cout << "\tlogutil ~/LogDir -o std\n"; cout << "\tlogutil -d ~/LogDir\n"; cout << "\tlogutil -d ~/LogDir -start 2016-06-18\n"; cout << "\tlogutil -d ~/LogDir -start 2016-06-18 -end 2016-06-19\n"; cout << "\tlogutil -d ~/LogDir -r ~/block_rules.json\n"; cout << "\tlogutil -d ~/LogDir -o ~/Log_ALL.log\n"; cout << "\tlogutil -f ~/LogDir/log.log -o ~/Log_ALL.log\n"; return 0; } vector<string> files; char *dirname = nullptr, *filename = nullptr, *outputFilename = nullptr; if (argc == 2) { if (isFile(argv[1])) { filename = argv[1]; } else { dirname = argv[1]; } } else { dirname = getCmdOption(argv, argv + argc, "-d"); filename = getCmdOption(argv, argv + argc, "-f"); } if (filename) { files.push_back(filename); } if (dirname) { ret = listFiles(dirname, files); if (ret != 0) { cerr << "Failed to visit dir : " << dirname << endl; return ret; } } if (files.size() > 1) { sortFiles(files); } char *filterRultFile = getCmdOption(argv, argv + argc, "-r"); char *startTime = getCmdOption(argv, argv + argc, "-start"); char *endTime = getCmdOption(argv, argv + argc, "-end"); outputFilename = getCmdOption(argv, argv + argc, "-o"); if (outputFilename && !strncmp(outputFilename, "std", 3)) { outputFilename = NULL; } else if (!outputFilename) { if (filename) { string folderName, filenameWoDir; splitFilename(string(filename), folderName, filenameWoDir); string newFilename(folderName + kPathSeparator + "All_" + filenameWoDir); outputFilename = new char[newFilename.length() + 1]; strcpy(outputFilename, newFilename.c_str()); } else if (dirname) { string newFilename(string(dirname) + kPathSeparator + "All.log"); outputFilename = new char[newFilename.length() + 1]; strcpy(outputFilename, newFilename.c_str()); } } LogEntryFilterFactory::registerCreator("root", LogEntryRootFilter::creator); LogEntryFilterFactory::registerCreator("log", LogEntryMessageFilter::creator); LogEntryFilterFactory::registerCreator("time", LogEntryTimeFilter::creator); LogEntryParser parser; if (filterRultFile) { auto fileRuleStream = fstream(filterRultFile); json fileRuleJson; fileRuleStream >> fileRuleJson; parser.addFilter(LogEntryFilterFactory::create(fileRuleJson)); } if (startTime || endTime) { string start = startTime ? (string) startTime : ""; string end = endTime ? (string) endTime : ""; LogEntryTimeFilter *filter = new LogEntryTimeFilter( LogEntryTimeFilter::getDate(start), LogEntryTimeFilter::getTime(start), LogEntryTimeFilter::getDate(end), LogEntryTimeFilter::getTime(end), true); parser.addFilter(filter); } vector<LogEntry *> entries; for (string file : files) { try { parser.parseFile(file, entries); } catch (runtime_error &error) { cerr << "Failed to parse file : " << file << ". error: " << error.what() << endl; } catch (...) { cerr << "Failed to parse file : " << file << endl; } } Rearranger rearranger; rearranger.sort(entries); int index = 1; for (LogEntry *entry : entries) { entry->line.orderedIndex = index; index += entry->line.lines.size(); } if (outputFilename) { ofstream os(outputFilename); for (LogEntry *entry : entries) { os << *entry; } printf("All done. File saved to %s\n", outputFilename); } else { for (LogEntry *entry : entries) { cout << *entry; } } return 0; } void sortFiles(vector<string> &files) { /* * A little tricky here: files must be sorted in natural order on filename. * Or output result might be mis-ordered on log entries with same timestamp but stored in separate files. * * For example. * * We'ev two logs files: * * 9.log ([2000-1-1 00:00:00,000] A) * 10.log ([2000-1-1 00:00:00,000] B) * * log [A] is printed before log [B] but both in the same time [2000-1-1 00:00:00,000]. * * After sorting by ascii comparing on filename: * 10.log * 9.log * * Then we first parse [B] from 10.log and then [A] from 9.log: * * [2000-1-1 00:00:00,000] B * [2000-1-1 00:00:00,000] A * * So the sorting order of files must be the same as generating. * */ sort(files.begin(), files.end(), [](string &lhs, string &rhs) { return doj::alphanum_comp(lhs, rhs) < 0; }); }<|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 <chrono> #include <sstream> #include <iomanip> #include "otbStopwatch.h" namespace otb { Stopwatch ::Stopwatch() : m_StartTime(), m_ElapsedMilliseconds(), m_IsRunning() { } void Stopwatch ::Start() { if (!this->m_IsRunning) { this->m_IsRunning = true; this->m_StartTime = this->GetTimestamp(); } } void Stopwatch ::Stop() { if (this->m_IsRunning) { this->m_ElapsedMilliseconds += GetRunningElapsedTime(); this->m_IsRunning = false; } } void Stopwatch ::Reset() { this->m_ElapsedMilliseconds = 0; this->m_IsRunning = false; } void Stopwatch ::Restart() { this->m_ElapsedMilliseconds = 0; this->m_IsRunning = true; this->m_StartTime = this->GetTimestamp(); } Stopwatch::DurationType Stopwatch ::GetElapsedMilliseconds() const { auto result = this->m_ElapsedMilliseconds; if (this->m_IsRunning) result += this->GetRunningElapsedTime(); return result; } std::string Stopwatch ::GetElapsedHumanReadableTime() const { auto result = this->GetElapsedMilliseconds(); int seconds = result/1000; int hours = seconds / 3600; seconds -= (hours * 3600); int minutes = seconds / 60; seconds -= (minutes * 60); std::ostringstream os; if (hours > 0) os << hours << "h " << std::setfill('0') << std::setw(2); if (minutes > 0 or hours>0) os << minutes << "m " << std::setfill('0') << std::setw(2); os << seconds << "s"; return os.str(); } bool Stopwatch ::IsRunning() const { return this->m_IsRunning; } Stopwatch Stopwatch ::StartNew() { Stopwatch sw; sw.Start(); return sw; } inline Stopwatch::TimepointType Stopwatch ::GetTimestamp() const { auto now = std::chrono::steady_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); } inline Stopwatch::DurationType Stopwatch ::GetRunningElapsedTime() const { return this->GetTimestamp() - this->m_StartTime; } } <commit_msg>COMP: Fix or operator not well supported by MSVC (+ a few style edits)<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 <chrono> #include <sstream> #include <iomanip> #include "otbStopwatch.h" namespace otb { Stopwatch ::Stopwatch() : m_StartTime(), m_ElapsedMilliseconds(), m_IsRunning() { } void Stopwatch ::Start() { if (!this->m_IsRunning) { this->m_IsRunning = true; this->m_StartTime = this->GetTimestamp(); } } void Stopwatch ::Stop() { if (this->m_IsRunning) { this->m_ElapsedMilliseconds += GetRunningElapsedTime(); this->m_IsRunning = false; } } void Stopwatch ::Reset() { this->m_ElapsedMilliseconds = 0; this->m_IsRunning = false; } void Stopwatch ::Restart() { this->m_ElapsedMilliseconds = 0; this->m_IsRunning = true; this->m_StartTime = this->GetTimestamp(); } Stopwatch::DurationType Stopwatch ::GetElapsedMilliseconds() const { auto result = this->m_ElapsedMilliseconds; if (this->m_IsRunning) result += this->GetRunningElapsedTime(); return result; } std::string Stopwatch ::GetElapsedHumanReadableTime() const { auto result = this->GetElapsedMilliseconds(); int seconds = result / 1000; int hours = seconds / 3600; seconds -= hours * 3600; int minutes = seconds / 60; seconds -= minutes * 60; std::ostringstream os; if (hours > 0) os << hours << "h " << std::setfill('0') << std::setw(2); if (minutes > 0 || hours > 0) os << minutes << "m " << std::setfill('0') << std::setw(2); os << seconds << "s"; return os.str(); } bool Stopwatch ::IsRunning() const { return this->m_IsRunning; } Stopwatch Stopwatch ::StartNew() { Stopwatch sw; sw.Start(); return sw; } inline Stopwatch::TimepointType Stopwatch ::GetTimestamp() const { auto now = std::chrono::steady_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); } inline Stopwatch::DurationType Stopwatch ::GetRunningElapsedTime() const { return this->GetTimestamp() - this->m_StartTime; } } <|endoftext|>
<commit_before>// // Parser.cpp // snowcrash // // Created by Zdenek Nemec on 4/8/13. // Copyright (c) 2013 Apiary.io. All rights reserved. // #include <exception> #include <sstream> #include "Parser.h" #include "MarkdownParser.h" #include "BlueprintParser.h" using namespace snowcrash; const int SourceAnnotation::OK; void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint) { try { // Parse Markdown MarkdownBlock::Stack markdown; MarkdownParser markdownParser; markdownParser.parse(source, result, markdown); if (result.error.code != Error::OK) return; // Parse Blueprint BlueprintParser::Parse(source, markdown, result, blueprint); } catch (const std::exception& e) { std::stringstream ss; ss << "parser exception: '" << e.what() << "'"; result.error = Error(ss.str(), 1); } catch (...) { result.error = Error("parser exception has occured", 1); } } <commit_msg>Add tabs & CR sanity check<commit_after>// // Parser.cpp // snowcrash // // Created by Zdenek Nemec on 4/8/13. // Copyright (c) 2013 Apiary.io. All rights reserved. // #include <exception> #include <sstream> #include "Parser.h" #include "MarkdownParser.h" #include "BlueprintParser.h" using namespace snowcrash; const int SourceAnnotation::OK; // Check source for unsupported character \t & \r // Returns true if passed (not found), false otherwise static bool CheckSource(const SourceData& source, Result& result) { std::string::size_type pos = source.find("\t"); if (pos != std::string::npos) { result.error = Error("the use of tab(s) `\\t` in source data isn't currently supported, please contact makers", 2); return false; } pos = source.find("\r"); if (pos != std::string::npos) { result.error = Error("the use of carriage return(s) `\\r` in source data isn't currently supported, please contact makers", 2); return false; } return true; } void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint) { try { // Sanity Check if (!CheckSource(source, result)) return; // Parse Markdown MarkdownBlock::Stack markdown; MarkdownParser markdownParser; markdownParser.parse(source, result, markdown); if (result.error.code != Error::OK) return; // Parse Blueprint BlueprintParser::Parse(source, markdown, result, blueprint); } catch (const std::exception& e) { std::stringstream ss; ss << "parser exception: '" << e.what() << "'"; result.error = Error(ss.str(), 1); } catch (...) { result.error = Error("parser exception has occured", 1); } } <|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 <mitkTestFixture.h> #include <mitkTestingMacros.h> #include <mitkIRESTManager.h> #include <mitkIRESTObserver.h> #include <mitkRESTClient.h> #include <mitkRESTUtil.h> #include <usGetModuleContext.h> #include <usModuleContext.h> #include <usServiceReference.h> #include <vtkDebugLeaks.h> class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver { CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite); // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet? MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish); // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients // MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON); -- " -- MITK_TEST(GetRequestInvalidURI_ThrowsException); MITK_TEST(PutRequestInvalidURI_ThrowsException); MITK_TEST(PostRequestInvalidURI_ThrowsException); CPPUNIT_TEST_SUITE_END(); public: mitk::IRESTManager *m_Service; web::json::value m_Data; web::http::http_response Notify(const web::uri &, const web::json::value &, const web::http::method &, const mitk::RESTUtil::ParamMap &headers) override { auto response = web::http::http_response(); response.set_body(m_Data); response.set_status_code(web::http::status_codes::OK); return response; } /** * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_Data = web::json::value(); m_Data[U("userId")] = web::json::value(1); m_Data[U("id")] = web::json::value(1); m_Data[U("title")] = web::json::value(U("this is a title")); m_Data[U("body")] = web::json::value(U("this is a body")); us::ServiceReference<mitk::IRESTManager> serviceRef = us::GetModuleContext()->GetServiceReference<mitk::IRESTManager>(); if (serviceRef) { m_Service = us::GetModuleContext()->GetService(serviceRef); } if (!m_Service) { CPPUNIT_FAIL("Getting Service in setUp() failed"); } m_Service->ReceiveRequest(U("http://localhost:8080/clienttest"), this); } void tearDown() override { m_Service->HandleDeleteObserver(this); } void GetRequestValidURI_ReturnsExpectedJSON() { web::json::value result; m_Service->SendRequest(U("http://localhost:8080/clienttest")) .then([&](pplx::task<web::json::value> resultTask) { try { result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); CPPUNIT_ASSERT_MESSAGE("Result is the expected JSON value", result == m_Data); } void MultipleGetRequestValidURI_AllTasksFinish() { int count = 0; // Create multiple tasks e.g. as shown below std::vector<pplx::task<void>> tasks; for (int i = 0; i < 20; ++i) { pplx::task<void> singleTask = m_Service->SendRequest(U("http://localhost:8080/clienttest")) .then([&](pplx::task<web::json::value> resultTask) { // Do something when a single task is done try { resultTask.get(); count += 1; } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); tasks.emplace_back(singleTask); } // Create a joinTask which includes all tasks you've created auto joinTask = pplx::when_all(begin(tasks), end(tasks)); // Run asynchonously joinTask .then([&](pplx::task<void> resultTask) { // Do something when all tasks are finished try { resultTask.get(); count += 1; } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == count); } void PutRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value result; m_Service ->SendJSONRequest( U("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put) .then([&](pplx::task<web::json::value> resultTask) { try { result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); CPPUNIT_ASSERT_MESSAGE( "Result is the expected JSON value, check if the link is still valid since this is an optional test", result == m_Data); } void PostRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value result; web::json::value data; data[U("userId")] = m_Data[U("userId")]; data[U("title")] = m_Data[U("title")]; data[U("body")] = m_Data[U("body")]; m_Service ->SendJSONRequest(U("https://jsonplaceholder.typicode.com/posts"), mitk::IRESTManager::RequestType::Post, &data) .then([&](pplx::task<web::json::value> resultTask) { try { result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); data[U("id")] = web::json::value(101); CPPUNIT_ASSERT_MESSAGE( "Result is the expected JSON value, check if the link is still valid since this is an optional test", result == data); } void PostRequestHeaders_Success() { mitk::RESTUtil::ParamMap headers; headers.insert(mitk::RESTUtil::ParamMap::value_type( U("Content-Type"), U("multipart/related; type=\"application/dicom\"; boundary=boundary"))); m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task<web::json::value> resultTask) { // Do something when a single task is done try { resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); } void GetException() { // Method which makes a get request to an invalid uri web::json::value result; m_Service->SendRequest(U("http://localhost:1234/invalid")) .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); }) .wait(); } void GetRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(GetException(), mitk::Exception); } void PutException() { // Method which makes a put request to an invalid uri web::json::value result; m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data) .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); }) .wait(); } void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); } void PostException() { // Method which makes a post request to an invalid uri web::json::value result; m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data) .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); }) .wait(); } void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); } }; MITK_TEST_SUITE_REGISTRATION(mitkRESTClient) <commit_msg>Remove unused parameter<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 <mitkTestFixture.h> #include <mitkTestingMacros.h> #include <mitkIRESTManager.h> #include <mitkIRESTObserver.h> #include <mitkRESTClient.h> #include <mitkRESTUtil.h> #include <usGetModuleContext.h> #include <usModuleContext.h> #include <usServiceReference.h> #include <vtkDebugLeaks.h> class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver { CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite); // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet? MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish); // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients // MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON); -- " -- MITK_TEST(GetRequestInvalidURI_ThrowsException); MITK_TEST(PutRequestInvalidURI_ThrowsException); MITK_TEST(PostRequestInvalidURI_ThrowsException); CPPUNIT_TEST_SUITE_END(); public: mitk::IRESTManager *m_Service; web::json::value m_Data; web::http::http_response Notify(const web::uri &, const web::json::value &, const web::http::method &, const mitk::RESTUtil::ParamMap &) override { auto response = web::http::http_response(); response.set_body(m_Data); response.set_status_code(web::http::status_codes::OK); return response; } /** * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_Data = web::json::value(); m_Data[U("userId")] = web::json::value(1); m_Data[U("id")] = web::json::value(1); m_Data[U("title")] = web::json::value(U("this is a title")); m_Data[U("body")] = web::json::value(U("this is a body")); us::ServiceReference<mitk::IRESTManager> serviceRef = us::GetModuleContext()->GetServiceReference<mitk::IRESTManager>(); if (serviceRef) { m_Service = us::GetModuleContext()->GetService(serviceRef); } if (!m_Service) { CPPUNIT_FAIL("Getting Service in setUp() failed"); } m_Service->ReceiveRequest(U("http://localhost:8080/clienttest"), this); } void tearDown() override { m_Service->HandleDeleteObserver(this); } void GetRequestValidURI_ReturnsExpectedJSON() { web::json::value result; m_Service->SendRequest(U("http://localhost:8080/clienttest")) .then([&](pplx::task<web::json::value> resultTask) { try { result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); CPPUNIT_ASSERT_MESSAGE("Result is the expected JSON value", result == m_Data); } void MultipleGetRequestValidURI_AllTasksFinish() { int count = 0; // Create multiple tasks e.g. as shown below std::vector<pplx::task<void>> tasks; for (int i = 0; i < 20; ++i) { pplx::task<void> singleTask = m_Service->SendRequest(U("http://localhost:8080/clienttest")) .then([&](pplx::task<web::json::value> resultTask) { // Do something when a single task is done try { resultTask.get(); count += 1; } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); tasks.emplace_back(singleTask); } // Create a joinTask which includes all tasks you've created auto joinTask = pplx::when_all(begin(tasks), end(tasks)); // Run asynchonously joinTask .then([&](pplx::task<void> resultTask) { // Do something when all tasks are finished try { resultTask.get(); count += 1; } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == count); } void PutRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value result; m_Service ->SendJSONRequest( U("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put) .then([&](pplx::task<web::json::value> resultTask) { try { result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); CPPUNIT_ASSERT_MESSAGE( "Result is the expected JSON value, check if the link is still valid since this is an optional test", result == m_Data); } void PostRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value result; web::json::value data; data[U("userId")] = m_Data[U("userId")]; data[U("title")] = m_Data[U("title")]; data[U("body")] = m_Data[U("body")]; m_Service ->SendJSONRequest(U("https://jsonplaceholder.typicode.com/posts"), mitk::IRESTManager::RequestType::Post, &data) .then([&](pplx::task<web::json::value> resultTask) { try { result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); data[U("id")] = web::json::value(101); CPPUNIT_ASSERT_MESSAGE( "Result is the expected JSON value, check if the link is still valid since this is an optional test", result == data); } void PostRequestHeaders_Success() { mitk::RESTUtil::ParamMap headers; headers.insert(mitk::RESTUtil::ParamMap::value_type( U("Content-Type"), U("multipart/related; type=\"application/dicom\"; boundary=boundary"))); m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task<web::json::value> resultTask) { // Do something when a single task is done try { resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); } void GetException() { // Method which makes a get request to an invalid uri web::json::value result; m_Service->SendRequest(U("http://localhost:1234/invalid")) .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); }) .wait(); } void GetRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(GetException(), mitk::Exception); } void PutException() { // Method which makes a put request to an invalid uri web::json::value result; m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data) .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); }) .wait(); } void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); } void PostException() { // Method which makes a post request to an invalid uri web::json::value result; m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data) .then([&](pplx::task<web::json::value> resultTask) { result = resultTask.get(); }) .wait(); } void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); } }; MITK_TEST_SUITE_REGISTRATION(mitkRESTClient) <|endoftext|>
<commit_before> #define _GLIBCXX_USE_NANOSLEEP #include "main.hpp" #include <algorithm> /* What I know: Cipher 1: is a shift cipher. Offset 13, so basically ROT-13! Cipher 2: is not a regular shift cipher. is a Vigenere cipher. Key length of 9! Cipher 3: is not a regular shift cipher. does not appear to be a Vigenere cipher, checked keylengths [1-50] could be columnar transposition could be monoalphabetic substitution Cipher 4: is not a regular shift cipher. does not appear to be a Vigenere cipher, checked keylengths [1-50] could be columnar transposition could be monoalphabetic substitution Ceasar cipher - no cipher shift cipher - Cipher 1, no other cipher monoalphabetic substitution cipher one-time-pad - basically uncrackable without finding secret key columnar transposition - of those, could be rail cipher or regular vignere cipher - Cipher 2, no other cipher */ int main(int argc, char** argv) { auto cipher1lower = toLowerCase(cipher1); auto cipher2lower = toLowerCase(cipher2); auto cipher3lower = toLowerCase(cipher3); auto cipher4lower = toLowerCase(cipher4); //"wecrlteerdsoeefeaocaivden" std::cout << crackRailCipher("wireeedseeeacaecvdltnrofo") << std::endl; /* std::cout << "Cipher 1, attempted crack of shift cipher:" << std::endl; std::cout << cipher1lower << std::endl; std::cout << crackShiftCipher(cipher1lower) << std::endl; std::cout << "-----------------------------------------------" << std::endl;*/ /* std::cout << "Cipher 2, attempted crack of Vigenere cipher:" << std::endl; std::cout << crackVigenereCipher(cipher2lower) << std::endl; std::cout << "-----------------------------------------------" << std::endl;*/ /* std::cout << "Cipher 4, attempted crack of vigenere cipher:" << std::endl; std::cout << crackVigenereCipher(cipher4lower) << std::endl; std::cout << "-----------------------------------------------" << std::endl;*/ } std::string crackShiftCipher(const std::string& ciphertext) { float bestDeviation = 4096; std::string currentGuess; for (std::size_t shift = 0; shift <= 26; shift++) { std::string copy(ciphertext); for (std::size_t j = 0; j < ciphertext.size(); j++) copy[j] = (ciphertext[j] - 97 + shift) % 26 + 97; float dev = getDeviationFromEnglish(copy); if (dev < bestDeviation) { bestDeviation = dev; currentGuess = copy; } } return currentGuess; } std::string crackVigenereCipher(const std::string& ciphertext) { float bestDeviation = 4096; std::string currentGuess; for (std::size_t keyLength = 1; keyLength <= 25; keyLength++) { std::string whole(ciphertext); //will be overridden for (std::size_t offset = 0; offset < keyLength; offset++) { std::string subStr; for (std::size_t j = offset; j < ciphertext.size(); j += keyLength) subStr += ciphertext[j]; auto cracked = crackShiftCipher(subStr); for (std::size_t j = 0; j < subStr.size(); j++) whole[j * keyLength + offset] = cracked[j]; } float dev = getDeviationFromEnglish(whole); if (dev < bestDeviation) { bestDeviation = dev; currentGuess = whole; std::cout << std::endl; std::cout << "Better guess! Keylength of " << keyLength << std::endl; std::cout << "Deviation from English: " << dev << std::endl; std::cout << currentGuess << std::endl; } } return currentGuess; } //wearediscoveredfleeatonce //wecrlteerdsoeefeadcaivden std::string crackRailCipher(const std::string& ciphertext) { int maxKeyLength = 40; if (maxKeyLength >= ciphertext.size()) maxKeyLength = ciphertext.size(); //for (int keyLength = 2; keyLength < maxKeyLength; keyLength++) int keyLength = 4; { std::string plaintext(ciphertext); int cipherIndex = 0; for (int offset = 0; offset < keyLength; offset++) { int diff = (keyLength - 1) * 2 - offset * 2; if (offset == keyLength - 1) diff = (keyLength - 1) * 2; std::cout << diff << std::endl; for (int j = offset; j < ciphertext.size(); j += diff) { plaintext[j] = ciphertext[cipherIndex]; cipherIndex++; } } std::cout << cipherIndex << ", " << ciphertext.size() << std::endl; std::cout << keyLength << ": " << plaintext << std::endl; } return ""; } std::string toLowerCase(const std::string& str) { std::string copy(str); std::transform(copy.begin(), copy.end(), copy.begin(), ::tolower); return copy; } float getDeviationFromEnglish(const std::string& str) { FrequencyMap map; for (std::size_t j = 0; j < str.size(); j++) map[str[j]] = map[str[j]] + 1; auto ENGLISH = getEnglishFrequencyMap(); float deviation = 0; for (auto& x: map) { float diff = x.second / str.size() - ENGLISH[x.first] / 100; deviation += diff * diff; } return deviation; } FrequencyMap getEnglishFrequencyMap() { static FrequencyMap english; if (!english.empty()) return english; english['a'] = 8.167f; english['b'] = 1.492f; english['c'] = 2.783f; english['d'] = 4.253f; english['e'] = 12.702f; english['f'] = 2.228f; english['g'] = 2.015f; english['h'] = 6.094f; english['i'] = 6.966f; english['j'] = 0.153f; english['k'] = 0.772f; english['l'] = 4.025f; english['m'] = 2.406f; english['n'] = 6.749f; english['o'] = 7.507f; english['p'] = 1.929f; english['q'] = 0.095f; english['r'] = 5.987f; english['s'] = 6.327f; english['t'] = 9.056f; english['u'] = 2.758f; english['v'] = 0.978f; english['w'] = 2.360f; english['x'] = 0.150f; english['y'] = 1.974f; english['z'] = 0.075f; return english; } <commit_msg>notes on other ciphers<commit_after> #define _GLIBCXX_USE_NANOSLEEP #include "main.hpp" #include <algorithm> /* What I know: Cipher 1: is a shift cipher. Shift key is 13, so basically ROT-13! Cipher 2: is not a regular shift cipher. is a Vigenere cipher. Key length of 9, key worcester Cipher 3: is not a regular shift cipher. does not appear to be a Vigenere cipher, checked keylengths [1-50] does not appear to be a Fence Rail cipher, checked leylengths [1-25] has very flat frequencies, suggesting something unusual monoalphabetic sub or column transpose couldn't do this One-time pad? Vigenere? Vigenere autokey? Hill? Variance from English: 0.0282431 One-time pad is impossible, V autokey nor Hill were listed. Cipher 4: is not a regular shift cipher. does not appear to be a Vigenere cipher, checked keylengths [1-50] does not appear to be a Fence Rail cipher, checked leylengths [1-25] has varying frequency distributions, suggesting substitutions Monoalphabetic? Columnar transpose? Affine cipher (p28)? Variance from English: 0.0521973 Hints and notes: Ceasar cipher - no cipher, rough distribution graph shift cipher - Cipher 1, no other cipher, rough distribution graph monoalphabetic substitution cipher, rough distribution graph one-time-pad - basically uncrackable without finding secret key, flat distrib columnar transposition - rail or regular, rough distribution graph vignere cipher - Cipher 2, no other cipher, flat distribution */ int main(int argc, char** argv) { auto cipher1lower = toLowerCase(cipher1); auto cipher2lower = toLowerCase(cipher2); auto cipher3lower = toLowerCase(cipher3); auto cipher4lower = toLowerCase(cipher4); std::cout << "Cipher 1, attempted crack of shift cipher:" << std::endl; std::cout << cipher1lower << std::endl; std::cout << crackShiftCipher(cipher1lower) << std::endl; std::cout << "-----------------------------------------------" << std::endl; std::cout << "Cipher 2, attempted crack of Vigenere cipher:" << std::endl; std::cout << cipher2lower << std::endl; std::cout << crackVigenereCipher(cipher2lower) << std::endl; std::cout << "-----------------------------------------------" << std::endl; /* std::cout << "Cipher 4, attempted crack of vigenere cipher:" << std::endl; std::cout << crackVigenereCipher(cipher4lower) << std::endl; std::cout << "-----------------------------------------------" << std::endl; //std::cout << crackRailCipher("wireeedseeeacaecvdltnrofo") << std::endl; //std::cout << getDeviationFromEnglish(cipher3lower) << std::endl; //std::cout << getDeviationFromEnglish(cipher4lower) << std::endl; std::cout << crackVigenereCipher(cipher3lower) << std::endl;*/ } std::string crackShiftCipher(const std::string& ciphertext) { float bestDeviation = 4096; std::string currentGuess; int best = -1; for (std::size_t shift = 0; shift <= 26; shift++) { std::string copy(ciphertext); for (std::size_t j = 0; j < ciphertext.size(); j++) copy[j] = (ciphertext[j] - 97 + shift) % 26 + 97; float dev = getDeviationFromEnglish(copy); if (dev < bestDeviation) { bestDeviation = dev; currentGuess = copy; best = shift; } } return currentGuess; } std::string crackVigenereCipher(const std::string& ciphertext) { float bestDeviation = 4096; std::string currentGuess; for (std::size_t keyLength = 1; keyLength <= 20; keyLength++) { std::string whole(ciphertext); //will be overridden for (std::size_t offset = 0; offset < keyLength; offset++) { std::string subStr; for (std::size_t j = offset; j < ciphertext.size(); j += keyLength) subStr += ciphertext[j]; auto cracked = crackShiftCipher(subStr); for (std::size_t j = 0; j < subStr.size(); j++) whole[j * keyLength + offset] = cracked[j]; } float dev = getDeviationFromEnglish(whole); if (dev < bestDeviation) { bestDeviation = dev; currentGuess = whole; std::cout << std::endl; std::cout << "Better guess! Keylength of " << keyLength << std::endl; std::cout << "Deviation from English: " << dev << std::endl; std::cout << currentGuess << std::endl; } } return currentGuess; } std::string crackRailCipher(const std::string& ciphertext) { int maxKeyLength = 40; if (maxKeyLength >= ciphertext.size()) maxKeyLength = ciphertext.size(); for (int keyLength = 2; keyLength < maxKeyLength; keyLength++) { std::string plaintext(ciphertext); int cipherIndex = 0; for (int offset = 0; offset < keyLength; offset++) { int diff = (keyLength - 1) * 2 - offset * 2; if (offset == keyLength - 1) diff = (keyLength - 1) * 2; for (int j = offset; j < ciphertext.size(); j += diff) { plaintext[j] = ciphertext[cipherIndex]; cipherIndex++; } } std::cout << keyLength << ": " << plaintext << std::endl; } return ""; } std::string toLowerCase(const std::string& str) { std::string copy(str); std::transform(copy.begin(), copy.end(), copy.begin(), ::tolower); return copy; } float getDeviationFromEnglish(const std::string& str) { FrequencyMap map; for (std::size_t j = 0; j < str.size(); j++) map[str[j]] = map[str[j]] + 1; auto ENGLISH = getEnglishFrequencyMap(); float deviation = 0; for (auto& x: map) { float diff = x.second / str.size() - ENGLISH[x.first] / 100; deviation += diff * diff; } return deviation; } FrequencyMap getEnglishFrequencyMap() { static FrequencyMap english; if (!english.empty()) return english; english['a'] = 8.167f; english['b'] = 1.492f; english['c'] = 2.783f; english['d'] = 4.253f; english['e'] = 12.702f; english['f'] = 2.228f; english['g'] = 2.015f; english['h'] = 6.094f; english['i'] = 6.966f; english['j'] = 0.153f; english['k'] = 0.772f; english['l'] = 4.025f; english['m'] = 2.406f; english['n'] = 6.749f; english['o'] = 7.507f; english['p'] = 1.929f; english['q'] = 0.095f; english['r'] = 5.987f; english['s'] = 6.327f; english['t'] = 9.056f; english['u'] = 2.758f; english['v'] = 0.978f; english['w'] = 2.360f; english['x'] = 0.150f; english['y'] = 1.974f; english['z'] = 0.075f; return english; } <|endoftext|>
<commit_before>#include <signal.h> #include <iostream> #include <boost/asio.hpp> #include <boost/asio/coroutine.hpp> #include <network/http/server.hpp> #include <network/http/http_request.hpp> #include <network/http/http_protocol.hpp> using namespace network::http; int main() { boost::asio::io_service io_service; network::http::server<http_protocol> server(io_service); boost::asio::signal_set signals(io_service); signals.add(SIGINT); signals.add(SIGTERM); #if defined(SIGQUIT) signals.add(SIGQUIT); #endif // defined(SIGQUIT) signals.async_wait([&](const boost::system::error_code& error, int signal_number) { io_service.stop(); }); boost::system::error_code ec = server.listen("127.0.0.1", "10081"); if (ec) return 1; io_service.run(); return 0; } <commit_msg>不要な include を削除<commit_after>#include <signal.h> #include <iostream> #include <boost/asio.hpp> #include <network/http/server.hpp> #include <network/http/http_protocol.hpp> using namespace network::http; int main() { boost::asio::io_service io_service; network::http::server<http_protocol> server(io_service); boost::asio::signal_set signals(io_service); signals.add(SIGINT); signals.add(SIGTERM); #if defined(SIGQUIT) signals.add(SIGQUIT); #endif // defined(SIGQUIT) signals.async_wait([&](const boost::system::error_code& error, int signal_number) { io_service.stop(); }); boost::system::error_code ec = server.listen("127.0.0.1", "10081"); if (ec) return 1; io_service.run(); return 0; } <|endoftext|>
<commit_before>#include "WPILib.h" #include "../ADBLib/src/ADBLib.h" #include "auton/AutoBot.h" #include "DreadbotDIO.h" #include <unistd.h> using namespace ADBLib; class Robot: public IterativeRobot { private: TractionDrive* drivebase; CANTalon* motors[5]; Joystick* jys; Joystick* jys2; ADBLib::Controller gpd; ADBLib::Controller gpd2; Compressor* compressor; Preferences* prefs; AHRS* ahrs; MultiVision* mv; SimplePneumatic* shooterPiston; SimplePneumatic* liftArm; SimplePneumatic* extendArm; SimplePneumatic* tail; SimplePneumatic* mandibles; CANTalon* fan; bool armElevAlt; //Stores if the alternate control was used last or not. true = alt, false=regular enum {UP, DOWN} armPos; AutoBot* autobot; void RobotInit() { //Awful hack in need of replacement system("if [ -f \"/sysLog.txt\" ] ; then i=0; while [ -f \"/robologs/sysLog.$i.txt\" ] ; do ((i++)) ; done ; mv \"/sysLog.txt\" \"/robologs/sysLog.$i.txt\" ; fi ;"); prefs = Preferences::GetInstance(); compressor = new Compressor(1); jys = new Joystick(0); jys2 = new Joystick(1); gpd.setJoystick(jys); gpd2.setJoystick(jys2); gpd.parseConfig("/ControlConfig.xml"); gpd2.parseConfig("/ControlConfig.xml"); gpd2.switchProfile("secondary"); for (int i = 1; i < 5; i++) { motors[i] = new CANTalon(i); motors[i]->SetControlMode(CANTalon::kPercentVbus); motors[i]->SetVoltageRampRate(0.5); } motors[2]->SetInverted(true); motors[1]->SetInverted(true); drivebase = new TractionDrive(motors[4], motors[2], motors[3], motors[1]); ahrs = new AHRS(SPI::Port::kMXP); mv = new MultiVision; mv->switchCamera("cam0"); liftArm = new SimplePneumatic(new DoubleSolenoid(0, 1)); shooterPiston = new SimplePneumatic(new Solenoid(3)); extendArm = new SimplePneumatic(new Solenoid(2)); tail = new SimplePneumatic(new Solenoid(5)); mandibles = new SimplePneumatic(new Solenoid(4)); fan = new CANTalon(5); autobot = new AutoBot; autobot->init(drivebase, shooterPiston, liftArm, extendArm, ahrs); armElevAlt = true; armPos = DOWN; //This might result in odd behavior at start Logger::log("Finished initializing robot; starting GRIP...", "sysLog"); //if (fork() == 0) // system("/home/lvuser/grip &"); Logger::log("Successfully started GRIP!", "sysLog"); } void AutonomousInit() { Logger::log("Started AUTONOMOUS with mode" + to_string(AutoBot::BREACH) + "!", "sysLog"); fan->Set(1); autobot->switchMode(getAutonMode()); compressor->Start(); } void AutonomousPeriodic() { autobot->update(); } void TeleopInit() { Logger::log("Started TELEOP!", "sysLog"); compressor->Start(); fan->Set(1); jys->SetRumble(Joystick::kLeftRumble, 1024); } void TeleopPeriodic() { //Vision during teleop mv->postImage(); //Primary driver controls mandibles->set(gpd["mandibles"]); if (gpd["armUp"] || gpd["armDown"]) { armElevAlt = false; if (gpd["armUp"]) { armPos = UP; liftArm->set(1); } else if (gpd["armDown"]) { armPos = DOWN; liftArm->set(-1); } } if (gpd2["armElevAlt"] != 0 || armElevAlt) { double input = gpd2["armElevAlt"]; if (input < 0) //No, these comparisons are NOT flipped. I don't know why though. { armPos = UP; liftArm->set(1); } else if (input > 0) { armPos = DOWN; liftArm->set(-1); } else liftArm->set(0); armElevAlt = true; } if (gpd["shooter"]) { //Shooter behavior varies with arm position if (armPos == UP) { extendArm->set(1); Wait(0.49); shooterPiston->set(1); Wait(0.3); shooterPiston->set(0); } else { shooterPiston->set(1); Wait(0.3); shooterPiston->set(0); } } drivebase->drive(0, -gpd["transY"], gpd["rot"]); extendArm->set(gpd2["extendArm"]); tail->set(gpd2["tail"]); } void DisabledInit() { Logger::log("DISABLING robot!", "sysLog"); Logger::flushLogBuffers(); compressor->Stop(); fan->Set(0); } void TestInit() { Logger::log("Started TEST!", "sysLog"); compressor->Start(); } void TestPeriodic() { } }; START_ROBOT_CLASS(Robot); <commit_msg>Add log file saving based on Mr. King's initLog() function<commit_after>#include "WPILib.h" #include "../ADBLib/src/ADBLib.h" #include "auton/AutoBot.h" #include "DreadbotDIO.h" #include <unistd.h> #include <dirent.h> #include <regex> #include <sys/stat.h> #include <string> using namespace ADBLib; using std::string; void moveLog(); class Robot: public IterativeRobot { private: TractionDrive* drivebase; CANTalon* motors[5]; Joystick* jys; Joystick* jys2; ADBLib::Controller gpd; ADBLib::Controller gpd2; Compressor* compressor; Preferences* prefs; AHRS* ahrs; MultiVision* mv; SimplePneumatic* shooterPiston; SimplePneumatic* liftArm; SimplePneumatic* extendArm; SimplePneumatic* tail; SimplePneumatic* mandibles; CANTalon* fan; bool armElevAlt; //Stores if the alternate control was used last or not. true = alt, false=regular enum {UP, DOWN} armPos; AutoBot* autobot; void RobotInit() { //Takes the existing sysLog.txt file in / and moves it to /logfiles/ //Also increments the log file name by a number so old logs are preserved. moveLog(); prefs = Preferences::GetInstance(); compressor = new Compressor(1); jys = new Joystick(0); jys2 = new Joystick(1); gpd.setJoystick(jys); gpd2.setJoystick(jys2); gpd.parseConfig("/ControlConfig.xml"); gpd2.parseConfig("/ControlConfig.xml"); gpd2.switchProfile("secondary"); for (int i = 1; i < 5; i++) { motors[i] = new CANTalon(i); motors[i]->SetControlMode(CANTalon::kPercentVbus); motors[i]->SetVoltageRampRate(0.5); } motors[2]->SetInverted(true); motors[1]->SetInverted(true); drivebase = new TractionDrive(motors[4], motors[2], motors[3], motors[1]); ahrs = new AHRS(SPI::Port::kMXP); mv = new MultiVision; mv->switchCamera("cam0"); liftArm = new SimplePneumatic(new DoubleSolenoid(0, 1)); shooterPiston = new SimplePneumatic(new Solenoid(3)); extendArm = new SimplePneumatic(new Solenoid(2)); tail = new SimplePneumatic(new Solenoid(5)); mandibles = new SimplePneumatic(new Solenoid(4)); fan = new CANTalon(5); autobot = new AutoBot; autobot->init(drivebase, shooterPiston, liftArm, extendArm, ahrs); armElevAlt = true; armPos = DOWN; //This might result in odd behavior at start Logger::log("Finished initializing robot; starting GRIP...", "sysLog"); //if (fork() == 0) // system("/home/lvuser/grip &"); Logger::log("Successfully started GRIP!", "sysLog"); } void AutonomousInit() { Logger::log("Started AUTONOMOUS with mode" + to_string(AutoBot::BREACH) + "!", "sysLog"); fan->Set(1); autobot->switchMode(getAutonMode()); compressor->Start(); } void AutonomousPeriodic() { autobot->update(); } void TeleopInit() { Logger::log("Started TELEOP!", "sysLog"); compressor->Start(); fan->Set(1); jys->SetRumble(Joystick::kLeftRumble, 1024); } void TeleopPeriodic() { //Vision during teleop mv->postImage(); //Primary driver controls mandibles->set(gpd["mandibles"]); if (gpd["armUp"] || gpd["armDown"]) { armElevAlt = false; if (gpd["armUp"]) { armPos = UP; liftArm->set(1); } else if (gpd["armDown"]) { armPos = DOWN; liftArm->set(-1); } } if (gpd2["armElevAlt"] != 0 || armElevAlt) { double input = gpd2["armElevAlt"]; if (input < 0) //No, these comparisons are NOT flipped. I don't know why though. { armPos = UP; liftArm->set(1); } else if (input > 0) { armPos = DOWN; liftArm->set(-1); } else liftArm->set(0); armElevAlt = true; } if (gpd["shooter"]) { //Shooter behavior varies with arm position if (armPos == UP) { extendArm->set(1); Wait(0.49); shooterPiston->set(1); Wait(0.3); shooterPiston->set(0); } else { shooterPiston->set(1); Wait(0.3); shooterPiston->set(0); } } drivebase->drive(0, -gpd["transY"], gpd["rot"]); extendArm->set(gpd2["extendArm"]); tail->set(gpd2["tail"]); } void DisabledInit() { Logger::log("DISABLING robot!", "sysLog"); Logger::flushLogBuffers(); compressor->Stop(); fan->Set(0); } void TestInit() { Logger::log("Started TEST!", "sysLog"); compressor->Start(); } void TestPeriodic() { } }; void moveLog() { //Credit to Mr. King for most of this function. It's been tweaked a lot to //CPP-ify it (for the sake of making it easier to explain to new programmers) //but everything filesystem-y is from him. Thank you! const string logdir = "/"; const string savedir = "/logfiles/"; const string prefix = "sysLog"; const string f_extens = ".txt"; // Will just give harmless error if directory already exists. // If there's a real error we'll catch it when the opendir() call // below fails. (returns NULL in case of failure) mkdir(savedir.c_str(), 0777); DIR* dp = opendir(savedir.c_str()); if (!dp) return; // Find the highest existing saved sysLog int max = 0; std::regex reg("\\d+"); dirent* ent = readdir(dp); while (ent) { std::smatch matches; if (std::regex_search(string(ent->d_name), matches, reg)) { int n = stoi(matches.str(0)); if (n > max) max = n; } ent = readdir(dp); } string dst = savedir + prefix + "_" + std::to_string(max + 1) + f_extens; rename((logdir + prefix + f_extens).c_str(), dst.c_str()); } START_ROBOT_CLASS(Robot); <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2018 BMW Car IT GmbH * %% * 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. * #L% */ #include <gtest/gtest.h> #include "joynr/exceptions/JoynrException.h" #include "joynr/JoynrRuntime.h" #include "joynr/Settings.h" #include "joynr/tests/DefaultMultipleVersionsInterfaceProvider.h" #include "joynr/tests/DefaultMultipleVersionsInterface1Provider.h" #include "joynr/tests/DefaultMultipleVersionsInterface2Provider.h" #include "joynr/tests/MultipleVersionsInterface1Proxy.h" #include "joynr/tests/MultipleVersionsInterface2Proxy.h" #include "joynr/tests/v2/MultipleVersionsInterfaceProxy.h" #include "tests/JoynrTest.h" using namespace ::testing; using namespace joynr; class MultipleVersionsTest : public Test { protected: MultipleVersionsTest() { } void SetUp() override { runtime1 = JoynrRuntime::createRuntime( std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings"), failOnFatalRuntimeError); runtime2 = JoynrRuntime::createRuntime( std::make_unique<Settings>("test-resources/libjoynrSystemIntegration2.settings"), failOnFatalRuntimeError); discoveryQos.setDiscoveryTimeoutMs(100); discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY); providerQos.setScope(types::ProviderScope::LOCAL); } void TearDown() override { test::util::removeAllCreatedSettingsAndPersistencyFiles(); } template <typename T> std::shared_ptr<T> buildProxy(std::shared_ptr<JoynrRuntime> runtime) { std::shared_ptr<ProxyBuilder<T>> testProxyBuilder( runtime->createProxyBuilder<T>(testDomain)); return testProxyBuilder->setMessagingQos(messagingQos) ->setDiscoveryQos(discoveryQos) ->build(); } /** * Builds a proxy of type T in the specified runtime. Then sets UInt8Attribute1 * to the specified value and checks if the set value can be retrieved correctly. * * @param runtime Builds the proxy in runtime. * @param value Sets the attribute to value. */ template <typename T> void setAndCheckAttribute(std::shared_ptr<JoynrRuntime> runtime, const uint8_t value) { std::shared_ptr<T> testProxy = buildProxy<T>(runtime); uint8_t uInt8Result = 0; testProxy->setUInt8Attribute1(value); testProxy->getUInt8Attribute1(uInt8Result); ASSERT_EQ(value, uInt8Result); } /** * Registers 2 providers and a fitting proxy for each. Then checks if methods of the providers *can be called correctly. * * @param secondRuntime If this is set to true, the second provider and its proxy are *registered/build in a second runtime. */ void buildTwoProvidersAndPerformChecks(bool secondRuntime) { std::shared_ptr<JoynrRuntime> selectedRuntime; if (secondRuntime) { selectedRuntime = runtime2; } else { selectedRuntime = runtime1; } auto testProvider1 = std::make_shared<tests::DefaultMultipleVersionsInterface1Provider>(); runtime1->registerProvider<tests::MultipleVersionsInterface1Provider>( testDomain, testProvider1, providerQos); auto testProvider2 = std::make_shared<tests::DefaultMultipleVersionsInterface2Provider>(); selectedRuntime->registerProvider<tests::MultipleVersionsInterface2Provider>( testDomain, testProvider2, providerQos); setAndCheckAttribute<tests::MultipleVersionsInterface1Proxy>( runtime1, expectedUInt8Result1); setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>( selectedRuntime, expectedUInt8Result2); runtime1->unregisterProvider<tests::MultipleVersionsInterface1Provider>( testDomain, testProvider1); selectedRuntime->unregisterProvider<tests::MultipleVersionsInterface2Provider>( testDomain, testProvider2); } const std::string testDomain = "multipleVersionsTestDomain"; const uint8_t expectedUInt8Result1 = 50; const uint8_t expectedUInt8Result2 = 100; DiscoveryQos discoveryQos; MessagingQos messagingQos; types::ProviderQos providerQos; std::shared_ptr<JoynrRuntime> runtime1; std::shared_ptr<JoynrRuntime> runtime2; private: DISALLOW_COPY_AND_ASSIGN(MultipleVersionsTest); }; TEST_F(MultipleVersionsTest, twoProxiesOfDifferentVersioningTypesVsOneProvider) { auto testProvider = std::make_shared<tests::DefaultMultipleVersionsInterfaceProvider>(); runtime1->registerProvider<tests::MultipleVersionsInterfaceProvider>( testDomain, testProvider, providerQos); setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>(runtime1, expectedUInt8Result1); setAndCheckAttribute<tests::v2::MultipleVersionsInterfaceProxy>(runtime1, expectedUInt8Result2); runtime1->unregisterProvider<tests::MultipleVersionsInterfaceProvider>( testDomain, testProvider); } TEST_F(MultipleVersionsTest, twoProvidersOfDifferentVersionsAndTwoFittingProxiesInSingleRuntime) { buildTwoProvidersAndPerformChecks(false); } TEST_F(MultipleVersionsTest, twoProvidersWithFittingProxiesInDifferentRuntimes) { buildTwoProvidersAndPerformChecks(true); } <commit_msg>[C++] Fixed MultipleVersionsTest by using separate CC settings per runtime<commit_after>/* * #%L * %% * Copyright (C) 2018 BMW Car IT GmbH * %% * 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. * #L% */ #include <gtest/gtest.h> #include "joynr/exceptions/JoynrException.h" #include "joynr/JoynrRuntime.h" #include "joynr/Settings.h" #include "joynr/tests/DefaultMultipleVersionsInterfaceProvider.h" #include "joynr/tests/DefaultMultipleVersionsInterface1Provider.h" #include "joynr/tests/DefaultMultipleVersionsInterface2Provider.h" #include "joynr/tests/MultipleVersionsInterface1Proxy.h" #include "joynr/tests/MultipleVersionsInterface2Proxy.h" #include "joynr/tests/v2/MultipleVersionsInterfaceProxy.h" #include "tests/JoynrTest.h" using namespace ::testing; using namespace joynr; class MultipleVersionsTest : public Test { protected: MultipleVersionsTest() { } void SetUp() override { const Settings libjoynrSettings1("test-resources/libjoynrSystemIntegration1.settings"); const Settings libjoynrSettings2("test-resources/libjoynrSystemIntegration2.settings"); auto settings1 = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings"); auto settings2 = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest2.settings"); Settings::merge(libjoynrSettings1, *settings1, false); Settings::merge(libjoynrSettings2, *settings2, false); runtime1 = JoynrRuntime::createRuntime(std::move(settings1), failOnFatalRuntimeError); runtime2 = JoynrRuntime::createRuntime(std::move(settings2), failOnFatalRuntimeError); discoveryQos.setDiscoveryTimeoutMs(100); discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY); providerQos.setScope(types::ProviderScope::LOCAL); } void TearDown() override { test::util::removeAllCreatedSettingsAndPersistencyFiles(); } template <typename T> std::shared_ptr<T> buildProxy(std::shared_ptr<JoynrRuntime> runtime) { std::shared_ptr<ProxyBuilder<T>> testProxyBuilder( runtime->createProxyBuilder<T>(testDomain)); return testProxyBuilder->setMessagingQos(messagingQos) ->setDiscoveryQos(discoveryQos) ->build(); } /** * Builds a proxy of type T in the specified runtime. Then sets UInt8Attribute1 * to the specified value and checks if the set value can be retrieved correctly. * * @param runtime Builds the proxy in runtime. * @param value Sets the attribute to value. */ template <typename T> void setAndCheckAttribute(std::shared_ptr<JoynrRuntime> runtime, const uint8_t value) { std::shared_ptr<T> testProxy = buildProxy<T>(runtime); uint8_t uInt8Result = 0; testProxy->setUInt8Attribute1(value); testProxy->getUInt8Attribute1(uInt8Result); ASSERT_EQ(value, uInt8Result); } /** * Registers 2 providers and a fitting proxy for each. Then checks if methods of the providers *can be called correctly. * * @param secondRuntime If this is set to true, the second provider and its proxy are *registered/build in a second runtime. */ void buildTwoProvidersAndPerformChecks(bool secondRuntime) { std::shared_ptr<JoynrRuntime> selectedRuntime; if (secondRuntime) { selectedRuntime = runtime2; } else { selectedRuntime = runtime1; } auto testProvider1 = std::make_shared<tests::DefaultMultipleVersionsInterface1Provider>(); runtime1->registerProvider<tests::MultipleVersionsInterface1Provider>( testDomain, testProvider1, providerQos); auto testProvider2 = std::make_shared<tests::DefaultMultipleVersionsInterface2Provider>(); selectedRuntime->registerProvider<tests::MultipleVersionsInterface2Provider>( testDomain, testProvider2, providerQos); setAndCheckAttribute<tests::MultipleVersionsInterface1Proxy>( runtime1, expectedUInt8Result1); setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>( selectedRuntime, expectedUInt8Result2); runtime1->unregisterProvider<tests::MultipleVersionsInterface1Provider>( testDomain, testProvider1); selectedRuntime->unregisterProvider<tests::MultipleVersionsInterface2Provider>( testDomain, testProvider2); } const std::string testDomain = "multipleVersionsTestDomain"; const uint8_t expectedUInt8Result1 = 50; const uint8_t expectedUInt8Result2 = 100; DiscoveryQos discoveryQos; MessagingQos messagingQos; types::ProviderQos providerQos; std::shared_ptr<JoynrRuntime> runtime1; std::shared_ptr<JoynrRuntime> runtime2; private: DISALLOW_COPY_AND_ASSIGN(MultipleVersionsTest); }; TEST_F(MultipleVersionsTest, twoProxiesOfDifferentVersioningTypesVsOneProvider) { auto testProvider = std::make_shared<tests::DefaultMultipleVersionsInterfaceProvider>(); runtime1->registerProvider<tests::MultipleVersionsInterfaceProvider>( testDomain, testProvider, providerQos); setAndCheckAttribute<tests::MultipleVersionsInterface2Proxy>(runtime1, expectedUInt8Result1); setAndCheckAttribute<tests::v2::MultipleVersionsInterfaceProxy>(runtime1, expectedUInt8Result2); runtime1->unregisterProvider<tests::MultipleVersionsInterfaceProvider>( testDomain, testProvider); } TEST_F(MultipleVersionsTest, twoProvidersOfDifferentVersionsAndTwoFittingProxiesInSingleRuntime) { buildTwoProvidersAndPerformChecks(false); } TEST_F(MultipleVersionsTest, twoProvidersWithFittingProxiesInDifferentRuntimes) { buildTwoProvidersAndPerformChecks(true); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestAMRGhostLayerStripping.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME TestAMRGhostLayerStripping.cxx -- Test for stripping ghost layers // // .SECTION Description // A simple test for testing the functionality of stripping out ghost layers // that partially cover lower resolution cells. The test constructs an AMR // configuration using the vtkAMRGaussianPulseSource which has a known structure. // Ghost layers are manually added to the hi-res grids and then stripped out. // Tests cover also configurations with different refinement ratios and // different numbers of ghost-layers. // C/C++ includes #include <cassert> #include <cmath> #include <iostream> #include <sstream> // VTK includes #include "vtkAMRGaussianPulseSource.h" #include "vtkAMRUtilities.h" #include "vtkCell.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkOverlappingAMR.h" #include "vtkUniformGrid.h" #include "vtkXMLImageDataWriter.h" #define DEBUG_ON //------------------------------------------------------------------------------ void WriteUniformGrid( vtkUniformGrid *g, std::string prefix ) { assert( "pre: Uniform grid (g) is NULL!" && (g != NULL) ); vtkXMLImageDataWriter *imgWriter = vtkXMLImageDataWriter::New(); std::ostringstream oss; oss << prefix << "." << imgWriter->GetDefaultFileExtension(); imgWriter->SetFileName( oss.str().c_str() ); imgWriter->SetInputData( g ); imgWriter->Write(); imgWriter->Delete(); } //------------------------------------------------------------------------------ double ComputePulse( const int dimension, double location[3], double pulseOrigin[3], double pulseWidth[3], double pulseAmplitude) { double pulse = 0.0; double r = 0.0; for( int i=0; i < dimension; ++i ) { double d = location[i]-pulseOrigin[i]; double d2 = d*d; double L2 = pulseWidth[i]*pulseWidth[i]; r += d2/L2; } // END for all dimensions pulse = pulseAmplitude * std::exp( -r ); return( pulse ); } //------------------------------------------------------------------------------ void ComputeCellCenter( vtkUniformGrid *grid, vtkIdType cellIdx, double centroid[3]) { assert("pre: input grid instance is NULL" && (grid != NULL)); assert("pre: cell index is out-of-bounds!" && (cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells())); vtkCell *myCell = grid->GetCell( cellIdx ); assert( "ERROR: Cell is NULL" && (myCell != NULL) ); double pcenter[3]; double *weights = new double[ myCell->GetNumberOfPoints() ]; int subId = myCell->GetParametricCenter( pcenter ); myCell->EvaluateLocation( subId, pcenter, centroid, weights ); delete [] weights; } //------------------------------------------------------------------------------ void GeneratePulseField(const int dimension,vtkUniformGrid* grid) { assert("pre: grid is NULL!" && (grid != NULL)); assert("pre: grid is empty!" && (grid->GetNumberOfCells() >= 1) ); double pulseOrigin[3]; double pulseWidth[3]; double pulseAmplitude; vtkAMRGaussianPulseSource *pulseSource = vtkAMRGaussianPulseSource::New(); pulseSource->GetPulseOrigin( pulseOrigin ); pulseSource->GetPulseWidth( pulseWidth ); pulseAmplitude = pulseSource->GetPulseAmplitude(); pulseSource->Delete(); vtkDoubleArray *centroidArray = vtkDoubleArray::New(); centroidArray->SetName("Centroid"); centroidArray->SetNumberOfComponents( 3 ); centroidArray->SetNumberOfTuples( grid->GetNumberOfCells() ); vtkDoubleArray *pulseField = vtkDoubleArray::New(); pulseField->SetName( "Gaussian-Pulse" ); pulseField->SetNumberOfComponents( 1 ); pulseField->SetNumberOfTuples( grid->GetNumberOfCells() ); double centroid[3]; vtkIdType cellIdx = 0; for(; cellIdx < grid->GetNumberOfCells(); ++cellIdx ) { ComputeCellCenter(grid,cellIdx,centroid); centroidArray->SetComponent(cellIdx,0,centroid[0]); centroidArray->SetComponent(cellIdx,1,centroid[1]); centroidArray->SetComponent(cellIdx,2,centroid[2]); double pulse = ComputePulse( dimension,centroid,pulseOrigin,pulseWidth,pulseAmplitude); pulseField->SetComponent(cellIdx,0,pulse); } // END for all cells grid->GetCellData()->AddArray( centroidArray ); centroidArray->Delete(); grid->GetCellData()->AddArray( pulseField ); pulseField->Delete(); } //------------------------------------------------------------------------------ vtkUniformGrid* GetGhostedGrid( const int dimension,vtkUniformGrid *refGrid, int ghost[6], const int NG) { assert("pre: NG >= 1" && (NG >= 1) ); // STEP 0: If the reference grid is NULL just return if( refGrid == NULL ) { return NULL; } // STEP 1: Acquire reference grid origin,spacing, dims int dims[3]; double origin[3]; double spacing[3]; refGrid->GetOrigin(origin); refGrid->GetSpacing(spacing); refGrid->GetDimensions(dims); // STEP 2: Adjust origin and dimensions for ghost cells along each dimension for( int i=0; i < 3; ++i ) { if( ghost[i*2]==1 ) { // Grow along min of dimension i dims[i] += NG; origin[i] -= NG*spacing[i]; } if( ghost[i*2+1]==1 ) { // Grow along max of dimension i dims[i] += NG; } } // END for all dimensions // STEP 3: Construt ghosted grid vtkUniformGrid *grid = vtkUniformGrid::New(); grid->Initialize(); grid->SetOrigin( origin ); grid->SetSpacing( spacing ); grid->SetDimensions( dims ); // STEP 4: Construct field data, i.e., Centroid and Gaussian-Pulse. The // data is recomputed here, since we know how to compute it. GeneratePulseField(dimension,grid); return( grid ); } //------------------------------------------------------------------------------ vtkOverlappingAMR *GetGhostedDataSet( const int dimension, const int NG, vtkOverlappingAMR *inputAMR) { vtkOverlappingAMR *ghostedAMR = vtkOverlappingAMR::New(); ghostedAMR->SetNumberOfLevels( inputAMR->GetNumberOfLevels() ); assert( "pre: Expected number of levels is 2" && (ghostedAMR->GetNumberOfLevels()==2)); // Copy the root grid vtkUniformGrid *rootGrid = vtkUniformGrid::New(); rootGrid->DeepCopy( inputAMR->GetDataSet(0,0) ); ghostedAMR->SetDataSet(0,0,rootGrid); rootGrid->Delete(); // Knowing the AMR configuration returned by vtkAMRGaussingPulseSource // we manually pad ghost-layers to the grids at level 1 (hi-res). How // ghost layers are created is encoded to a ghost vector for each grid, // {imin,imax,jmin,jmax,kmin,kmax}, where a value of "1" indicates that ghost // cells are created in that direction or a "0" to indicate that ghost cells // are not created in the given direction. int ghost[2][6] = { {0,1,0,1,0,0}, // ghost vector for grid (1,0) -- grow at imax,jmax {1,0,1,0,0,0} // ghost vector for grid (1,1) -- grow at imin,jmin }; for( int i=0; i < 2; ++i ) { vtkUniformGrid *grid = inputAMR->GetDataSet(1,i); vtkUniformGrid *ghostedGrid = GetGhostedGrid(dimension,grid,ghost[i],NG); ghostedAMR->SetDataSet(1,i,ghostedGrid); #ifdef DEBUG_ON std::ostringstream oss; oss.clear(); oss.str(""); oss << "GHOSTED_GRID_1_" << i; WriteUniformGrid( ghostedGrid, oss.str() ); #endif ghostedGrid->Delete(); } // END for all grids vtkAMRUtilities::GenerateMetaData(ghostedAMR); return( ghostedAMR ); } //------------------------------------------------------------------------------ vtkOverlappingAMR *GetAMRDataSet( const int dimension, const int refinementRatio) { vtkAMRGaussianPulseSource *amrGPSource = vtkAMRGaussianPulseSource::New(); amrGPSource->SetDimension( dimension ); amrGPSource->SetRefinementRatio( refinementRatio ); amrGPSource->Update(); vtkOverlappingAMR *myAMR = vtkOverlappingAMR::New(); myAMR->ShallowCopy( amrGPSource->GetOutput() ); amrGPSource->Delete(); return( myAMR ); } //------------------------------------------------------------------------------ int TestAMRGhostLayerStripping(int argc, char *argv[]) { // Get rid of compiler warnings on unused vars argc = argc; argv = argv; int rc = 0; int NDIM = 3; int NumberOfRefinmentRatios = 1; int rRatios[1] = { 2 }; int NumberOfGhostTests = 1; int ng[ 1 ] = { 1 }; for( int dim=2; dim <= NDIM; ++dim ) { for( int r=0; r < NumberOfRefinmentRatios; ++r ) { for( int g=0; g < NumberOfGhostTests; ++g ) { std::cout << "====\n"; std::cout << "Checking AMR data dim=" << dim << " r=" << rRatios[r]; std::cout << " NG=" << ng[g] << std::endl; std::cout.flush(); // Get the non-ghosted dataset vtkOverlappingAMR *amrData = GetAMRDataSet(dim,rRatios[r]); assert("pre: amrData should not be NULL!" && (amrData != NULL) ); if(vtkAMRUtilities::HasPartiallyOverlappingGhostCells(amrData)) { ++rc; std::cerr << "ERROR: erroneously detected partially overlapping " << "ghost cells on non-ghosted grid!\n"; } // Get the ghosted dataset std::cout << "===\n"; std::cout << "Checking ghosted data...\n"; std::cout.flush(); vtkOverlappingAMR *ghostedAMRData= GetGhostedDataSet(dim,ng[g],amrData); assert("pre: ghosted AMR data is NULL!" && (ghostedAMRData != NULL) ); if(!vtkAMRUtilities::HasPartiallyOverlappingGhostCells(ghostedAMRData)) { ++rc; std::cerr << "ERROR: failed detection of partially overlapping " << "ghost cells!\n"; } vtkOverlappingAMR *strippedAMRData = vtkOverlappingAMR::New(); vtkAMRUtilities::StripGhostLayers( ghostedAMRData, strippedAMRData ); amrData->Delete(); ghostedAMRData->Delete(); strippedAMRData->Delete(); } // END for all ghost tests } // END for all refinementRatios to test } // END for all dimensions to test return rc; } <commit_msg>ENH: Test suite for stripping out ghost layers<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestAMRGhostLayerStripping.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME TestAMRGhostLayerStripping.cxx -- Test for stripping ghost layers // // .SECTION Description // A simple test for testing the functionality of stripping out ghost layers // that partially cover lower resolution cells. The test constructs an AMR // configuration using the vtkAMRGaussianPulseSource which has a known structure. // Ghost layers are manually added to the hi-res grids and then stripped out. // Tests cover also configurations with different refinement ratios and // different numbers of ghost-layers. // C/C++ includes #include <cassert> #include <cmath> #include <iostream> #include <sstream> // VTK includes #include "vtkAMRBox.h" #include "vtkAMRGaussianPulseSource.h" #include "vtkAMRUtilities.h" #include "vtkCell.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkMathUtilities.h" #include "vtkOverlappingAMR.h" #include "vtkUniformGrid.h" #include "vtkXMLImageDataWriter.h" //#define DEBUG_ON //------------------------------------------------------------------------------ void WriteUniformGrid( vtkUniformGrid *g, std::string prefix ) { assert( "pre: Uniform grid (g) is NULL!" && (g != NULL) ); vtkXMLImageDataWriter *imgWriter = vtkXMLImageDataWriter::New(); std::ostringstream oss; oss << prefix << "." << imgWriter->GetDefaultFileExtension(); imgWriter->SetFileName( oss.str().c_str() ); imgWriter->SetInputData( g ); imgWriter->Write(); imgWriter->Delete(); } //------------------------------------------------------------------------------ double ComputePulse( const int dimension, double location[3], double pulseOrigin[3], double pulseWidth[3], double pulseAmplitude) { double pulse = 0.0; double r = 0.0; for( int i=0; i < dimension; ++i ) { double d = location[i]-pulseOrigin[i]; double d2 = d*d; double L2 = pulseWidth[i]*pulseWidth[i]; r += d2/L2; } // END for all dimensions pulse = pulseAmplitude * std::exp( -r ); return( pulse ); } //------------------------------------------------------------------------------ void ComputeCellCenter( vtkUniformGrid *grid, vtkIdType cellIdx, double centroid[3]) { assert("pre: input grid instance is NULL" && (grid != NULL)); assert("pre: cell index is out-of-bounds!" && (cellIdx >= 0) && (cellIdx < grid->GetNumberOfCells())); vtkCell *myCell = grid->GetCell( cellIdx ); assert( "ERROR: Cell is NULL" && (myCell != NULL) ); double pcenter[3]; double *weights = new double[ myCell->GetNumberOfPoints() ]; int subId = myCell->GetParametricCenter( pcenter ); myCell->EvaluateLocation( subId, pcenter, centroid, weights ); delete [] weights; } //------------------------------------------------------------------------------ void GeneratePulseField(const int dimension,vtkUniformGrid* grid) { assert("pre: grid is NULL!" && (grid != NULL)); assert("pre: grid is empty!" && (grid->GetNumberOfCells() >= 1) ); double pulseOrigin[3]; double pulseWidth[3]; double pulseAmplitude; vtkAMRGaussianPulseSource *pulseSource = vtkAMRGaussianPulseSource::New(); pulseSource->GetPulseOrigin( pulseOrigin ); pulseSource->GetPulseWidth( pulseWidth ); pulseAmplitude = pulseSource->GetPulseAmplitude(); pulseSource->Delete(); vtkDoubleArray *centroidArray = vtkDoubleArray::New(); centroidArray->SetName("Centroid"); centroidArray->SetNumberOfComponents( 3 ); centroidArray->SetNumberOfTuples( grid->GetNumberOfCells() ); vtkDoubleArray *pulseField = vtkDoubleArray::New(); pulseField->SetName( "Gaussian-Pulse" ); pulseField->SetNumberOfComponents( 1 ); pulseField->SetNumberOfTuples( grid->GetNumberOfCells() ); double centroid[3]; vtkIdType cellIdx = 0; for(; cellIdx < grid->GetNumberOfCells(); ++cellIdx ) { ComputeCellCenter(grid,cellIdx,centroid); centroidArray->SetComponent(cellIdx,0,centroid[0]); centroidArray->SetComponent(cellIdx,1,centroid[1]); centroidArray->SetComponent(cellIdx,2,centroid[2]); double pulse = ComputePulse( dimension,centroid,pulseOrigin,pulseWidth,pulseAmplitude); pulseField->SetComponent(cellIdx,0,pulse); } // END for all cells grid->GetCellData()->AddArray( centroidArray ); centroidArray->Delete(); grid->GetCellData()->AddArray( pulseField ); pulseField->Delete(); } //------------------------------------------------------------------------------ vtkUniformGrid* GetGhostedGrid( const int dimension,vtkUniformGrid *refGrid, int ghost[6], const int NG) { assert("pre: NG >= 1" && (NG >= 1) ); // STEP 0: If the reference grid is NULL just return if( refGrid == NULL ) { return NULL; } // STEP 1: Acquire reference grid origin,spacing, dims int dims[3]; double origin[3]; double spacing[3]; refGrid->GetOrigin(origin); refGrid->GetSpacing(spacing); refGrid->GetDimensions(dims); // STEP 2: Adjust origin and dimensions for ghost cells along each dimension for( int i=0; i < 3; ++i ) { if( ghost[i*2]==1 ) { // Grow along min of dimension i dims[i] += NG; origin[i] -= NG*spacing[i]; } if( ghost[i*2+1]==1 ) { // Grow along max of dimension i dims[i] += NG; } } // END for all dimensions // STEP 3: Construt ghosted grid vtkUniformGrid *grid = vtkUniformGrid::New(); grid->Initialize(); grid->SetOrigin( origin ); grid->SetSpacing( spacing ); grid->SetDimensions( dims ); // STEP 4: Construct field data, i.e., Centroid and Gaussian-Pulse. The // data is recomputed here, since we know how to compute it. GeneratePulseField(dimension,grid); return( grid ); } //------------------------------------------------------------------------------ vtkOverlappingAMR *GetGhostedDataSet( const int dimension, const int NG, vtkOverlappingAMR *inputAMR) { vtkOverlappingAMR *ghostedAMR = vtkOverlappingAMR::New(); ghostedAMR->SetNumberOfLevels( inputAMR->GetNumberOfLevels() ); assert( "pre: Expected number of levels is 2" && (ghostedAMR->GetNumberOfLevels()==2)); // Copy the root grid vtkUniformGrid *rootGrid = vtkUniformGrid::New(); rootGrid->DeepCopy( inputAMR->GetDataSet(0,0) ); ghostedAMR->SetDataSet(0,0,rootGrid); rootGrid->Delete(); // Knowing the AMR configuration returned by vtkAMRGaussingPulseSource // we manually pad ghost-layers to the grids at level 1 (hi-res). How // ghost layers are created is encoded to a ghost vector for each grid, // {imin,imax,jmin,jmax,kmin,kmax}, where a value of "1" indicates that ghost // cells are created in that direction or a "0" to indicate that ghost cells // are not created in the given direction. int ghost[2][6] = { {0,1,0,1,0,0}, // ghost vector for grid (1,0) -- grow at imax,jmax {1,0,1,0,0,0} // ghost vector for grid (1,1) -- grow at imin,jmin }; for( int i=0; i < 2; ++i ) { vtkUniformGrid *grid = inputAMR->GetDataSet(1,i); vtkUniformGrid *ghostedGrid = GetGhostedGrid(dimension,grid,ghost[i],NG); ghostedAMR->SetDataSet(1,i,ghostedGrid); #ifdef DEBUG_ON std::ostringstream oss; oss.clear(); oss.str(""); oss << dimension << "D_GHOSTED_GRID_1_" << i; WriteUniformGrid( ghostedGrid, oss.str() ); #endif ghostedGrid->Delete(); } // END for all grids vtkAMRUtilities::GenerateMetaData(ghostedAMR); return( ghostedAMR ); } //------------------------------------------------------------------------------ vtkOverlappingAMR *GetAMRDataSet( const int dimension, const int refinementRatio) { vtkAMRGaussianPulseSource *amrGPSource = vtkAMRGaussianPulseSource::New(); amrGPSource->SetDimension( dimension ); amrGPSource->SetRefinementRatio( refinementRatio ); amrGPSource->Update(); vtkOverlappingAMR *myAMR = vtkOverlappingAMR::New(); myAMR->ShallowCopy( amrGPSource->GetOutput() ); amrGPSource->Delete(); return( myAMR ); } //------------------------------------------------------------------------------ void WriteUnGhostedGrids( const int dimension, vtkOverlappingAMR *amr) { assert("pre: AMR dataset is NULL!" && (amr != NULL) ); std::ostringstream oss; oss.clear(); unsigned int levelIdx = 0; for(;levelIdx < amr->GetNumberOfLevels(); ++levelIdx ) { unsigned dataIdx = 0; for(;dataIdx < amr->GetNumberOfDataSets(levelIdx); ++dataIdx ) { vtkUniformGrid *grid = amr->GetDataSet(levelIdx,dataIdx); if( grid != NULL ) { oss.str(""); oss << dimension << "D_UNGHOSTED_GRID_" << levelIdx << "_" << dataIdx; WriteUniformGrid(grid,oss.str()); } } // END for all data-sets } // END for all levels } //------------------------------------------------------------------------------ bool CheckFields(vtkUniformGrid *grid) { // Since we know exactly what the fields are, i.e., gaussian-pulse and // centroid, we manually check the grid for correctness. assert("pre: grid is NULL" && (grid != NULL) ); vtkCellData *CD = grid->GetCellData(); if( !CD->HasArray("Centroid") || !CD->HasArray("Gaussian-Pulse") ) { return false; } vtkDoubleArray *centroidArray = vtkDoubleArray::SafeDownCast(CD->GetArray("Centroid")); assert("pre: centroid arrays is NULL!" && (centroidArray != NULL) ); if( centroidArray->GetNumberOfComponents() != 3 ) { return false; } double *centers = static_cast<double*>(centroidArray->GetVoidPointer(0)); vtkDoubleArray *pulseArray = vtkDoubleArray::SafeDownCast(CD->GetArray("Gaussian-Pulse")); assert("pre: pulse array is NULL!" && (pulseArray != NULL) ); if( pulseArray->GetNumberOfComponents() != 1) { return false; } double *pulses = static_cast<double*>(pulseArray->GetVoidPointer(0)); // Get default pulse parameters double pulseOrigin[3]; double pulseWidth[3]; double pulseAmplitude; vtkAMRGaussianPulseSource *pulseSource = vtkAMRGaussianPulseSource::New(); pulseSource->GetPulseOrigin( pulseOrigin ); pulseSource->GetPulseWidth( pulseWidth ); pulseAmplitude = pulseSource->GetPulseAmplitude(); pulseSource->Delete(); double centroid[3]; int dim = grid->GetDataDimension(); vtkIdType cellIdx = 0; for(; cellIdx < grid->GetNumberOfCells(); ++cellIdx) { ComputeCellCenter(grid,cellIdx,centroid); double val = ComputePulse( dim,centroid,pulseOrigin,pulseWidth,pulseAmplitude); if( !vtkMathUtilities::FuzzyCompare(val,pulses[cellIdx],1e-9) ) { std::cerr << "ERROR: pulse data mismatch!\n"; std::cerr << "expected=" << val << " computed=" << pulses[cellIdx]; std::cerr << std::endl; return false; } if( !vtkMathUtilities::FuzzyCompare(centroid[0],centers[cellIdx*3]) || !vtkMathUtilities::FuzzyCompare(centroid[1],centers[cellIdx*3+1]) || !vtkMathUtilities::FuzzyCompare(centroid[2],centers[cellIdx*3+2]) ) { std::cerr << "ERROR: centroid data mismatch!\n"; return false; } }// END for all cells return true; } //------------------------------------------------------------------------------ bool AMRDataSetsAreEqual( vtkOverlappingAMR *computed, vtkOverlappingAMR *expected) { assert("pre: computed AMR dataset is NULL" && (computed != NULL) ); assert("pre: expected AMR dataset is NULL" && (expected != NULL) ); if( computed == expected ) { return true; } if( computed->GetNumberOfLevels() != expected->GetNumberOfLevels() ) { return false; } unsigned int levelIdx = 0; for(; levelIdx < computed->GetNumberOfLevels(); ++levelIdx ) { if( computed->GetNumberOfDataSets(levelIdx) != expected->GetNumberOfDataSets(levelIdx)) { return false; } unsigned int dataIdx = 0; for(;dataIdx < computed->GetNumberOfDataSets(levelIdx); ++dataIdx) { vtkAMRBox computedBox; computed->GetMetaData(levelIdx,dataIdx,computedBox); vtkAMRBox expectedBox; expected->GetMetaData(levelIdx,dataIdx,expectedBox); if( !(computedBox == expectedBox) ) { std::cerr << "ERROR: AMR data mismatch!\n"; return false; } vtkUniformGrid *computedGrid = computed->GetDataSet(levelIdx,dataIdx); vtkUniformGrid *expectedGrid = expected->GetDataSet(levelIdx,dataIdx); for( int i=0; i < 3; ++i ) { if(computedGrid->GetDimensions()[i] != expectedGrid->GetDimensions()[i] ) { std::cerr << "ERROR: grid dimensions mismatch!\n"; return false; } if( !vtkMathUtilities::FuzzyCompare( computedGrid->GetOrigin()[i], expectedGrid->GetOrigin()[i]) ) { std::cerr << "ERROR: grid origin mismathc!\n"; return false; } }// END for all dimensions if(!CheckFields(computedGrid) ) { std::cerr << "ERROR: grid fields were not as expected!\n"; return false; } }// END for all data } // END for all levels return true; } //------------------------------------------------------------------------------ int TestGhostStripping( const int dimension, const int refinementRatio, const int NG) { int rc = 0; std::cout << "====\n"; std::cout << "Checking AMR data dim=" << dimension << " r=" << refinementRatio << " NG=" << NG << std::endl; std::cout.flush(); // Get the non-ghosted dataset vtkOverlappingAMR *amrData = GetAMRDataSet(dimension,refinementRatio); assert("pre: amrData should not be NULL!" && (amrData != NULL) ); if(vtkAMRUtilities::HasPartiallyOverlappingGhostCells(amrData)) { ++rc; std::cerr << "ERROR: erroneously detected partially overlapping " << "ghost cells on non-ghosted grid!\n"; } // Get the ghosted dataset vtkOverlappingAMR *ghostedAMRData=GetGhostedDataSet(dimension,NG,amrData); assert("pre: ghosted AMR data is NULL!" && (ghostedAMRData != NULL) ); if( NG == refinementRatio ) { // There are no partially overlapping ghost cells if(vtkAMRUtilities::HasPartiallyOverlappingGhostCells( ghostedAMRData)) { ++rc; std::cerr << "ERROR: detected partially overlapping " << "ghost cells when there shouldn't be any!\n"; } } else { if(!vtkAMRUtilities::HasPartiallyOverlappingGhostCells( ghostedAMRData)) { ++rc; std::cerr << "ERROR: failed detection of partially overlapping " << "ghost cells!\n"; } } vtkOverlappingAMR *strippedAMRData = vtkOverlappingAMR::New(); vtkAMRUtilities::StripGhostLayers( ghostedAMRData, strippedAMRData ); #ifdef DEBUG_ON WriteUnGhostedGrids(dimension,strippedAMRData); #endif // The strippedAMRData is expected to be exactly the same as the initial // unghosted AMR dataset if(!AMRDataSetsAreEqual(strippedAMRData,amrData) ) { ++rc; std::cerr << "ERROR: AMR data did not match expected data!\n"; } amrData->Delete(); ghostedAMRData->Delete(); strippedAMRData->Delete(); return( rc ); } //------------------------------------------------------------------------------ int TestAMRGhostLayerStripping(int argc, char *argv[]) { // Get rid of compiler warnings on unused vars argc = argc; argv = argv; int rc = 0; int DIM0 = 2; int NDIM = 3; int NumberOfRefinmentRatios = 3; int rRatios[3] = { 2,3,4 }; for( int dim=DIM0; dim <= NDIM; ++dim ) { for( int r=0; r < NumberOfRefinmentRatios; ++r ) { for( int ng=1; ng <= rRatios[r]; ++ng ) { rc += TestGhostStripping(dim,rRatios[r],ng); } // END for all ghost-layer tests } // END for all refinementRatios to test } // END for all dimensions to test return rc; } <|endoftext|>
<commit_before> // For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "CameraControllable.h" #include "EC_NetworkPosition.h" #include "SceneEvents.h" #include "Entity.h" #include "SceneManager.h" #include "EC_OgrePlaceable.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include "EC_OgreMesh.h" #include "EC_AvatarAppearance.h" //#include "RexTypes.h" #include "InputEvents.h" #include "InputServiceInterface.h" #include <Ogre.h> namespace RexLogic { CameraControllable::CameraControllable(Foundation::Framework *fw) : framework_(fw) , action_event_category_(fw->GetEventManager()->QueryEventCategory("Action")) , current_state_(ThirdPerson) , firstperson_pitch_(0) , firstperson_yaw_(0) , drag_pitch_(0) , drag_yaw_(0) { camera_distance_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "default_distance", 20.f); camera_min_distance_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "min_distance", 1.f); camera_max_distance_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "max_distance", 50.f); camera_offset_ = Core::ParseString<Core::Vector3df>( framework_->GetDefaultConfig().DeclareSetting("Camera", "third_person_offset", Core::ToString(Core::Vector3df(0, 0, 1.8f)))); camera_offset_firstperson_ = Core::ParseString<Core::Vector3df>( framework_->GetDefaultConfig().DeclareSetting("Camera", "first_person_offset", Core::ToString(Core::Vector3df(0.5f, 0, 0.8f)))); sensitivity_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "translation_sensitivity", 25.f); zoom_sensitivity_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "zoom_sensitivity", 0.015f); firstperson_sensitivity_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "mouselook_rotation_sensitivity", 1.3f); action_trans_[RexTypes::Actions::MoveForward] = Core::Vector3df::NEGATIVE_UNIT_Z; action_trans_[RexTypes::Actions::MoveBackward] = Core::Vector3df::UNIT_Z; action_trans_[RexTypes::Actions::MoveLeft] = Core::Vector3df::NEGATIVE_UNIT_X; action_trans_[RexTypes::Actions::MoveRight] = Core::Vector3df::UNIT_X; action_trans_[RexTypes::Actions::MoveUp] = Core::Vector3df::UNIT_Y; action_trans_[RexTypes::Actions::MoveDown] = Core::Vector3df::NEGATIVE_UNIT_Y; } bool CameraControllable::HandleSceneEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { //! \todo This is where our user agent model design breaks down. We assume only one controllable entity exists and that it is a target for the camera. //! Should be changed so in some way the target can be changed and is not automatically assigned. -cm if (event_id == Scene::Events::EVENT_CONTROLLABLE_ENTITY) target_entity_ = checked_static_cast<Scene::Events::EntityEventData*>(data)->entity; return false; } bool CameraControllable::HandleInputEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id == Input::Events::INPUTSTATE_THIRDPERSON && current_state_ != ThirdPerson) { current_state_ = ThirdPerson; firstperson_pitch_ = 0.0f; } if (event_id == Input::Events::INPUTSTATE_FIRSTPERSON && current_state_ != FirstPerson) { current_state_ = FirstPerson; firstperson_pitch_ = 0.0f; } if (event_id == Input::Events::INPUTSTATE_FREECAMERA && current_state_ != FreeLook) { current_state_ = FreeLook; firstperson_pitch_ = 0.0f; } if (event_id == Input::Events::SCROLL) { CameraZoomEvent event_data; //event_data.entity = entity_.lock(); // no entity for camera, :( -cm event_data.amount = checked_static_cast<Input::Events::SingleAxisMovement*>(data)->z_.rel_; //if (event_data.entity) // only send the event if we have an existing entity, no point otherwise framework_->GetEventManager()->SendEvent(action_event_category_, RexTypes::Actions::Zoom, &event_data); } return false; } bool CameraControllable::HandleActionEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id == RexTypes::Actions::Zoom) { Core::Real value = checked_static_cast<CameraZoomEvent*>(data)->amount; camera_distance_ -= (value * zoom_sensitivity_); camera_distance_ = Core::clamp(camera_distance_, camera_min_distance_, camera_max_distance_); } if (current_state_ == FreeLook) { ActionTransMap::const_iterator it = action_trans_.find(event_id); if (it != action_trans_.end()) { // start movement const Core::Vector3df &vec = it->second; free_translation_.x = ( vec.x == 0 ) ? free_translation_.x : vec.x; free_translation_.y = ( vec.y == 0 ) ? free_translation_.y : vec.y; free_translation_.z = ( vec.z == 0 ) ? free_translation_.z : vec.z; } it = action_trans_.find(event_id - 1); if (it != action_trans_.end()) { // stop movement const Core::Vector3df &vec = it->second; free_translation_.x = ( vec.x == 0 ) ? free_translation_.x : 0; free_translation_.y = ( vec.y == 0 ) ? free_translation_.y : 0; free_translation_.z = ( vec.z == 0 ) ? free_translation_.z : 0; } normalized_free_translation_ = free_translation_; normalized_free_translation_.normalize(); } return false; } void CameraControllable::AddTime(Core::f64 frametime) { boost::shared_ptr<Input::InputServiceInterface> input = framework_->GetService<Input::InputServiceInterface>(Foundation::Service::ST_Input).lock(); if (input) { boost::optional<const Input::Events::Movement&> movement = input->PollSlider(Input::Events::MOUSELOOK); if (movement) { drag_yaw_ = static_cast<Core::Real>(movement->x_.rel_) * -0.005f; drag_pitch_ = static_cast<Core::Real>(movement->y_.rel_) * -0.005f; } else if (drag_pitch_ != 0 || drag_yaw_ != 0) { drag_yaw_ = 0; drag_pitch_ = 0; } } boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Scene::EntityPtr target = target_entity_.lock(); if (renderer && target) { Ogre::Camera *camera = renderer->GetCurrentCamera(); // for smoothness, we apparently need to get rotation from network position and position from placeable. Go figure. -cm EC_NetworkPosition *netpos = checked_static_cast<EC_NetworkPosition*>(target->GetComponent(EC_NetworkPosition::NameStatic()).get()); OgreRenderer::EC_OgrePlaceable *placeable = checked_static_cast<OgreRenderer::EC_OgrePlaceable*>(target->GetComponent(OgreRenderer::EC_OgrePlaceable::NameStatic()).get()); if (netpos && placeable) { Core::Vector3df avatar_pos = placeable->GetPosition(); Core::Quaternion avatar_orientation = netpos->rotation_; if (current_state_ == FirstPerson || current_state_ == ThirdPerson) { // this is mostly for third person camera, but also needed by first person camera since it sets proper initial orientation for the camera Core::Vector3df pos = avatar_pos; pos += (avatar_orientation * Core::Vector3df::NEGATIVE_UNIT_X * camera_distance_); pos += (avatar_orientation * camera_offset_); camera->setPosition(pos.x, pos.y, pos.z); Core::Vector3df lookat = avatar_pos + avatar_orientation * camera_offset_; camera->lookAt(lookat.x, lookat.y, lookat.z); } if (current_state_ == FirstPerson) { bool fallback = true; // Try to use head bone from target entity to get the first person camera position Foundation::ComponentPtr mesh_ptr = target->GetComponent(OgreRenderer::EC_OgreMesh::NameStatic()); Foundation::ComponentPtr appearance_ptr = target->GetComponent(EC_AvatarAppearance::NameStatic()); if (mesh_ptr && appearance_ptr) { OgreRenderer::EC_OgreMesh& mesh = *checked_static_cast<OgreRenderer::EC_OgreMesh*>(mesh_ptr.get()); EC_AvatarAppearance& appearance = *checked_static_cast<EC_AvatarAppearance*>(appearance_ptr.get()); Ogre::Entity* ent = mesh.GetEntity(); if (ent) { Ogre::SkeletonInstance* skel = ent->getSkeleton(); if (skel && skel->hasBone(appearance.GetProperty("headbone"))) { // Hack: force Ogre to update skeleton with current animation state, even if avatar invisible if (ent->getAllAnimationStates()) skel->setAnimationState(*ent->getAllAnimationStates()); Ogre::Bone* bone = skel->getBone(appearance.GetProperty("headbone")); Ogre::Vector3 headpos = bone->_getDerivedPosition(); Core::Real adjustheight = mesh.GetAdjustPosition().z + 0.15; Core::Vector3df ourheadpos(-headpos.z + 0.5f, -headpos.x, headpos.y + adjustheight); RexTypes::Vector3 campos = avatar_pos + (avatar_orientation * ourheadpos); camera->setPosition(campos.x, campos.y, campos.z); fallback = false; } } } // Fallback using fixed position if (fallback) { RexTypes::Vector3 campos = avatar_pos + (avatar_orientation * camera_offset_firstperson_); camera->setPosition(campos.x, campos.y, campos.z); } // update camera pitch if (drag_pitch_ != 0) { firstperson_pitch_ += drag_pitch_ * firstperson_sensitivity_; firstperson_pitch_ = Core::clamp(firstperson_pitch_, -Core::HALF_PI, Core::HALF_PI); } camera->pitch(Ogre::Radian(firstperson_pitch_)); } if (current_state_ == FreeLook) { const float trans_dt = (float)frametime * sensitivity_; Ogre::Vector3 pos = camera->getPosition(); pos += camera->getOrientation() * Ogre::Vector3(normalized_free_translation_.x, normalized_free_translation_.y, normalized_free_translation_.z) * trans_dt; camera->setPosition(pos); camera->pitch(Ogre::Radian(drag_pitch_ * firstperson_sensitivity_)); camera->yaw(Ogre::Radian(drag_yaw_ * firstperson_sensitivity_)); } } } // switch between first and third person modes, depending on how close we are to the avatar switch (current_state_) { case FirstPerson: { if (camera_distance_ != camera_min_distance_) { current_state_ = ThirdPerson; Core::event_category_id_t event_category = framework_->GetEventManager()->QueryEventCategory("Input"); framework_->GetEventManager()->SendEvent(event_category, Input::Events::INPUTSTATE_THIRDPERSON, NULL); firstperson_pitch_ = 0.0f; } break; } case ThirdPerson: { if (camera_distance_ == camera_min_distance_) { Core::event_category_id_t event_category = framework_->GetEventManager()->QueryEventCategory("Input"); framework_->GetEventManager()->SendEvent(event_category, Input::Events::INPUTSTATE_FIRSTPERSON, NULL); current_state_ = FirstPerson; firstperson_pitch_ = 0.0f; } break; } } } //experimental for py api void CameraControllable::SetYawPitch(Core::Real newyaw, Core::Real newpitch) { boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Ogre::Camera *camera = renderer->GetCurrentCamera(); firstperson_yaw_ = newyaw; firstperson_pitch_ = newpitch; camera->yaw(Ogre::Radian(firstperson_yaw_)); camera->pitch(Ogre::Radian(firstperson_pitch_)); } /* Core::Vector3df CameraControllable::GetCameraUp(){ boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Ogre::Camera *camera = renderer->GetCurrentCamera(); Ogre::Vector3 up = camera->getUp(); return Core::Vector3df(up.x, up.y, up.z); } Core::Vector3df CameraControllable::GetCameraRight(){ boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Ogre::Camera *camera = renderer->GetCurrentCamera(); Ogre::Vector3 right = camera->getRight(); return Core::Vector3df(right.x, right.y, right.z); } */ } <commit_msg>Added optional "viewbone" property which will be used for 1st person view tracking instead of "headbone", without need for hardcoded offset. (headbone usually points at neck of avatar skeleton)<commit_after> // For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "CameraControllable.h" #include "EC_NetworkPosition.h" #include "SceneEvents.h" #include "Entity.h" #include "SceneManager.h" #include "EC_OgrePlaceable.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include "EC_OgreMesh.h" #include "EC_AvatarAppearance.h" //#include "RexTypes.h" #include "InputEvents.h" #include "InputServiceInterface.h" #include <Ogre.h> namespace RexLogic { CameraControllable::CameraControllable(Foundation::Framework *fw) : framework_(fw) , action_event_category_(fw->GetEventManager()->QueryEventCategory("Action")) , current_state_(ThirdPerson) , firstperson_pitch_(0) , firstperson_yaw_(0) , drag_pitch_(0) , drag_yaw_(0) { camera_distance_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "default_distance", 20.f); camera_min_distance_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "min_distance", 1.f); camera_max_distance_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "max_distance", 50.f); camera_offset_ = Core::ParseString<Core::Vector3df>( framework_->GetDefaultConfig().DeclareSetting("Camera", "third_person_offset", Core::ToString(Core::Vector3df(0, 0, 1.8f)))); camera_offset_firstperson_ = Core::ParseString<Core::Vector3df>( framework_->GetDefaultConfig().DeclareSetting("Camera", "first_person_offset", Core::ToString(Core::Vector3df(0.5f, 0, 0.8f)))); sensitivity_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "translation_sensitivity", 25.f); zoom_sensitivity_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "zoom_sensitivity", 0.015f); firstperson_sensitivity_ = framework_->GetDefaultConfig().DeclareSetting("Camera", "mouselook_rotation_sensitivity", 1.3f); action_trans_[RexTypes::Actions::MoveForward] = Core::Vector3df::NEGATIVE_UNIT_Z; action_trans_[RexTypes::Actions::MoveBackward] = Core::Vector3df::UNIT_Z; action_trans_[RexTypes::Actions::MoveLeft] = Core::Vector3df::NEGATIVE_UNIT_X; action_trans_[RexTypes::Actions::MoveRight] = Core::Vector3df::UNIT_X; action_trans_[RexTypes::Actions::MoveUp] = Core::Vector3df::UNIT_Y; action_trans_[RexTypes::Actions::MoveDown] = Core::Vector3df::NEGATIVE_UNIT_Y; } bool CameraControllable::HandleSceneEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { //! \todo This is where our user agent model design breaks down. We assume only one controllable entity exists and that it is a target for the camera. //! Should be changed so in some way the target can be changed and is not automatically assigned. -cm if (event_id == Scene::Events::EVENT_CONTROLLABLE_ENTITY) target_entity_ = checked_static_cast<Scene::Events::EntityEventData*>(data)->entity; return false; } bool CameraControllable::HandleInputEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id == Input::Events::INPUTSTATE_THIRDPERSON && current_state_ != ThirdPerson) { current_state_ = ThirdPerson; firstperson_pitch_ = 0.0f; } if (event_id == Input::Events::INPUTSTATE_FIRSTPERSON && current_state_ != FirstPerson) { current_state_ = FirstPerson; firstperson_pitch_ = 0.0f; } if (event_id == Input::Events::INPUTSTATE_FREECAMERA && current_state_ != FreeLook) { current_state_ = FreeLook; firstperson_pitch_ = 0.0f; } if (event_id == Input::Events::SCROLL) { CameraZoomEvent event_data; //event_data.entity = entity_.lock(); // no entity for camera, :( -cm event_data.amount = checked_static_cast<Input::Events::SingleAxisMovement*>(data)->z_.rel_; //if (event_data.entity) // only send the event if we have an existing entity, no point otherwise framework_->GetEventManager()->SendEvent(action_event_category_, RexTypes::Actions::Zoom, &event_data); } return false; } bool CameraControllable::HandleActionEvent(Core::event_id_t event_id, Foundation::EventDataInterface* data) { if (event_id == RexTypes::Actions::Zoom) { Core::Real value = checked_static_cast<CameraZoomEvent*>(data)->amount; camera_distance_ -= (value * zoom_sensitivity_); camera_distance_ = Core::clamp(camera_distance_, camera_min_distance_, camera_max_distance_); } if (current_state_ == FreeLook) { ActionTransMap::const_iterator it = action_trans_.find(event_id); if (it != action_trans_.end()) { // start movement const Core::Vector3df &vec = it->second; free_translation_.x = ( vec.x == 0 ) ? free_translation_.x : vec.x; free_translation_.y = ( vec.y == 0 ) ? free_translation_.y : vec.y; free_translation_.z = ( vec.z == 0 ) ? free_translation_.z : vec.z; } it = action_trans_.find(event_id - 1); if (it != action_trans_.end()) { // stop movement const Core::Vector3df &vec = it->second; free_translation_.x = ( vec.x == 0 ) ? free_translation_.x : 0; free_translation_.y = ( vec.y == 0 ) ? free_translation_.y : 0; free_translation_.z = ( vec.z == 0 ) ? free_translation_.z : 0; } normalized_free_translation_ = free_translation_; normalized_free_translation_.normalize(); } return false; } void CameraControllable::AddTime(Core::f64 frametime) { boost::shared_ptr<Input::InputServiceInterface> input = framework_->GetService<Input::InputServiceInterface>(Foundation::Service::ST_Input).lock(); if (input) { boost::optional<const Input::Events::Movement&> movement = input->PollSlider(Input::Events::MOUSELOOK); if (movement) { drag_yaw_ = static_cast<Core::Real>(movement->x_.rel_) * -0.005f; drag_pitch_ = static_cast<Core::Real>(movement->y_.rel_) * -0.005f; } else if (drag_pitch_ != 0 || drag_yaw_ != 0) { drag_yaw_ = 0; drag_pitch_ = 0; } } boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Scene::EntityPtr target = target_entity_.lock(); if (renderer && target) { Ogre::Camera *camera = renderer->GetCurrentCamera(); // for smoothness, we apparently need to get rotation from network position and position from placeable. Go figure. -cm EC_NetworkPosition *netpos = checked_static_cast<EC_NetworkPosition*>(target->GetComponent(EC_NetworkPosition::NameStatic()).get()); OgreRenderer::EC_OgrePlaceable *placeable = checked_static_cast<OgreRenderer::EC_OgrePlaceable*>(target->GetComponent(OgreRenderer::EC_OgrePlaceable::NameStatic()).get()); if (netpos && placeable) { Core::Vector3df avatar_pos = placeable->GetPosition(); Core::Quaternion avatar_orientation = netpos->rotation_; if (current_state_ == FirstPerson || current_state_ == ThirdPerson) { // this is mostly for third person camera, but also needed by first person camera since it sets proper initial orientation for the camera Core::Vector3df pos = avatar_pos; pos += (avatar_orientation * Core::Vector3df::NEGATIVE_UNIT_X * camera_distance_); pos += (avatar_orientation * camera_offset_); camera->setPosition(pos.x, pos.y, pos.z); Core::Vector3df lookat = avatar_pos + avatar_orientation * camera_offset_; camera->lookAt(lookat.x, lookat.y, lookat.z); } if (current_state_ == FirstPerson) { bool fallback = true; // Try to use head bone from target entity to get the first person camera position Foundation::ComponentPtr mesh_ptr = target->GetComponent(OgreRenderer::EC_OgreMesh::NameStatic()); Foundation::ComponentPtr appearance_ptr = target->GetComponent(EC_AvatarAppearance::NameStatic()); if (mesh_ptr && appearance_ptr) { OgreRenderer::EC_OgreMesh& mesh = *checked_static_cast<OgreRenderer::EC_OgreMesh*>(mesh_ptr.get()); EC_AvatarAppearance& appearance = *checked_static_cast<EC_AvatarAppearance*>(appearance_ptr.get()); Ogre::Entity* ent = mesh.GetEntity(); if (ent) { Ogre::SkeletonInstance* skel = ent->getSkeleton(); std::string view_bone_name; Core::Real adjustheight = mesh.GetAdjustPosition().z; if (appearance.HasProperty("viewbone")) { // This bone property is exclusively for view tracking & assumed to be correct position, no offset view_bone_name = appearance.GetProperty("viewbone"); } else if (appearance.HasProperty("headbone")) { view_bone_name = appearance.GetProperty("headbone"); // The biped head bone is anchored at the neck usually. Therefore a guessed fixed offset is needed, // which is not preferable, but necessary adjustheight += 0.15; } if (!view_bone_name.empty()) { if (skel && skel->hasBone(view_bone_name)) { // Hack: force Ogre to update skeleton with current animation state, even if avatar invisible if (ent->getAllAnimationStates()) skel->setAnimationState(*ent->getAllAnimationStates()); Ogre::Bone* bone = skel->getBone(view_bone_name); Ogre::Vector3 headpos = bone->_getDerivedPosition(); Core::Vector3df ourheadpos(-headpos.z + 0.5f, -headpos.x, headpos.y + adjustheight); RexTypes::Vector3 campos = avatar_pos + (avatar_orientation * ourheadpos); camera->setPosition(campos.x, campos.y, campos.z); fallback = false; } } } } // Fallback using fixed position if (fallback) { RexTypes::Vector3 campos = avatar_pos + (avatar_orientation * camera_offset_firstperson_); camera->setPosition(campos.x, campos.y, campos.z); } // update camera pitch if (drag_pitch_ != 0) { firstperson_pitch_ += drag_pitch_ * firstperson_sensitivity_; firstperson_pitch_ = Core::clamp(firstperson_pitch_, -Core::HALF_PI, Core::HALF_PI); } camera->pitch(Ogre::Radian(firstperson_pitch_)); } if (current_state_ == FreeLook) { const float trans_dt = (float)frametime * sensitivity_; Ogre::Vector3 pos = camera->getPosition(); pos += camera->getOrientation() * Ogre::Vector3(normalized_free_translation_.x, normalized_free_translation_.y, normalized_free_translation_.z) * trans_dt; camera->setPosition(pos); camera->pitch(Ogre::Radian(drag_pitch_ * firstperson_sensitivity_)); camera->yaw(Ogre::Radian(drag_yaw_ * firstperson_sensitivity_)); } } } // switch between first and third person modes, depending on how close we are to the avatar switch (current_state_) { case FirstPerson: { if (camera_distance_ != camera_min_distance_) { current_state_ = ThirdPerson; Core::event_category_id_t event_category = framework_->GetEventManager()->QueryEventCategory("Input"); framework_->GetEventManager()->SendEvent(event_category, Input::Events::INPUTSTATE_THIRDPERSON, NULL); firstperson_pitch_ = 0.0f; } break; } case ThirdPerson: { if (camera_distance_ == camera_min_distance_) { Core::event_category_id_t event_category = framework_->GetEventManager()->QueryEventCategory("Input"); framework_->GetEventManager()->SendEvent(event_category, Input::Events::INPUTSTATE_FIRSTPERSON, NULL); current_state_ = FirstPerson; firstperson_pitch_ = 0.0f; } break; } } } //experimental for py api void CameraControllable::SetYawPitch(Core::Real newyaw, Core::Real newpitch) { boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Ogre::Camera *camera = renderer->GetCurrentCamera(); firstperson_yaw_ = newyaw; firstperson_pitch_ = newpitch; camera->yaw(Ogre::Radian(firstperson_yaw_)); camera->pitch(Ogre::Radian(firstperson_pitch_)); } /* Core::Vector3df CameraControllable::GetCameraUp(){ boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Ogre::Camera *camera = renderer->GetCurrentCamera(); Ogre::Vector3 up = camera->getUp(); return Core::Vector3df(up.x, up.y, up.z); } Core::Vector3df CameraControllable::GetCameraRight(){ boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock(); Ogre::Camera *camera = renderer->GetCurrentCamera(); Ogre::Vector3 right = camera->getRight(); return Core::Vector3df(right.x, right.y, right.z); } */ } <|endoftext|>
<commit_before>#include "image_writer.h" #include "heatmap_writer.h" #include "json_writer.h" #include "logger.h" #include "parser.h" #include "regex.h" #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <float.h> using namespace wotreplay; using namespace boost::filesystem; namespace po = boost::program_options; void show_help(int argc, const char *argv[], po::options_description &desc) { std::stringstream help_message; help_message << desc << "\n"; logger.write(help_message.str()); } float distance(const std::tuple<float, float, float> &left, const std::tuple<float, float, float> &right) { float delta_x = std::get<0>(left) - std::get<0>(right); float delta_y = std::get<1>(left) - std::get<1>(right); float delta_z = std::get<2>(left) - std::get<2>(right); // distance in xy plane float dist1 = std::sqrt(delta_x*delta_x + delta_y*delta_y); return std::sqrt(dist1*dist1 + delta_z*delta_z); } static bool is_not_empty(const packet_t &packet) { // list of default properties with no special meaning std::set<property_t> standard_properties = { property_t::clock, property_t::player_id, property_t::type, property_t::sub_type }; auto properties = packet.get_properties(); for (int i = 0; i < properties.size(); ++i) { property_t property = static_cast<property_t>(i); // packet has property, but can not be found in default properties if (properties[i] && standard_properties.find(property) == standard_properties.end()) { return true; } } return false; } int create_minimaps(const po::variables_map &vm, const std::string &output, bool debug) { if ( vm.count("output") == 0 ) { logger.write(wotreplay::log_level_t::error, "parameter output is required to use this mode"); return -EXIT_FAILURE; } boost::format file_name_format("%1%/%2%_%3%_%4%.png"); image_writer_t writer; for (const auto &arena_entry : get_arenas()) { const arena_t &arena = arena_entry.second; for (const auto &configuration_entry : arena.configurations) { for (int team_id : { 0, 1 }) { const std::string game_mode = configuration_entry.first; writer.init(arena, game_mode); writer.set_recorder_team(team_id); writer.set_use_fixed_teamcolors(false); std::string file_name = (file_name_format % output % arena.name % game_mode % team_id).str(); std::ofstream os(file_name, std::ios::binary); writer.finish(); writer.write(os); } } } return EXIT_SUCCESS; } std::unique_ptr<writer_t> create_writer(const std::string &type, const po::variables_map &vm) { std::unique_ptr<writer_t> writer; if (type == "png") { writer = std::unique_ptr<writer_t>(new image_writer_t()); auto &image_writer = dynamic_cast<image_writer_t&>(*writer); image_writer.set_show_self(true); image_writer.set_use_fixed_teamcolors(false); } else if (type == "json") { writer = std::unique_ptr<writer_t>(new json_writer_t()); if (vm.count("supress-empty")) { writer->set_filter(&is_not_empty); } } else if (type == "heatmap") { writer = std::unique_ptr<writer_t>(new heatmap_writer_t()); auto &heatmap_writer = dynamic_cast<heatmap_writer_t&>(*writer); if (vm.count("skip")) { heatmap_writer.skip = vm["skip"].as<double>(); } if (vm.count("bounds_min") && vm.count("bounds_max")) { heatmap_writer.bounds = std::make_pair(vm["bounds_min"].as<double>(), vm["bounds_max"].as<double>()); } } else { logger.writef(log_level_t::error, "Invalid output type (%1%), supported types: png, json and heatmap.\n", type); } return writer; } int process_replay_directory(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) { if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) { logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n"); return -EXIT_FAILURE; } parser_t parser; parser.set_debug(debug); parser.load_data(); std::map<std::string, std::unique_ptr<writer_t>> writers; for (auto it = directory_iterator(input); it != directory_iterator(); ++it) { if (!is_regular_file(*it) || it->path().extension() != ".wotreplay") { continue; } std::ifstream in(it->path().string(), std::ios::binary); if (!in) { logger.writef(log_level_t::error, "Failed to open file: %1%\n", it->path().string()); return -EXIT_FAILURE; } game_t game; try { parser.parse(in, game); } catch (std::exception &e) { logger.writef(log_level_t::error, "Failed to parse file (%1%): %2%\n", it->path().string(), e.what()); continue; } // if we can't load arena data, skip this replay if (game.get_arena().name.empty()) { continue; } std::string name = (boost::format("%s_%s") % game.get_map_name() % game.get_game_mode()).str(); auto writer = writers.find(name); if (writer == writers.end()) { auto new_writer = create_writer(type, vm); auto result = writers.insert(std::make_pair(name, std::move(new_writer))); writer = result.first; (writer->second)->init(game.get_arena(), game.get_game_mode()); } (writer->second)->update(game); } for (auto it = writers.begin(); it != writers.end(); ++it) { path file_name = path(output) / (boost::format("%s.png") % it->first).str(); std::ofstream out(file_name.string(), std::ios::binary); it->second->finish(); it->second->write(out); } return EXIT_SUCCESS; } int process_replay_file(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) { if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) { logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n"); return -EXIT_FAILURE; } std::ifstream in(input, std::ios::binary); if (!in) { logger.writef(log_level_t::error, "Failed to open file: %1%\n", input); return -EXIT_FAILURE; } parser_t parser; game_t game; parser.set_debug(debug); parser.load_data(); parser.parse(in, game); std::unique_ptr<writer_t> writer = create_writer(type, vm); if (!writer) { return -EXIT_FAILURE; } writer->init(game.get_arena(), game.get_game_mode()); writer->update(game); writer->finish(); std::ostream *out; if (vm.count("output") > 0) { out = new std::ofstream(output, std::ios::binary); if (!out) { logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input); std::exit(0); } } else { out = &std::cout; } writer->write(*out); if (dynamic_cast<std::ofstream*>(out)) { dynamic_cast<std::ofstream*>(out)->close(); delete out; } return EXIT_SUCCESS; } int main(int argc, const char * argv[]) { po::options_description desc("Allowed options"); std::string type, output, input, root; double skip, bounds_min, bounds_max; desc.add_options() ("type" , po::value(&type), "select output type") ("output", po::value(&output), "output file or directory") ("input" , po::value(&input), "input file or directory") ("root" , po::value(&root), "set root directory") ("help" , "produce help message") ("debug" , "enable parser debugging") ("supress-empty", "supress empty packets from json output") ("create-minimaps", "create all empty minimaps in output directory") ("parse", "parse a replay file") ("quiet", "supress diagnostic messages") ("skip", po::value(&skip), "for heatmaps, skip a certain number of seconds after the start of the battle (default: 60)") ("bounds-min", po::value(&bounds_min), "for heatmaps, set min value to display (default: 0.66)") ("bounds-max", po::value(&bounds_max), "for heatmaps, set max value to display (default: 0.999)"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (std::exception &e) { show_help(argc, argv, desc); std::exit(-1); } catch (...) { logger.write(log_level_t::error, "Unknown error.\n"); std::exit(-1); } if (vm.count("help") > 0) { show_help(argc, argv, desc); std::exit(0); } if (vm.count("root") > 0 && chdir(root.c_str()) != 0) { logger.writef(log_level_t::error, "Cannot change working directory to: %1%\n", root); std::exit(0); } bool debug = vm.count("debug") > 0; if (debug) { logger.set_log_level(log_level_t::debug); } else if (vm.count("quiet") > 0) { logger.set_log_level(log_level_t::none); } else { logger.set_log_level(log_level_t::warning); } int exit_code; if (vm.count("parse") > 0) { // parse if (is_directory(input)) { exit_code = process_replay_directory(vm, input, output, type, debug); } else { exit_code = process_replay_file(vm, input, output, type, debug); } } else if (vm.count("create-minimaps") > 0) { // create all minimaps exit_code = create_minimaps(vm, output, debug); } else { logger.write(wotreplay::log_level_t::error, "Error: no mode specified\n"); exit_code = -EXIT_FAILURE; } if (exit_code < 0) { show_help(argc, argv, desc); } return exit_code; }<commit_msg>Fix issue with arguments bounds-min and bounds-max not getting picked up<commit_after>#include "image_writer.h" #include "heatmap_writer.h" #include "json_writer.h" #include "logger.h" #include "parser.h" #include "regex.h" #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <float.h> using namespace wotreplay; using namespace boost::filesystem; namespace po = boost::program_options; void show_help(int argc, const char *argv[], po::options_description &desc) { std::stringstream help_message; help_message << desc << "\n"; logger.write(help_message.str()); } float distance(const std::tuple<float, float, float> &left, const std::tuple<float, float, float> &right) { float delta_x = std::get<0>(left) - std::get<0>(right); float delta_y = std::get<1>(left) - std::get<1>(right); float delta_z = std::get<2>(left) - std::get<2>(right); // distance in xy plane float dist1 = std::sqrt(delta_x*delta_x + delta_y*delta_y); return std::sqrt(dist1*dist1 + delta_z*delta_z); } static bool is_not_empty(const packet_t &packet) { // list of default properties with no special meaning std::set<property_t> standard_properties = { property_t::clock, property_t::player_id, property_t::type, property_t::sub_type }; auto properties = packet.get_properties(); for (int i = 0; i < properties.size(); ++i) { property_t property = static_cast<property_t>(i); // packet has property, but can not be found in default properties if (properties[i] && standard_properties.find(property) == standard_properties.end()) { return true; } } return false; } int create_minimaps(const po::variables_map &vm, const std::string &output, bool debug) { if ( vm.count("output") == 0 ) { logger.write(wotreplay::log_level_t::error, "parameter output is required to use this mode"); return -EXIT_FAILURE; } boost::format file_name_format("%1%/%2%_%3%_%4%.png"); image_writer_t writer; for (const auto &arena_entry : get_arenas()) { const arena_t &arena = arena_entry.second; for (const auto &configuration_entry : arena.configurations) { for (int team_id : { 0, 1 }) { const std::string game_mode = configuration_entry.first; writer.init(arena, game_mode); writer.set_recorder_team(team_id); writer.set_use_fixed_teamcolors(false); std::string file_name = (file_name_format % output % arena.name % game_mode % team_id).str(); std::ofstream os(file_name, std::ios::binary); writer.finish(); writer.write(os); } } } return EXIT_SUCCESS; } std::unique_ptr<writer_t> create_writer(const std::string &type, const po::variables_map &vm) { std::unique_ptr<writer_t> writer; if (type == "png") { writer = std::unique_ptr<writer_t>(new image_writer_t()); auto &image_writer = dynamic_cast<image_writer_t&>(*writer); image_writer.set_show_self(true); image_writer.set_use_fixed_teamcolors(false); } else if (type == "json") { writer = std::unique_ptr<writer_t>(new json_writer_t()); if (vm.count("supress-empty")) { writer->set_filter(&is_not_empty); } } else if (type == "heatmap") { writer = std::unique_ptr<writer_t>(new heatmap_writer_t()); auto &heatmap_writer = dynamic_cast<heatmap_writer_t&>(*writer); if (vm.count("skip")) { heatmap_writer.skip = vm["skip"].as<double>(); } if (vm.count("bounds-min") && vm.count("bounds-max")) { heatmap_writer.bounds = std::make_pair(vm["bounds-min"].as<double>(), vm["bounds-max"].as<double>()); } } else { logger.writef(log_level_t::error, "Invalid output type (%1%), supported types: png, json and heatmap.\n", type); } return writer; } int process_replay_directory(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) { if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) { logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n"); return -EXIT_FAILURE; } parser_t parser; parser.set_debug(debug); parser.load_data(); std::map<std::string, std::unique_ptr<writer_t>> writers; for (auto it = directory_iterator(input); it != directory_iterator(); ++it) { if (!is_regular_file(*it) || it->path().extension() != ".wotreplay") { continue; } std::ifstream in(it->path().string(), std::ios::binary); if (!in) { logger.writef(log_level_t::error, "Failed to open file: %1%\n", it->path().string()); return -EXIT_FAILURE; } game_t game; try { parser.parse(in, game); } catch (std::exception &e) { logger.writef(log_level_t::error, "Failed to parse file (%1%): %2%\n", it->path().string(), e.what()); continue; } // if we can't load arena data, skip this replay if (game.get_arena().name.empty()) { continue; } std::string name = (boost::format("%s_%s") % game.get_map_name() % game.get_game_mode()).str(); auto writer = writers.find(name); if (writer == writers.end()) { auto new_writer = create_writer(type, vm); auto result = writers.insert(std::make_pair(name, std::move(new_writer))); writer = result.first; (writer->second)->init(game.get_arena(), game.get_game_mode()); } (writer->second)->update(game); } for (auto it = writers.begin(); it != writers.end(); ++it) { path file_name = path(output) / (boost::format("%s.png") % it->first).str(); std::ofstream out(file_name.string(), std::ios::binary); it->second->finish(); it->second->write(out); } return EXIT_SUCCESS; } int process_replay_file(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) { if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) { logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n"); return -EXIT_FAILURE; } std::ifstream in(input, std::ios::binary); if (!in) { logger.writef(log_level_t::error, "Failed to open file: %1%\n", input); return -EXIT_FAILURE; } parser_t parser; game_t game; parser.set_debug(debug); parser.load_data(); parser.parse(in, game); std::unique_ptr<writer_t> writer = create_writer(type, vm); if (!writer) { return -EXIT_FAILURE; } writer->init(game.get_arena(), game.get_game_mode()); writer->update(game); writer->finish(); std::ostream *out; if (vm.count("output") > 0) { out = new std::ofstream(output, std::ios::binary); if (!out) { logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input); std::exit(0); } } else { out = &std::cout; } writer->write(*out); if (dynamic_cast<std::ofstream*>(out)) { dynamic_cast<std::ofstream*>(out)->close(); delete out; } return EXIT_SUCCESS; } int main(int argc, const char * argv[]) { po::options_description desc("Allowed options"); std::string type, output, input, root; double skip, bounds_min, bounds_max; desc.add_options() ("type" , po::value(&type), "select output type") ("output", po::value(&output), "output file or directory") ("input" , po::value(&input), "input file or directory") ("root" , po::value(&root), "set root directory") ("help" , "produce help message") ("debug" , "enable parser debugging") ("supress-empty", "supress empty packets from json output") ("create-minimaps", "create all empty minimaps in output directory") ("parse", "parse a replay file") ("quiet", "supress diagnostic messages") ("skip", po::value(&skip), "for heatmaps, skip a certain number of seconds after the start of the battle (default: 60)") ("bounds-min", po::value(&bounds_min), "for heatmaps, set min value to display (default: 0.66)") ("bounds-max", po::value(&bounds_max), "for heatmaps, set max value to display (default: 0.999)"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (std::exception &e) { show_help(argc, argv, desc); std::exit(-1); } catch (...) { logger.write(log_level_t::error, "Unknown error.\n"); std::exit(-1); } if (vm.count("help") > 0) { show_help(argc, argv, desc); std::exit(0); } if (vm.count("root") > 0 && chdir(root.c_str()) != 0) { logger.writef(log_level_t::error, "Cannot change working directory to: %1%\n", root); std::exit(0); } bool debug = vm.count("debug") > 0; if (debug) { logger.set_log_level(log_level_t::debug); } else if (vm.count("quiet") > 0) { logger.set_log_level(log_level_t::none); } else { logger.set_log_level(log_level_t::warning); } int exit_code; if (vm.count("parse") > 0) { // parse if (is_directory(input)) { exit_code = process_replay_directory(vm, input, output, type, debug); } else { exit_code = process_replay_file(vm, input, output, type, debug); } } else if (vm.count("create-minimaps") > 0) { // create all minimaps exit_code = create_minimaps(vm, output, debug); } else { logger.write(wotreplay::log_level_t::error, "Error: no mode specified\n"); exit_code = -EXIT_FAILURE; } if (exit_code < 0) { show_help(argc, argv, desc); } return exit_code; }<|endoftext|>
<commit_before>//============================================================================ // Name : ctm_c.cpp // Author : Edward // Version : // Copyright : GPL // Description : Implementation of CTM by C++ //============================================================================ #include <iostream> #include <math.h> using namespace std; #include "CellTransModel.h" void initialModel(CellTransModel &mdl); void startSim(CellTransModel &mdl, float lens[]); void printLens(vector<float> lens); void simOneCycle(CellTransModel &mdl, float c, float g1, float g2, vector<float> &lens); int main() { cout << "Hello World!" << endl; // prints Hello World! // testing the CTM in CPU CellTransModel model; initialModel(model); float lens[]= {31,10,40,45,10,42,48,51}; startSim(model,lens); vector<float> lengths; model.readLanes(lengths); printLens(lengths); float c = 90; simOneCycle(model,c,45,45,lengths); printLens(lengths); simOneCycle(model,c,45,45,lengths); printLens(lengths); simOneCycle(model,c,55,45,lengths); printLens(lengths); string str; cin >> str; return 0; } void initialModel(CellTransModel &mdl) { // lanes // entry lanes for intersection 1 cout<<mdl.addLane("L1",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L2",LANE_TYPE_NORMAL,60,0.6,0.03,0.1); cout<<mdl.addLane("L3",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L4",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<endl; // entry lanes for intersection 2 cout<<mdl.addLane("L5",LANE_TYPE_NORMAL,60,0.6,0.03,0.1); cout<<mdl.addLane("L6",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L7",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L8",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<endl; // exit lanes mdl.addLane("LE1",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE2",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE3",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE4",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE5",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE6",LANE_TYPE_EXIT,0,0,0,1); // intersections vector<string> in_lanes, out_lanes; float inner_cells[2][2] = {{2,0.6},{2,0.6}}; float phase1[4][8] = {{LINK_TYPE_DIRECT, 1, 1,0, 0,0,0,0}, {LINK_TYPE_DIRECT, 1, 0,0, 2,0,0,0}, {LINK_TYPE_DIRECT, 1, 1,1, 0,1,0,0}, {LINK_TYPE_DIRECT, 1, 0,1, 2,1,0,0}}; float phase2[4][8] = {{LINK_TYPE_DIRECT, 1, 1,2, 0,0,0,0}, {LINK_TYPE_DIRECT, 1, 0,0, 2,2,0,0}, {LINK_TYPE_DIRECT, 1, 1,3, 0,1,0,0}, {LINK_TYPE_DIRECT, 1, 0,1, 2,3,0,0}}; // intersection 1 in_lanes.push_back("L1");in_lanes.push_back("L2"); in_lanes.push_back("L3");in_lanes.push_back("L4"); out_lanes.push_back("L5");out_lanes.push_back("LE1"); out_lanes.push_back("LE2");out_lanes.push_back("LE3"); cout<<mdl.addIntersection("I1",in_lanes,out_lanes,2,inner_cells); cout<<mdl.addPhase("I1",4,phase1);cout<<mdl.addPhase("I1",4,phase2); cout<<endl; in_lanes.clear(); out_lanes.clear(); // intersection 2 in_lanes.push_back("L5");in_lanes.push_back("L6"); in_lanes.push_back("L7");in_lanes.push_back("L8"); out_lanes.push_back("LE4");out_lanes.push_back("L2"); out_lanes.push_back("LE5");out_lanes.push_back("LE6"); cout<<mdl.addIntersection("I2",in_lanes,out_lanes,2,inner_cells); cout<<mdl.addPhase("I2",4,phase1);cout<<mdl.addPhase("I2",4,phase2); cout<<endl; in_lanes.clear(); out_lanes.clear(); // build CTM if(mdl.buildCTM()) cout << "Building successfully." <<endl; else cout << "Failed to build CTM." << endl; } void startSim(CellTransModel &mdl, float lens[]) { vector<float> lanes; for(int i=0;i<8;i++) lanes.push_back(lens[i]); for(int i=0;i<6;i++) lanes.push_back(0); vector<int> ints; ints.push_back(0);ints.push_back(0); mdl.startSim(lanes,ints); } void printLens(vector<float> lens) { cout << "queue lengths = "; for (int i=0;i<7;i++) cout << lens[i] << "\t"; cout << lens[7] << endl; } void simOneCycle(CellTransModel &mdl, float c, float g1, float g2, vector<float> &lens) { string s1,s2; float t1,t2,t3; if (g1<g2) { s1 = "I1"; s2 = "I2"; t1 = g1; t2 = g2-g1; t3 = c-g2; } else { s1 = "I2"; s2 = "I1"; t1 = g2; t2 = g1-g2; t3 = c-g1; } // step 1 if (t1>=1) { int sp = (int)floor(t1); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t1 -= sp; } if (t1>1e-6) mdl.sim(t1); mdl.switchIntersection(s1); mdl.readLanes(lens); printLens(lens); // step 2 if (t2>=1) { int sp = (int)floor(t2); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t2 -= sp; } if (t2>0) mdl.sim(t2); mdl.switchIntersection(s2); mdl.readLanes(lens); printLens(lens); // step 3 if (t3>=1) { int sp = (int)floor(t3); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t3 -= sp; } if (t3>0) mdl.sim(t3); mdl.switchIntersection("I1");mdl.switchIntersection("I2"); mdl.readLanes(lens); } <commit_msg>Test 2<commit_after>//============================================================================ // Name : ctm_c.cpp // Author : Edward // Version : // Copyright : GPL // Description : Implementation of CTM by C++ //============================================================================ #include <iostream> #include <math.h> using namespace std; #include "CellTransModel.h" void initialModel(CellTransModel &mdl); void startSim(CellTransModel &mdl, float lens[]); void printLens(vector<float> lens); void simOneCycle(CellTransModel &mdl, float c, float g1, float g2, vector<float> &lens); void simTest2(CellTransModel &mdl, vector<float> &lens); int main() { cout << "Hello World!" << endl; // prints Hello World! // testing the CTM in CPU CellTransModel model; initialModel(model); float lens[]= {31,10,40,45,10,42,48,51}; startSim(model,lens); vector<float> lengths; model.readLanes(lengths); printLens(lengths); // float c = 90; // simOneCycle(model,c,45,45,lengths); // printLens(lengths); // simOneCycle(model,c,45,45,lengths); // printLens(lengths); // simOneCycle(model,c,55,45,lengths); // printLens(lengths); simTest2(model,lengths); string str; cin >> str; return 0; } void initialModel(CellTransModel &mdl) { // lanes // entry lanes for intersection 1 cout<<mdl.addLane("L1",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L2",LANE_TYPE_NORMAL,60,0.6,0.03,0.1); cout<<mdl.addLane("L3",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L4",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<endl; // entry lanes for intersection 2 cout<<mdl.addLane("L5",LANE_TYPE_NORMAL,60,0.6,0.03,0.1); cout<<mdl.addLane("L6",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L7",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<mdl.addLane("L8",LANE_TYPE_ENTRY,60,0.6,0.3,0); cout<<endl; // exit lanes mdl.addLane("LE1",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE2",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE3",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE4",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE5",LANE_TYPE_EXIT,0,0,0,1); mdl.addLane("LE6",LANE_TYPE_EXIT,0,0,0,1); // intersections vector<string> in_lanes, out_lanes; float inner_cells[2][2] = {{2,0.6},{2,0.6}}; float phase1[4][8] = {{LINK_TYPE_DIRECT, 1, 1,0, 0,0,0,0}, {LINK_TYPE_DIRECT, 1, 0,0, 2,0,0,0}, {LINK_TYPE_DIRECT, 1, 1,1, 0,1,0,0}, {LINK_TYPE_DIRECT, 1, 0,1, 2,1,0,0}}; float phase2[4][8] = {{LINK_TYPE_DIRECT, 1, 1,2, 0,0,0,0}, {LINK_TYPE_DIRECT, 1, 0,0, 2,2,0,0}, {LINK_TYPE_DIRECT, 1, 1,3, 0,1,0,0}, {LINK_TYPE_DIRECT, 1, 0,1, 2,3,0,0}}; // intersection 1 in_lanes.push_back("L1");in_lanes.push_back("L2"); in_lanes.push_back("L3");in_lanes.push_back("L4"); out_lanes.push_back("L5");out_lanes.push_back("LE1"); out_lanes.push_back("LE2");out_lanes.push_back("LE3"); cout<<mdl.addIntersection("I1",in_lanes,out_lanes,2,inner_cells); cout<<mdl.addPhase("I1",4,phase1);cout<<mdl.addPhase("I1",4,phase2); cout<<endl; in_lanes.clear(); out_lanes.clear(); // intersection 2 in_lanes.push_back("L5");in_lanes.push_back("L6"); in_lanes.push_back("L7");in_lanes.push_back("L8"); out_lanes.push_back("LE4");out_lanes.push_back("L2"); out_lanes.push_back("LE5");out_lanes.push_back("LE6"); cout<<mdl.addIntersection("I2",in_lanes,out_lanes,2,inner_cells); cout<<mdl.addPhase("I2",4,phase1);cout<<mdl.addPhase("I2",4,phase2); cout<<endl; in_lanes.clear(); out_lanes.clear(); // build CTM if(mdl.buildCTM()) cout << "Building successfully." <<endl; else cout << "Failed to build CTM." << endl; } void startSim(CellTransModel &mdl, float lens[]) { vector<float> lanes; for(int i=0;i<8;i++) lanes.push_back(lens[i]); for(int i=0;i<6;i++) lanes.push_back(0); vector<int> ints; ints.push_back(0);ints.push_back(0); mdl.startSim(lanes,ints); } void printLens(vector<float> lens) { cout << "queue lengths = "; for (int i=0;i<7;i++) cout << lens[i] << "\t"; cout << lens[7] << endl; } void simOneCycle(CellTransModel &mdl, float c, float g1, float g2, vector<float> &lens) { string s1,s2; float t1,t2,t3; if (g1<g2) { s1 = "I1"; s2 = "I2"; t1 = g1; t2 = g2-g1; t3 = c-g2; } else { s1 = "I2"; s2 = "I1"; t1 = g2; t2 = g1-g2; t3 = c-g1; } // step 1 if (t1>=1) { int sp = (int)floor(t1); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t1 -= sp; } if (t1>1e-6) mdl.sim(t1); mdl.switchIntersection(s1); // step 2 if (t2>=1) { int sp = (int)floor(t2); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t2 -= sp; } if (t2>0) mdl.sim(t2); mdl.switchIntersection(s2); // step 3 if (t3>=1) { int sp = (int)floor(t3); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t3 -= sp; } if (t3>0) mdl.sim(t3); mdl.switchIntersection("I1");mdl.switchIntersection("I2"); mdl.readLanes(lens); } void simTest2(CellTransModel &mdl, vector<float> &lens) { double t1; for(int i=0;i<9;i++) { t1 = 5; if (t1>=1) { int sp = (int)floor(t1); if (!mdl.sim(1.0,sp)) cout << "Simulation Error!" << endl; t1 -= sp; } if (t1>1e-6) mdl.sim(t1); mdl.readLanes(lens); printLens(lens); } } <|endoftext|>
<commit_before>#include <tr1/memory> #include <vector> #include <cstdlib> #include <cstdio> #include <signal.h> #include <getopt.h> #include "barrier.h" #include "streamer.h" #include "socket.h" #include <unistd.h> using std::vector; using std::tr1::shared_ptr; static bool run = true; static void terminate(void) { run = false; } int main(int argc, char** argv) { unsigned num_conn = 1; unsigned rem_port = 0; unsigned loc_port = 0; unsigned interval = 0; unsigned length = 0; // Parse program arguments and options int opt; while ((opt = getopt(argc, argv, ":hc:p:q:n:i:")) != -1) { char* ptr; switch (opt) { // Missing a value for the option case ':': fprintf(stderr, "Option %s requires a value\n", argv[optind-1]); return ':'; // Unknown option was given case '?': fprintf(stderr, "Ignoring unknown option '%c'\n", optopt); break; // Print program usage and quit case 'h': // TODO: Give usage return 'h'; // Set number of connections case 'c': ptr = NULL; if ((num_conn = strtoul(optarg, &ptr, 0)) > 1024 || num_conn < 1 || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -c requires a valid number of connections [1-1024]\n"); return 'c'; } break; // Set the remote starting port case 'p': ptr = NULL; if ((rem_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -p requires a valid port number [0-65535]\n"); return 'p'; } break; // Set the local starting port case 'q': ptr = NULL; if ((loc_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -q requires a valid port number [0-65535]\n"); return 'p'; } break; // Set the size of the byte chunk to be sent case 'n': ptr = NULL; if ((length = strtoul(optarg, &ptr, 0)) > BUFFER_SIZE || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -n requires a chunk size in bytes [1-%d] or 0 for off\n", BUFFER_SIZE); return 'n'; } break; // Set the interval between each time a chunk is sent case 'i': ptr = NULL; if ((interval = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -i requires an interval in milliseconds [1-65535] or 0 for off\n"); return 'i'; } break; } } // Check if all mandatory options were set if (optind < argc && rem_port == 0) { fprintf(stderr, "Option -p is required for client\n"); return 'p'; } else if (optind == argc && loc_port == 0) { fprintf(stderr, "Option -q is required for server\n"); return 'q'; } // Handle interrupt signal signal(SIGINT, (void (*)(int)) &terminate); // Create a barrier Barrier barrier(num_conn + 1); // Test streamer Client client(barrier, "localhost", 5000); client.start(); barrier.wait(); while (run); return 0; } <commit_msg>still just some testing<commit_after>#include <tr1/memory> #include <vector> #include <cstdlib> #include <cstdio> #include <signal.h> #include <getopt.h> #include "barrier.h" #include "streamer.h" #include "socket.h" #include <unistd.h> using std::vector; using std::tr1::shared_ptr; static bool run = true; static void terminate(void) { run = false; } int main(int argc, char** argv) { unsigned num_conns = 1; unsigned remote_port = 0; unsigned local_port = 0; unsigned interval = 0; unsigned length = 0; // Parse program arguments and options int opt; while ((opt = getopt(argc, argv, ":hc:p:q:n:i:")) != -1) { char* ptr; switch (opt) { // Missing a value for the option case ':': fprintf(stderr, "Option %s requires a value\n", argv[optind-1]); return ':'; // Unknown option was given case '?': fprintf(stderr, "Ignoring unknown option '%c'\n", optopt); break; // Print program usage and quit case 'h': // TODO: Give usage return 'h'; // Set number of connections case 'c': ptr = NULL; if ((num_conns = strtoul(optarg, &ptr, 0)) > 1024 || num_conns < 1 || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -c requires a valid number of connections [1-1024]\n"); return 'c'; } break; // Set the remote starting port case 'p': ptr = NULL; if ((remote_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -p requires a valid port number [0-65535]\n"); return 'p'; } break; // Set the local starting port case 'q': ptr = NULL; if ((local_port = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -q requires a valid port number [0-65535]\n"); return 'p'; } break; // Set the size of the byte chunk to be sent case 'n': ptr = NULL; if ((length = strtoul(optarg, &ptr, 0)) > BUFFER_SIZE || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -n requires a chunk size in bytes [1-%d] or 0 for off\n", BUFFER_SIZE); return 'n'; } break; // Set the interval between each time a chunk is sent case 'i': ptr = NULL; if ((interval = strtoul(optarg, &ptr, 0)) > 0xffff || ptr == NULL || *ptr != '\0') { fprintf(stderr, "Option -i requires an interval in milliseconds [1-65535] or 0 for off\n"); return 'i'; } break; } } // Check if all mandatory options were set if (optind < argc && remote_port == 0) { fprintf(stderr, "Option -p is required for client\n"); return 'p'; } else if (optind == argc && local_port == 0) { fprintf(stderr, "Option -q is required for server\n"); return 'q'; } // Handle interrupt signal signal(SIGINT, (void (*)(int)) &terminate); // Create a barrier Barrier barrier(num_conns + 1); // Test streamer Server server(barrier, local_port); server.start(); barrier.wait(); while (run); return 0; } <|endoftext|>
<commit_before>#include "Shell.hpp" #include <iostream> #include <sstream> #include "FileSystem.hpp" using namespace std; const int MAXCOMMANDS = 8; const int NUMAVAILABLECOMMANDS = 16; string availableCommands[NUMAVAILABLECOMMANDS] = { "quit", "format", "ls", "create", "cat", "save", "load", "rm", "copy", "append", "rename", "mkdir", "cd", "pwd", "help", "chmod" }; Shell::Shell(const string &user) { this->user = user; currentDir = "/"; } bool Shell::getCommand() { string userCommand, commandArr[MAXCOMMANDS]; cout << user << ":" << currentDir << "$ "; getline(cin, userCommand); int nrOfCommands = parseCommandString(userCommand, commandArr); if (nrOfCommands > 0) { int cIndex = findCommand(commandArr[0]); switch (cIndex) { case 0: // quit cout << "Exiting" << endl; return false; break; case 1: // format fileSystem.format(); currentDir = "/"; break; case 2: // ls cout << "Listing directory" << endl; if (nrOfCommands < 2) fileSystem.ls(absolutePath(currentDir)); else fileSystem.ls(absolutePath(commandArr[1])); break; case 3: // create fileSystem.create(absolutePath(commandArr[1])); break; case 4: // cat fileSystem.cat(absolutePath(commandArr[1])); break; case 5: // save fileSystem.save(commandArr[1]); break; case 6: // load fileSystem.load(commandArr[1]); break; case 7: // rm fileSystem.rm(absolutePath(commandArr[1])); break; case 8: // copy fileSystem.copy(absolutePath(commandArr[1]), absolutePath(commandArr[2])); break; case 9: // append fileSystem.append(absolutePath(commandArr[1]), absolutePath(commandArr[2])); break; case 10: // rename fileSystem.rename(absolutePath(commandArr[1]), absolutePath(commandArr[2])); break; case 11: // mkdir fileSystem.mkdir(absolutePath(commandArr[1])); break; case 12: // cd if (fileSystem.directoryExists(absolutePath(commandArr[1]))) { currentDir = "/" + absolutePath(commandArr[1]); if (currentDir[currentDir.length() - 1] != '/') currentDir += "/"; } else { cout << "Directory does not exist." << endl; } break; case 13: // pwd cout << currentDir << endl; break; case 14: // help cout << help() << endl; break; case 15: // chmod if (commandArr[2].length() != 0){ int perm = stoi(commandArr[2]); fileSystem.chmod(absolutePath(commandArr[1]), perm); } else { cout << "Invalid amount of arguments." << endl; } break; default: cout << "Unknown command: " << commandArr[0] << endl; } } return true; } int Shell::parseCommandString(const string &userCommand, string strArr[]) { stringstream ssin(userCommand); int counter = 0; while (ssin.good() && counter < MAXCOMMANDS) { ssin >> strArr[counter]; counter++; } if (strArr[0] == "") { counter = 0; } return counter; } int Shell::findCommand(string &command) { int index = -1; for (int i = 0; i < NUMAVAILABLECOMMANDS && index == -1; ++i) { if (command == availableCommands[i]) { index = i; } } return index; } string Shell::absolutePath(string path) const { /// Fix relative path if (path.length() == 0 || path[0] != '/') path = currentDir + path; path = path.substr(1); vector<string> parts = split(path, '/'); vector<string> temp; /// Replace ./ and ../ for (string part : parts) { if (part == "..") { if (!temp.empty()) temp.pop_back(); } else if (part != ".") { temp.push_back(part); } } path = ""; for (size_t i=0; i<temp.size(); i++) { if (i > 0) path += "/"; path += temp[i]; } return path; } string Shell::help() { string helpStr; helpStr += "OSD Disk Tool .oO Help Screen Oo.\n"; helpStr += "-----------------------------------------------------------------------------------\n"; helpStr += "* quit: Quit OSD Disk Tool\n"; helpStr += "* format; Formats disk\n"; helpStr += "* ls <path>: Lists contents of <path>.\n"; helpStr += "* create <path>: Creates a file and stores contents in <path>\n"; helpStr += "* cat <path>: Dumps contents of <file>.\n"; helpStr += "* save <real-file>: Saves disk to <real-file>\n"; helpStr += "* read <real-file>: Reads <real-file> onto disk\n"; helpStr += "* rm <file>: Removes <file>\n"; helpStr += "* copy <source> <destination>: Copy <source> to <destination>\n"; helpStr += "* append <source> <destination>: Appends contents of <source> to <destination>\n"; helpStr += "* rename <old-file> <new-file>: Renames <old-file> to <new-file>\n"; helpStr += "* mkdir <directory>: Creates a new directory called <directory>\n"; helpStr += "* cd <directory>: Changes current working directory to <directory>\n"; helpStr += "* pwd: Get current working directory\n"; helpStr += "* help: Prints this help screen\n"; return helpStr; } vector<string> Shell::split(string text, char delimiter) { vector<string> parts; while (text.find(delimiter) != string::npos) { size_t pos = text.find(delimiter); parts.push_back(text.substr(0, pos)); text = text.substr(pos+1); } if (!text.empty()) parts.push_back(text); return parts; } <commit_msg>Shell code cleanup<commit_after>#include "Shell.hpp" #include <iostream> #include <sstream> #include "FileSystem.hpp" using namespace std; const int MAXCOMMANDS = 8; const int NUMAVAILABLECOMMANDS = 16; string availableCommands[NUMAVAILABLECOMMANDS] = { "quit", "format", "ls", "create", "cat", "save", "load", "rm", "copy", "append", "rename", "mkdir", "cd", "pwd", "help", "chmod" }; Shell::Shell(const string &user) { this->user = user; currentDir = "/"; } bool Shell::getCommand() { string userCommand, commandArr[MAXCOMMANDS]; cout << user << ":" << currentDir << "$ "; getline(cin, userCommand); int nrOfCommands = parseCommandString(userCommand, commandArr); if (nrOfCommands > 0) { int cIndex = findCommand(commandArr[0]); switch (cIndex) { case 0: // quit cout << "Exiting" << endl; return false; break; case 1: // format fileSystem.format(); currentDir = "/"; break; case 2: // ls cout << "Listing directory" << endl; if (nrOfCommands < 2) fileSystem.ls(absolutePath(currentDir)); else fileSystem.ls(absolutePath(commandArr[1])); break; case 3: // create fileSystem.create(absolutePath(commandArr[1])); break; case 4: // cat fileSystem.cat(absolutePath(commandArr[1])); break; case 5: // save fileSystem.save(commandArr[1]); break; case 6: // load fileSystem.load(commandArr[1]); break; case 7: // rm fileSystem.rm(absolutePath(commandArr[1])); break; case 8: // copy fileSystem.copy(absolutePath(commandArr[1]), absolutePath(commandArr[2])); break; case 9: // append fileSystem.append(absolutePath(commandArr[1]), absolutePath(commandArr[2])); break; case 10: // rename fileSystem.rename(absolutePath(commandArr[1]), absolutePath(commandArr[2])); break; case 11: // mkdir fileSystem.mkdir(absolutePath(commandArr[1])); break; case 12: // cd if (fileSystem.directoryExists(absolutePath(commandArr[1]))) { currentDir = "/" + absolutePath(commandArr[1]); if (currentDir[currentDir.length() - 1] != '/') currentDir += "/"; } else { cout << "Directory does not exist." << endl; } break; case 13: // pwd cout << currentDir << endl; break; case 14: // help cout << help() << endl; break; case 15: // chmod if (commandArr[2].length() != 0){ int perm = stoi(commandArr[2]); fileSystem.chmod(absolutePath(commandArr[1]), perm); } else { cout << "Invalid amount of arguments." << endl; } break; default: cout << "Unknown command: " << commandArr[0] << endl; } } return true; } int Shell::parseCommandString(const string &userCommand, string strArr[]) { stringstream ssin(userCommand); int counter = 0; while (ssin.good() && counter < MAXCOMMANDS) { ssin >> strArr[counter]; counter++; } if (strArr[0] == "") { counter = 0; } return counter; } int Shell::findCommand(string &command) { int index = -1; for (int i = 0; i < NUMAVAILABLECOMMANDS && index == -1; ++i) { if (command == availableCommands[i]) { index = i; } } return index; } string Shell::absolutePath(string path) const { // Fix relative path if (path.length() == 0 || path[0] != '/') path = currentDir + path; path = path.substr(1); vector<string> parts = split(path, '/'); vector<string> temp; // Replace ./ and ../ for (string part : parts) { if (part == "..") { if (!temp.empty()) temp.pop_back(); } else if (part != ".") { temp.push_back(part); } } path = ""; for (size_t i=0; i<temp.size(); i++) { if (i > 0) path += "/"; path += temp[i]; } return path; } string Shell::help() { string helpStr; helpStr += "OSD Disk Tool .oO Help Screen Oo.\n"; helpStr += "-----------------------------------------------------------------------------------\n"; helpStr += "* quit: Quit OSD Disk Tool\n"; helpStr += "* format; Formats disk\n"; helpStr += "* ls <path>: Lists contents of <path>.\n"; helpStr += "* create <path>: Creates a file and stores contents in <path>\n"; helpStr += "* cat <path>: Dumps contents of <file>.\n"; helpStr += "* save <real-file>: Saves disk to <real-file>\n"; helpStr += "* read <real-file>: Reads <real-file> onto disk\n"; helpStr += "* rm <file>: Removes <file>\n"; helpStr += "* copy <source> <destination>: Copy <source> to <destination>\n"; helpStr += "* append <source> <destination>: Appends contents of <source> to <destination>\n"; helpStr += "* rename <old-file> <new-file>: Renames <old-file> to <new-file>\n"; helpStr += "* mkdir <directory>: Creates a new directory called <directory>\n"; helpStr += "* cd <directory>: Changes current working directory to <directory>\n"; helpStr += "* pwd: Get current working directory\n"; helpStr += "* chmod <file> <permissions>: Change permissions for <file> to <permissions>.\n"; helpStr += "* help: Prints this help screen\n"; return helpStr; } vector<string> Shell::split(string text, char delimiter) { vector<string> parts; while (text.find(delimiter) != string::npos) { size_t pos = text.find(delimiter); parts.push_back(text.substr(0, pos)); text = text.substr(pos+1); } if (!text.empty()) parts.push_back(text); return parts; } <|endoftext|>
<commit_before>//******************************************************************** // //This program displays a list of numbers and their squares. // //By: JESUS HILARIO HERNANDEZ //Last Updated: October 5th, 2016 // //******************************************************************** #include <iostream> using namespace std; int main() { /* Input validation when using numbers. */ int number; cout << "Enter a number in the range 1-10: "; while (!(cin >> number) || (number < 1 || number > 10)) { // Explain error cout << "ERROR: A number must be pressed.\n" << "Enter a value in the range 1-10: "; // Clear input stream cin.clear(); // Discard previous input cin.ignore(1200, '\n'); } cout << "You entered the number " << number << endl; /* Input validation when using characters */ char choice; cout << "Enter Y or N: "; cin >> choice; while (!(choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N')) { cout << "ERROR: Either Y or N must be pressed.\n" << "Enter Y or N: "; // clear input stream cin.clear(); // discard previous input cin.ignore(1200, '\n'); // enter choice again cin >> choice; } cout << "You have chosen " << choice << endl; /* Input validation when using strings */ string stringChoice; cout << "Enter \"yes\" or \"no\": "; cin >> stringChoice; while (!(stringChoice == "yes") && !(stringChoice == "no")) { cout << "ERROR: You must type either \"yes\" or \"no\".\n" << "Enter \"yes\" or \"no\": "; // clear input stream cin.clear(); // discard previous input cin.ignore(1200, '\n'); cin >> stringChoice; } cout << "You have enter: " << stringChoice << endl; return 0; } <commit_msg>Update input-validation-using-while-loops.cpp<commit_after>//******************************************************************** //This program displays a list of numbers and their squares. // //By: JESUS HILARIO HERNANDEZ //Last Updated: December 6th, 2016 //******************************************************************** #include <iostream> using namespace std; int main() { /* Input validation when using numbers. */ int number; cout << "Enter a number in the range 1-10: "; while (!(cin >> number) || (number < 1 || number > 10)) { // Explain error cout << "ERROR: A number must be pressed.\n" << "Enter a value in the range 1-10: "; // Clear input stream cin.clear(); // Discard previous input cin.ignore(1200, '\n'); } cout << "You entered the number " << number << endl; /* Input validation when using characters */ char choice; cout << "Enter Y or N: "; cin >> choice; while (!(choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N')) { cout << "ERROR: Either Y or N must be pressed.\n" << "Enter Y or N: "; // clear input stream cin.clear(); // discard previous input cin.ignore(1200, '\n'); // enter choice again cin >> choice; } cout << "You have chosen " << choice << endl; /* Input validation when using strings */ string stringChoice; cout << "Enter \"yes\" or \"no\": "; cin >> stringChoice; while (!(stringChoice == "yes") && !(stringChoice == "no")) { cout << "ERROR: You must type either \"yes\" or \"no\".\n" << "Enter \"yes\" or \"no\": "; // clear input stream cin.clear(); // discard previous input cin.ignore(1200, '\n'); // Re-enter choice again cin >> stringChoice; } cout << "You have enter: " << stringChoice << endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: datman.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2004-06-17 16:15:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BIB_DATMAN_HXX #define _BIB_DATMAN_HXX #ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_ #include <com/sun/star/awt/XControlModel.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORM_HPP_ #include <com/sun/star/form/XForm.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_ #include <com/sun/star/sdb/XSQLQueryComposer.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_ #include <com/sun/star/form/XFormController.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_ #include <com/sun/star/form/XLoadable.hpp> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif // #100312# -------------------- #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_ #include <com/sun/star/frame/XDispatchProviderInterceptor.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_ #include <com/sun/star/frame/XDispatchProviderInterception.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif class Window; //----------------------------------------------------------------------------- namespace bib { class BibView; // #100312# ----------- class BibBeamer; } class BibToolBar; struct BibDBDescriptor; // #100312# --------------------- class BibInterceptorHelper :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor > { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception; protected: ~BibInterceptorHelper( ); public: BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch); void ReleaseInterceptor(); // XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException); // XDispatchProviderInterceptor virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException); }; typedef cppu::WeakComponentImplHelper2 < ::com::sun::star::beans::XPropertyChangeListener , ::com::sun::star::form::XLoadable > BibDataManager_Base; class BibDataManager :public ::comphelper::OMutexAndBroadcastHelper ,public BibDataManager_Base { private: ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > m_xForm; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > m_xGridModel; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSourceProps; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer > m_xParser; ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > m_xFormCtrl; // #100312# ------------------- ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xFormDispatch; BibInterceptorHelper* m_pInterceptorHelper; ::rtl::OUString aActiveDataTable; ::rtl::OUString aDataSourceURL; ::rtl::OUString aQuoteChar; ::com::sun::star::uno::Any aUID; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xBibCursor; ::cppu::OInterfaceContainerHelper m_aLoadListeners; ::bib::BibView* pBibView; BibToolBar* pToolbar; rtl::OUString sIdentifierMapping; protected: void InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid); void SetMeAsUidListener(); void RemoveMeAsUidListener(); void UpdateAddressbookCursor(::rtl::OUString aSourceName); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > createGridModel( const ::rtl::OUString& rName ); // XLoadable virtual void SAL_CALL load( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unload( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reload( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLoaded( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); public: BibDataManager(); ~BibDataManager(); virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > createDatabaseForm( BibDBDescriptor& aDesc); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel(); ::com::sun::star::uno::Sequence< ::rtl::OUString> getDataSources(); ::rtl::OUString getActiveDataSource() {return aDataSourceURL;} void setActiveDataSource(const ::rtl::OUString& rURL); ::rtl::OUString getActiveDataTable(); void setActiveDataTable(const ::rtl::OUString& rTable); void setFilter(const ::rtl::OUString& rQuery); ::rtl::OUString getFilter(); ::com::sun::star::uno::Sequence< ::rtl::OUString> getQueryFields(); ::rtl::OUString getQueryField(); void startQueryWith(const ::rtl::OUString& rQuery); const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer >& getParser() { return m_xParser; } const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& getForm() { return m_xForm; } ::rtl::OUString getControlName(sal_Int32 nFormatKey ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > loadControlModel(const ::rtl::OUString& rName, sal_Bool bForceListBox = sal_False); void saveCtrModel(const ::rtl::OUString& rName, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel); sal_Bool moveRelative(long nMove); void CreateMappingDialog(Window* pParent); ::rtl::OUString CreateDBChangeDialog(Window* pParent); void DispatchDBChangeDialog(); sal_Bool HasActiveConnection() const; void SetView( ::bib::BibView* pView ) { pBibView = pView; } void SetToolbar(BibToolBar* pSet); const rtl::OUString& GetIdentifierMapping(); void ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();} ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController(); // #100312# ---------- void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer); sal_Bool HasActiveConnection(); }; #endif <commit_msg>INTEGRATION: CWS dba20 (1.11.90); FILE MERGED 2004/11/18 10:44:54 fs 1.11.90.1: #i37070# XSQLQueryComposer superseded by XSingleSelectQueryComposer<commit_after>/************************************************************************* * * $RCSfile: datman.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2005-01-05 12:41:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BIB_DATMAN_HXX #define _BIB_DATMAN_HXX #ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_ #include <com/sun/star/awt/XControlModel.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORM_HPP_ #include <com/sun/star/form/XForm.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XSINGLESELECTQUERYCOMPOSER_HPP_ #include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp> #endif #ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_ #include <com/sun/star/form/XFormController.hpp> #endif #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_ #include <com/sun/star/form/XLoadable.hpp> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif // #100312# -------------------- #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_ #include <com/sun/star/frame/XDispatchProviderInterceptor.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_ #include <com/sun/star/frame/XDispatchProviderInterception.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif class Window; //----------------------------------------------------------------------------- namespace bib { class BibView; // #100312# ----------- class BibBeamer; } class BibToolBar; struct BibDBDescriptor; // #100312# --------------------- class BibInterceptorHelper :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor > { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception; protected: ~BibInterceptorHelper( ); public: BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch); void ReleaseInterceptor(); // XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException); // XDispatchProviderInterceptor virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException); }; typedef cppu::WeakComponentImplHelper2 < ::com::sun::star::beans::XPropertyChangeListener , ::com::sun::star::form::XLoadable > BibDataManager_Base; class BibDataManager :public ::comphelper::OMutexAndBroadcastHelper ,public BibDataManager_Base { private: ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > m_xForm; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > m_xGridModel; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSourceProps; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer > m_xParser; ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > m_xFormCtrl; // #100312# ------------------- ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xFormDispatch; BibInterceptorHelper* m_pInterceptorHelper; ::rtl::OUString aActiveDataTable; ::rtl::OUString aDataSourceURL; ::rtl::OUString aQuoteChar; ::com::sun::star::uno::Any aUID; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xBibCursor; ::cppu::OInterfaceContainerHelper m_aLoadListeners; ::bib::BibView* pBibView; BibToolBar* pToolbar; rtl::OUString sIdentifierMapping; protected: void InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid); void SetMeAsUidListener(); void RemoveMeAsUidListener(); void UpdateAddressbookCursor(::rtl::OUString aSourceName); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > createGridModel( const ::rtl::OUString& rName ); // XLoadable virtual void SAL_CALL load( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unload( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reload( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLoaded( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); public: BibDataManager(); ~BibDataManager(); virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > createDatabaseForm( BibDBDescriptor& aDesc); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel(); ::com::sun::star::uno::Sequence< ::rtl::OUString> getDataSources(); ::rtl::OUString getActiveDataSource() {return aDataSourceURL;} void setActiveDataSource(const ::rtl::OUString& rURL); ::rtl::OUString getActiveDataTable(); void setActiveDataTable(const ::rtl::OUString& rTable); void setFilter(const ::rtl::OUString& rQuery); ::rtl::OUString getFilter(); ::com::sun::star::uno::Sequence< ::rtl::OUString> getQueryFields(); ::rtl::OUString getQueryField(); void startQueryWith(const ::rtl::OUString& rQuery); const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >& getParser() { return m_xParser; } const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& getForm() { return m_xForm; } ::rtl::OUString getControlName(sal_Int32 nFormatKey ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > loadControlModel(const ::rtl::OUString& rName, sal_Bool bForceListBox = sal_False); void saveCtrModel(const ::rtl::OUString& rName, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > & rCtrModel); sal_Bool moveRelative(long nMove); void CreateMappingDialog(Window* pParent); ::rtl::OUString CreateDBChangeDialog(Window* pParent); void DispatchDBChangeDialog(); sal_Bool HasActiveConnection() const; void SetView( ::bib::BibView* pView ) { pBibView = pView; } void SetToolbar(BibToolBar* pSet); const rtl::OUString& GetIdentifierMapping(); void ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();} ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > GetFormController(); // #100312# ---------- void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer); sal_Bool HasActiveConnection(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: slideview.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2007-07-20 06:24:59 $ * * 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 INCLUDED_SLIDESHOW_SLIDEVIEW_HXX #define INCLUDED_SLIDESHOW_SLIDEVIEW_HXX #include "unoview.hxx" /* Definition of SlideView factory method */ namespace slideshow { namespace internal { class EventQueue; class EventMultiplexer; /** Factory for SlideView @param xView UNO slide view this object should encapsulate @param rEventQueue Global event queue, to be used for notification messages. @param rViewChangeFunc Functor to call, when the UNO view signals a repaint. */ UnoViewSharedPtr createSlideView( ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShowView> const& xView, EventQueue& rEventQueue, EventMultiplexer& rEventMultiplexer ); } } #endif /* INCLUDED_SLIDESHOW_SLIDEVIEW_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.4.46); FILE MERGED 2008/03/31 14:00:31 rt 1.4.46.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: slideview.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_SLIDESHOW_SLIDEVIEW_HXX #define INCLUDED_SLIDESHOW_SLIDEVIEW_HXX #include "unoview.hxx" /* Definition of SlideView factory method */ namespace slideshow { namespace internal { class EventQueue; class EventMultiplexer; /** Factory for SlideView @param xView UNO slide view this object should encapsulate @param rEventQueue Global event queue, to be used for notification messages. @param rViewChangeFunc Functor to call, when the UNO view signals a repaint. */ UnoViewSharedPtr createSlideView( ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShowView> const& xView, EventQueue& rEventQueue, EventMultiplexer& rEventMultiplexer ); } } #endif /* INCLUDED_SLIDESHOW_SLIDEVIEW_HXX */ <|endoftext|>
<commit_before>#include "Tiler.h" #include "cinder/gl/gl.h" #include "cinder/app/App.h" #include "cinder/Rand.h" #include <algorithm> #include <sstream> using namespace reza::tiler; using namespace cinder; using namespace glm; using namespace std; Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window, bool alpha ) : mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ), mAlpha( alpha ) { mWindowWidth = app::toPixels( mWindowRef->getWidth() ); mWindowHeight = app::toPixels( mWindowRef->getHeight() ); mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth ); mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight ); mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth ); mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight ); mCurrentTile = -1; if( mAlpha ) { auto fmt = gl::Fbo::Format().samples( gl::Fbo::getMaxSamples() ); mFboRef = gl::Fbo::create( mWindowWidth, mWindowHeight, fmt ); mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); mFboRef->unbindFramebuffer(); } } bool Tiler::nextTile() { if( mCurrentTile == mNumTilesX * mNumTilesY ) { if( mAlpha ) { mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } mCurrentTile = -1; return false; } if( mCurrentTile == -1 ) { mCurrentTile = 0; if( mSurfaceRef && mSurfaceRef->getSize() != ivec2( mImageWidth, mImageHeight ) ) { mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha ); } else { mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha ); } } else { if( mAlpha ) { mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } } int tileX = mCurrentTile % mNumTilesX; int tileY = mCurrentTile / mNumTilesX; int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth; int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight; mCurrentArea.x1 = tileX * mTileWidth; mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth; mCurrentArea.y1 = tileY * mTileHeight; mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight; update(); mCurrentTile++; return true; } void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane ) { CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane ); setMatrices( cam ); } void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight ) { ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f ); } void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = true; } void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = false; } bool Tiler::getAlpha() { return mAlpha; } ci::Surface& Tiler::getSurface() { while ( nextTile() ) { } return *mSurfaceRef; } void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn ) { mDrawBgFn = drawBgFn; } void Tiler::setDrawFn( const std::function<void()> &drawFn ) { mDrawFn = drawFn; } void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn ) { mDrawHudFn = drawHudFn; } void Tiler::setMatrices( const CameraPersp &camera ) { mCamera = camera; float left, top, right, bottom, nearPlane, farPlane; camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane ); if( camera.isPersp() ) { frustum( left, right, bottom, top, nearPlane, farPlane ); } else { ortho( left, right, bottom, top, nearPlane, farPlane ); } } void Tiler::update() { if( mAlpha ) { mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); } float sx = (float) mCurrentArea.x1 / (float) mImageWidth; float sy = (float) mCurrentArea.y1 / (float) mImageHeight; float ex = (float) mCurrentArea.x2 / (float) mImageWidth; float ey = (float) mCurrentArea.y2 / (float) mImageHeight; vec2 ul = vec2(sx, sy); vec2 ur = vec2(ex, sy); vec2 lr = vec2(ex, ey); vec2 ll = vec2(sx, ey); float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); if( mDrawBgFn ) { gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); mDrawBgFn( ul, ur, lr, ll ); gl::popViewport(); gl::popMatrices(); } CameraPersp cam = mCamera; gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); gl::pushProjectionMatrix(); if( mCurrentFrustumPersp ) { gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } else { gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } gl::pushViewMatrix(); gl::setViewMatrix( cam.getViewMatrix() ); if( mDrawFn ) { mDrawFn(); } gl::popViewMatrix(); gl::popProjectionMatrix(); gl::popViewport(); gl::popMatrices(); if( mDrawHudFn ) { mDrawHudFn( ul, ur, lr, ll ); } if( mAlpha ) { mFboRef->unbindFramebuffer(); } }<commit_msg>flipped y texcoord when drawing background<commit_after>#include "Tiler.h" #include "cinder/gl/gl.h" #include "cinder/app/App.h" #include "cinder/Rand.h" #include <algorithm> #include <sstream> using namespace reza::tiler; using namespace cinder; using namespace glm; using namespace std; Tiler::Tiler( int32_t imageWidth, int32_t imageHeight, int32_t tileWidth, int32_t tileHeight, ci::app::WindowRef window, bool alpha ) : mImageWidth( app::toPixels( imageWidth ) ), mImageHeight( app::toPixels( imageHeight ) ), mWindowRef( window ), mDrawFn( nullptr ), mDrawBgFn( nullptr ), mDrawHudFn( nullptr ), mAlpha( alpha ) { mWindowWidth = app::toPixels( mWindowRef->getWidth() ); mWindowHeight = app::toPixels( mWindowRef->getHeight() ); mTileWidth = std::min( ( int32_t ) app::toPixels( tileWidth ), mWindowWidth ); mTileHeight = std::min( ( int32_t ) app::toPixels( tileHeight ), mWindowHeight ); mNumTilesX = ( int32_t ) ceil( mImageWidth / (float)mTileWidth ); mNumTilesY = ( int32_t ) ceil( mImageHeight / (float)mTileHeight ); mCurrentTile = -1; if( mAlpha ) { auto fmt = gl::Fbo::Format().samples( gl::Fbo::getMaxSamples() ); mFboRef = gl::Fbo::create( mWindowWidth, mWindowHeight, fmt ); mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); mFboRef->unbindFramebuffer(); } } bool Tiler::nextTile() { if( mCurrentTile == mNumTilesX * mNumTilesY ) { if( mAlpha ) { mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } mCurrentTile = -1; return false; } if( mCurrentTile == -1 ) { mCurrentTile = 0; if( mSurfaceRef && mSurfaceRef->getSize() != ivec2( mImageWidth, mImageHeight ) ) { mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha ); } else { mSurfaceRef = Surface::create( mImageWidth, mImageHeight, mAlpha ); } } else { if( mAlpha ) { mSurfaceRef->copyFrom( mFboRef->readPixels8u( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } else { mSurfaceRef->copyFrom( mWindowRef->getRenderer()->copyWindowSurface( Area( ivec2( 0 ) , ci::app::toPixels( mWindowRef->getSize() ) ), mCurrentArea.getHeight() ), Area( 0, 0, mCurrentArea.getWidth(), mCurrentArea.getHeight() ), mCurrentArea.getUL() ); } } int tileX = mCurrentTile % mNumTilesX; int tileY = mCurrentTile / mNumTilesX; int currentTileWidth = ( ( tileX == mNumTilesX - 1 ) && ( mImageWidth != mTileWidth * mNumTilesX ) ) ? ( mImageWidth % mTileWidth ) : mTileWidth; int currentTileHeight = ( ( tileY == mNumTilesY - 1 ) && ( mImageHeight != mTileHeight * mNumTilesY ) ) ? ( mImageHeight % mTileHeight ) : mTileHeight; mCurrentArea.x1 = tileX * mTileWidth; mCurrentArea.x2 = mCurrentArea.x1 + currentTileWidth; mCurrentArea.y1 = tileY * mTileHeight; mCurrentArea.y2 = mCurrentArea.y1 + currentTileHeight; update(); mCurrentTile++; return true; } void Tiler::setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees, float nearPlane, float farPlane ) { CameraPersp cam( screenWidth, screenHeight, fovDegrees, nearPlane, farPlane ); setMatrices( cam ); } void Tiler::setMatricesWindow( int32_t windowWidth, int32_t windowHeight ) { ortho( 0, (float)windowWidth, (float)windowHeight, 0, -1.0f, 1.0f ); } void Tiler::frustum( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = true; } void Tiler::ortho( float left, float right, float bottom, float top, float nearPlane, float farPlane ) { mCurrentFrustumCoords = Rectf( vec2( left, top ), vec2( right, bottom ) ); mCurrentFrustumNear = nearPlane; mCurrentFrustumFar = farPlane; mCurrentFrustumPersp = false; } bool Tiler::getAlpha() { return mAlpha; } ci::Surface& Tiler::getSurface() { while ( nextTile() ) { } return *mSurfaceRef; } void Tiler::setDrawBgFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawBgFn ) { mDrawBgFn = drawBgFn; } void Tiler::setDrawFn( const std::function<void()> &drawFn ) { mDrawFn = drawFn; } void Tiler::setDrawHudFn( const std::function<void( glm::vec2, glm::vec2, glm::vec2, glm::vec2 )> &drawHudFn ) { mDrawHudFn = drawHudFn; } void Tiler::setMatrices( const CameraPersp &camera ) { mCamera = camera; float left, top, right, bottom, nearPlane, farPlane; camera.getFrustum( &left, &top, &right, &bottom, &nearPlane, &farPlane ); if( camera.isPersp() ) { frustum( left, right, bottom, top, nearPlane, farPlane ); } else { ortho( left, right, bottom, top, nearPlane, farPlane ); } } void Tiler::update() { if( mAlpha ) { mFboRef->bindFramebuffer(); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); } float sx = (float) mCurrentArea.x1 / (float) mImageWidth; float sy = 1.0 - (float) mCurrentArea.y1 / (float) mImageHeight; float ex = (float) mCurrentArea.x2 / (float) mImageWidth; float ey = 1.0 - (float) mCurrentArea.y2 / (float) mImageHeight; vec2 ul = vec2( sx, sy ); vec2 ur = vec2( ex, sy ); vec2 lr = vec2( ex, ey ); vec2 ll = vec2( sx, ey ); if( mDrawBgFn ) { gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); mDrawBgFn( ul, ur, lr, ll ); gl::popViewport(); gl::popMatrices(); } float left = mCurrentFrustumCoords.x1 + mCurrentArea.x1 / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float right = left + mCurrentArea.getWidth() / (float)mImageWidth * mCurrentFrustumCoords.getWidth(); float top = mCurrentFrustumCoords.y1 + mCurrentArea.y1 / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); float bottom = top + mCurrentArea.getHeight() / (float)mImageHeight * mCurrentFrustumCoords.getHeight(); CameraPersp cam = mCamera; gl::pushMatrices(); gl::pushViewport(); gl::viewport( mCurrentArea.getSize() ); gl::pushProjectionMatrix(); if( mCurrentFrustumPersp ) { gl::setProjectionMatrix( glm::frustum( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } else { gl::setProjectionMatrix( glm::ortho( left, right, bottom, top, mCurrentFrustumNear, mCurrentFrustumFar ) ); } gl::pushViewMatrix(); gl::setViewMatrix( cam.getViewMatrix() ); if( mDrawFn ) { mDrawFn(); } gl::popViewMatrix(); gl::popProjectionMatrix(); gl::popViewport(); gl::popMatrices(); if( mDrawHudFn ) { mDrawHudFn( ul, ur, lr, ll ); } if( mAlpha ) { mFboRef->unbindFramebuffer(); } }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../StroikaPreComp.h" #include "Event.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* ******************************************************************************** ************************************** Event *********************************** ******************************************************************************** */ #if qTrack_ThreadUtils_HandleCounts uint32_t Event::sCurAllocatedHandleCount = 0; #endif void Event::Wait (Time::DurationSecondsType timeout) { CheckForThreadAborting (); #if qPlatform_Windows AssertNotNull (fEventHandle); // must be careful about rounding errors in int->DurationSecondsType->int Again: DWORD result = ::WaitForSingleObjectEx (fEventHandle, Platform::Windows::Duration2Milliseconds (timeout), true); switch (result) { case WAIT_TIMEOUT: DoThrow (WaitTimedOutException ()); case WAIT_ABANDONED: DoThrow (WaitAbandonedException ()); case WAIT_IO_COMPLETION: CheckForThreadAborting (); goto Again; // roughly right to goto again - should decrement timeout- APC other than for abort - we should just keep waiting } Verify (result == WAIT_OBJECT_0); #elif qUseThreads_StdCPlusPlus std::unique_lock<std::mutex> lock (fMutex_); Time::DurationSecondsType until = Time::GetTickCount () + timeout; Assert (until >= timeout); // so no funny overflow issues... while (not fTriggered_) { CheckForThreadAborting (); Time::DurationSecondsType remaining = until - Time::GetTickCount (); if (remaining < 0) { DoThrow (WaitTimedOutException ()); } //tmphack til I figure out this lock/waiting stuff - remaining = min (remaining, 5); if (fConditionVariable_.wait_for (lock, std::chrono::duration<double> (remaining)) == std::cv_status::timeout) { // DoThrow (WaitTimedOutException ()); } } fTriggered_ = false ; // autoreset #else AssertNotImplemented (); #endif } <commit_msg>A few hacks to the POSIX Event::Wait () code to try and debug that stuff on linux<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../StroikaPreComp.h" #include "Event.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* ******************************************************************************** ************************************** Event *********************************** ******************************************************************************** */ #if qTrack_ThreadUtils_HandleCounts uint32_t Event::sCurAllocatedHandleCount = 0; #endif void Event::Wait (Time::DurationSecondsType timeout) { CheckForThreadAborting (); #if qPlatform_Windows AssertNotNull (fEventHandle); // must be careful about rounding errors in int->DurationSecondsType->int Again: DWORD result = ::WaitForSingleObjectEx (fEventHandle, Platform::Windows::Duration2Milliseconds (timeout), true); switch (result) { case WAIT_TIMEOUT: DoThrow (WaitTimedOutException ()); case WAIT_ABANDONED: DoThrow (WaitAbandonedException ()); case WAIT_IO_COMPLETION: CheckForThreadAborting (); goto Again; // roughly right to goto again - should decrement timeout- APC other than for abort - we should just keep waiting } Verify (result == WAIT_OBJECT_0); #elif qUseThreads_StdCPlusPlus std::unique_lock<std::mutex> lock (fMutex_); Time::DurationSecondsType until = Time::GetTickCount () + timeout; Assert (until >= timeout); // so no funny overflow issues... while (not fTriggered_) { CheckForThreadAborting (); Time::DurationSecondsType remaining = until - Time::GetTickCount (); if (remaining < 0) { DoThrow (WaitTimedOutException ()); } //tmphack til I figure out this lock/waiting stuff - if (remaining > 5) { remaining = 5; } if (fConditionVariable_.wait_for (lock, std::chrono::duration<double> (remaining)) == std::cv_status::timeout) { // DoThrow (WaitTimedOutException ()); } } fTriggered_ = false ; // autoreset #else AssertNotImplemented (); #endif } <|endoftext|>
<commit_before>#include <QApplication> #include "qkeymapper.h" #ifdef DEBUG_LOGOUT_ON //#include "vld.h" #endif int main(int argc, char *argv[]) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QApplication a(argc, argv); QApplication::setStyle(QStyleFactory::create("Fusion")); #ifdef ADJUST_PRIVILEGES // BOOL adjustresult = QKeyMapper::AdjustPrivileges(); // qDebug() << "AdjustPrivileges Result:" << adjustresult; BOOL adjustresult = QKeyMapper::EnableDebugPrivilege(); qDebug() << "EnableDebugPrivilege Result:" << adjustresult; #endif QKeyMapper w; // Remove "?" Button from QDialog Qt::WindowFlags flags = Qt::Dialog; flags |= Qt::WindowMinimizeButtonHint; flags |= Qt::WindowCloseButtonHint; w.setWindowFlags(flags); w.show(); return a.exec(); } <commit_msg>Add debug timestamp for log output.<commit_after>#include <QApplication> #include "qkeymapper.h" #ifdef DEBUG_LOGOUT_ON //#include "vld.h" #endif int main(int argc, char *argv[]) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QApplication a(argc, argv); QApplication::setStyle(QStyleFactory::create("Fusion")); #ifdef DEBUG_LOGOUT_ON qSetMessagePattern("%{time [hh:mm:ss.zzz]} Message:%{message}"); #endif #ifdef ADJUST_PRIVILEGES // BOOL adjustresult = QKeyMapper::AdjustPrivileges(); // qDebug() << "AdjustPrivileges Result:" << adjustresult; BOOL adjustresult = QKeyMapper::EnableDebugPrivilege(); qDebug() << "EnableDebugPrivilege Result:" << adjustresult; #endif QKeyMapper w; // Remove "?" Button from QDialog Qt::WindowFlags flags = Qt::Dialog; flags |= Qt::WindowMinimizeButtonHint; flags |= Qt::WindowCloseButtonHint; w.setWindowFlags(flags); w.show(); return a.exec(); } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ADPiecewiseLinearInterpolationMaterial.h" #include "MooseVariableFE.h" registerADMooseObject("MooseApp", ADPiecewiseLinearInterpolationMaterial); defineADValidParams( ADPiecewiseLinearInterpolationMaterial, ADMaterial, params.addClassDescription( "Compute a property using a piecewise linear interpolation to define " "its dependence on a variable"); params.addRequiredParam<std::string>("property", "The name of the property this material will compute"); params.addRequiredCoupledVar( "variable", "The name of the variable whose value is used as the abscissa in the interpolation"); params.addParam<std::vector<Real>>("x", "The abscissa values"); params.addParam<std::vector<Real>>("y", "The ordinate values"); params.addParam<std::vector<Real>>("xy_data", "All function data, supplied in abscissa, ordinate pairs"); params.addParam<Real>("scale_factor", 1.0, "Scale factor to be applied to the ordinate values");); template <ComputeStage compute_stage> ADPiecewiseLinearInterpolationMaterial<compute_stage>::ADPiecewiseLinearInterpolationMaterial( const InputParameters & parameters) : ADMaterial<compute_stage>(parameters), _prop_name(adGetParam<std::string>("property")), _coupled_var(adCoupledValue("variable")), _scale_factor(adGetParam<Real>("scale_factor")), _property(adDeclareADProperty<Real>(_prop_name)) { std::vector<Real> x; std::vector<Real> y; if ((parameters.isParamValid("x")) || (parameters.isParamValid("y"))) { if (!((parameters.isParamValid("x")) && (parameters.isParamValid("y")))) mooseError("In ", _name, ": Both 'x' and 'y' must be specified if either one is specified."); if (parameters.isParamValid("xy_data")) mooseError("In ", _name, ": Cannot specify 'x', 'y', and 'xy_data' together."); x = adGetParam<std::vector<Real>>("x"); y = adGetParam<std::vector<Real>>("y"); } else if (parameters.isParamValid("xy_data")) { std::vector<Real> xy = adGetParam<std::vector<Real>>("xy_data"); unsigned int xy_size = xy.size(); if (xy_size % 2 != 0) mooseError("In ", _name, ": Length of data provided in 'xy_data' must be a multiple of 2."); unsigned int x_size = xy_size / 2; x.reserve(x_size); y.reserve(x_size); for (unsigned int i = 0; i < xy_size / 2; ++i) { x.push_back(xy[i * 2]); y.push_back(xy[i * 2 + 1]); } } try { _linear_interp = libmesh_make_unique<LinearInterpolation>(x, y); } catch (std::domain_error & e) { mooseError("In ", _name, ": ", e.what()); } } template <ComputeStage compute_stage> void ADPiecewiseLinearInterpolationMaterial<compute_stage>::computeQpProperties() { _property[_qp] = _scale_factor * _linear_interp->sampleDerivative(_coupled_var[_qp].value()) * _coupled_var[_qp]; } template <> void ADPiecewiseLinearInterpolationMaterial<RESIDUAL>::computeQpProperties() { Moose::out << "res: " << _coupled_var[_qp] << std::endl; _property[_qp] = _scale_factor * _linear_interp->sample(_coupled_var[_qp]); Moose::out << "res prop: " << _property[_qp] << std::endl; } <commit_msg>Fix up calculation of material property value and derivatives<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ADPiecewiseLinearInterpolationMaterial.h" #include "MooseVariableFE.h" registerADMooseObject("MooseApp", ADPiecewiseLinearInterpolationMaterial); defineADValidParams( ADPiecewiseLinearInterpolationMaterial, ADMaterial, params.addClassDescription( "Compute a property using a piecewise linear interpolation to define " "its dependence on a variable"); params.addRequiredParam<std::string>("property", "The name of the property this material will compute"); params.addRequiredCoupledVar( "variable", "The name of the variable whose value is used as the abscissa in the interpolation"); params.addParam<std::vector<Real>>("x", "The abscissa values"); params.addParam<std::vector<Real>>("y", "The ordinate values"); params.addParam<std::vector<Real>>("xy_data", "All function data, supplied in abscissa, ordinate pairs"); params.addParam<Real>("scale_factor", 1.0, "Scale factor to be applied to the ordinate values");); template <ComputeStage compute_stage> ADPiecewiseLinearInterpolationMaterial<compute_stage>::ADPiecewiseLinearInterpolationMaterial( const InputParameters & parameters) : ADMaterial<compute_stage>(parameters), _prop_name(adGetParam<std::string>("property")), _coupled_var(adCoupledValue("variable")), _scale_factor(adGetParam<Real>("scale_factor")), _property(adDeclareADProperty<Real>(_prop_name)) { std::vector<Real> x; std::vector<Real> y; if ((parameters.isParamValid("x")) || (parameters.isParamValid("y"))) { if (!((parameters.isParamValid("x")) && (parameters.isParamValid("y")))) mooseError("In ", _name, ": Both 'x' and 'y' must be specified if either one is specified."); if (parameters.isParamValid("xy_data")) mooseError("In ", _name, ": Cannot specify 'x', 'y', and 'xy_data' together."); x = adGetParam<std::vector<Real>>("x"); y = adGetParam<std::vector<Real>>("y"); } else if (parameters.isParamValid("xy_data")) { std::vector<Real> xy = adGetParam<std::vector<Real>>("xy_data"); unsigned int xy_size = xy.size(); if (xy_size % 2 != 0) mooseError("In ", _name, ": Length of data provided in 'xy_data' must be a multiple of 2."); unsigned int x_size = xy_size / 2; x.reserve(x_size); y.reserve(x_size); for (unsigned int i = 0; i < xy_size / 2; ++i) { x.push_back(xy[i * 2]); y.push_back(xy[i * 2 + 1]); } } try { _linear_interp = libmesh_make_unique<LinearInterpolation>(x, y); } catch (std::domain_error & e) { mooseError("In ", _name, ": ", e.what()); } } template <ComputeStage compute_stage> void ADPiecewiseLinearInterpolationMaterial<compute_stage>::computeQpProperties() { _property[_qp].value() = _scale_factor * _linear_interp->sample(_coupled_var[_qp].value()); _property[_qp].derivatives() = _scale_factor * _linear_interp->sampleDerivative(_coupled_var[_qp].value()) * _coupled_var[_qp].derivatives(); } template <> void ADPiecewiseLinearInterpolationMaterial<RESIDUAL>::computeQpProperties() { _property[_qp] = _scale_factor * _linear_interp->sample(_coupled_var[_qp]); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2004 Jürgen Riegel <[email protected]> * * Copyright (c) 2012 Luke Parry <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QAction> # include <QMenu> # include <QTimer> #include <QPointer> #include <boost/signal.hpp> #include <boost/bind.hpp> #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Console.h> #include <Base/Parameter.h> #include <Base/Exception.h> #include <Base/Sequencer.h> #include <App/Application.h> #include <App/Document.h> #include <App/DocumentObject.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Document.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/ViewProvider.h> #include <Gui/ViewProviderDocumentObject.h> #include <Gui/ViewProviderDocumentObjectGroup.h> #include "MDIViewPage.h" #include "ViewProviderPage.h" #include <Mod/TechDraw/App/DrawPage.h> #include <Mod/TechDraw/App/DrawView.h> #include <Mod/TechDraw/App/DrawProjGroupItem.h> #include <Mod/TechDraw/App/DrawViewDimension.h> #include <Mod/TechDraw/App/DrawHatch.h> #include <Mod/TechDraw/App/DrawUtil.h> using namespace TechDrawGui; PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject) //************************************************************************** // Construction/Destruction ViewProviderPage::ViewProviderPage() : m_mdiView(0), m_docReady(true) { sPixmap = "TechDraw_Tree_Page"; Visibility.setStatus(App::Property::Hidden,true); DisplayMode.setStatus(App::Property::Hidden,true); } ViewProviderPage::~ViewProviderPage() { } void ViewProviderPage::attach(App::DocumentObject *pcFeat) { ViewProviderDocumentObject::attach(pcFeat); auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1); auto feature = getDrawPage(); if (feature != nullptr) { connectGuiRepaint = feature->signalGuiPaint.connect(bnd); } else { Base::Console().Log("VPP::attach has no Feature!\n"); } } void ViewProviderPage::setDisplayMode(const char* ModeName) { ViewProviderDocumentObject::setDisplayMode(ModeName); } std::vector<std::string> ViewProviderPage::getDisplayModes(void) const { // get the modes of the father std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes(); StrList.push_back("Drawing"); return StrList; } void ViewProviderPage::show(void) { showMDIViewPage(); } void ViewProviderPage::hide(void) { if (!m_mdiView.isNull()) { //m_mdiView is a QPointer // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614 //Gui::getMainWindow()->activatePreviousWindow(); Gui::getMainWindow()->removeWindow(m_mdiView); } ViewProviderDocumentObject::hide(); } void ViewProviderPage::updateData(const App::Property* prop) { if (prop == &(getDrawPage()->KeepUpdated)) { if (getDrawPage()->KeepUpdated.getValue()) { sPixmap = "TechDraw_Tree_Page"; if (!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } else { sPixmap = "TechDraw_Tree_Page_Unsync"; } } //if a view is added/deleted, rebuild the visual if (prop == &(getDrawPage()->Views)) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } //if the template is changed, rebuild the visual } else if (prop == &(getDrawPage()->Template)) { if(m_mdiView && !getDrawPage()->isUnsetting()) { m_mdiView->matchSceneRectToTemplate(); m_mdiView->updateTemplate(); } } Gui::ViewProviderDocumentObject::updateData(prop); } bool ViewProviderPage::onDelete(const std::vector<std::string> &items) { if (!m_mdiView.isNull()) { Gui::getMainWindow()->removeWindow(m_mdiView); Gui::getMainWindow()->activatePreviousWindow(); m_mdiView->deleteLater(); // Delete the drawing m_mdiView; } else { // MDIViewPage is not displayed yet so don't try to delete it! Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n"); } Gui::Selection().clearSelection(); return ViewProviderDocumentObject::onDelete(items); } void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member); // act->setData(QVariant(1)); // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073 //this is edit ModNum act->setData(QVariant((int) ViewProvider::Default)); } bool ViewProviderPage::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) { showMDIViewPage(); // show the drawing Gui::getMainWindow()->setActiveWindow(m_mdiView); return false; } else { Gui::ViewProviderDocumentObject::setEdit(ModNum); } return true; } bool ViewProviderPage::doubleClicked(void) { showMDIViewPage(); Gui::getMainWindow()->setActiveWindow(m_mdiView); return true; } bool ViewProviderPage::showMDIViewPage() { if (isRestoring()) { return true; } if (m_mdiView.isNull()){ Gui::Document* doc = Gui::Application::Instance->getDocument (pcObject->getDocument()); m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow()); m_mdiView->setWindowTitle(QObject::tr("Drawing viewer") + QString::fromLatin1("[*]")); m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page")); m_mdiView->updateDrawing(true); Gui::getMainWindow()->addWindow(m_mdiView); m_mdiView->viewAll(); } else { m_mdiView->updateDrawing(true); m_mdiView->updateTemplate(true); } return true; } std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const { std::vector<App::DocumentObject*> temp; App::DocumentObject *templateFeat = 0; templateFeat = getDrawPage()->Template.getValue(); if(templateFeat) { temp.push_back(templateFeat); } // Collect any child views // for Page, valid children are any View except: DrawProjGroupItem // DrawViewDimension // any FeatuerView in a DrawViewClip // DrawHatch const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues(); try { for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) { TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it); App::DocumentObject *docObj = *it; // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId()) || (featView && featView->isInClip()) ) continue; else temp.push_back(*it); } return temp; } catch (...) { std::vector<App::DocumentObject*> tmp; return tmp; } } void ViewProviderPage::unsetEdit(int ModNum) { Q_UNUSED(ModNum); static_cast<void>(showMDIViewPage()); return; } MDIViewPage* ViewProviderPage::getMDIViewPage() { if (m_mdiView.isNull()) { Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n"); return 0; } else { return m_mdiView; } } void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg) { if(!m_mdiView.isNull()) { if(msg.Type == Gui::SelectionChanges::SetSelection) { m_mdiView->clearSelection(); std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName); for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { Gui::SelectionSingleton::SelObj selObj = *it; if(selObj.pObject == getDrawPage()) continue; std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me wf: don't think this is ever executed } } else { m_mdiView->selectFeature(selObj.pObject, true); } } } else { bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false; Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument()); App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName); if(obj) { std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me } else { m_mdiView->selectFeature(obj, selectState); } } } } //else (Gui::SelectionChanges::SetPreselect) } } void ViewProviderPage::onChanged(const App::Property *prop) { if (prop == &(getDrawPage()->Template)) { if(m_mdiView) { m_mdiView->updateTemplate(); } } Gui::ViewProviderDocumentObject::onChanged(prop); } void ViewProviderPage::startRestoring() { m_docReady = false; Gui::ViewProviderDocumentObject::startRestoring(); } void ViewProviderPage::finishRestoring() { m_docReady = true; static_cast<void>(showMDIViewPage()); Gui::ViewProviderDocumentObject::finishRestoring(); } bool ViewProviderPage::isShow(void) const { return Visibility.getValue(); } //! Redo the whole visual page void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp) { if (dp == getDrawPage()) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } } TechDraw::DrawPage* ViewProviderPage::getDrawPage() const { //during redo, pcObject can become invalid, but non-zero?? if (!pcObject) { Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n"); return nullptr; } return dynamic_cast<TechDraw::DrawPage*>(pcObject); } <commit_msg>Fix #2967 Ph2 Do not show page on restore.<commit_after>/*************************************************************************** * Copyright (c) 2004 Jürgen Riegel <[email protected]> * * Copyright (c) 2012 Luke Parry <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QAction> # include <QMenu> # include <QTimer> #include <QPointer> #include <boost/signal.hpp> #include <boost/bind.hpp> #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Console.h> #include <Base/Parameter.h> #include <Base/Exception.h> #include <Base/Sequencer.h> #include <App/Application.h> #include <App/Document.h> #include <App/DocumentObject.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Document.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/ViewProvider.h> #include <Gui/ViewProviderDocumentObject.h> #include <Gui/ViewProviderDocumentObjectGroup.h> #include "MDIViewPage.h" #include "ViewProviderPage.h" #include <Mod/TechDraw/App/DrawPage.h> #include <Mod/TechDraw/App/DrawView.h> #include <Mod/TechDraw/App/DrawProjGroupItem.h> #include <Mod/TechDraw/App/DrawViewDimension.h> #include <Mod/TechDraw/App/DrawHatch.h> #include <Mod/TechDraw/App/DrawUtil.h> using namespace TechDrawGui; PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject) //************************************************************************** // Construction/Destruction ViewProviderPage::ViewProviderPage() : m_mdiView(0), m_docReady(true) { sPixmap = "TechDraw_Tree_Page"; Visibility.setStatus(App::Property::Hidden,true); DisplayMode.setStatus(App::Property::Hidden,true); } ViewProviderPage::~ViewProviderPage() { } void ViewProviderPage::attach(App::DocumentObject *pcFeat) { ViewProviderDocumentObject::attach(pcFeat); auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1); auto feature = getDrawPage(); if (feature != nullptr) { connectGuiRepaint = feature->signalGuiPaint.connect(bnd); } else { Base::Console().Log("VPP::attach has no Feature!\n"); } } void ViewProviderPage::setDisplayMode(const char* ModeName) { ViewProviderDocumentObject::setDisplayMode(ModeName); } std::vector<std::string> ViewProviderPage::getDisplayModes(void) const { // get the modes of the father std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes(); StrList.push_back("Drawing"); return StrList; } void ViewProviderPage::show(void) { showMDIViewPage(); } void ViewProviderPage::hide(void) { if (!m_mdiView.isNull()) { //m_mdiView is a QPointer // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614 //Gui::getMainWindow()->activatePreviousWindow(); Gui::getMainWindow()->removeWindow(m_mdiView); } ViewProviderDocumentObject::hide(); } void ViewProviderPage::updateData(const App::Property* prop) { if (prop == &(getDrawPage()->KeepUpdated)) { if (getDrawPage()->KeepUpdated.getValue()) { sPixmap = "TechDraw_Tree_Page"; if (!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } else { sPixmap = "TechDraw_Tree_Page_Unsync"; } } //if a view is added/deleted, rebuild the visual if (prop == &(getDrawPage()->Views)) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } //if the template is changed, rebuild the visual } else if (prop == &(getDrawPage()->Template)) { if(m_mdiView && !getDrawPage()->isUnsetting()) { m_mdiView->matchSceneRectToTemplate(); m_mdiView->updateTemplate(); } } Gui::ViewProviderDocumentObject::updateData(prop); } bool ViewProviderPage::onDelete(const std::vector<std::string> &items) { if (!m_mdiView.isNull()) { Gui::getMainWindow()->removeWindow(m_mdiView); Gui::getMainWindow()->activatePreviousWindow(); m_mdiView->deleteLater(); // Delete the drawing m_mdiView; } else { // MDIViewPage is not displayed yet so don't try to delete it! Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n"); } Gui::Selection().clearSelection(); return ViewProviderDocumentObject::onDelete(items); } void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member); // act->setData(QVariant(1)); // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073 //this is edit ModNum act->setData(QVariant((int) ViewProvider::Default)); } bool ViewProviderPage::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) { showMDIViewPage(); // show the drawing Gui::getMainWindow()->setActiveWindow(m_mdiView); return false; } else { Gui::ViewProviderDocumentObject::setEdit(ModNum); } return true; } bool ViewProviderPage::doubleClicked(void) { showMDIViewPage(); Gui::getMainWindow()->setActiveWindow(m_mdiView); return true; } bool ViewProviderPage::showMDIViewPage() { if (isRestoring()) { return true; } if (m_mdiView.isNull()){ Gui::Document* doc = Gui::Application::Instance->getDocument (pcObject->getDocument()); m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow()); m_mdiView->setWindowTitle(QObject::tr("Drawing viewer") + QString::fromLatin1("[*]")); m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page")); m_mdiView->updateDrawing(true); Gui::getMainWindow()->addWindow(m_mdiView); m_mdiView->viewAll(); } else { m_mdiView->updateDrawing(true); m_mdiView->updateTemplate(true); } return true; } std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const { std::vector<App::DocumentObject*> temp; App::DocumentObject *templateFeat = 0; templateFeat = getDrawPage()->Template.getValue(); if(templateFeat) { temp.push_back(templateFeat); } // Collect any child views // for Page, valid children are any View except: DrawProjGroupItem // DrawViewDimension // any FeatuerView in a DrawViewClip // DrawHatch const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues(); try { for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) { TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it); App::DocumentObject *docObj = *it; // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId()) || (featView && featView->isInClip()) ) continue; else temp.push_back(*it); } return temp; } catch (...) { std::vector<App::DocumentObject*> tmp; return tmp; } } void ViewProviderPage::unsetEdit(int ModNum) { Q_UNUSED(ModNum); static_cast<void>(showMDIViewPage()); return; } MDIViewPage* ViewProviderPage::getMDIViewPage() { if (m_mdiView.isNull()) { Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n"); return 0; } else { return m_mdiView; } } void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg) { if(!m_mdiView.isNull()) { if(msg.Type == Gui::SelectionChanges::SetSelection) { m_mdiView->clearSelection(); std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName); for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { Gui::SelectionSingleton::SelObj selObj = *it; if(selObj.pObject == getDrawPage()) continue; std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me wf: don't think this is ever executed } } else { m_mdiView->selectFeature(selObj.pObject, true); } } } else { bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false; Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument()); App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName); if(obj) { std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me } else { m_mdiView->selectFeature(obj, selectState); } } } } //else (Gui::SelectionChanges::SetPreselect) } } void ViewProviderPage::onChanged(const App::Property *prop) { if (prop == &(getDrawPage()->Template)) { if(m_mdiView) { m_mdiView->updateTemplate(); } } Gui::ViewProviderDocumentObject::onChanged(prop); } void ViewProviderPage::startRestoring() { m_docReady = false; Gui::ViewProviderDocumentObject::startRestoring(); } void ViewProviderPage::finishRestoring() { m_docReady = true; //control drawing opening on restore based on Preference //mantis #2967 ph2 - don't even show blank page Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); bool autoUpdate = hGrp->GetBool("KeepPagesUpToDate", 1l); if (autoUpdate) { static_cast<void>(showMDIViewPage()); } Gui::ViewProviderDocumentObject::finishRestoring(); } bool ViewProviderPage::isShow(void) const { return Visibility.getValue(); } //! Redo the whole visual page void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp) { if (dp == getDrawPage()) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } } TechDraw::DrawPage* ViewProviderPage::getDrawPage() const { //during redo, pcObject can become invalid, but non-zero?? if (!pcObject) { Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n"); return nullptr; } return dynamic_cast<TechDraw::DrawPage*>(pcObject); } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2009 * * School of Computing, University of Utah, * Salt Lake City, UT 84112, USA * * and the Gauss Group * http://www.cs.utah.edu/formal_verification * * See LICENSE for licensing information */ #ifndef _TRACE_HPP #define _TRACE_HPP #include <vector> #include <list> #include <algorithm> #include <sstream> #include <memory> #include <boost/range/adaptor/reversed.hpp> #include "Envelope.hpp" #include "Transition.hpp" using std::unique_ptr; using std::shared_ptr; using std::vector; using std::list; // XXX: remove /* * Each process collects a list of transitions. */ class Trace { public: const int pid; Trace(int p) : pid(p) {} inline unsigned int size() const { return tlist.size(); } inline Transition & get(int index) const { return *tlist[index]; } inline Transition & getLast() const { return *tlist.back(); } bool add(unique_ptr<Envelope> t); inline auto begin() { return tlist.begin(); } inline auto end() { return tlist.end(); } inline auto begin() const { return tlist.begin(); } inline auto end() const { return tlist.end(); } auto reverse() { return boost::adaptors::reverse(tlist); } vector<shared_ptr<Transition> > getRequestedProcs(const Transition &child) const { assert(child.pid == pid); vector<shared_ptr<Transition> > result; for (auto req_proc : child.getEnvelope().req_procs) { result.push_back(tlist[req_proc]); } return result; } private: vector<shared_ptr<Transition> > tlist; list<int> ulist; bool intraCB (const Transition &f, const Transition &s) const; }; #endif <commit_msg>In getLast() return a shared_ptr instead of a const &.<commit_after>/* * Copyright (c) 2008-2009 * * School of Computing, University of Utah, * Salt Lake City, UT 84112, USA * * and the Gauss Group * http://www.cs.utah.edu/formal_verification * * See LICENSE for licensing information */ #ifndef _TRACE_HPP #define _TRACE_HPP #include <vector> #include <list> #include <algorithm> #include <sstream> #include <memory> #include <boost/range/adaptor/reversed.hpp> #include "Envelope.hpp" #include "Transition.hpp" using std::unique_ptr; using std::shared_ptr; using std::vector; using std::list; // XXX: remove /* * Each process collects a list of transitions. */ class Trace { public: const int pid; Trace(int p) : pid(p) {} inline unsigned int size() const { return tlist.size(); } inline Transition & get(int index) const { return *tlist[index]; } inline shared_ptr<Transition> getLast() const { return tlist.back(); } bool add(unique_ptr<Envelope> t); inline auto begin() { return tlist.begin(); } inline auto end() { return tlist.end(); } inline auto begin() const { return tlist.begin(); } inline auto end() const { return tlist.end(); } auto reverse() { return boost::adaptors::reverse(tlist); } vector<shared_ptr<Transition> > getRequestedProcs(const Transition &child) const { assert(child.pid == pid); vector<shared_ptr<Transition> > result; for (auto req_proc : child.getEnvelope().req_procs) { result.push_back(tlist[req_proc]); } return result; } private: vector<shared_ptr<Transition> > tlist; list<int> ulist; bool intraCB (const Transition &f, const Transition &s) const; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: modulepcr.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-16 13:19:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX #include "modulepcr.hxx" #endif #ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H #include <rtl/instance.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/getglobalmutex.hxx> #endif //........................................................................ namespace pcr { //........................................................................ IMPLEMENT_MODULE( PcrModule, "pcr" ) //........................................................................ } // namespace pcr //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.8.276); FILE MERGED 2008/04/01 12:29:50 thb 1.8.276.2: #i85898# Stripping all external header guards 2008/03/31 12:31:50 rt 1.8.276.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: modulepcr.cxx,v $ * $Revision: 1.9 $ * * 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_extensions.hxx" #include "modulepcr.hxx" #ifndef INCLUDED_OSL_DOUBLECHECKEDLOCKING_H #include <rtl/instance.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/getglobalmutex.hxx> #endif //........................................................................ namespace pcr { //........................................................................ IMPLEMENT_MODULE( PcrModule, "pcr" ) //........................................................................ } // namespace pcr //........................................................................ <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2004 Jürgen Riegel <[email protected]> * * Copyright (c) 2012 Luke Parry <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QAction> # include <QMenu> # include <QTimer> #include <QPointer> #include <boost/signal.hpp> #include <boost/bind.hpp> #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Console.h> #include <Base/Parameter.h> #include <Base/Exception.h> #include <Base/Sequencer.h> #include <App/Application.h> #include <App/Document.h> #include <App/DocumentObject.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Document.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/ViewProvider.h> #include <Gui/ViewProviderDocumentObject.h> #include <Gui/ViewProviderDocumentObjectGroup.h> #include "MDIViewPage.h" #include "ViewProviderPage.h" #include <Mod/TechDraw/App/DrawPage.h> #include <Mod/TechDraw/App/DrawView.h> #include <Mod/TechDraw/App/DrawProjGroupItem.h> #include <Mod/TechDraw/App/DrawViewDimension.h> #include <Mod/TechDraw/App/DrawHatch.h> #include <Mod/TechDraw/App/DrawUtil.h> using namespace TechDrawGui; PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject) //************************************************************************** // Construction/Destruction ViewProviderPage::ViewProviderPage() : m_mdiView(0), m_docReady(true) { sPixmap = "TechDraw_Tree_Page"; Visibility.setStatus(App::Property::Hidden,true); DisplayMode.setStatus(App::Property::Hidden,true); } ViewProviderPage::~ViewProviderPage() { } void ViewProviderPage::attach(App::DocumentObject *pcFeat) { ViewProviderDocumentObject::attach(pcFeat); auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1); auto feature = getDrawPage(); if (feature != nullptr) { connectGuiRepaint = feature->signalGuiPaint.connect(bnd); } else { Base::Console().Log("VPP::attach has no Feature!\n"); } } void ViewProviderPage::setDisplayMode(const char* ModeName) { ViewProviderDocumentObject::setDisplayMode(ModeName); } std::vector<std::string> ViewProviderPage::getDisplayModes(void) const { // get the modes of the father std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes(); StrList.push_back("Drawing"); return StrList; } void ViewProviderPage::show(void) { showMDIViewPage(); } void ViewProviderPage::hide(void) { if (!m_mdiView.isNull()) { //m_mdiView is a QPointer // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614 //Gui::getMainWindow()->activatePreviousWindow(); Gui::getMainWindow()->removeWindow(m_mdiView); } ViewProviderDocumentObject::hide(); } void ViewProviderPage::updateData(const App::Property* prop) { if (prop == &(getDrawPage()->KeepUpdated)) { if (getDrawPage()->KeepUpdated.getValue()) { sPixmap = "TechDraw_Tree_Page"; if (!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } else { sPixmap = "TechDraw_Tree_Page_Unsync"; } } //if a view is added/deleted, rebuild the visual if (prop == &(getDrawPage()->Views)) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } //if the template is changed, rebuild the visual } else if (prop == &(getDrawPage()->Template)) { if(m_mdiView && !getDrawPage()->isUnsetting()) { m_mdiView->matchSceneRectToTemplate(); m_mdiView->updateTemplate(); } //if the Label changes, rename the tab } else if (prop == &(getDrawPage()->Label)) { if(m_mdiView) { QString tabTitle = QString::fromUtf8(getDrawPage()->Label.getValue()); m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]")); } } Gui::ViewProviderDocumentObject::updateData(prop); } bool ViewProviderPage::onDelete(const std::vector<std::string> &items) { if (!m_mdiView.isNull()) { Gui::getMainWindow()->removeWindow(m_mdiView); Gui::getMainWindow()->activatePreviousWindow(); m_mdiView->deleteLater(); // Delete the drawing m_mdiView; } else { // MDIViewPage is not displayed yet so don't try to delete it! Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n"); } Gui::Selection().clearSelection(); return ViewProviderDocumentObject::onDelete(items); } void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member); // act->setData(QVariant(1)); // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073 //this is edit ModNum act->setData(QVariant((int) ViewProvider::Default)); } bool ViewProviderPage::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) { showMDIViewPage(); // show the drawing Gui::getMainWindow()->setActiveWindow(m_mdiView); return false; } else { Gui::ViewProviderDocumentObject::setEdit(ModNum); } return true; } bool ViewProviderPage::doubleClicked(void) { showMDIViewPage(); Gui::getMainWindow()->setActiveWindow(m_mdiView); return true; } bool ViewProviderPage::showMDIViewPage() { if (isRestoring()) { return true; } if (m_mdiView.isNull()){ Gui::Document* doc = Gui::Application::Instance->getDocument (pcObject->getDocument()); m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow()); QString tabTitle = QString::fromUtf8(getDrawPage()->getNameInDocument()); m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]")); m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page")); m_mdiView->updateDrawing(true); Gui::getMainWindow()->addWindow(m_mdiView); m_mdiView->viewAll(); } else { m_mdiView->updateDrawing(true); m_mdiView->updateTemplate(true); } return true; } std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const { std::vector<App::DocumentObject*> temp; App::DocumentObject *templateFeat = 0; templateFeat = getDrawPage()->Template.getValue(); if(templateFeat) { temp.push_back(templateFeat); } // Collect any child views // for Page, valid children are any View except: DrawProjGroupItem // DrawViewDimension // any FeatuerView in a DrawViewClip // DrawHatch const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues(); try { for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) { TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it); App::DocumentObject *docObj = *it; // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId()) || (featView && featView->isInClip()) ) continue; else temp.push_back(*it); } return temp; } catch (...) { std::vector<App::DocumentObject*> tmp; return tmp; } } void ViewProviderPage::unsetEdit(int ModNum) { Q_UNUSED(ModNum); static_cast<void>(showMDIViewPage()); return; } MDIViewPage* ViewProviderPage::getMDIViewPage() { if (m_mdiView.isNull()) { Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n"); return 0; } else { return m_mdiView; } } void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg) { if(!m_mdiView.isNull()) { if(msg.Type == Gui::SelectionChanges::SetSelection) { m_mdiView->clearSelection(); std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName); for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { Gui::SelectionSingleton::SelObj selObj = *it; if(selObj.pObject == getDrawPage()) continue; std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me wf: don't think this is ever executed } } else { m_mdiView->selectFeature(selObj.pObject, true); } } } else { bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false; Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument()); App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName); if(obj) { std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me } else { m_mdiView->selectFeature(obj, selectState); } } } } //else (Gui::SelectionChanges::SetPreselect) } } void ViewProviderPage::onChanged(const App::Property *prop) { if (prop == &(getDrawPage()->Template)) { if(m_mdiView) { m_mdiView->updateTemplate(); } } Gui::ViewProviderDocumentObject::onChanged(prop); } void ViewProviderPage::startRestoring() { m_docReady = false; Gui::ViewProviderDocumentObject::startRestoring(); } void ViewProviderPage::finishRestoring() { m_docReady = true; //control drawing opening on restore based on Preference //mantis #2967 ph2 - don't even show blank page Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); bool autoUpdate = hGrp->GetBool("KeepPagesUpToDate", 1l); if (autoUpdate) { static_cast<void>(showMDIViewPage()); } Gui::ViewProviderDocumentObject::finishRestoring(); } bool ViewProviderPage::isShow(void) const { return Visibility.getValue(); } //! Redo the whole visual page void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp) { if (dp == getDrawPage()) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } } TechDraw::DrawPage* ViewProviderPage::getDrawPage() const { //during redo, pcObject can become invalid, but non-zero?? if (!pcObject) { Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n"); return nullptr; } return dynamic_cast<TechDraw::DrawPage*>(pcObject); } <commit_msg>Change removeWindow logic for consistency<commit_after>/*************************************************************************** * Copyright (c) 2004 Jürgen Riegel <[email protected]> * * Copyright (c) 2012 Luke Parry <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QAction> # include <QMenu> # include <QTimer> #include <QPointer> #include <boost/signal.hpp> #include <boost/bind.hpp> #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Console.h> #include <Base/Parameter.h> #include <Base/Exception.h> #include <Base/Sequencer.h> #include <App/Application.h> #include <App/Document.h> #include <App/DocumentObject.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Document.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/ViewProvider.h> #include <Gui/ViewProviderDocumentObject.h> #include <Gui/ViewProviderDocumentObjectGroup.h> #include "MDIViewPage.h" #include "ViewProviderPage.h" #include <Mod/TechDraw/App/DrawPage.h> #include <Mod/TechDraw/App/DrawView.h> #include <Mod/TechDraw/App/DrawProjGroupItem.h> #include <Mod/TechDraw/App/DrawViewDimension.h> #include <Mod/TechDraw/App/DrawHatch.h> #include <Mod/TechDraw/App/DrawUtil.h> using namespace TechDrawGui; PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject) //************************************************************************** // Construction/Destruction ViewProviderPage::ViewProviderPage() : m_mdiView(0), m_docReady(true) { sPixmap = "TechDraw_Tree_Page"; Visibility.setStatus(App::Property::Hidden,true); DisplayMode.setStatus(App::Property::Hidden,true); } ViewProviderPage::~ViewProviderPage() { } void ViewProviderPage::attach(App::DocumentObject *pcFeat) { ViewProviderDocumentObject::attach(pcFeat); auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, _1); auto feature = getDrawPage(); if (feature != nullptr) { connectGuiRepaint = feature->signalGuiPaint.connect(bnd); } else { Base::Console().Log("VPP::attach has no Feature!\n"); } } void ViewProviderPage::setDisplayMode(const char* ModeName) { ViewProviderDocumentObject::setDisplayMode(ModeName); } std::vector<std::string> ViewProviderPage::getDisplayModes(void) const { // get the modes of the father std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes(); StrList.push_back("Drawing"); return StrList; } void ViewProviderPage::show(void) { showMDIViewPage(); } void ViewProviderPage::hide(void) { if (!m_mdiView.isNull()) { //m_mdiView is a QPointer // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614 //Gui::getMainWindow()->activatePreviousWindow(); Gui::getMainWindow()->removeWindow(m_mdiView); } ViewProviderDocumentObject::hide(); } void ViewProviderPage::updateData(const App::Property* prop) { if (prop == &(getDrawPage()->KeepUpdated)) { if (getDrawPage()->KeepUpdated.getValue()) { sPixmap = "TechDraw_Tree_Page"; if (!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } else { sPixmap = "TechDraw_Tree_Page_Unsync"; } } //if a view is added/deleted, rebuild the visual if (prop == &(getDrawPage()->Views)) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } //if the template is changed, rebuild the visual } else if (prop == &(getDrawPage()->Template)) { if(m_mdiView && !getDrawPage()->isUnsetting()) { m_mdiView->matchSceneRectToTemplate(); m_mdiView->updateTemplate(); } //if the Label changes, rename the tab } else if (prop == &(getDrawPage()->Label)) { if(m_mdiView) { QString tabTitle = QString::fromUtf8(getDrawPage()->Label.getValue()); m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]")); } } Gui::ViewProviderDocumentObject::updateData(prop); } bool ViewProviderPage::onDelete(const std::vector<std::string> &items) { if (!m_mdiView.isNull()) { Gui::getMainWindow()->removeWindow(m_mdiView); // Gui::getMainWindow()->activatePreviousWindow(); //changed for consistency. see comment in hide() above. //note: doesn't fix problem here. //3d view is still not maximized after page is deleted. m_mdiView->deleteLater(); // Delete the drawing m_mdiView; } else { // MDIViewPage is not displayed yet so don't try to delete it! Base::Console().Log("INFO - ViewProviderPage::onDelete - Page object deleted when viewer not displayed\n"); } Gui::Selection().clearSelection(); return ViewProviderDocumentObject::onDelete(items); } void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { Gui::ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); QAction* act = menu->addAction(QObject::tr("Show drawing"), receiver, member); // act->setData(QVariant(1)); // Removed to resolve compile after cb16fec6bb67cec15be3fc2aeb251ab524134073 //this is edit ModNum act->setData(QVariant((int) ViewProvider::Default)); } bool ViewProviderPage::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) { showMDIViewPage(); // show the drawing Gui::getMainWindow()->setActiveWindow(m_mdiView); return false; } else { Gui::ViewProviderDocumentObject::setEdit(ModNum); } return true; } bool ViewProviderPage::doubleClicked(void) { showMDIViewPage(); Gui::getMainWindow()->setActiveWindow(m_mdiView); return true; } bool ViewProviderPage::showMDIViewPage() { if (isRestoring()) { return true; } if (m_mdiView.isNull()){ Gui::Document* doc = Gui::Application::Instance->getDocument (pcObject->getDocument()); m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow()); QString tabTitle = QString::fromUtf8(getDrawPage()->getNameInDocument()); m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]")); m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_Tree_Page")); m_mdiView->updateDrawing(true); Gui::getMainWindow()->addWindow(m_mdiView); m_mdiView->viewAll(); } else { m_mdiView->updateDrawing(true); m_mdiView->updateTemplate(true); } return true; } std::vector<App::DocumentObject*> ViewProviderPage::claimChildren(void) const { std::vector<App::DocumentObject*> temp; App::DocumentObject *templateFeat = 0; templateFeat = getDrawPage()->Template.getValue(); if(templateFeat) { temp.push_back(templateFeat); } // Collect any child views // for Page, valid children are any View except: DrawProjGroupItem // DrawViewDimension // any FeatuerView in a DrawViewClip // DrawHatch const std::vector<App::DocumentObject *> &views = getDrawPage()->Views.getValues(); try { for(std::vector<App::DocumentObject *>::const_iterator it = views.begin(); it != views.end(); ++it) { TechDraw::DrawView* featView = dynamic_cast<TechDraw::DrawView*> (*it); App::DocumentObject *docObj = *it; // Don't collect if dimension, projection group item, hatch or member of ClipGroup as these should be grouped elsewhere if(docObj->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) || docObj->isDerivedFrom(TechDraw::DrawHatch::getClassTypeId()) || (featView && featView->isInClip()) ) continue; else temp.push_back(*it); } return temp; } catch (...) { std::vector<App::DocumentObject*> tmp; return tmp; } } void ViewProviderPage::unsetEdit(int ModNum) { Q_UNUSED(ModNum); static_cast<void>(showMDIViewPage()); return; } MDIViewPage* ViewProviderPage::getMDIViewPage() { if (m_mdiView.isNull()) { Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n"); return 0; } else { return m_mdiView; } } void ViewProviderPage::onSelectionChanged(const Gui::SelectionChanges& msg) { if(!m_mdiView.isNull()) { if(msg.Type == Gui::SelectionChanges::SetSelection) { m_mdiView->clearSelection(); std::vector<Gui::SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(msg.pDocName); for (std::vector<Gui::SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { Gui::SelectionSingleton::SelObj selObj = *it; if(selObj.pObject == getDrawPage()) continue; std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me wf: don't think this is ever executed } } else { m_mdiView->selectFeature(selObj.pObject, true); } } } else { bool selectState = (msg.Type == Gui::SelectionChanges::AddSelection) ? true : false; Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument()); App::DocumentObject *obj = doc->getDocument()->getObject(msg.pObjectName); if(obj) { std::string str = msg.pSubName; // If it's a subfeature, don't select feature if (!str.empty()) { if (TechDraw::DrawUtil::getGeomTypeFromName(str) == "Face" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Edge" || TechDraw::DrawUtil::getGeomTypeFromName(str) == "Vertex") { // TODO implement me } else { m_mdiView->selectFeature(obj, selectState); } } } } //else (Gui::SelectionChanges::SetPreselect) } } void ViewProviderPage::onChanged(const App::Property *prop) { if (prop == &(getDrawPage()->Template)) { if(m_mdiView) { m_mdiView->updateTemplate(); } } Gui::ViewProviderDocumentObject::onChanged(prop); } void ViewProviderPage::startRestoring() { m_docReady = false; Gui::ViewProviderDocumentObject::startRestoring(); } void ViewProviderPage::finishRestoring() { m_docReady = true; //control drawing opening on restore based on Preference //mantis #2967 ph2 - don't even show blank page Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); bool autoUpdate = hGrp->GetBool("KeepPagesUpToDate", 1l); if (autoUpdate) { static_cast<void>(showMDIViewPage()); } Gui::ViewProviderDocumentObject::finishRestoring(); } bool ViewProviderPage::isShow(void) const { return Visibility.getValue(); } //! Redo the whole visual page void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp) { if (dp == getDrawPage()) { if(!m_mdiView.isNull() && !getDrawPage()->isUnsetting()) { m_mdiView->updateDrawing(); } } } TechDraw::DrawPage* ViewProviderPage::getDrawPage() const { //during redo, pcObject can become invalid, but non-zero?? if (!pcObject) { Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n"); return nullptr; } return dynamic_cast<TechDraw::DrawPage*>(pcObject); } <|endoftext|>
<commit_before> /* * Copyright (C) 2013 Michael Imamura * * 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 "StdAfx.h" #include <iostream> #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "App.h" #include "Exception.h" using namespace AISDL; /// Initialize each of the SDL subsystems. static void InitApp() { SDL_LogSetAllPriority(SDL_LOG_PRIORITY_INFO); SDL_Log("Starting up all SDL subsystems and libraries."); if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { throw Exception(std::string("SDL init: ") + SDL_GetError()); } int reqFmts = IMG_INIT_JPG | IMG_INIT_PNG; int actualFmts = IMG_Init(reqFmts); if ((actualFmts & reqFmts) != reqFmts) { throw Exception(std::string("SDL_image init: ") + IMG_GetError()); } if (TTF_Init() == -1) { throw Exception(std::string("SDL_ttf init: ") + TTF_GetError()); } } /// Shutdown each of the SDL subsystems. static void ShutdownApp() { TTF_Quit(); IMG_Quit(); SDL_Quit(); } #ifdef _WIN32 int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { #else int main(int argc, char** argv) { #endif srand(static_cast<unsigned int>(time(nullptr))); try { InitApp(); App().Run(); } catch (Exception &ex) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Adventures in SDL2", ex.what(), NULL); std::cerr << ex.what() << std::endl; return 1; } ShutdownApp(); return 0; } <commit_msg>Use simpler Exception constructor.<commit_after> /* * Copyright (C) 2013 Michael Imamura * * 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 "StdAfx.h" #include <iostream> #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include "App.h" #include "Exception.h" using namespace AISDL; /// Initialize each of the SDL subsystems. static void InitApp() { SDL_LogSetAllPriority(SDL_LOG_PRIORITY_INFO); SDL_Log("Starting up all SDL subsystems and libraries."); if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { throw Exception("SDL init", SDL_GetError()); } int reqFmts = IMG_INIT_JPG | IMG_INIT_PNG; int actualFmts = IMG_Init(reqFmts); if ((actualFmts & reqFmts) != reqFmts) { throw Exception("SDL_image init", IMG_GetError()); } if (TTF_Init() == -1) { throw Exception("SDL_ttf init", TTF_GetError()); } } /// Shutdown each of the SDL subsystems. static void ShutdownApp() { TTF_Quit(); IMG_Quit(); SDL_Quit(); } #ifdef _WIN32 int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { #else int main(int argc, char** argv) { #endif srand(static_cast<unsigned int>(time(nullptr))); try { InitApp(); App().Run(); } catch (Exception &ex) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Adventures in SDL2", ex.what(), NULL); std::cerr << ex.what() << std::endl; return 1; } ShutdownApp(); return 0; } <|endoftext|>
<commit_before>#include <tclap/CmdLine.h> #include <llvm/IR/Module.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/Support/TargetSelect.h> #include "utils/util.hpp" #include "utils/error.hpp" #include "lexer.hpp" #include "parser/tokenParser.hpp" #include "llvm/globalTypes.hpp" #include "llvm/compiler.hpp" #include "interpreter/interpreter.hpp" int main(int argc, const char* argv[]) { try { TCLAP::CmdLine cmd("test-lang", ' ', "pre-release"); TCLAP::SwitchArg printTokens("", "tokens", "Print token list", cmd); TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd); TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd); TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd); TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd); std::vector<std::string> runnerValues {"llvm-lli", "llvm-llc", "tree-walk"}; TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues); TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false, "llvm-lli", &runnerConstraint, cmd); TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", true, std::string(), "string", cmd); cmd.parse(argc, argv); auto lx = Lexer(); lx.tokenize(code.getValue()); if (printTokens.getValue()) for (auto tok : lx.getTokens()) println(tok); if (doNotParse.getValue()) return 0; auto px = TokenParser(); px.parse(lx.getTokens()); if (printAST.getValue()) px.getTree().print(); if (doNotRun.getValue()) return 0; if (runner.getValue() == "tree-walk") { auto in = TreeWalkInterpreter(); in.interpret(px.getTree()); return 0; } CompileVisitor::Link v = CompileVisitor::create(globalContext, "Command Line Module", px.getTree()); v->visit(); if (printIR.getValue()) v->getModule()->dump(); if (runner.getValue() == "llvm-lli") { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); std::string onError = ""; auto eb = new llvm::EngineBuilder(v->getModule()); llvm::ExecutionEngine* ee = eb ->setEngineKind(llvm::EngineKind::Interpreter) .setErrorStr(&onError) .create(); auto main = v->getEntryPoint(); if (onError != "") throw InternalError("ExecutionEngine error", { METADATA_PAIRS, {"supplied error string", onError} }); return ee->runFunctionAsMain(main, {}, {}); } else if (runner.getValue() == "llvm-llc") { println("Not yet implemented!"); // TODO } } catch (TCLAP::ArgException& arg) { std::cerr << "TCLAP error " << arg.error() << " for " << arg.argId() << std::endl; } return 0; } <commit_msg>Improved error handling in main<commit_after>#include <tclap/CmdLine.h> #include <llvm/IR/Module.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/Support/TargetSelect.h> #include "utils/util.hpp" #include "utils/error.hpp" #include "lexer.hpp" #include "parser/tokenParser.hpp" #include "llvm/globalTypes.hpp" #include "llvm/compiler.hpp" #include "interpreter/interpreter.hpp" enum ExitCodes: int { NORMAL_EXIT = 0, // Everything is OK TCLAP_ERROR = 11, // TCLAP did something bad, should not happen CLI_ERROR = 1, // The user is retar-- uh I mean the user used a wrong option USER_PROGRAM_ERROR = 2, // The thing we had to lex/parse/run has an issue INTERNAL_ERROR = 3 // Unrecoverable error in this program, almost always a bug }; int main(int argc, const char* argv[]) { try { TCLAP::CmdLine cmd("test-lang", ' ', "pre-release"); TCLAP::SwitchArg printTokens("", "tokens", "Print token list", cmd); TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd); TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd); TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd); TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd); std::vector<std::string> runnerValues {"llvm-lli", "llvm-llc", "tree-walk"}; TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues); TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false, "llvm-lli", &runnerConstraint, cmd); TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", false, std::string(), "string", cmd); TCLAP::ValueArg<std::string> filePath("f", "file", "Load code from this file", false, std::string(), "path", cmd); cmd.parse(argc, argv); if (code.getValue().empty() && filePath.getValue().empty()) { TCLAP::ArgException arg("Must specify either option -e or -f"); cmd.getOutput()->failure(cmd, arg); } auto lx = Lexer(); lx.tokenize(code.getValue()); if (printTokens.getValue()) for (auto tok : lx.getTokens()) println(tok); if (doNotParse.getValue()) return NORMAL_EXIT; auto px = TokenParser(); px.parse(lx.getTokens()); if (printAST.getValue()) px.getTree().print(); if (doNotRun.getValue()) return NORMAL_EXIT; if (runner.getValue() == "tree-walk") { auto in = TreeWalkInterpreter(); in.interpret(px.getTree()); return NORMAL_EXIT; } CompileVisitor::Link v = CompileVisitor::create(globalContext, "Command Line Module", px.getTree()); v->visit(); if (printIR.getValue()) v->getModule()->dump(); if (runner.getValue() == "llvm-lli") { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); std::string onError = ""; auto eb = new llvm::EngineBuilder(v->getModule()); llvm::ExecutionEngine* ee = eb ->setEngineKind(llvm::EngineKind::Interpreter) .setErrorStr(&onError) .create(); auto main = v->getEntryPoint(); if (onError != "") throw InternalError("ExecutionEngine error", { METADATA_PAIRS, {"supplied error string", onError} }); return ee->runFunctionAsMain(main, {}, {}); } else if (runner.getValue() == "llvm-llc") { println("Not yet implemented!"); // TODO } } catch (const TCLAP::ExitException& arg) { return CLI_ERROR; } catch (const TCLAP::ArgException& arg) { println("TCLAP error", arg.error(), "for", arg.argId()); return TCLAP_ERROR; } catch (const Error& err) { println(err.what()); return USER_PROGRAM_ERROR; } catch (const InternalError& err) { println(err.what()); return INTERNAL_ERROR; } return 0; } <|endoftext|>
<commit_before>#include <memory> #include <unistd.h> #include "glload/gl_3_2.h" #include "glload/gll.hpp" #include <GL/glfw.h> #include "config/globals.hpp" #include "scene/scenemanager.hpp" #include "scene/perspectivecamera.hpp" #include "scene/scenegroup.hpp" #include "sceneitems/genericplanet.hpp" //HACK for stupid C-functions. Need to edit GLFW-source scene::PerspectiveCamera* cameraPtr; int main(int argc, char** argv) { glfwInit(); glfwOpenWindowHint(GLFW_FSAA_SAMPLES, config::globals::multiSamples); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindow(config::globals::initialWidth, config::globals::initialHeight, 8, 8, 8, 8, 24, 24, GLFW_WINDOW); glfwSetWindowTitle("Awesome planetary simulation demo"); //Load OpenGL functions if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) { return 1; } //Enable depth test glEnable(GL_DEPTH_TEST); //Backface culling glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); //Set clear colour to black glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //Define world scene::SceneGroup* world = new scene::SceneGroup; cameraPtr = new scene::PerspectiveCamera(world); scene::SceneManager sceneManager(cameraPtr, world); cameraPtr->changeCameraPosition(glm::vec3(20.0f, 0.0f, 150.0f), glm::vec3(0.0f, 0.0f, -1.0f)); cameraPtr->rescale(config::globals::initialWidth, config::globals::initialHeight); //TODO Hack support for lambda's in GLFW glfwSetWindowSizeCallback([](int width, int height) { cameraPtr->rescale(width, height); }); cameraPtr->setKeyPressed(scene::PerspectiveCamera::UP_KEY_PRESSED); glfwSetKeyCallback([](int key, int action) { switch(key) { case GLFW_KEY_UP: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::UP_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_DOWN: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::DOWN_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_LEFT: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::LEFT_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_RIGHT: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::RIGHT_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'W': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::W_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'A': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::A_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'S': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::S_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'D': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::D_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_PAGEUP: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEUP_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_PAGEDOWN: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEDOWN_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; } }); scene::SceneItem* planeta = new sceneitems::GenericPlanet(glm::vec3(0.0f, 0.0f, 0.0f), 16.0f); scene::SceneItem* planetb = new sceneitems::GenericPlanet(glm::vec3(150.0f, 0.0f, -12.0f), 16.0f); scene::SceneItem* planetc = new sceneitems::GenericPlanet(glm::vec3(-35.0f, 45.0f, 0.0f), 20.0f); scene::SceneItem* planetd = new sceneitems::GenericPlanet(glm::vec3(0.0f, -45.0f, 30.0f), 5.0f); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planeta)); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetb)); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetc)); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetd)); //Start main render loop sceneManager.startSceneLoop(); } <commit_msg>Remove odd start movement<commit_after>#include <memory> #include <unistd.h> #include "glload/gl_3_2.h" #include "glload/gll.hpp" #include <GL/glfw.h> #include "config/globals.hpp" #include "scene/scenemanager.hpp" #include "scene/perspectivecamera.hpp" #include "scene/scenegroup.hpp" #include "sceneitems/genericplanet.hpp" //HACK for stupid C-functions. Need to edit GLFW-source scene::PerspectiveCamera* cameraPtr; int main(int argc, char** argv) { glfwInit(); glfwOpenWindowHint(GLFW_FSAA_SAMPLES, config::globals::multiSamples); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindow(config::globals::initialWidth, config::globals::initialHeight, 8, 8, 8, 8, 24, 24, GLFW_WINDOW); glfwSetWindowTitle("Awesome planetary simulation demo"); //Load OpenGL functions if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) { return 1; } //Enable depth test glEnable(GL_DEPTH_TEST); //Backface culling glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); //Set clear colour to black glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //Define world scene::SceneGroup* world = new scene::SceneGroup; cameraPtr = new scene::PerspectiveCamera(world); scene::SceneManager sceneManager(cameraPtr, world); cameraPtr->changeCameraPosition(glm::vec3(20.0f, 0.0f, 150.0f), glm::vec3(0.0f, 0.0f, -1.0f)); cameraPtr->rescale(config::globals::initialWidth, config::globals::initialHeight); //TODO Hack support for lambda's in GLFW glfwSetWindowSizeCallback([](int width, int height) { cameraPtr->rescale(width, height); }); glfwSetKeyCallback([](int key, int action) { switch(key) { case GLFW_KEY_UP: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::UP_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_DOWN: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::DOWN_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_LEFT: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::LEFT_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_RIGHT: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::RIGHT_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'W': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::W_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'A': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::A_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'S': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::S_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case 'D': if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::D_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_PAGEUP: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEUP_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; case GLFW_KEY_PAGEDOWN: if(action == GLFW_PRESS) { cameraPtr->setKeyPressed(scene::PerspectiveCamera::PAGEDOWN_KEY_PRESSED); } else { cameraPtr->setKeyPressed(scene::PerspectiveCamera::NO_KEY_PRESSED); } break; } }); scene::SceneItem* planeta = new sceneitems::GenericPlanet(glm::vec3(0.0f, 0.0f, 0.0f), 16.0f); scene::SceneItem* planetb = new sceneitems::GenericPlanet(glm::vec3(150.0f, 0.0f, -12.0f), 16.0f); scene::SceneItem* planetc = new sceneitems::GenericPlanet(glm::vec3(-35.0f, 45.0f, 0.0f), 20.0f); scene::SceneItem* planetd = new sceneitems::GenericPlanet(glm::vec3(0.0f, -45.0f, 30.0f), 5.0f); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planeta)); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetb)); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetc)); sceneManager.addItem(std::unique_ptr<scene::SceneItem>(planetd)); //Start main render loop sceneManager.startSceneLoop(); } <|endoftext|>
<commit_before>/* main.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer */ #include <algorithm> #include <cassert> #include <chrono> #include <ctime> #include <future> #include <iostream> #include <thread> #include "algorithm/algorithm.hpp" #include "individual/individual.hpp" #include "problem/problem.hpp" #include "random_generator/random_generator.hpp" int main() { using individual::Individual; using namespace problem; const Problem problem{get_data(), 64, 128, 3, 3}; const int trials = 16; int trial = 0; const unsigned long hardware_threads = std::thread::hardware_concurrency(); const unsigned long blocks = hardware_threads != 0 ? hardware_threads : 2; assert(trials % blocks == 0); std::vector<Individual> candidates; std::chrono::time_point<std::chrono::system_clock> start, end; // begin timing trials std::time_t time = std::time(nullptr); start = std::chrono::system_clock::now(); // spawn trials number of threads in blocks for (unsigned long t = 0; t < trials / blocks; ++t) { std::vector<std::future<const Individual>> results; for (unsigned long i = 0; i < blocks; ++i) results.emplace_back(std::async(std::launch::async, algorithm::genetic, problem, time, ++trial)); // gather results for (std::future<const Individual> & result : results) candidates.emplace_back(result.get()); } // end timing trials end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; const Individual best = *std::min_element(candidates.begin(), candidates.end(), algorithm::compare_fitness); std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n" << "Average time: " << elapsed_seconds.count() / trials << "s\n" << best.print(); } <commit_msg>Outputting which trial was best<commit_after>/* main.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer */ #include <algorithm> #include <cassert> #include <chrono> #include <ctime> #include <future> #include <iostream> #include <thread> #include "algorithm/algorithm.hpp" #include "individual/individual.hpp" #include "problem/problem.hpp" #include "random_generator/random_generator.hpp" int main() { using individual::Individual; using namespace problem; const Problem problem{get_data(), 64, 128, 3, 3}; const int trials = 16; int trial = 0; const unsigned long hardware_threads = std::thread::hardware_concurrency(); const unsigned long blocks = hardware_threads != 0 ? hardware_threads : 2; assert(trials % blocks == 0); std::vector<Individual> candidates; std::chrono::time_point<std::chrono::system_clock> start, end; // begin timing trials std::time_t time = std::time(nullptr); start = std::chrono::system_clock::now(); // spawn trials number of threads in blocks for (unsigned long t = 0; t < trials / blocks; ++t) { std::vector<std::future<const Individual>> results; for (unsigned long i = 0; i < blocks; ++i) results.emplace_back(std::async(std::launch::async, algorithm::genetic, problem, time, ++trial)); // gather results for (std::future<const Individual> & result : results) candidates.emplace_back(result.get()); } // end timing trials end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::vector<Individual>::iterator best = std::min_element(candidates.begin(), candidates.end(), algorithm::compare_fitness); std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n" << "Average time: " << elapsed_seconds.count() / trials << "s\n" << "Best trial: " << time << "_" << std::distance(candidates.begin(), best) + 1 << "\n" << best->print(); } <|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. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "mitkITKDICOMSeriesReaderHelper.h" #include "mitkITKDICOMSeriesReaderHelper.txx" #define switch3DCase(IOType, T) \ case IOType: return LoadDICOMByITK< T >(filenames, correctTilt, tiltInfo, io); bool mitk::ITKDICOMSeriesReaderHelper ::CanHandleFile(const std::string& filename) { MITK_DEBUG << "ITKDICOMSeriesReaderHelper::CanHandleFile " << filename; itk::GDCMImageIO::Pointer tester = itk::GDCMImageIO::New(); if ( tester->CanReadFile(filename.c_str()) ) { tester->SetFileName( filename.c_str() ); tester->ReadImageInformation(); std::string numberOfFrames; if (tester->GetValueFromTag("0028|0008", numberOfFrames)) { std::istringstream converter(numberOfFrames); int i; if (converter >> i) { MITK_DEBUG << "Number of Frames for " << filename << ": " << numberOfFrames; return (i <= 1); // cannot handle multi-frame } else { return true; // we assume single-frame } } else { MITK_DEBUG << "No Number of Frames tag for " << filename; // friendly old single-frame file return true; } } MITK_DEBUG << "GDCMImageIO found: No DICOM in " << filename; // does not seem to be DICOM return false; } mitk::Image::Pointer mitk::ITKDICOMSeriesReaderHelper ::Load( const StringContainer& filenames, bool correctTilt, const GantryTiltInformation& tiltInfo ) { if( filenames.empty() ) { MITK_DEBUG << "Calling LoadDicomSeries with empty filename string container. Probably invalid application logic."; return NULL; // this is not actually an error but the result is very simple } typedef itk::GDCMImageIO DcmIoType; DcmIoType::Pointer io = DcmIoType::New(); try { if (io->CanReadFile(filenames.front().c_str())) { io->SetFileName(filenames.front().c_str()); io->ReadImageInformation(); if (io->GetPixelType() == itk::ImageIOBase::SCALAR) { switch (io->GetComponentType()) { switch3DCase(DcmIoType::UCHAR, unsigned char) switch3DCase(DcmIoType::CHAR, char) switch3DCase(DcmIoType::USHORT, unsigned short) switch3DCase(DcmIoType::SHORT, short) switch3DCase(DcmIoType::UINT, unsigned int) switch3DCase(DcmIoType::INT, int) switch3DCase(DcmIoType::ULONG, long unsigned int) switch3DCase(DcmIoType::LONG, long int) switch3DCase(DcmIoType::FLOAT, float) switch3DCase(DcmIoType::DOUBLE, double) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } else if (io->GetPixelType() == itk::ImageIOBase::RGB) { switch (io->GetComponentType()) { switch3DCase(DcmIoType::UCHAR, itk::RGBPixel<unsigned char>) switch3DCase(DcmIoType::CHAR, itk::RGBPixel<char>) switch3DCase(DcmIoType::USHORT, itk::RGBPixel<unsigned short>) switch3DCase(DcmIoType::SHORT, itk::RGBPixel<short>) switch3DCase(DcmIoType::UINT, itk::RGBPixel<unsigned int>) switch3DCase(DcmIoType::INT, itk::RGBPixel<int>) switch3DCase(DcmIoType::ULONG, itk::RGBPixel<long unsigned int>) switch3DCase(DcmIoType::LONG, itk::RGBPixel<long int>) switch3DCase(DcmIoType::FLOAT, itk::RGBPixel<float>) switch3DCase(DcmIoType::DOUBLE, itk::RGBPixel<double>) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } MITK_ERROR << "Unsupported DICOM pixel type"; return NULL; } } catch(itk::MemoryAllocationError& e) { MITK_ERROR << "Out of memory. Cannot load DICOM series: " << e.what(); } catch(std::exception& e) { MITK_ERROR << "Error encountered when loading DICOM series:" << e.what(); } catch(...) { MITK_ERROR << "Unspecified error encountered when loading DICOM series."; } return NULL; } #define switch3DnTCase(IOType, T) \ case IOType: return LoadDICOMByITK3DnT< T >(filenamesLists, correctTilt, tiltInfo, io); mitk::Image::Pointer mitk::ITKDICOMSeriesReaderHelper ::Load3DnT( const StringContainerList& filenamesLists, bool correctTilt, const GantryTiltInformation& tiltInfo ) { if( filenamesLists.empty() || filenamesLists.front().empty() ) { MITK_DEBUG << "Calling LoadDicomSeries with empty filename string container. Probably invalid application logic."; return NULL; // this is not actually an error but the result is very simple } typedef itk::GDCMImageIO DcmIoType; DcmIoType::Pointer io = DcmIoType::New(); try { if (io->CanReadFile(filenamesLists.front().front().c_str())) { io->SetFileName(filenamesLists.front().front().c_str()); io->ReadImageInformation(); if (io->GetPixelType() == itk::ImageIOBase::SCALAR) { switch (io->GetComponentType()) { switch3DnTCase(DcmIoType::UCHAR, unsigned char) switch3DnTCase(DcmIoType::CHAR, char) switch3DnTCase(DcmIoType::USHORT, unsigned short) switch3DnTCase(DcmIoType::SHORT, short) switch3DnTCase(DcmIoType::UINT, unsigned int) switch3DnTCase(DcmIoType::INT, int) switch3DnTCase(DcmIoType::ULONG, long unsigned int) switch3DnTCase(DcmIoType::LONG, long int) switch3DnTCase(DcmIoType::FLOAT, float) switch3DnTCase(DcmIoType::DOUBLE, double) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } else if (io->GetPixelType() == itk::ImageIOBase::RGB) { switch (io->GetComponentType()) { switch3DnTCase(DcmIoType::UCHAR, itk::RGBPixel<unsigned char>) switch3DnTCase(DcmIoType::CHAR, itk::RGBPixel<char>) switch3DnTCase(DcmIoType::USHORT, itk::RGBPixel<unsigned short>) switch3DnTCase(DcmIoType::SHORT, itk::RGBPixel<short>) switch3DnTCase(DcmIoType::UINT, itk::RGBPixel<unsigned int>) switch3DnTCase(DcmIoType::INT, itk::RGBPixel<int>) switch3DnTCase(DcmIoType::ULONG, itk::RGBPixel<long unsigned int>) switch3DnTCase(DcmIoType::LONG, itk::RGBPixel<long int>) switch3DnTCase(DcmIoType::FLOAT, itk::RGBPixel<float>) switch3DnTCase(DcmIoType::DOUBLE, itk::RGBPixel<double>) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } MITK_ERROR << "Unsupported DICOM pixel type"; return NULL; } } catch(itk::MemoryAllocationError& e) { MITK_ERROR << "Out of memory. Cannot load DICOM series: " << e.what(); } catch(std::exception& e) { MITK_ERROR << "Error encountered when loading DICOM series:" << e.what(); } catch(...) { MITK_ERROR << "Unspecified error encountered when loading DICOM series."; } return NULL; } <commit_msg>removed unnecessary check that prevented multiframe support<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. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "mitkITKDICOMSeriesReaderHelper.h" #include "mitkITKDICOMSeriesReaderHelper.txx" #define switch3DCase(IOType, T) \ case IOType: return LoadDICOMByITK< T >(filenames, correctTilt, tiltInfo, io); bool mitk::ITKDICOMSeriesReaderHelper ::CanHandleFile(const std::string& filename) { MITK_DEBUG << "ITKDICOMSeriesReaderHelper::CanHandleFile " << filename; itk::GDCMImageIO::Pointer tester = itk::GDCMImageIO::New(); return tester->CanReadFile(filename.c_str()); } mitk::Image::Pointer mitk::ITKDICOMSeriesReaderHelper ::Load( const StringContainer& filenames, bool correctTilt, const GantryTiltInformation& tiltInfo ) { if( filenames.empty() ) { MITK_DEBUG << "Calling LoadDicomSeries with empty filename string container. Probably invalid application logic."; return NULL; // this is not actually an error but the result is very simple } typedef itk::GDCMImageIO DcmIoType; DcmIoType::Pointer io = DcmIoType::New(); try { if (io->CanReadFile(filenames.front().c_str())) { io->SetFileName(filenames.front().c_str()); io->ReadImageInformation(); if (io->GetPixelType() == itk::ImageIOBase::SCALAR) { switch (io->GetComponentType()) { switch3DCase(DcmIoType::UCHAR, unsigned char) switch3DCase(DcmIoType::CHAR, char) switch3DCase(DcmIoType::USHORT, unsigned short) switch3DCase(DcmIoType::SHORT, short) switch3DCase(DcmIoType::UINT, unsigned int) switch3DCase(DcmIoType::INT, int) switch3DCase(DcmIoType::ULONG, long unsigned int) switch3DCase(DcmIoType::LONG, long int) switch3DCase(DcmIoType::FLOAT, float) switch3DCase(DcmIoType::DOUBLE, double) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } else if (io->GetPixelType() == itk::ImageIOBase::RGB) { switch (io->GetComponentType()) { switch3DCase(DcmIoType::UCHAR, itk::RGBPixel<unsigned char>) switch3DCase(DcmIoType::CHAR, itk::RGBPixel<char>) switch3DCase(DcmIoType::USHORT, itk::RGBPixel<unsigned short>) switch3DCase(DcmIoType::SHORT, itk::RGBPixel<short>) switch3DCase(DcmIoType::UINT, itk::RGBPixel<unsigned int>) switch3DCase(DcmIoType::INT, itk::RGBPixel<int>) switch3DCase(DcmIoType::ULONG, itk::RGBPixel<long unsigned int>) switch3DCase(DcmIoType::LONG, itk::RGBPixel<long int>) switch3DCase(DcmIoType::FLOAT, itk::RGBPixel<float>) switch3DCase(DcmIoType::DOUBLE, itk::RGBPixel<double>) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } MITK_ERROR << "Unsupported DICOM pixel type"; return NULL; } } catch(itk::MemoryAllocationError& e) { MITK_ERROR << "Out of memory. Cannot load DICOM series: " << e.what(); } catch(std::exception& e) { MITK_ERROR << "Error encountered when loading DICOM series:" << e.what(); } catch(...) { MITK_ERROR << "Unspecified error encountered when loading DICOM series."; } return NULL; } #define switch3DnTCase(IOType, T) \ case IOType: return LoadDICOMByITK3DnT< T >(filenamesLists, correctTilt, tiltInfo, io); mitk::Image::Pointer mitk::ITKDICOMSeriesReaderHelper ::Load3DnT( const StringContainerList& filenamesLists, bool correctTilt, const GantryTiltInformation& tiltInfo ) { if( filenamesLists.empty() || filenamesLists.front().empty() ) { MITK_DEBUG << "Calling LoadDicomSeries with empty filename string container. Probably invalid application logic."; return NULL; // this is not actually an error but the result is very simple } typedef itk::GDCMImageIO DcmIoType; DcmIoType::Pointer io = DcmIoType::New(); try { if (io->CanReadFile(filenamesLists.front().front().c_str())) { io->SetFileName(filenamesLists.front().front().c_str()); io->ReadImageInformation(); if (io->GetPixelType() == itk::ImageIOBase::SCALAR) { switch (io->GetComponentType()) { switch3DnTCase(DcmIoType::UCHAR, unsigned char) switch3DnTCase(DcmIoType::CHAR, char) switch3DnTCase(DcmIoType::USHORT, unsigned short) switch3DnTCase(DcmIoType::SHORT, short) switch3DnTCase(DcmIoType::UINT, unsigned int) switch3DnTCase(DcmIoType::INT, int) switch3DnTCase(DcmIoType::ULONG, long unsigned int) switch3DnTCase(DcmIoType::LONG, long int) switch3DnTCase(DcmIoType::FLOAT, float) switch3DnTCase(DcmIoType::DOUBLE, double) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } else if (io->GetPixelType() == itk::ImageIOBase::RGB) { switch (io->GetComponentType()) { switch3DnTCase(DcmIoType::UCHAR, itk::RGBPixel<unsigned char>) switch3DnTCase(DcmIoType::CHAR, itk::RGBPixel<char>) switch3DnTCase(DcmIoType::USHORT, itk::RGBPixel<unsigned short>) switch3DnTCase(DcmIoType::SHORT, itk::RGBPixel<short>) switch3DnTCase(DcmIoType::UINT, itk::RGBPixel<unsigned int>) switch3DnTCase(DcmIoType::INT, itk::RGBPixel<int>) switch3DnTCase(DcmIoType::ULONG, itk::RGBPixel<long unsigned int>) switch3DnTCase(DcmIoType::LONG, itk::RGBPixel<long int>) switch3DnTCase(DcmIoType::FLOAT, itk::RGBPixel<float>) switch3DnTCase(DcmIoType::DOUBLE, itk::RGBPixel<double>) default: MITK_ERROR << "Found unsupported DICOM scalar pixel type: (enum value) " << io->GetComponentType(); } } MITK_ERROR << "Unsupported DICOM pixel type"; return NULL; } } catch(itk::MemoryAllocationError& e) { MITK_ERROR << "Out of memory. Cannot load DICOM series: " << e.what(); } catch(std::exception& e) { MITK_ERROR << "Error encountered when loading DICOM series:" << e.what(); } catch(...) { MITK_ERROR << "Unspecified error encountered when loading DICOM series."; } return NULL; } <|endoftext|>
<commit_before>#include <chrono> #include <iostream> #include <vector> #include <armadillo> using std::chrono::high_resolution_clock; using std::chrono::duration; namespace { uint32_t num = 1; uint32_t fft_size = 48000; uint32_t conv_ir_size = 72000; uint32_t conv_sig_size = 5760000; } duration<double> Convolution(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::fvec output (sig_size+ir_size-1); auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { for (uint32_t sample_cnt=0;sample_cnt<sig_size;++sample_cnt) { for (uint32_t ir_cnt=0;ir_cnt<ir_size;++ir_cnt) { output[sample_cnt] += sig[sample_cnt+ir_cnt] * ir[ir_cnt]; } } } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloConv(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::conv(sig, ir); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFftConv(uint32_t ir_size, uint32_t sig_size) { arma::fvec sig {arma::randn<arma::fvec>(sig_size+ir_size-1)}; sig.subvec(sig_size,sig_size+ir_size-2) = arma::zeros<arma::fvec>(ir_size-1); arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig) % arma::fft(ir,sig_size+ir_size-1)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFftPow2Conv(uint32_t ir_size, uint32_t sig_size) { uint32_t size = pow(2,ceil(log2(sig_size+ir_size-1))); arma::fvec sig {arma::randn<arma::fvec>(sig_size)}; arma::fvec ir {arma::randn<arma::fvec>(ir_size)}; arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig,size) % arma::fft(ir,size)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return end - begin; } duration<double> ArmadilloFft(uint32_t fft_size) { arma::fvec input {arma::randn<arma::fvec>(fft_size)}; arma::cx_fvec output_fd; arma::cx_fvec output_td; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output_fd = arma::fft(input); output_td = arma::ifft(output_fd); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output_td)); auto end = high_resolution_clock::now(); return end - begin; } int main(int argc, char* argv[]) { auto arma_fft_time = ArmadilloFft(::fft_size); std::cout << "Armadillo FFT: " << arma_fft_time.count() << std::endl; auto arma_fft_pow2_conv_time = ArmadilloFftPow2Conv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo FFT-Pow2-convolution: " << arma_fft_pow2_conv_time.count() << std::endl; auto arma_fft_conv_time = ArmadilloFftConv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo FFT-convolution: " << arma_fft_conv_time.count() << std::endl; auto arma_conv_time = ArmadilloConv(::conv_ir_size, ::conv_sig_size); std::cout << "Armadillo convolution: " << arma_conv_time.count() << std::endl; auto conv_time = Convolution(::conv_ir_size, ::conv_sig_size); std::cout << "convolution: " << conv_time.count() << std::endl; } <commit_msg>fix convolution calculation, compare results<commit_after>#include <chrono> #include <iostream> #include <vector> #include <utility> // std::pair #include <armadillo> using std::chrono::high_resolution_clock; using std::chrono::duration; namespace { uint32_t num = 1; uint32_t fft_size = 48000; uint32_t conv_ir_size = 72000; uint32_t conv_sig_size = 5760000; } std::pair<duration<double>, arma::fvec> Convolution(arma::fvec sig, arma::fvec ir) { size_t size = (::conv_sig_size+::conv_ir_size-1); ir = arma::flipud(ir); arma::fvec sig_new = arma::zeros<arma::fvec>(::conv_sig_size + 2*(::conv_ir_size-1)); sig_new.subvec(::conv_ir_size - 1, ::conv_sig_size + ::conv_ir_size -2) = sig; arma::fvec output (::conv_sig_size + ::conv_ir_size - 1, arma::fill::zeros); auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { for (uint32_t sample_cnt=0;sample_cnt<size;++sample_cnt) { for (uint32_t ir_cnt=0;ir_cnt<::conv_ir_size;++ir_cnt) { output[sample_cnt] += sig_new[sample_cnt+ir_cnt] * ir[ir_cnt]; } } } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return std::make_pair(end - begin, output); } std::pair<duration<double>, arma::fvec> ArmadilloConv(arma::fvec sig, arma::fvec ir) { arma::fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::conv(sig, ir); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(output); auto end = high_resolution_clock::now(); return std::make_pair(end - begin, output); } std::pair<duration<double>, arma::fvec> ArmadilloFftConv(arma::fvec sig, arma::fvec ir) { arma::cx_fvec output; size_t size = sig.size() + ir.size() - 1; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig, size) % arma::fft(ir, size)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return std::make_pair(end - begin, arma::real(output)); } std::pair<duration<double>, arma::fvec> ArmadilloFftPow2Conv(arma::fvec sig, arma::fvec ir) { uint32_t size = pow(2,ceil(log2(::conv_sig_size + ::conv_ir_size - 1))); arma::cx_fvec output; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output = arma::ifft(arma::fft(sig,size) % arma::fft(ir,size)); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output)); auto end = high_resolution_clock::now(); return std::make_pair(end - begin, arma::real(output.subvec(0, ::conv_sig_size + ::conv_ir_size - 2))); } std::pair<duration<double>,arma::fvec> ArmadilloFft(arma::fvec input) { arma::cx_fvec output_fd; arma::cx_fvec output_td; auto begin = high_resolution_clock::now(); for (uint32_t cnt=0;cnt<::num;++cnt) { output_fd = arma::fft(input); output_td = arma::ifft(output_fd); } std::vector<float> output_copy = arma::conv_to<std::vector<float>>::from(arma::real(output_td)); auto end = high_resolution_clock::now(); return std::make_pair(end - begin,arma::real(output_td)); } int main(int argc, char* argv[]) { // generate input signals arma::fvec sig {arma::randn<arma::fvec>(::conv_sig_size)}; arma::fvec ir {arma::randn<arma::fvec>(::conv_ir_size)}; auto result_arma_fft = ArmadilloFft(sig); std::cout << "Armadillo FFT: " << result_arma_fft.first.count() << std::endl; // normal convolution, this is our reference output auto result_conv = Convolution(sig, ir); std::cout << "convolution: " << result_conv.first.count() << std::endl; auto result_arma_fft_pow2_conv = ArmadilloFftPow2Conv(sig, ir); std::cout << "Armadillo FFT-Pow2-convolution: " << result_arma_fft_pow2_conv.first.count() << "\n\tmaximum difference of result: " << arma::abs(result_conv.second - result_arma_fft_pow2_conv.second).max() << std::endl; auto result_arma_fft_conv = ArmadilloFftConv(sig, ir); std::cout << "Armadillo FFT-convolution: " << result_arma_fft_conv.first.count() << "\n\tmaximum difference of result: " << arma::abs(result_conv.second - result_arma_fft_conv.second).max() << std::endl; auto result_arma_conv = ArmadilloConv(sig, ir); std::cout << "Armadillo convolution: " << result_arma_conv.first.count() << "\n\tmaximum difference of result: " << arma::abs(result_conv.second - result_arma_conv.second).max() << std::endl; } <|endoftext|>
<commit_before>#include <iostream> #include <queue> #include <sys/wait.h> #include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "Shell.h" #include "Input.h" using namespace std; int main() { Input in; // while(1) { in.getInput(); queue<string> tasks = in.Parse(); char** c; while (tasks.size() != 0) { c = in.toChar(tasks.front()); tasks.pop(); } pid_t pid = fork(); if (pid == 0) { // cout << "child: " << pid << endl; if (execvp(c[0], c) == -1) { perror("exec"); exit(0); } } if (pid > 0) { if ( wait(0) == 1 ) { perror("wait"); } // cout << "parent: " << pid << endl; } // int i = 0; // while (c[i] != '\0') { // cout << c[i] << endl; // ++i; // } // in.getInput(); cout << flush; delete c; // } return 0; } <commit_msg>moved execute into loop<commit_after>#include <iostream> #include <queue> #include <sys/wait.h> #include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "Shell.h" #include "Input.h" using namespace std; int main() { Input in; // while(1) { in.getInput(); queue<string> tasks = in.Parse(); char** c; Execute ex; while (tasks.size() != 0) { c = in.toChar(tasks.front()); ex.execute(c); tasks.pop(); } // Execute ex; // ex.execute(c); // int i = 0; // while (c[i] != '\0') { // cout << c[i] << endl; // ++i; // } // in.getInput(); cout << flush; delete c; // } return 0; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkProcessObject.h" #include "itkSmartPointerForwardReference.txx" #include "itkRealTimeClock.h" #include "itkTemporalDataObject.h" // Manual instantiation is necessary to prevent link errors template class itk::SmartPointerForwardReference< itk::ProcessObject >; namespace itk { //---------------------------------------------------------------------------- TemporalDataObject::TemporalDataObject() : m_LargestPossibleTemporalRegion(), m_RequestedTemporalRegion(), m_BufferedTemporalRegion(), m_TemporalUnit(Frame) { m_DataObjectBuffer = BufferType::New(); } //---------------------------------------------------------------------------- TemporalDataObject ::~TemporalDataObject() {} //---------------------------------------------------------------------------- const TemporalDataObject::TemporalRegionType TemporalDataObject ::GetUnbufferedRequestedTemporalRegion() { // Get the start and end of the buffered and requested temporal regions unsigned long reqStart = m_RequestedTemporalRegion.GetFrameStart(); unsigned long reqEnd = m_RequestedTemporalRegion.GetFrameStart() + m_RequestedTemporalRegion.GetFrameDuration() - 1; unsigned long bufStart = m_BufferedTemporalRegion.GetFrameStart(); unsigned long bufEnd = m_BufferedTemporalRegion.GetFrameStart() + m_BufferedTemporalRegion.GetFrameDuration() - 1; //DEBUG std::cout << "req start: " << reqStart << " req end: " << reqEnd << std::endl; std::cout << "buf start: " << bufStart << " buf end: " << bufEnd << std::endl; // Handle case with unbuffered frames at beginning and end if (reqStart < bufStart && reqEnd > bufEnd) { itkDebugMacro(<< "Unbuffered frames at beginning and end. Returning entire " << "requested region as unbuffered"); return this->m_RequestedTemporalRegion; } // Handle case with unbuffered frames at end -- TODO: FIX FOR REAL TIME!!!!! else if(reqEnd > bufEnd) { TemporalRegionType out; out.SetFrameStart(bufEnd + 1); out.SetFrameDuration(reqEnd - bufEnd); return out; } // Handle case with unbuffered frames at beginning -- TODO: FIX FOR REAL TIME!!!!! else if(reqStart < bufStart) { TemporalRegionType out; out.SetFrameStart(reqStart); out.SetFrameDuration(bufStart - reqStart); return out; } // Otherwise, nothing unbuffered else { TemporalRegionType out; out.SetFrameStart(0); out.SetFrameDuration(0); return out; } } //---------------------------------------------------------------------------- void TemporalDataObject ::SetRequestedRegionToLargestPossibleRegion() { this->SetRequestedTemporalRegion( this->GetLargestPossibleTemporalRegion() ); } //---------------------------------------------------------------------------- bool TemporalDataObject ::RequestedRegionIsOutsideOfTheBufferedRegion() { bool frameFlag = m_RequestedTemporalRegion.GetFrameStart() < m_BufferedTemporalRegion.GetFrameStart(); frameFlag |= m_RequestedTemporalRegion.GetFrameDuration() > m_BufferedTemporalRegion.GetFrameDuration(); bool realTimeFlag = m_RequestedTemporalRegion.GetRealStart() < m_BufferedTemporalRegion.GetRealStart(); realTimeFlag |= m_RequestedTemporalRegion.GetRealDuration() > m_BufferedTemporalRegion.GetRealDuration(); switch( m_TemporalUnit ) { case Frame: { return frameFlag; } case RealTime: { return realTimeFlag; } case FrameAndRealTime: { return frameFlag || realTimeFlag; } default: itkExceptionMacro( << "itk::TemporalDataObject::" << "RequestedRegionIsOutsideOfTheBufferedRegion() " << "Invalid Temporal Unit" ); return true; } } //---------------------------------------------------------------------------- bool TemporalDataObject ::VerifyRequestedRegion() { bool frameFlag = m_RequestedTemporalRegion.GetFrameStart() >= m_LargestPossibleTemporalRegion.GetFrameStart(); frameFlag &= m_RequestedTemporalRegion.GetFrameDuration() <= m_LargestPossibleTemporalRegion.GetFrameDuration(); bool realTimeFlag = m_RequestedTemporalRegion.GetRealStart() >= m_LargestPossibleTemporalRegion.GetRealStart(); realTimeFlag &= m_RequestedTemporalRegion.GetRealDuration() <= m_LargestPossibleTemporalRegion.GetRealDuration(); switch( m_TemporalUnit ) { case Frame: { return frameFlag; } case RealTime: { return realTimeFlag; } case FrameAndRealTime: { return frameFlag && realTimeFlag; } default: itkExceptionMacro( << "itk::TemporalDataObject::VerifyRequestedRegion() " << "Invalid Temporal Unit" ); return false; } } //---------------------------------------------------------------------------- void TemporalDataObject ::CopyInformation(const DataObject *data) { // Standard call to the superclass' method Superclass::CopyInformation(data); const TemporalDataObject* temporalData; temporalData = dynamic_cast< const TemporalDataObject* >( data ); if ( temporalData ) { // Copy the meta data for this data type this->SetLargestPossibleTemporalRegion( temporalData->GetLargestPossibleTemporalRegion() ); for( unsigned int i = 0; i < this->m_DataObjectBuffer->GetNumberOfBuffers(); ++i ) { if( this->m_DataObjectBuffer->BufferIsFull(i) ) { m_DataObjectBuffer->GetBufferContents(i)->CopyInformation( temporalData->m_DataObjectBuffer->GetBufferContents(i) ); } } } else { // pointer could not be cast back down itkExceptionMacro( << "itk::TemporalDataObject::CopyInformation() " << "cannot cast " << typeid( data ).name() << " to " << typeid( const TemporalDataObject* ).name() ); } } //---------------------------------------------------------------------------- void TemporalDataObject ::Graft(const DataObject *data) { const TemporalDataObject* temporalData; temporalData = dynamic_cast< const TemporalDataObject* >( data ); if( temporalData ) { // Copy the meta-information this->CopyInformation( temporalData ); this->SetBufferedTemporalRegion( temporalData->GetBufferedTemporalRegion() ); this->SetRequestedTemporalRegion( temporalData->GetRequestedTemporalRegion() ); for( unsigned int i = 0; i < this->m_DataObjectBuffer->GetNumberOfBuffers(); ++i ) { if( this->m_DataObjectBuffer->BufferIsFull(i) ) { m_DataObjectBuffer->GetBufferContents(i)->Graft( temporalData->m_DataObjectBuffer->GetBufferContents(i) ); } } } else { // pointer could not be cast back down itkExceptionMacro( << "itk::TemporalDataObject::Graft() " << "cannot cast " << typeid( data ).name() << " to " << typeid( const TemporalDataObject* ).name() ); } } //---------------------------------------------------------------------------- void TemporalDataObject ::SetRequestedRegion(DataObject *data) { TemporalDataObject *temporalData; temporalData = dynamic_cast< TemporalDataObject * >( data ); if ( temporalData ) { // only copy the RequestedTemporalRegion if the parameter object is // a temporal data object this->SetRequestedTemporalRegion( temporalData->GetRequestedTemporalRegion() ); for( unsigned int i = 0; i < this->m_DataObjectBuffer->GetNumberOfBuffers(); ++i ) { if( this->m_DataObjectBuffer->BufferIsFull(i) ) { m_DataObjectBuffer->GetBufferContents(i)->SetRequestedRegion( temporalData->m_DataObjectBuffer->GetBufferContents(i) ); } } } else { // pointer could not be cast back down itkExceptionMacro( << "itk::TemporalDataObject:SetRequestedRegion() " << "cannot cast " << typeid( data ).name() << " to " << typeid( const TemporalDataObject* ).name() ); } } //---------------------------------------------------------------------------- void TemporalDataObject ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Data Object Buffer: " << m_DataObjectBuffer.GetPointer() << std::endl; os << indent << "LargestPossibleTemporalRegion: " << std::endl; this->GetLargestPossibleTemporalRegion().Print( os, indent.GetNextIndent() ); os << indent << "BufferedTemporalRegion: " << std::endl; this->GetBufferedTemporalRegion().Print( os, indent.GetNextIndent() ); os << indent << "RequestedTemporalRegion: " << std::endl; this->GetRequestedTemporalRegion().Print( os, indent.GetNextIndent() ); } } // end namespace itk <commit_msg>ENH: Fix calculations for unbuffered region<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkProcessObject.h" #include "itkSmartPointerForwardReference.txx" #include "itkRealTimeClock.h" #include "itkTemporalDataObject.h" // Manual instantiation is necessary to prevent link errors template class itk::SmartPointerForwardReference< itk::ProcessObject >; namespace itk { //---------------------------------------------------------------------------- TemporalDataObject::TemporalDataObject() : m_LargestPossibleTemporalRegion(), m_RequestedTemporalRegion(), m_BufferedTemporalRegion(), m_TemporalUnit(Frame) { m_DataObjectBuffer = BufferType::New(); } //---------------------------------------------------------------------------- TemporalDataObject ::~TemporalDataObject() {} //---------------------------------------------------------------------------- const TemporalDataObject::TemporalRegionType TemporalDataObject ::GetUnbufferedRequestedTemporalRegion() { // If nothing is buffered or nothing is requested, just return the entire request if (m_BufferedTemporalRegion.GetFrameDuration() == 0 || m_RequestedTemporalRegion.GetFrameDuration() == 0) { return m_RequestedTemporalRegion; } // Get the start and end of the buffered and requested temporal regions unsigned long reqStart = m_RequestedTemporalRegion.GetFrameStart(); unsigned long reqEnd = m_RequestedTemporalRegion.GetFrameStart() + m_RequestedTemporalRegion.GetFrameDuration() - 1; unsigned long bufStart = m_BufferedTemporalRegion.GetFrameStart(); unsigned long bufEnd = m_BufferedTemporalRegion.GetFrameStart() + m_BufferedTemporalRegion.GetFrameDuration() - 1; // If the request starts after the buffered region, return the whole request if (reqStart > bufEnd) { return m_RequestedTemporalRegion; } // Handle case with unbuffered frames at beginning and end if (reqStart < bufStart && reqEnd > bufEnd) { itkDebugMacro(<< "Unbuffered frames at beginning and end. Returning entire " << "requested region as unbuffered"); return this->m_RequestedTemporalRegion; } // Handle case with unbuffered frames at end -- TODO: FIX FOR REAL TIME!!!!! else if(reqEnd > bufEnd) { TemporalRegionType out; out.SetFrameStart(bufEnd + 1); out.SetFrameDuration(reqEnd - bufEnd); return out; } // Handle case with unbuffered frames at beginning -- TODO: FIX FOR REAL TIME!!!!! else if(reqStart < bufStart) { TemporalRegionType out; out.SetFrameStart(reqStart); out.SetFrameDuration(bufStart - reqStart); return out; } // Otherwise, nothing unbuffered else { TemporalRegionType out; out.SetFrameStart(0); out.SetFrameDuration(0); return out; } } //---------------------------------------------------------------------------- void TemporalDataObject ::SetRequestedRegionToLargestPossibleRegion() { this->SetRequestedTemporalRegion( this->GetLargestPossibleTemporalRegion() ); } //---------------------------------------------------------------------------- bool TemporalDataObject ::RequestedRegionIsOutsideOfTheBufferedRegion() { bool frameFlag = m_RequestedTemporalRegion.GetFrameStart() < m_BufferedTemporalRegion.GetFrameStart(); frameFlag |= m_RequestedTemporalRegion.GetFrameDuration() > m_BufferedTemporalRegion.GetFrameDuration(); bool realTimeFlag = m_RequestedTemporalRegion.GetRealStart() < m_BufferedTemporalRegion.GetRealStart(); realTimeFlag |= m_RequestedTemporalRegion.GetRealDuration() > m_BufferedTemporalRegion.GetRealDuration(); switch( m_TemporalUnit ) { case Frame: { return frameFlag; } case RealTime: { return realTimeFlag; } case FrameAndRealTime: { return frameFlag || realTimeFlag; } default: itkExceptionMacro( << "itk::TemporalDataObject::" << "RequestedRegionIsOutsideOfTheBufferedRegion() " << "Invalid Temporal Unit" ); return true; } } //---------------------------------------------------------------------------- bool TemporalDataObject ::VerifyRequestedRegion() { bool frameFlag = m_RequestedTemporalRegion.GetFrameStart() >= m_LargestPossibleTemporalRegion.GetFrameStart(); frameFlag &= m_RequestedTemporalRegion.GetFrameDuration() <= m_LargestPossibleTemporalRegion.GetFrameDuration(); bool realTimeFlag = m_RequestedTemporalRegion.GetRealStart() >= m_LargestPossibleTemporalRegion.GetRealStart(); realTimeFlag &= m_RequestedTemporalRegion.GetRealDuration() <= m_LargestPossibleTemporalRegion.GetRealDuration(); switch( m_TemporalUnit ) { case Frame: { return frameFlag; } case RealTime: { return realTimeFlag; } case FrameAndRealTime: { return frameFlag && realTimeFlag; } default: itkExceptionMacro( << "itk::TemporalDataObject::VerifyRequestedRegion() " << "Invalid Temporal Unit" ); return false; } } //---------------------------------------------------------------------------- void TemporalDataObject ::CopyInformation(const DataObject *data) { // Standard call to the superclass' method Superclass::CopyInformation(data); const TemporalDataObject* temporalData; temporalData = dynamic_cast< const TemporalDataObject* >( data ); if ( temporalData ) { // Copy the meta data for this data type this->SetLargestPossibleTemporalRegion( temporalData->GetLargestPossibleTemporalRegion() ); for( unsigned int i = 0; i < this->m_DataObjectBuffer->GetNumberOfBuffers(); ++i ) { if( this->m_DataObjectBuffer->BufferIsFull(i) ) { m_DataObjectBuffer->GetBufferContents(i)->CopyInformation( temporalData->m_DataObjectBuffer->GetBufferContents(i) ); } } } else { // pointer could not be cast back down itkExceptionMacro( << "itk::TemporalDataObject::CopyInformation() " << "cannot cast " << typeid( data ).name() << " to " << typeid( const TemporalDataObject* ).name() ); } } //---------------------------------------------------------------------------- void TemporalDataObject ::Graft(const DataObject *data) { const TemporalDataObject* temporalData; temporalData = dynamic_cast< const TemporalDataObject* >( data ); if( temporalData ) { // Copy the meta-information this->CopyInformation( temporalData ); this->SetBufferedTemporalRegion( temporalData->GetBufferedTemporalRegion() ); this->SetRequestedTemporalRegion( temporalData->GetRequestedTemporalRegion() ); for( unsigned int i = 0; i < this->m_DataObjectBuffer->GetNumberOfBuffers(); ++i ) { if( this->m_DataObjectBuffer->BufferIsFull(i) ) { m_DataObjectBuffer->GetBufferContents(i)->Graft( temporalData->m_DataObjectBuffer->GetBufferContents(i) ); } } } else { // pointer could not be cast back down itkExceptionMacro( << "itk::TemporalDataObject::Graft() " << "cannot cast " << typeid( data ).name() << " to " << typeid( const TemporalDataObject* ).name() ); } } //---------------------------------------------------------------------------- void TemporalDataObject ::SetRequestedRegion(DataObject *data) { TemporalDataObject *temporalData; temporalData = dynamic_cast< TemporalDataObject * >( data ); if ( temporalData ) { // only copy the RequestedTemporalRegion if the parameter object is // a temporal data object this->SetRequestedTemporalRegion( temporalData->GetRequestedTemporalRegion() ); for( unsigned int i = 0; i < this->m_DataObjectBuffer->GetNumberOfBuffers(); ++i ) { if( this->m_DataObjectBuffer->BufferIsFull(i) ) { m_DataObjectBuffer->GetBufferContents(i)->SetRequestedRegion( temporalData->m_DataObjectBuffer->GetBufferContents(i) ); } } } else { // pointer could not be cast back down itkExceptionMacro( << "itk::TemporalDataObject:SetRequestedRegion() " << "cannot cast " << typeid( data ).name() << " to " << typeid( const TemporalDataObject* ).name() ); } } //---------------------------------------------------------------------------- void TemporalDataObject ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Data Object Buffer: " << m_DataObjectBuffer.GetPointer() << std::endl; os << indent << "LargestPossibleTemporalRegion: " << std::endl; this->GetLargestPossibleTemporalRegion().Print( os, indent.GetNextIndent() ); os << indent << "BufferedTemporalRegion: " << std::endl; this->GetBufferedTemporalRegion().Print( os, indent.GetNextIndent() ); os << indent << "RequestedTemporalRegion: " << std::endl; this->GetRequestedTemporalRegion().Print( os, indent.GetNextIndent() ); } } // end namespace itk <|endoftext|>
<commit_before>#include <thread> #include <condition_variable> #include <mutex> #include <sstream> #include <lcm/lcm-cpp.hpp> #include <ConciseArgs> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <bot_lcmgl_client/lcmgl.h> #include <lcmtypes/drc/map_scans_t.hpp> #include <lcmtypes/drc/affordance_collection_t.hpp> #include <lcmtypes/drc/block_fit_request_t.hpp> #include <maps/ScanBundleView.hpp> #include <maps/LcmTranslator.hpp> #include <pcl/common/io.h> #include <pcl/common/transforms.h> #include "BlockFitter.hpp" struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; bool mRunContinuously; bool mDoFilter; bool mRemoveGround; bool mGrabExactPoses; bool mDebug; Eigen::Vector3f mBlockSize; int mAlgorithm; bool mDoTrigger; std::string mNamePrefix; bool mTriggered; drc::map_scans_t mData; int64_t mLastDataTime; Eigen::Isometry3f mSensorPose; Eigen::Isometry3f mGroundPose; std::thread mWorkerThread; std::condition_variable mCondition; std::mutex mProcessMutex; std::mutex mDataMutex; State() { mRunContinuously = false; mDoFilter = true; mRemoveGround = true; mGrabExactPoses = false; mDebug = false; mAlgorithm = planeseg::BlockFitter::RectangleFitAlgorithm::MinimumArea; mBlockSize << 15+3/8.0, 15+5/8.0, 5+5/8.0; mBlockSize *=0.0254; mDoTrigger = false; mNamePrefix = "cinderblock"; mTriggered = true; } void start() { mLastDataTime = 0; mData.utime = 0; mLcmWrapper->get()->subscribe("MAP_SCANS", &State::onScans, this); mWorkerThread = std::thread(std::ref(*this)); mLcmWrapper->startHandleThread(true); } void stop() { mLcmWrapper->stopHandleThread(); if (mWorkerThread.joinable()) mWorkerThread.join(); } void operator()() { while (true) { // wait for data std::unique_lock<std::mutex> lock(mProcessMutex); mCondition.wait_for(lock, std::chrono::milliseconds(100)); // grab data drc::map_scans_t data; Eigen::Isometry3f sensorPose; Eigen::Isometry3f groundPose; { std::unique_lock<std::mutex> dataLock(mDataMutex); if (mData.utime == mLastDataTime) continue; data = mData; sensorPose = mSensorPose; groundPose = mGroundPose; mLastDataTime = mData.utime; } // convert scans to point cloud maps::ScanBundleView view; maps::LcmTranslator::fromLcm(data, view); maps::PointCloud rawCloud, curCloud; std::vector<float> allDeltas; for (const auto& scan : view.getScans()) { // compute range deltas int numRanges = scan->getNumRanges(); std::vector<float> deltas; const auto& ranges = scan->getRanges(); float prevRange = -1; int curIndex = 0; for (int i = 0; i < numRanges; ++i, ++curIndex) { if (ranges[i] <= 0) continue; prevRange = ranges[i]; deltas.push_back(0); break; } for (int i = curIndex+1; i < numRanges; ++i) { float range = ranges[i]; if (range <= 0) continue; deltas.push_back(range-prevRange); prevRange = range; } // add this scan to cloud scan->get(curCloud, true); rawCloud += curCloud; allDeltas.insert(allDeltas.end(), deltas.begin(), deltas.end()); } pcl::transformPointCloud (rawCloud, rawCloud, Eigen::Affine3f(view.getTransform().matrix()).inverse()); planeseg::LabeledCloud::Ptr cloud(new planeseg::LabeledCloud()); pcl::copyPointCloud(rawCloud, *cloud); /* TODO: change point type for (int i = 0; i < (int)cloud->size(); ++i) { cloud->points[i].label = 1000*allDeltas[i]; } */ // remove points outside max radius const float kValidRadius = 5; // meters; TODO: could make this a param const float kValidRadius2 = kValidRadius*kValidRadius; planeseg::LabeledCloud::Ptr tempCloud(new planeseg::LabeledCloud()); for (int i = 0; i < (int)cloud->size(); ++i) { Eigen::Vector3f p = cloud->points[i].getVector3fMap(); float dist2 = (p-sensorPose.translation()).squaredNorm(); if (dist2 > kValidRadius2) continue; tempCloud->push_back(cloud->points[i]); } std::swap(cloud, tempCloud); // process planeseg::BlockFitter fitter; fitter.setSensorPose(sensorPose.translation(), sensorPose.rotation().col(2)); fitter.setGroundBand(groundPose.translation()[2]-1.0, groundPose.translation()[2]+0.5); if (mDoFilter) fitter.setAreaThresholds(0.8, 1.2); else fitter.setAreaThresholds(0, 1000); fitter.setBlockDimensions(mBlockSize); fitter.setRemoveGround(mRemoveGround); fitter.setRectangleFitAlgorithm ((planeseg::BlockFitter::RectangleFitAlgorithm)mAlgorithm); fitter.setDebug(mDebug); fitter.setCloud(cloud); auto result = fitter.go(); if (!result.mSuccess) { std::cout << "error: could not detect blocks" << std::endl; continue; } // // construct json string // // header std::string json; json += "{\n"; json += " \"command\": \"echo_response\",\n"; json += " \"descriptions\": {\n"; std::string timeString = std::to_string(mBotWrapper->getCurrentTime()); // blocks for (int i = 0; i < (int)result.mBlocks.size(); ++i) { const auto& block = result.mBlocks[i]; std::string dimensionsString, positionString, quaternionString; { std::ostringstream oss; Eigen::Vector3f size = block.mSize; oss << size[0] << ", " << size[1] << ", " << size[2]; dimensionsString = oss.str(); } { std::ostringstream oss; Eigen::Vector3f p = block.mPose.translation(); oss << p[0] << ", " << p[1] << ", " << p[2]; positionString = oss.str(); } { std::ostringstream oss; Eigen::Quaternionf q(block.mPose.rotation()); oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z(); quaternionString = oss.str(); } std::string uuid = timeString + "_" + std::to_string(i+1); json += " \"" + uuid + "\": {\n"; json += " \"classname\": \"BoxAffordanceItem\",\n"; json += " \"pose\": [[" + positionString + "], [" + quaternionString + "]],\n"; json += " \"uuid\": \"" + uuid + "\",\n"; json += " \"Dimensions\": [" + dimensionsString + "],\n"; json += " \"Name\": \"" + mNamePrefix + " " + std::to_string(i) + "\"\n"; json += " },\n"; } // ground { std::string positionString, quaternionString; Eigen::Vector3f groundNormal = result.mGroundPlane.head<3>(); { std::ostringstream oss; Eigen::Vector3f p = groundPose.translation(); p -= (groundNormal.dot(p)+result.mGroundPlane[3])*groundNormal; p -= 0.005*groundNormal; // account for thickness of slab oss << p[0] << ", " << p[1] << ", " << p[2]; positionString = oss.str(); } { std::ostringstream oss; Eigen::Matrix3f rot = Eigen::Matrix3f::Identity(); rot.col(2) = groundNormal.normalized(); rot.col(1) = rot.col(2).cross(Eigen::Vector3f::UnitX()).normalized(); rot.col(0) = rot.col(1).cross(rot.col(2)).normalized(); Eigen::Quaternionf q(rot); oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z(); quaternionString = oss.str(); } json += " \"ground affordance\": {\n"; json += " \"classname\": \"BoxAffordanceItem\",\n"; json += " \"pose\": [[" + positionString + "], [" + quaternionString + "]],\n"; json += " \"uuid\": \"ground affordance\",\n"; json += " \"Dimensions\": [100, 100, 0.01],\n"; json += " \"Name\": \"ground affordance\",\n"; json += " \"Visible\": 0\n"; json += " }\n"; } // footer json += " },\n"; json += " \"commandId\": \"" + timeString + "\",\n"; json += " \"collectionId\": \"block-fitter\"\n"; json += "}\n"; // publish result drc::affordance_collection_t msg; msg.utime = data.utime; msg.name = json; msg.naffs = 0; mLcmWrapper->get()->publish("AFFORDANCE_COLLECTION_COMMAND", &msg); std::cout << "Published affordance collection" << std::endl; // publish lcmgl if (mDebug) { bot_lcmgl_t* lcmgl; lcmgl = bot_lcmgl_init(mLcmWrapper->get()->getUnderlyingLCM(), "block-fitter"); for (const auto& block : result.mBlocks) { bot_lcmgl_color3f(lcmgl, 1, 0, 0); bot_lcmgl_line_width(lcmgl, 4); bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP); for (const auto& pt : block.mHull) { bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]); } bot_lcmgl_end(lcmgl); } bot_lcmgl_color3f(lcmgl, 0, 1, 0); bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP); for (const auto& pt : result.mGroundPolygon) { bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]); } bot_lcmgl_end(lcmgl); bot_lcmgl_switch_buffer(lcmgl); bot_lcmgl_destroy(lcmgl); } if (!mRunContinuously) break; } mLcmWrapper->stopHandleThread(); } void onScans(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const drc::map_scans_t* iMessage) { std::unique_lock<std::mutex> lock(mDataMutex); if (!mTriggered) return; mData = *iMessage; int64_t scanTime = iMessage->utime; int64_t headPoseTime = mBotWrapper->getLatestTime("head", "local"); int64_t groundPoseTime = mBotWrapper->getLatestTime("ground", "local"); if ((groundPoseTime == 0) || (headPoseTime == 0) || (mGrabExactPoses && ((std::abs(headPoseTime-scanTime) > 1e6) || (std::abs(groundPoseTime-scanTime) > 1e6)))) { std::cout << "warning: got scans but no valid pose found" << std::endl; return; } mBotWrapper->getTransform("head", "local", mSensorPose, iMessage->utime); mBotWrapper->getTransform("ground", "local", mGroundPose, iMessage->utime); mCondition.notify_one(); if (mDoTrigger) mTriggered = false; } void onTrigger(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const drc::block_fit_request_t* iMessage) { mNamePrefix = iMessage->name_prefix; mBlockSize << iMessage->dimensions[0], iMessage->dimensions[1], iMessage->dimensions[2]; mAlgorithm = iMessage->algorithm; mLastDataTime = 0; // force processing of new data mTriggered = true; std::cout << "received trigger" << std::endl; } }; int main(const int iArgc, const char** iArgv) { std::string sizeString(""); std::string triggerChannel; State state; ConciseArgs opt(iArgc, (char**)iArgv); opt.add(state.mRunContinuously, "c", "continuous", "run continuously"); opt.add(state.mDoFilter, "f", "filter", "filter blocks based on size"); opt.add(sizeString, "s", "blocksize", "prior size for blocks \"x y z\""); opt.add(state.mRemoveGround, "g", "remove-ground", "whether to remove ground before processing"); opt.add(state.mAlgorithm, "a", "algorithm", "0=min_area, 1=closest_size, 2=closest_hull"); opt.add(state.mGrabExactPoses, "p", "exact-poses", "wait for synchronized poses"); opt.add(triggerChannel, "t", "trigger-channel", "perform block fit only when trigger is received"); opt.add(state.mDebug, "d", "debug", "debug flag"); opt.parse(); if (sizeString.length() > 0) { std::istringstream iss(sizeString); float x, y, z; if (iss >> x) { if (iss >> y) { if (iss >> z) { state.mBlockSize << x,y,z; std::cout << "using block size " << state.mBlockSize.transpose() << std::endl; } } } } state.mBotWrapper.reset(new drc::BotWrapper()); state.mLcmWrapper.reset(new drc::LcmWrapper(state.mBotWrapper->getLcm())); if (triggerChannel.length() > 0) { state.mDoTrigger = true; state.mTriggered = false; state.mLcmWrapper->get()->subscribe(triggerChannel, &State::onTrigger, &state); } state.start(); state.stop(); return 1; } <commit_msg>named ground affordance dimensions<commit_after>#include <thread> #include <condition_variable> #include <mutex> #include <sstream> #include <lcm/lcm-cpp.hpp> #include <ConciseArgs> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <bot_lcmgl_client/lcmgl.h> #include <lcmtypes/drc/map_scans_t.hpp> #include <lcmtypes/drc/affordance_collection_t.hpp> #include <lcmtypes/drc/block_fit_request_t.hpp> #include <maps/ScanBundleView.hpp> #include <maps/LcmTranslator.hpp> #include <pcl/common/io.h> #include <pcl/common/transforms.h> #include "BlockFitter.hpp" struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; bool mRunContinuously; bool mDoFilter; bool mRemoveGround; bool mGrabExactPoses; bool mDebug; Eigen::Vector3f mBlockSize; int mAlgorithm; bool mDoTrigger; std::string mNamePrefix; bool mTriggered; drc::map_scans_t mData; int64_t mLastDataTime; Eigen::Isometry3f mSensorPose; Eigen::Isometry3f mGroundPose; std::thread mWorkerThread; std::condition_variable mCondition; std::mutex mProcessMutex; std::mutex mDataMutex; State() { mRunContinuously = false; mDoFilter = true; mRemoveGround = true; mGrabExactPoses = false; mDebug = false; mAlgorithm = planeseg::BlockFitter::RectangleFitAlgorithm::MinimumArea; mBlockSize << 15+3/8.0, 15+5/8.0, 5+5/8.0; mBlockSize *=0.0254; mDoTrigger = false; mNamePrefix = "cinderblock"; mTriggered = true; } void start() { mLastDataTime = 0; mData.utime = 0; mLcmWrapper->get()->subscribe("MAP_SCANS", &State::onScans, this); mWorkerThread = std::thread(std::ref(*this)); mLcmWrapper->startHandleThread(true); } void stop() { mLcmWrapper->stopHandleThread(); if (mWorkerThread.joinable()) mWorkerThread.join(); } void operator()() { while (true) { // wait for data std::unique_lock<std::mutex> lock(mProcessMutex); mCondition.wait_for(lock, std::chrono::milliseconds(100)); // grab data drc::map_scans_t data; Eigen::Isometry3f sensorPose; Eigen::Isometry3f groundPose; { std::unique_lock<std::mutex> dataLock(mDataMutex); if (mData.utime == mLastDataTime) continue; data = mData; sensorPose = mSensorPose; groundPose = mGroundPose; mLastDataTime = mData.utime; } // convert scans to point cloud maps::ScanBundleView view; maps::LcmTranslator::fromLcm(data, view); maps::PointCloud rawCloud, curCloud; std::vector<float> allDeltas; for (const auto& scan : view.getScans()) { // compute range deltas int numRanges = scan->getNumRanges(); std::vector<float> deltas; const auto& ranges = scan->getRanges(); float prevRange = -1; int curIndex = 0; for (int i = 0; i < numRanges; ++i, ++curIndex) { if (ranges[i] <= 0) continue; prevRange = ranges[i]; deltas.push_back(0); break; } for (int i = curIndex+1; i < numRanges; ++i) { float range = ranges[i]; if (range <= 0) continue; deltas.push_back(range-prevRange); prevRange = range; } // add this scan to cloud scan->get(curCloud, true); rawCloud += curCloud; allDeltas.insert(allDeltas.end(), deltas.begin(), deltas.end()); } pcl::transformPointCloud (rawCloud, rawCloud, Eigen::Affine3f(view.getTransform().matrix()).inverse()); planeseg::LabeledCloud::Ptr cloud(new planeseg::LabeledCloud()); pcl::copyPointCloud(rawCloud, *cloud); /* TODO: change point type for (int i = 0; i < (int)cloud->size(); ++i) { cloud->points[i].label = 1000*allDeltas[i]; } */ // remove points outside max radius const float kValidRadius = 5; // meters; TODO: could make this a param const float kValidRadius2 = kValidRadius*kValidRadius; planeseg::LabeledCloud::Ptr tempCloud(new planeseg::LabeledCloud()); for (int i = 0; i < (int)cloud->size(); ++i) { Eigen::Vector3f p = cloud->points[i].getVector3fMap(); float dist2 = (p-sensorPose.translation()).squaredNorm(); if (dist2 > kValidRadius2) continue; tempCloud->push_back(cloud->points[i]); } std::swap(cloud, tempCloud); // process planeseg::BlockFitter fitter; fitter.setSensorPose(sensorPose.translation(), sensorPose.rotation().col(2)); fitter.setGroundBand(groundPose.translation()[2]-1.0, groundPose.translation()[2]+0.5); if (mDoFilter) fitter.setAreaThresholds(0.8, 1.2); else fitter.setAreaThresholds(0, 1000); fitter.setBlockDimensions(mBlockSize); fitter.setRemoveGround(mRemoveGround); fitter.setRectangleFitAlgorithm ((planeseg::BlockFitter::RectangleFitAlgorithm)mAlgorithm); fitter.setDebug(mDebug); fitter.setCloud(cloud); auto result = fitter.go(); if (!result.mSuccess) { std::cout << "error: could not detect blocks" << std::endl; continue; } // // construct json string // // header std::string json; json += "{\n"; json += " \"command\": \"echo_response\",\n"; json += " \"descriptions\": {\n"; std::string timeString = std::to_string(mBotWrapper->getCurrentTime()); // blocks for (int i = 0; i < (int)result.mBlocks.size(); ++i) { const auto& block = result.mBlocks[i]; std::string dimensionsString, positionString, quaternionString; { std::ostringstream oss; Eigen::Vector3f size = block.mSize; oss << size[0] << ", " << size[1] << ", " << size[2]; dimensionsString = oss.str(); } { std::ostringstream oss; Eigen::Vector3f p = block.mPose.translation(); oss << p[0] << ", " << p[1] << ", " << p[2]; positionString = oss.str(); } { std::ostringstream oss; Eigen::Quaternionf q(block.mPose.rotation()); oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z(); quaternionString = oss.str(); } std::string uuid = timeString + "_" + std::to_string(i+1); json += " \"" + uuid + "\": {\n"; json += " \"classname\": \"BoxAffordanceItem\",\n"; json += " \"pose\": [[" + positionString + "], [" + quaternionString + "]],\n"; json += " \"uuid\": \"" + uuid + "\",\n"; json += " \"Dimensions\": [" + dimensionsString + "],\n"; json += " \"Name\": \"" + mNamePrefix + " " + std::to_string(i) + "\"\n"; json += " },\n"; } // ground { std::string positionString, quaternionString, dimensionsString; Eigen::Vector3f groundNormal = result.mGroundPlane.head<3>(); Eigen::Vector3f groundSize(100,100,0.01); { std::ostringstream oss; Eigen::Vector3f p = groundPose.translation(); p -= (groundNormal.dot(p)+result.mGroundPlane[3])*groundNormal; p -= (groundSize[2]/2)*groundNormal; oss << p[0] << ", " << p[1] << ", " << p[2]; positionString = oss.str(); } { std::ostringstream oss; Eigen::Matrix3f rot = Eigen::Matrix3f::Identity(); rot.col(2) = groundNormal.normalized(); rot.col(1) = rot.col(2).cross(Eigen::Vector3f::UnitX()).normalized(); rot.col(0) = rot.col(1).cross(rot.col(2)).normalized(); Eigen::Quaternionf q(rot); oss << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z(); quaternionString = oss.str(); } { std::ostringstream oss; Eigen::Vector3f size = groundSize; oss << size[0] << ", " << size[1] << ", " << size[2]; dimensionsString = oss.str(); } json += " \"ground affordance\": {\n"; json += " \"classname\": \"BoxAffordanceItem\",\n"; json += " \"pose\": [[" + positionString + "], [" + quaternionString + "]],\n"; json += " \"uuid\": \"ground affordance\",\n"; json += " \"Dimensions\": [" + dimensionsString+ "],\n"; json += " \"Name\": \"ground affordance\",\n"; json += " \"Visible\": 0\n"; json += " }\n"; } // footer json += " },\n"; json += " \"commandId\": \"" + timeString + "\",\n"; json += " \"collectionId\": \"block-fitter\"\n"; json += "}\n"; // publish result drc::affordance_collection_t msg; msg.utime = data.utime; msg.name = json; msg.naffs = 0; mLcmWrapper->get()->publish("AFFORDANCE_COLLECTION_COMMAND", &msg); std::cout << "Published affordance collection" << std::endl; // publish lcmgl if (mDebug) { bot_lcmgl_t* lcmgl; lcmgl = bot_lcmgl_init(mLcmWrapper->get()->getUnderlyingLCM(), "block-fitter"); for (const auto& block : result.mBlocks) { bot_lcmgl_color3f(lcmgl, 1, 0, 0); bot_lcmgl_line_width(lcmgl, 4); bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP); for (const auto& pt : block.mHull) { bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]); } bot_lcmgl_end(lcmgl); } bot_lcmgl_color3f(lcmgl, 0, 1, 0); bot_lcmgl_begin(lcmgl, LCMGL_LINE_LOOP); for (const auto& pt : result.mGroundPolygon) { bot_lcmgl_vertex3f(lcmgl, pt[0], pt[1], pt[2]); } bot_lcmgl_end(lcmgl); bot_lcmgl_switch_buffer(lcmgl); bot_lcmgl_destroy(lcmgl); } if (!mRunContinuously) break; } mLcmWrapper->stopHandleThread(); } void onScans(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const drc::map_scans_t* iMessage) { std::unique_lock<std::mutex> lock(mDataMutex); if (!mTriggered) return; mData = *iMessage; int64_t scanTime = iMessage->utime; int64_t headPoseTime = mBotWrapper->getLatestTime("head", "local"); int64_t groundPoseTime = mBotWrapper->getLatestTime("ground", "local"); if ((groundPoseTime == 0) || (headPoseTime == 0) || (mGrabExactPoses && ((std::abs(headPoseTime-scanTime) > 1e6) || (std::abs(groundPoseTime-scanTime) > 1e6)))) { std::cout << "warning: got scans but no valid pose found" << std::endl; return; } mBotWrapper->getTransform("head", "local", mSensorPose, iMessage->utime); mBotWrapper->getTransform("ground", "local", mGroundPose, iMessage->utime); mCondition.notify_one(); if (mDoTrigger) mTriggered = false; } void onTrigger(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const drc::block_fit_request_t* iMessage) { mNamePrefix = iMessage->name_prefix; mBlockSize << iMessage->dimensions[0], iMessage->dimensions[1], iMessage->dimensions[2]; mAlgorithm = iMessage->algorithm; mLastDataTime = 0; // force processing of new data mTriggered = true; std::cout << "received trigger" << std::endl; } }; int main(const int iArgc, const char** iArgv) { std::string sizeString(""); std::string triggerChannel; State state; ConciseArgs opt(iArgc, (char**)iArgv); opt.add(state.mRunContinuously, "c", "continuous", "run continuously"); opt.add(state.mDoFilter, "f", "filter", "filter blocks based on size"); opt.add(sizeString, "s", "blocksize", "prior size for blocks \"x y z\""); opt.add(state.mRemoveGround, "g", "remove-ground", "whether to remove ground before processing"); opt.add(state.mAlgorithm, "a", "algorithm", "0=min_area, 1=closest_size, 2=closest_hull"); opt.add(state.mGrabExactPoses, "p", "exact-poses", "wait for synchronized poses"); opt.add(triggerChannel, "t", "trigger-channel", "perform block fit only when trigger is received"); opt.add(state.mDebug, "d", "debug", "debug flag"); opt.parse(); if (sizeString.length() > 0) { std::istringstream iss(sizeString); float x, y, z; if (iss >> x) { if (iss >> y) { if (iss >> z) { state.mBlockSize << x,y,z; std::cout << "using block size " << state.mBlockSize.transpose() << std::endl; } } } } state.mBotWrapper.reset(new drc::BotWrapper()); state.mLcmWrapper.reset(new drc::LcmWrapper(state.mBotWrapper->getLcm())); if (triggerChannel.length() > 0) { state.mDoTrigger = true; state.mTriggered = false; state.mLcmWrapper->get()->subscribe(triggerChannel, &State::onTrigger, &state); } state.start(); state.stop(); return 1; } <|endoftext|>
<commit_before>#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <fstream> #include <sys/stat.h> #include <unistd.h> #include <thread> #include <mutex> #include <cmath> #include "concurrentqueue.h" using namespace std; using namespace cv; using namespace moodycamel; class Utils { private: static void extractHistogram(Mat frame, int num, vector< pair<int, Mat> > &hTemp); static std::mutex mutex; public: static void writeOutputFile(string outFile, vector< pair<int,int> > shots); static bool checkFile(string name); static bool checkOutputFile(string name); static vector<Mat> extractVideoHistograms(string videoPath); static vector<Mat> extractVideoHistograms2(string videoPath); static bool pairCompare(const pair<int, Mat> &fElem, const pair<int, Mat> &sElem); };<commit_msg>Some garbage got though the last commit<commit_after>#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <fstream> #include <sys/stat.h> #include <unistd.h> #include <thread> #include <mutex> #include <cmath> using namespace std; using namespace cv; class Utils { private: static void extractHistogram(Mat frame, int num, vector< pair<int, Mat> > &hTemp); static std::mutex mutex; public: static void writeOutputFile(string outFile, vector< pair<int,int> > shots); static bool checkFile(string name); static bool checkOutputFile(string name); static vector<Mat> extractVideoHistograms(string videoPath); static bool pairCompare(const pair<int, Mat> &fElem, const pair<int, Mat> &sElem); };<|endoftext|>
<commit_before>#ifndef UTILS_HPP #define UTILS_HPP #include <type_traits> #include <utility> ////////////////////////// Tuple unpack utils ////////////////////////// http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer namespace util { // helper class template < typename F, typename... Args, std::size_t... I > auto call_helper(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)> { return func(std::get<I>(params)...); } template< typename F, typename... Args > auto call(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)> { return call_helper<F, Args..., std::index_sequence_for<Args...> >(func, params); } } ////////////////////////// Bitflags enumerations template <typename T> struct is_enum_flags : std::false_type { //static_assert(std::is_enum<T>::value, "T must be an enum type"); }; ////////////////////////// operator| template < typename T, typename = std::enable_if_t<is_enum_flags<T>::value> > inline T operator|(T a, T b) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(a) | static_cast<std::underlying_type_t<T>>(b)); } ////////////////////////// operator|= template < typename T, typename = std::enable_if_t<is_enum_flags<T>::value> > inline T& operator|=(T& a, T b) { a = a | b; return a; } ////////////////////////// operator&= template < typename T, typename = std::enable_if_t<is_enum_flags<T>::value> > inline T operator&(T a, T b) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(a) & static_cast<std::underlying_type_t<T>>(b)); } #endif // !UTILS_HPP <commit_msg>things<commit_after>#ifndef UTILS_HPP #define UTILS_HPP #include <type_traits> #include <utility> ////////////////////////// Tuple unpack utils ////////////////////////// http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer namespace util { // helper class template < typename F, typename... Args, std::size_t... I > auto call_helper(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)> { return func(std::get<I>(params)...); } template< typename F, typename... Args > auto call(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)> { return call_helper<F, Args..., std::index_sequence_for<Args...> >(func, params); } } ////////////////////////// Bitflags enumerations template <typename T> struct is_enum_flags : std::false_type { //static_assert(std::is_enum<T>::value, "T must be an enum type"); }; ////////////////////////// operator| template < typename T, typename = std::enable_if_t<is_enum_flags<T>::value> > inline T operator|(T a, T b) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(a) | static_cast<std::underlying_type_t<T>>(b)); } ////////////////////////// operator|= template < typename T, typename = std::enable_if_t<is_enum_flags<T>::value> > inline T& operator|=(T& a, T b) { a = a | b; return a; } ////////////////////////// operator&= template < typename T, typename = std::enable_if_t<is_enum_flags<T>::value> > inline T operator&(T a, T b) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(a) & static_cast<std::underlying_type_t<T>>(b)); } #endif // !UTILS_HPP <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: main.C,v 1.5 2004/07/16 11:18:18 amoll Exp $ // // order of includes is important: first qapplication, than BALL includes #include <qapplication.h> #include <BALL/SYSTEM/path.h> #include <BALL/SYSTEM/directory.h> #include "mainframe.h" #include <BALL/FORMAT/DCDFile.h> #include <BALL/MOLMEC/COMMON/snapShot.h> #include <BALL/VIEW/RENDERING/POVRenderer.h> #include <iostream> #include <sys/wait.h> using namespace BALL; using namespace BALL::VIEW; void showUsage() { Log.insert(std::cerr); Log.error() << "DCD2PNG <PDBFILE.pdb | HINFILE.hin> <DCDFILE.dcd> [<BALLViewProject.bvp>] [<DIRECTORY>]" << std::endl; Log.error() << "Read a molecular file, and create PNG images from them in the given directory." << std::endl; Log.remove(std::cerr); } int main(int argc, char **argv) { if (argc < 3) { showUsage(); return 1; } // =============== testing if we can write in current directoy ===================== bool dir_error = false; char* home_dir = 0; try { BALL::String temp_file_name; BALL::File::createTemporaryFilename(temp_file_name); BALL::File out(temp_file_name, std::ios::out); out << "test" << std::endl; out.remove(); } catch(...) { // oh, we have a problem, look for the users home dir dir_error = true; // default for UNIX/LINUX home_dir = getenv("HOME"); if (home_dir == 0) { // windows home_dir = getenv("HOMEPATH"); } // changedir to the homedir if (home_dir != 0) { BALL::Directory dir(home_dir); dir_error = !dir.setCurrent(); } if (dir_error) { Log.error() << "You dont have write access to the current working directory\n"<< "and I can not find your home directory. This can cause\n" << "unexpected behaviour. Please start DCD2PNG from your homedir with\n" << "absolute path.\n"; } } // =============== initialize Mainframe ============================================ QApplication application(argc, argv); BALL::Mainframe mainframe; // application.setMainWidget(&mainframe); mainframe.setIdentifier("MAIN"); mainframe.registerThis(); mainframe.hide(); // if we need to use the users homedir as working dir, do so if (home_dir != 0 && !dir_error) { mainframe.setWorkingDir(home_dir); } // =============== parsing command line arguments ================================== String dcd_file_name; String molecular_file_name; String working_dir = "."; bool error = false; System* system; Position nr = 100000000; DisplayProperties::getInstance(0)->enableCreationForNewMolecules(false); for (BALL::Index i = 1; i < argc && !error; ++i) { BALL::String argument(argv[i]); if (argument.hasSuffix(".bvp")) { DisplayProperties::getInstance(0)->enableCreationForNewMolecules(true); mainframe.loadBALLViewProjectFile(argument); continue; } if (argument.hasSuffix(".pdb") || argument.hasSuffix(".hin")) { MolecularFileDialog* mfd = MolecularFileDialog::getInstance(0); if (mfd == 0) return 0; system = mfd->openFile(argument); molecular_file_name = argument; continue; } if (argument.hasSuffix(".dcd")) { dcd_file_name = argument; continue; } if (argument.hasPrefix("-s")) { argument.after("-s"); try { nr = argument.toUnsignedInt(); } catch(...) { } continue; } Directory d(argument); if (d.isValid()) { mainframe.setWorkingDir(argument); working_dir = argument; continue; } error = true; } if (molecular_file_name == "" || dcd_file_name == "" || error) { showUsage(); application.quit(); return 0; } if (dcd_file_name == "") { DisplayProperties::getInstance(0)->enableCreationForNewMolecules(true); DisplayProperties::getInstance(0)->applyButtonClicked(); } Size width = 1000; Size height = 750; DCDFile dcdfile(dcd_file_name); Scene::getInstance(0)->resize(width, height); int writepipe[2]; pid_t childpid; #define PARENT_WRITE writepipe[0] #define CHILD_READ writepipe[1] int status; // if (pipe(writepipe) < 0 ) return -1; String povray_options; povray_options = "-V -D +Imytemp +W" + String(width) + " +H" + String(height) + " +O" + working_dir + "/"; std::cout << povray_options << std::endl; SnapShotManager sm(system, 0, &dcdfile, false); POVRenderer pov; pov.setFileName("mytemp"); Position nr2 = 0; sm.applyFirstSnapShot(); while(sm.applyNextSnapShot()) { String pov_arg = povray_options + String(nr) + ".png" ; Scene::getInstance(0)->exportScene(pov); nr++; nr2++; // abort, if we can not fork! if ( (childpid = fork()) < 0) { std::cout << "Could not fork!" << std::endl; return -1; } // we are in the parent process and wait for the child to finish else if (childpid != 0) { waitpid( -1, &status, 0 ); } // we are in the child process and start povray else { // close(1); execl ("/home/student/amoll/bin/povray", "povray", pov_arg.c_str(), 0); } // close(1); // dup (writepipe[1]); // execl ("/home/student/amoll/bin/mytest", "mytest", "+I- +Oa.png", 0); } std::cout << "Written " + String(nr2) + " images." << std::endl; // mainframe.show(); // return application.exec(); return 0; } <commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: main.C,v 1.6 2004/07/16 13:55:32 amoll Exp $ // // order of includes is important: first qapplication, than BALL includes #include <qapplication.h> #include <BALL/SYSTEM/path.h> #include <BALL/SYSTEM/directory.h> #include "mainframe.h" #include <BALL/FORMAT/DCDFile.h> #include <BALL/MOLMEC/COMMON/snapShot.h> #include <BALL/VIEW/RENDERING/POVRenderer.h> #include <iostream> #include <sys/wait.h> using namespace BALL; using namespace BALL::VIEW; void showUsage() { Log.insert(std::cerr); Log.error() << "DCD2PNG <PDBFILE.pdb | HINFILE.hin> <DCDFILE.dcd> [<BALLViewProject.bvp>] [<DIRECTORY>]" << std::endl; Log.error() << "Read a molecular file, and create PNG images from them in the given directory." << std::endl; Log.remove(std::cerr); } int main(int argc, char **argv) { if (argc < 3) { showUsage(); return 1; } // =============== testing if we can write in current directoy ===================== bool dir_error = false; char* home_dir = 0; try { BALL::String temp_file_name; BALL::File::createTemporaryFilename(temp_file_name); BALL::File out(temp_file_name, std::ios::out); out << "test" << std::endl; out.remove(); } catch(...) { // oh, we have a problem, look for the users home dir dir_error = true; // default for UNIX/LINUX home_dir = getenv("HOME"); if (home_dir == 0) { // windows home_dir = getenv("HOMEPATH"); } // changedir to the homedir if (home_dir != 0) { BALL::Directory dir(home_dir); dir_error = !dir.setCurrent(); } if (dir_error) { Log.error() << "You dont have write access to the current working directory\n"<< "and I can not find your home directory. This can cause\n" << "unexpected behaviour. Please start DCD2PNG from your homedir with\n" << "absolute path.\n"; } } // =============== initialize Mainframe ============================================ QApplication application(argc, argv); BALL::Mainframe mainframe; // application.setMainWidget(&mainframe); mainframe.setIdentifier("MAIN"); mainframe.registerThis(); mainframe.hide(); // if we need to use the users homedir as working dir, do so if (home_dir != 0 && !dir_error) { mainframe.setWorkingDir(home_dir); } // =============== parsing command line arguments ================================== String dcd_file_name; String molecular_file_name; String working_dir = "."; bool error = false; System* system; Position nr = 100000000; DisplayProperties::getInstance(0)->enableCreationForNewMolecules(false); for (BALL::Index i = 1; i < argc && !error; ++i) { BALL::String argument(argv[i]); if (argument.hasSuffix(".bvp")) { DisplayProperties::getInstance(0)->enableCreationForNewMolecules(true); mainframe.loadBALLViewProjectFile(argument); continue; } if (argument.hasSuffix(".pdb") || argument.hasSuffix(".hin")) { MolecularFileDialog* mfd = MolecularFileDialog::getInstance(0); if (mfd == 0) return 0; system = mfd->openFile(argument); molecular_file_name = argument; continue; } if (argument.hasSuffix(".dcd")) { dcd_file_name = argument; continue; } if (argument.hasPrefix("-s")) { argument.after("-s"); try { nr = argument.toUnsignedInt(); } catch(...) { } continue; } Directory d(argument); if (d.isValid()) { mainframe.setWorkingDir(argument); working_dir = argument; continue; } error = true; } if (molecular_file_name == "" || dcd_file_name == "" || error) { showUsage(); application.quit(); return 0; } if (dcd_file_name == "") { DisplayProperties::getInstance(0)->enableCreationForNewMolecules(true); DisplayProperties::getInstance(0)->applyButtonClicked(); } Size width = 1000; Size height = 750; DCDFile dcdfile(dcd_file_name); Scene::getInstance(0)->resize(width, height); int writepipe[2]; pid_t childpid; if (pipe(writepipe) < 0 ) { std::cerr << "Could not pipe!" << std::endl; return -1; } String povray_options; povray_options = "-V -D +I- +W" + String(width) + " +H" + String(height) + " +O" + working_dir + "/"; SnapShotManager sm(system, 0, &dcdfile, false); POVRenderer pov; std::stringstream pov_renderer_output; pov.setOstream(pov_renderer_output); pov.setHumanReadable(false); Position nr2 = 0; sm.applyFirstSnapShot(); while(sm.applyNextSnapShot()) { String pov_arg = povray_options + String(nr) + ".png" ; Scene::getInstance(0)->exportScene(pov); // abort, if we can not fork! if ( (childpid = fork()) < 0) { std::cerr << "Could not fork!" << std::endl; return -1; } else if (childpid != 0) { // we are in the parent process and wait for the child to finish // Parent closes it's read end of the pipe close (writepipe[0]); sleep(1); while (pov_renderer_output.good()) { char buffer[1000]; pov_renderer_output.getline(buffer, 1000); Size n = strlen(buffer); if(write(writepipe[1], buffer, n) != (int) n) { std::cerr << "Could not write to pipe!" << std::endl; return -1; } write(writepipe[1], "\n", 1); } // Parent closes it's write end of the pipe, this sends EOF to reader close (writepipe[1]); int status; waitpid( -1, &status, 0 ); } else { // we are in the child process and start povray // Child closes it's write end of the pipe close (writepipe[1]); // handle stdin already closed if(writepipe[0] != STDIN_FILENO) { if(dup2(writepipe[0], STDIN_FILENO) < 0) { std::cout << "Could not dup2!" << std::endl; return -1; } close(writepipe[0]); } execl ("/home/student/amoll/bin/povray", "povray", pov_arg.c_str(), 0); } nr++; nr2++; } std::cout << "Written " + String(nr2) + " images." << std::endl; // mainframe.show(); // return application.exec(); return 0; } <|endoftext|>
<commit_before>#include "InterpolationFunction.h" #include <QtGlobal> #include <math.h> #include <QtCore/QStringList> #include "Workspace.h" #include "SimulatedAnnealing.h" #include <set> #include <limits> #include <boost/foreach.hpp> //Optimierer: min_a (A*a - y) extern "C"{ int sgels_(char *trans, int *m, int *n, int * nrhs, float *a, int *lda, float *b, int *ldb, float *work, int *lwork, int *info); int dgels_(char *trans, int *m, int *n, int * nrhs, double *a, int *lda, double *b, int *ldb, double *work, int *lwork, int *info); } InterpolationFunction::InterpolationFunction(QString pjob_file, QString result) : m_pjob_file(pjob_file), m_result(result), m_mu(0.5), m_d(0) { buildParameterSorting(); m_interpolationPoints = interpolationPoints(); m_interpolationValues = interpolationValues(); Q_ASSERT(m_interpolationPoints.size() == m_interpolationValues.size()); remove_infs_and_nans(m_interpolationPoints, m_interpolationValues); Q_ASSERT(m_interpolationPoints.size() == m_interpolationValues.size()); BOOST_FOREACH(std::vector<double>& point, m_interpolationPoints){ Q_ASSERT(point.size() == m_interpolationPoints[0].size()); } m_xarr = new double[m_interpolationPoints[0].size()]; calculateMeanDistance(); calculateAlphas(m_interpolationPoints,m_interpolationValues); } void InterpolationFunction::buildParameterSorting(){ QSet< QHash<QString,double> > parameterCombinations = Workspace::getInstace().getResults().parameterCombinationsFor(m_pjob_file); QSet< QString > parameterNames; QHash<QString,double> combination; foreach(combination, parameterCombinations){ QString parameterName; foreach(parameterName, combination.keys()) parameterNames.insert(parameterName); } QStringList sortedParameterNames = parameterNames.toList(); qSort(sortedParameterNames); for(int i=0;i<sortedParameterNames.size();++i) m_parameterSorting[sortedParameterNames.at(i)] = i; } vector< vector<double> > InterpolationFunction::interpolationPoints(){ vector< vector<double> > result; QSet< QHash<QString,double> > parameterCombinations = Workspace::getInstace().getResults().parameterCombinationsFor(m_pjob_file); QHash<QString,double> combination; foreach(combination, parameterCombinations){ QString parameterName; vector<double> parameterValues; parameterValues.resize(combination.size()); foreach(parameterName, combination.keys()) parameterValues[m_parameterSorting[parameterName]] = combination[parameterName]; result.push_back(parameterValues); } return result; } vector<double> InterpolationFunction::interpolationValues(){ vector<double> result; QSet< QHash<QString,double> > parameterCombinations = Workspace::getInstace().getResults().parameterCombinationsFor(m_pjob_file); QHash<QString,double> combination; foreach(combination, parameterCombinations){ result.push_back(Workspace::getInstace().getResults().getValue(m_pjob_file,m_result,combination)); } return result; } InterpolationFunction::~InterpolationFunction(){ delete[] m_xarr; } double InterpolationFunction::getValue(QHash< QString, double > parameters){ if(m_interpolationPoints.size() == 0) return 0; Q_ASSERT(parameters.size() == static_cast<int>(m_interpolationPoints[0].size())); QString parameterName; foreach(parameterName, parameters.keys()) m_xarr[m_parameterSorting[parameterName]] = parameters[parameterName]; return f(m_xarr); } double InterpolationFunction::f(double* x){ //if(!m_hasSolution) return 0; double sum=0; // //x skalieren: // Data* main = Schlangensicht::getInstance().getMainData(); // for(unsigned int i=0; i < m_scaledPoints[0].size(); ++i){ // x[i] = (x[i] - main->getMinForVariable(main->getVariables()[i])) / // (main->getMaxForVariable(main->getVariables()[i]) - main->getMinForVariable(main->getVariables()[i])); // } for(unsigned int i=0; i < m_interpolationPoints.size(); ++i) sum += m_alphas[i] * R(i,m_interpolationPoints, x); // //Ausgabe skalieren: // sum = m_interpolationValues->getMin() + sum*(m_interpolationValues->getMax() - m_interpolationValues->getMin()); return sum; } void InterpolationFunction::calculateAlphas(vector<vector<double> > points, vector<double> values){ unsigned int size = points.size(); int* pivot = new int[size]; double* b = new double[size]; double* AT = new double[size*size]; for(unsigned int i=0;i<size;++i) b[i] = values[i]; unsigned int dim = points[0].size(); double* arr = new double[dim]; // to call a Fortran routine from C we // have to transform the matrix // c: spaltenweise // fortran: zeilenweise for (unsigned int i=0; i<size; i++) for(unsigned int j=0; j<size; j++){ for(unsigned int x=0; x<dim; x++) arr[x] = points[j][x]; AT[j+size*i]=R(i,points,arr); } delete[] arr; int info; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //---------------------- LAPACK: min_a (A*a - y) ---------------------------- //INPUT: A in AT, y in b //OUTPUT: a in b int m,n; m=n=size; int nrhs=1; int lwork=m*n; double* work2 = new double[m*n + m*n]; dgels_("N",&m,&n,&nrhs,AT,&m,b,&m,work2,&lwork,&info); //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- m_alphas.resize(size); for(unsigned int i=0;i<size;++i) if(0 == info){//Ergebnis nun in b m_alphas[i] = b[i]; }else{ m_alphas[i] = 0; } delete[] pivot; delete[] b; delete[] AT; delete[] work2; } double InterpolationFunction::R(unsigned int di, const vector<vector<double> >& points, double* xj){ float distance_sq = 0; float result_sq; for(unsigned int i=0; i < points[0].size(); ++i) distance_sq += (points[di][i]-xj[i])*(points[di][i]-xj[i]); result_sq = distance_sq + m_d*m_meanDistanceOfInterpolationPoints*m_d*m_meanDistanceOfInterpolationPoints; return pow(double(result_sq), double(m_mu)); } double InterpolationFunction::distance(vector<double> x,vector<double> y){ float sum=0; for(unsigned int i=0; i < x.size(); ++i) sum += (x[i]-y[i])*(x[i]-y[i]); return sqrt(sum); } void InterpolationFunction::calculateMeanDistance(){ unsigned int size = m_interpolationPoints.size(); float meanDistance=0; for(unsigned int i=0;i<size;++i){ float min; bool firstTime = true; for(unsigned int j=0;j<size;++j) if(j!=i){ float d = distance(m_interpolationPoints[i],m_interpolationPoints[j]); if(firstTime || d<min){ min = d; firstTime = false; } } meanDistance += min; } m_meanDistanceOfInterpolationPoints = meanDistance / size; } QString InterpolationFunction::pjob_file(){ return m_pjob_file; } QString InterpolationFunction::result(){ return m_result; } QDoubleHash InterpolationFunction::findMinimum(){ SimulatedAnnealing sa(this); return sa.findMinimum(); } QDoubleHash InterpolationFunction::findMaximum(){ SimulatedAnnealing sa(this); return sa.findMaximum(); } void InterpolationFunction::remove_infs_and_nans(vector< vector<double> >& points, vector<double>& values){ set<unsigned int> indices_to_remove; for(unsigned int i=0;i<values.size();i++){ if((values[i] != values[i]) || (values[i] == numeric_limits<double>::infinity())) indices_to_remove.insert(i); } vector< vector<double> > new_points; vector<double> new_values; for(unsigned int i=0;i<values.size();i++){ if(indices_to_remove.count(i)) continue; new_points.push_back(points[i]); new_values.push_back(values[i]); } points = new_points; values = new_values; } <commit_msg>Fixed InterpolationFunction and therefore 3D-View.<commit_after>#include "InterpolationFunction.h" #include <QtGlobal> #include <math.h> #include <QtCore/QStringList> #include "Workspace.h" #include "SimulatedAnnealing.h" #include <set> #include <limits> #include <boost/foreach.hpp> //Optimierer: min_a (A*a - y) extern "C"{ int sgels_(char *trans, int *m, int *n, int * nrhs, float *a, int *lda, float *b, int *ldb, float *work, int *lwork, int *info); int dgels_(char *trans, int *m, int *n, int * nrhs, double *a, int *lda, double *b, int *ldb, double *work, int *lwork, int *info); } InterpolationFunction::InterpolationFunction(QString pjob_file, QString result) : m_pjob_file(pjob_file), m_result(result), m_mu(0.5), m_d(0) { buildParameterSorting(); m_interpolationPoints = interpolationPoints(); m_interpolationValues = interpolationValues(); Q_ASSERT(m_interpolationPoints.size() == m_interpolationValues.size()); remove_infs_and_nans(m_interpolationPoints, m_interpolationValues); Q_ASSERT(m_interpolationPoints.size() == m_interpolationValues.size()); BOOST_FOREACH(std::vector<double>& point, m_interpolationPoints){ Q_ASSERT(point.size() == m_interpolationPoints[0].size()); } m_xarr = new double[m_interpolationPoints[0].size()]; calculateMeanDistance(); calculateAlphas(m_interpolationPoints,m_interpolationValues); } void InterpolationFunction::buildParameterSorting(){ QSet< QHash<QString,double> > parameterCombinations = Workspace::getInstace().getResults().parameterCombinationsFor(m_pjob_file); QSet< QString > parameterNames; QHash<QString,double> combination; foreach(combination, parameterCombinations){ QString parameterName; foreach(parameterName, combination.keys()) parameterNames.insert(parameterName); } QStringList sortedParameterNames = parameterNames.toList(); qSort(sortedParameterNames); for(int i=0;i<sortedParameterNames.size();++i) m_parameterSorting[sortedParameterNames.at(i)] = i; } vector< vector<double> > InterpolationFunction::interpolationPoints(){ vector< vector<double> > result; QSet< QHash<QString,double> > parameterCombinations = Workspace::getInstace().getResults().parameterCombinationsFor(m_pjob_file); QHash<QString,double> combination; foreach(combination, parameterCombinations){ QString parameterName; vector<double> parameterValues; parameterValues.resize(combination.size()); foreach(parameterName, combination.keys()) parameterValues[m_parameterSorting[parameterName]] = combination[parameterName]; result.push_back(parameterValues); } return result; } vector<double> InterpolationFunction::interpolationValues(){ vector<double> result; QSet< QHash<QString,double> > parameterCombinations = Workspace::getInstace().getResults().parameterCombinationsFor(m_pjob_file); QHash<QString,double> combination; foreach(combination, parameterCombinations){ result.push_back(Workspace::getInstace().getResults().getValue(m_pjob_file,m_result,combination)); } return result; } InterpolationFunction::~InterpolationFunction(){ delete[] m_xarr; } double InterpolationFunction::getValue(QHash< QString, double > parameters){ if(m_interpolationPoints.size() == 0) return 0; Q_ASSERT(parameters.size() == static_cast<int>(m_interpolationPoints[0].size())); QString parameterName; foreach(parameterName, parameters.keys()) m_xarr[m_parameterSorting[parameterName]] = parameters[parameterName]; return f(m_xarr); } double InterpolationFunction::f(double* x){ //if(!m_hasSolution) return 0; double sum=0; // //x skalieren: // Data* main = Schlangensicht::getInstance().getMainData(); // for(unsigned int i=0; i < m_scaledPoints[0].size(); ++i){ // x[i] = (x[i] - main->getMinForVariable(main->getVariables()[i])) / // (main->getMaxForVariable(main->getVariables()[i]) - main->getMinForVariable(main->getVariables()[i])); // } for(unsigned int i=0; i < m_interpolationPoints.size(); ++i) sum += m_alphas[i] * R(i,m_interpolationPoints, x); // //Ausgabe skalieren: // sum = m_interpolationValues->getMin() + sum*(m_interpolationValues->getMax() - m_interpolationValues->getMin()); return sum; } void InterpolationFunction::calculateAlphas(vector<vector<double> > points, vector<double> values){ unsigned int size = points.size(); int* pivot = new int[size]; double* b = new double[size]; double* AT = new double[size*size]; for(unsigned int i=0;i<size;++i) b[i] = values[i]; unsigned int dim = points[0].size(); double* arr = new double[dim]; // to call a Fortran routine from C we // have to transform the matrix // c: spaltenweise // fortran: zeilenweise for (unsigned int i=0; i<size; i++) for(unsigned int j=0; j<size; j++){ for(unsigned int x=0; x<dim; x++) arr[x] = points[j][x]; AT[j+size*i]=R(i,points,arr); } delete[] arr; int info; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //---------------------- LAPACK: min_a (A*a - y) ---------------------------- //INPUT: A in AT, y in b //OUTPUT: a in b int m,n; m=n=size; int nrhs=1; int lwork=m*n; double* work2 = new double[m*n + m*n]; int lwork2=2*m*n; dgels_("N",&m,&n,&nrhs,AT,&m,b,&m,work2,&lwork2,&info); //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- m_alphas.resize(size); for(unsigned int i=0;i<size;++i) if(0 == info){//Ergebnis nun in b m_alphas[i] = b[i]; }else{ m_alphas[i] = 0; } delete[] pivot; delete[] b; delete[] AT; delete[] work2; } double InterpolationFunction::R(unsigned int di, const vector<vector<double> >& points, double* xj){ float distance_sq = 0; float result_sq; for(unsigned int i=0; i < points[0].size(); ++i) distance_sq += (points[di][i]-xj[i])*(points[di][i]-xj[i]); result_sq = distance_sq + m_d*m_meanDistanceOfInterpolationPoints*m_d*m_meanDistanceOfInterpolationPoints; return pow(double(result_sq), double(m_mu)); } double InterpolationFunction::distance(vector<double> x,vector<double> y){ float sum=0; for(unsigned int i=0; i < x.size(); ++i) sum += (x[i]-y[i])*(x[i]-y[i]); return sqrt(sum); } void InterpolationFunction::calculateMeanDistance(){ unsigned int size = m_interpolationPoints.size(); float meanDistance=0; for(unsigned int i=0;i<size;++i){ float min; bool firstTime = true; for(unsigned int j=0;j<size;++j) if(j!=i){ float d = distance(m_interpolationPoints[i],m_interpolationPoints[j]); if(firstTime || d<min){ min = d; firstTime = false; } } meanDistance += min; } m_meanDistanceOfInterpolationPoints = meanDistance / size; } QString InterpolationFunction::pjob_file(){ return m_pjob_file; } QString InterpolationFunction::result(){ return m_result; } QDoubleHash InterpolationFunction::findMinimum(){ SimulatedAnnealing sa(this); return sa.findMinimum(); } QDoubleHash InterpolationFunction::findMaximum(){ SimulatedAnnealing sa(this); return sa.findMaximum(); } void InterpolationFunction::remove_infs_and_nans(vector< vector<double> >& points, vector<double>& values){ set<unsigned int> indices_to_remove; for(unsigned int i=0;i<values.size();i++){ if((values[i] != values[i]) || (values[i] == numeric_limits<double>::infinity())) indices_to_remove.insert(i); } vector< vector<double> > new_points; vector<double> new_values; for(unsigned int i=0;i<values.size();i++){ if(indices_to_remove.count(i)) continue; new_points.push_back(points[i]); new_values.push_back(values[i]); } points = new_points; values = new_values; } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/executors/CPUThreadPoolExecutor.h> #include <folly/Memory.h> #include <folly/concurrency/QueueObserver.h> #include <folly/executors/task_queue/PriorityLifoSemMPMCQueue.h> #include <folly/executors/task_queue/PriorityUnboundedBlockingQueue.h> #include <folly/executors/task_queue/UnboundedBlockingQueue.h> #include <folly/portability/GFlags.h> DEFINE_bool( dynamic_cputhreadpoolexecutor, true, "CPUThreadPoolExecutor will dynamically create and destroy threads"); namespace folly { namespace { // queue_alloc custom allocator is necessary until C++17 // http://open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3396.htm // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65122 // https://bugs.llvm.org/show_bug.cgi?id=22634 using default_queue = UnboundedBlockingQueue<CPUThreadPoolExecutor::CPUTask>; using default_queue_alloc = AlignedSysAllocator<default_queue, FixedAlign<alignof(default_queue)>>; constexpr folly::StringPiece executorName = "CPUThreadPoolExecutor"; } // namespace const size_t CPUThreadPoolExecutor::kDefaultMaxQueueSize = 1 << 14; CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, std::unique_ptr<BlockingQueue<CPUTask>> taskQueue, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads, FLAGS_dynamic_cputhreadpoolexecutor ? 0 : numThreads, std::move(threadFactory)), taskQueue_(taskQueue.release()) { setNumThreads(numThreads); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor( std::pair<size_t, size_t> numThreads, std::unique_ptr<BlockingQueue<CPUTask>> taskQueue, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads.first, numThreads.second, std::move(threadFactory)), taskQueue_(taskQueue.release()) { setNumThreads(numThreads.first); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads, FLAGS_dynamic_cputhreadpoolexecutor ? 0 : numThreads, std::move(threadFactory)), taskQueue_(std::allocate_shared<default_queue>(default_queue_alloc{})) { setNumThreads(numThreads); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor( std::pair<size_t, size_t> numThreads, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads.first, numThreads.second, std::move(threadFactory)), taskQueue_(std::allocate_shared<default_queue>(default_queue_alloc{})) { setNumThreads(numThreads.first); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor(size_t numThreads) : CPUThreadPoolExecutor( numThreads, std::make_shared<NamedThreadFactory>("CPUThreadPool")) {} CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, int8_t numPriorities, std::shared_ptr<ThreadFactory> threadFactory) : CPUThreadPoolExecutor( numThreads, std::make_unique<PriorityUnboundedBlockingQueue<CPUTask>>( numPriorities), std::move(threadFactory)) {} CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, int8_t numPriorities, size_t maxQueueSize, std::shared_ptr<ThreadFactory> threadFactory) : CPUThreadPoolExecutor( numThreads, std::make_unique<PriorityLifoSemMPMCQueue<CPUTask>>( numPriorities, maxQueueSize), std::move(threadFactory)) {} CPUThreadPoolExecutor::~CPUThreadPoolExecutor() { deregisterThreadPoolExecutor(this); stop(); CHECK(threadsToStop_ == 0); for (auto& observer : queueObservers_) { delete observer.load(std::memory_order_relaxed); } } QueueObserver* FOLLY_NULLABLE CPUThreadPoolExecutor::getQueueObserver(int8_t pri) { if (!queueObserverFactory_) { return nullptr; } auto& slot = queueObservers_[static_cast<uint8_t>(pri)]; if (auto observer = slot.load(std::memory_order_acquire)) { return observer; } // common case is only one queue, need only one observer if (getNumPriorities() == 1 && pri != 0) { return getQueueObserver(0); } QueueObserver* existingObserver = nullptr; QueueObserver* newObserver = queueObserverFactory_->create(pri).release(); if (!slot.compare_exchange_strong(existingObserver, newObserver)) { delete newObserver; return existingObserver; } else { return newObserver; } } void CPUThreadPoolExecutor::add(Func func) { add(std::move(func), std::chrono::milliseconds(0)); } void CPUThreadPoolExecutor::add( Func func, std::chrono::milliseconds expiration, Func expireCallback) { CPUTask task{std::move(func), expiration, std::move(expireCallback), 0}; if (auto queueObserver = getQueueObserver(0)) { task.queueObserverPayload() = queueObserver->onEnqueued(); } auto result = taskQueue_->add(std::move(task)); if (!result.reusedThread) { ensureActiveThreads(); } } void CPUThreadPoolExecutor::addWithPriority(Func func, int8_t priority) { add(std::move(func), priority, std::chrono::milliseconds(0)); } void CPUThreadPoolExecutor::add( Func func, int8_t priority, std::chrono::milliseconds expiration, Func expireCallback) { CHECK(getNumPriorities() > 0); CPUTask task( std::move(func), expiration, std::move(expireCallback), priority); if (auto queueObserver = getQueueObserver(priority)) { task.queueObserverPayload() = queueObserver->onEnqueued(); } auto result = taskQueue_->addWithPriority(std::move(task), priority); if (!result.reusedThread) { ensureActiveThreads(); } } uint8_t CPUThreadPoolExecutor::getNumPriorities() const { return taskQueue_->getNumPriorities(); } size_t CPUThreadPoolExecutor::getTaskQueueSize() const { return taskQueue_->size(); } BlockingQueue<CPUThreadPoolExecutor::CPUTask>* CPUThreadPoolExecutor::getTaskQueue() { return taskQueue_.get(); } // threadListLock_ must be writelocked. bool CPUThreadPoolExecutor::tryDecrToStop() { auto toStop = threadsToStop_.load(std::memory_order_relaxed); if (toStop <= 0) { return false; } threadsToStop_.store(toStop - 1, std::memory_order_relaxed); return true; } bool CPUThreadPoolExecutor::taskShouldStop(folly::Optional<CPUTask>& task) { if (tryDecrToStop()) { return true; } if (task) { return false; } else { return tryTimeoutThread(); } return true; } void CPUThreadPoolExecutor::threadRun(ThreadPtr thread) { this->threadPoolHook_.registerThread(); ExecutorBlockingGuard guard{ExecutorBlockingGuard::ForbidTag{}, executorName}; thread->startupBaton.post(); while (true) { auto task = taskQueue_->try_take_for(threadTimeout_); // Handle thread stopping, either by task timeout, or // by 'poison' task added in join() or stop(). if (UNLIKELY(!task || task.value().poison)) { // Actually remove the thread from the list. SharedMutex::WriteHolder w{&threadListLock_}; if (taskShouldStop(task)) { for (auto& o : observers_) { o->threadStopped(thread.get()); } threadList_.remove(thread); stoppedThreads_.add(thread); return; } else { continue; } } if (auto queueObserver = getQueueObserver(task->queuePriority())) { queueObserver->onDequeued(task->queueObserverPayload()); } runTask(thread, std::move(task.value())); if (UNLIKELY(threadsToStop_ > 0 && !isJoin_)) { SharedMutex::WriteHolder w{&threadListLock_}; if (tryDecrToStop()) { threadList_.remove(thread); stoppedThreads_.add(thread); return; } } } } void CPUThreadPoolExecutor::stopThreads(size_t n) { threadsToStop_ += n; for (size_t i = 0; i < n; i++) { taskQueue_->addWithPriority(CPUTask(), Executor::LO_PRI); } } // threadListLock_ is read (or write) locked. size_t CPUThreadPoolExecutor::getPendingTaskCountImpl() const { return taskQueue_->size(); } std::unique_ptr<folly::QueueObserverFactory> CPUThreadPoolExecutor::createQueueObserverFactory() { for (auto& observer : queueObservers_) { observer.store(nullptr, std::memory_order_release); } return QueueObserverFactory::make( "cpu." + getName(), taskQueue_->getNumPriorities()); } } // namespace folly <commit_msg>better lag detector factory caching<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/executors/CPUThreadPoolExecutor.h> #include <folly/Memory.h> #include <folly/concurrency/QueueObserver.h> #include <folly/executors/task_queue/PriorityLifoSemMPMCQueue.h> #include <folly/executors/task_queue/PriorityUnboundedBlockingQueue.h> #include <folly/executors/task_queue/UnboundedBlockingQueue.h> #include <folly/portability/GFlags.h> DEFINE_bool( dynamic_cputhreadpoolexecutor, true, "CPUThreadPoolExecutor will dynamically create and destroy threads"); namespace folly { namespace { // queue_alloc custom allocator is necessary until C++17 // http://open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3396.htm // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65122 // https://bugs.llvm.org/show_bug.cgi?id=22634 using default_queue = UnboundedBlockingQueue<CPUThreadPoolExecutor::CPUTask>; using default_queue_alloc = AlignedSysAllocator<default_queue, FixedAlign<alignof(default_queue)>>; constexpr folly::StringPiece executorName = "CPUThreadPoolExecutor"; } // namespace const size_t CPUThreadPoolExecutor::kDefaultMaxQueueSize = 1 << 14; CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, std::unique_ptr<BlockingQueue<CPUTask>> taskQueue, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads, FLAGS_dynamic_cputhreadpoolexecutor ? 0 : numThreads, std::move(threadFactory)), taskQueue_(taskQueue.release()) { setNumThreads(numThreads); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor( std::pair<size_t, size_t> numThreads, std::unique_ptr<BlockingQueue<CPUTask>> taskQueue, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads.first, numThreads.second, std::move(threadFactory)), taskQueue_(taskQueue.release()) { setNumThreads(numThreads.first); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads, FLAGS_dynamic_cputhreadpoolexecutor ? 0 : numThreads, std::move(threadFactory)), taskQueue_(std::allocate_shared<default_queue>(default_queue_alloc{})) { setNumThreads(numThreads); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor( std::pair<size_t, size_t> numThreads, std::shared_ptr<ThreadFactory> threadFactory) : ThreadPoolExecutor( numThreads.first, numThreads.second, std::move(threadFactory)), taskQueue_(std::allocate_shared<default_queue>(default_queue_alloc{})) { setNumThreads(numThreads.first); registerThreadPoolExecutor(this); } CPUThreadPoolExecutor::CPUThreadPoolExecutor(size_t numThreads) : CPUThreadPoolExecutor( numThreads, std::make_shared<NamedThreadFactory>("CPUThreadPool")) {} CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, int8_t numPriorities, std::shared_ptr<ThreadFactory> threadFactory) : CPUThreadPoolExecutor( numThreads, std::make_unique<PriorityUnboundedBlockingQueue<CPUTask>>( numPriorities), std::move(threadFactory)) {} CPUThreadPoolExecutor::CPUThreadPoolExecutor( size_t numThreads, int8_t numPriorities, size_t maxQueueSize, std::shared_ptr<ThreadFactory> threadFactory) : CPUThreadPoolExecutor( numThreads, std::make_unique<PriorityLifoSemMPMCQueue<CPUTask>>( numPriorities, maxQueueSize), std::move(threadFactory)) {} CPUThreadPoolExecutor::~CPUThreadPoolExecutor() { deregisterThreadPoolExecutor(this); stop(); CHECK(threadsToStop_ == 0); if (getNumPriorities() == 1) { delete queueObservers_[0]; } else { for (auto& observer : queueObservers_) { delete observer.load(std::memory_order_relaxed); } } } QueueObserver* FOLLY_NULLABLE CPUThreadPoolExecutor::getQueueObserver(int8_t pri) { if (!queueObserverFactory_) { return nullptr; } auto& slot = queueObservers_[folly::to_unsigned(pri)]; if (auto observer = slot.load(std::memory_order_acquire)) { return observer; } // common case is only one queue, need only one observer if (getNumPriorities() == 1 && pri != 0) { auto sharedObserver = getQueueObserver(0); slot.store(sharedObserver, std::memory_order_release); return sharedObserver; } QueueObserver* existingObserver = nullptr; auto newObserver = queueObserverFactory_->create(pri); if (!slot.compare_exchange_strong(existingObserver, newObserver.get())) { return existingObserver; } else { return newObserver.release(); } } void CPUThreadPoolExecutor::add(Func func) { add(std::move(func), std::chrono::milliseconds(0)); } void CPUThreadPoolExecutor::add( Func func, std::chrono::milliseconds expiration, Func expireCallback) { CPUTask task{std::move(func), expiration, std::move(expireCallback), 0}; if (auto queueObserver = getQueueObserver(0)) { task.queueObserverPayload() = queueObserver->onEnqueued(); } auto result = taskQueue_->add(std::move(task)); if (!result.reusedThread) { ensureActiveThreads(); } } void CPUThreadPoolExecutor::addWithPriority(Func func, int8_t priority) { add(std::move(func), priority, std::chrono::milliseconds(0)); } void CPUThreadPoolExecutor::add( Func func, int8_t priority, std::chrono::milliseconds expiration, Func expireCallback) { CHECK(getNumPriorities() > 0); CPUTask task( std::move(func), expiration, std::move(expireCallback), priority); if (auto queueObserver = getQueueObserver(priority)) { task.queueObserverPayload() = queueObserver->onEnqueued(); } auto result = taskQueue_->addWithPriority(std::move(task), priority); if (!result.reusedThread) { ensureActiveThreads(); } } uint8_t CPUThreadPoolExecutor::getNumPriorities() const { return taskQueue_->getNumPriorities(); } size_t CPUThreadPoolExecutor::getTaskQueueSize() const { return taskQueue_->size(); } BlockingQueue<CPUThreadPoolExecutor::CPUTask>* CPUThreadPoolExecutor::getTaskQueue() { return taskQueue_.get(); } // threadListLock_ must be writelocked. bool CPUThreadPoolExecutor::tryDecrToStop() { auto toStop = threadsToStop_.load(std::memory_order_relaxed); if (toStop <= 0) { return false; } threadsToStop_.store(toStop - 1, std::memory_order_relaxed); return true; } bool CPUThreadPoolExecutor::taskShouldStop(folly::Optional<CPUTask>& task) { if (tryDecrToStop()) { return true; } if (task) { return false; } else { return tryTimeoutThread(); } return true; } void CPUThreadPoolExecutor::threadRun(ThreadPtr thread) { this->threadPoolHook_.registerThread(); ExecutorBlockingGuard guard{ExecutorBlockingGuard::ForbidTag{}, executorName}; thread->startupBaton.post(); while (true) { auto task = taskQueue_->try_take_for(threadTimeout_); // Handle thread stopping, either by task timeout, or // by 'poison' task added in join() or stop(). if (UNLIKELY(!task || task.value().poison)) { // Actually remove the thread from the list. SharedMutex::WriteHolder w{&threadListLock_}; if (taskShouldStop(task)) { for (auto& o : observers_) { o->threadStopped(thread.get()); } threadList_.remove(thread); stoppedThreads_.add(thread); return; } else { continue; } } if (auto queueObserver = getQueueObserver(task->queuePriority())) { queueObserver->onDequeued(task->queueObserverPayload()); } runTask(thread, std::move(task.value())); if (UNLIKELY(threadsToStop_ > 0 && !isJoin_)) { SharedMutex::WriteHolder w{&threadListLock_}; if (tryDecrToStop()) { threadList_.remove(thread); stoppedThreads_.add(thread); return; } } } } void CPUThreadPoolExecutor::stopThreads(size_t n) { threadsToStop_ += n; for (size_t i = 0; i < n; i++) { taskQueue_->addWithPriority(CPUTask(), Executor::LO_PRI); } } // threadListLock_ is read (or write) locked. size_t CPUThreadPoolExecutor::getPendingTaskCountImpl() const { return taskQueue_->size(); } std::unique_ptr<folly::QueueObserverFactory> CPUThreadPoolExecutor::createQueueObserverFactory() { for (auto& observer : queueObservers_) { observer.store(nullptr, std::memory_order_release); } return QueueObserverFactory::make( "cpu." + getName(), taskQueue_->getNumPriorities()); } } // namespace folly <|endoftext|>
<commit_before>/* main.cpp - CS 472 Project #3: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer */ #include <cstdlib> #include <chrono> #include <ctime> #include <iostream> #include <tuple> #include "algorithm/algorithm.hpp" #include "individual/individual.hpp" #include "options/options.hpp" #include "random_generator/random_generator.hpp" #include "trials/trials.hpp" int main(int argc, char* argv[]) { // Retrieve program options. const options::Options options = options::parse(argc, argv); // Chrono start, end, and Unix time variables. std::chrono::time_point<std::chrono::system_clock> start, end; std::time_t time = std::time(nullptr); // Begin timing trials. start = std::chrono::system_clock::now(); // Run trials and save best Individual. const std::tuple<int, individual::Individual> best = trials::run(time, options); // End timing trials. end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; // Print total time info and which trial was best. std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n" << "Average time: " << elapsed_seconds.count() / options.trials << "s\nBest trial: " << time << "_" << std::get<0>(best) << "\n" << std::get<1>(best).print(); return EXIT_SUCCESS; } <commit_msg>Learned about std::tie<commit_after>/* main.cpp - CS 472 Project #3: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer */ #include <cstdlib> #include <chrono> #include <ctime> #include <iostream> #include <tuple> #include "algorithm/algorithm.hpp" #include "individual/individual.hpp" #include "options/options.hpp" #include "random_generator/random_generator.hpp" #include "trials/trials.hpp" int main(int argc, char* argv[]) { // Retrieve program options. const options::Options options = options::parse(argc, argv); // Chrono start, end, and Unix time variables. std::chrono::time_point<std::chrono::system_clock> start, end; std::time_t time = std::time(nullptr); // Begin timing trials. start = std::chrono::system_clock::now(); // Run trials and save best Individual. int best_index; individual::Individual best; std::tie(best_index, best) = trials::run(time, options); // End timing trials. end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; // Print total time info and which trial was best. std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n" << "Average time: " << elapsed_seconds.count() / options.trials << "s\nBest trial: " << time << "_" << best_index << "\n" << best.print(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FormattedField.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: obo $ $Date: 2007-03-09 13:26:13 $ * * 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 _FORMS_FORMATTEDFIELD_HXX_ #define _FORMS_FORMATTEDFIELD_HXX_ #ifndef _FORMS_EDITBASE_HXX_ #include "EditBase.hxx" #endif #ifndef _COMPHELPER_PROPERTY_MULTIPLEX_HXX_ #include <comphelper/propmultiplex.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef FORMS_ERRORBROADCASTER_HXX #include "errorbroadcaster.hxx" #endif //......................................................................... namespace frm { //================================================================== //= OFormattedModel //================================================================== class OFormattedModel :public OEditBaseModel ,public OErrorBroadcaster { // das Original, falls ich die Format-Properties meines aggregierten Models gefaket, d.h. von dem Feld, an das // ich gebunden bin, weitergereicht habe (nur gueltig wenn loaded) ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> m_xOriginalFormatter; ::com::sun::star::util::Date m_aNullDate; ::com::sun::star::uno::Any m_aSaveValue; sal_Int32 m_nFieldType; sal_Int16 m_nKeyType; sal_Bool m_bOriginalNumeric : 1, m_bNumeric : 1; // analog fuer TreatAsNumeric-Property protected: ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcDefaultFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormatsSupplier() const; sal_Int32 calcFormatKey() const; DECLARE_DEFAULT_LEAF_XTOR( OFormattedModel ); friend InterfaceRef SAL_CALL OFormattedModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); friend class OFormattedFieldWrapper; protected: // XInterface DECLARE_UNO3_AGG_DEFAULTS( OFormattedModel, OEditBaseModel ); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // XAggregation virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(); // XServiceInfo IMPLEMENTATION_NAME(OFormattedModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // XPersistObject virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception); // XLoadListener virtual void SAL_CALL loaded(const ::com::sun::star::lang::EventObject& rEvent) throw ( ::com::sun::star::uno::RuntimeException); // XPropertyState void setPropertyToDefaultByHandle(sal_Int32 nHandle); ::com::sun::star::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const; void SAL_CALL setPropertyToDefault(const ::rtl::OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; virtual void describeAggregateProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; // XPropertyChangeListener virtual void _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw(::com::sun::star::uno::RuntimeException); // prevent method hiding using OEditBaseModel::disposing; using OEditBaseModel::getFastPropertyValue; protected: virtual sal_uInt16 getPersistenceFlags() const; // as we have an own version handling for persistence // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ) const; virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ) const; virtual void onConnectedExternalValue( ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual void onDisconnectedDbColumn(); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: /** retrieves the type which should be used to communicate with the current external binding The type depends on the current number format, and the types which are supported by the current external binding. As a least fallback, |double|'s type is returned. (In approveValueBinding, we ensure that only bindings supporting |double|'s are accepted.) @precond hasExternalValueBinding returns <TRUE/> */ ::com::sun::star::uno::Type getExternalValueType() const; private: DECLARE_XCLONEABLE(); void implConstruct(); void updateFormatterNullDate(); }; //================================================================== //= OFormattedControl //================================================================== typedef ::cppu::ImplHelper1< ::com::sun::star::awt::XKeyListener> OFormattedControl_BASE; class OFormattedControl : public OBoundControl ,public OFormattedControl_BASE { sal_uInt32 m_nKeyEvent; public: OFormattedControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OFormattedControl(); DECLARE_UNO3_AGG_DEFAULTS(OFormattedControl, OBoundControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OFormattedControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XKeyListener virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XControl virtual void SAL_CALL setDesignMode(sal_Bool bOn) throw ( ::com::sun::star::uno::RuntimeException); // disambiguation using OBoundControl::disposing; private: DECL_LINK( OnKeyPressed, void* ); }; //......................................................................... } //......................................................................... #endif // _FORMS_FORMATTEDFIELD_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.17.82); FILE MERGED 2008/04/01 15:16:30 thb 1.17.82.3: #i85898# Stripping all external header guards 2008/04/01 12:30:22 thb 1.17.82.2: #i85898# Stripping all external header guards 2008/03/31 13:11:33 rt 1.17.82.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: FormattedField.hxx,v $ * $Revision: 1.18 $ * * 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 _FORMS_FORMATTEDFIELD_HXX_ #define _FORMS_FORMATTEDFIELD_HXX_ #include "EditBase.hxx" #include <comphelper/propmultiplex.hxx> #include <cppuhelper/implbase1.hxx> #include "errorbroadcaster.hxx" //......................................................................... namespace frm { //================================================================== //= OFormattedModel //================================================================== class OFormattedModel :public OEditBaseModel ,public OErrorBroadcaster { // das Original, falls ich die Format-Properties meines aggregierten Models gefaket, d.h. von dem Feld, an das // ich gebunden bin, weitergereicht habe (nur gueltig wenn loaded) ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> m_xOriginalFormatter; ::com::sun::star::util::Date m_aNullDate; ::com::sun::star::uno::Any m_aSaveValue; sal_Int32 m_nFieldType; sal_Int16 m_nKeyType; sal_Bool m_bOriginalNumeric : 1, m_bNumeric : 1; // analog fuer TreatAsNumeric-Property protected: ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcDefaultFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormatsSupplier() const; sal_Int32 calcFormatKey() const; DECLARE_DEFAULT_LEAF_XTOR( OFormattedModel ); friend InterfaceRef SAL_CALL OFormattedModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); friend class OFormattedFieldWrapper; protected: // XInterface DECLARE_UNO3_AGG_DEFAULTS( OFormattedModel, OEditBaseModel ); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // XAggregation virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(); // XServiceInfo IMPLEMENTATION_NAME(OFormattedModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // XPersistObject virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception); // XLoadListener virtual void SAL_CALL loaded(const ::com::sun::star::lang::EventObject& rEvent) throw ( ::com::sun::star::uno::RuntimeException); // XPropertyState void setPropertyToDefaultByHandle(sal_Int32 nHandle); ::com::sun::star::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const; void SAL_CALL setPropertyToDefault(const ::rtl::OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; virtual void describeAggregateProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; // XPropertyChangeListener virtual void _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw(::com::sun::star::uno::RuntimeException); // prevent method hiding using OEditBaseModel::disposing; using OEditBaseModel::getFastPropertyValue; protected: virtual sal_uInt16 getPersistenceFlags() const; // as we have an own version handling for persistence // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ) const; virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ) const; virtual void onConnectedExternalValue( ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual void onDisconnectedDbColumn(); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: /** retrieves the type which should be used to communicate with the current external binding The type depends on the current number format, and the types which are supported by the current external binding. As a least fallback, |double|'s type is returned. (In approveValueBinding, we ensure that only bindings supporting |double|'s are accepted.) @precond hasExternalValueBinding returns <TRUE/> */ ::com::sun::star::uno::Type getExternalValueType() const; private: DECLARE_XCLONEABLE(); void implConstruct(); void updateFormatterNullDate(); }; //================================================================== //= OFormattedControl //================================================================== typedef ::cppu::ImplHelper1< ::com::sun::star::awt::XKeyListener> OFormattedControl_BASE; class OFormattedControl : public OBoundControl ,public OFormattedControl_BASE { sal_uInt32 m_nKeyEvent; public: OFormattedControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OFormattedControl(); DECLARE_UNO3_AGG_DEFAULTS(OFormattedControl, OBoundControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OFormattedControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XKeyListener virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XControl virtual void SAL_CALL setDesignMode(sal_Bool bOn) throw ( ::com::sun::star::uno::RuntimeException); // disambiguation using OBoundControl::disposing; private: DECL_LINK( OnKeyPressed, void* ); }; //......................................................................... } //......................................................................... #endif // _FORMS_FORMATTEDFIELD_HXX_ <|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: FormattedField.hxx,v $ * $Revision: 1.18 $ * * 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 _FORMS_FORMATTEDFIELD_HXX_ #define _FORMS_FORMATTEDFIELD_HXX_ #include "EditBase.hxx" #include <comphelper/propmultiplex.hxx> #include <cppuhelper/implbase1.hxx> #include "errorbroadcaster.hxx" //......................................................................... namespace frm { //================================================================== //= OFormattedModel //================================================================== class OFormattedModel :public OEditBaseModel ,public OErrorBroadcaster { // das Original, falls ich die Format-Properties meines aggregierten Models gefaket, d.h. von dem Feld, an das // ich gebunden bin, weitergereicht habe (nur gueltig wenn loaded) ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> m_xOriginalFormatter; ::com::sun::star::util::Date m_aNullDate; ::com::sun::star::uno::Any m_aSaveValue; sal_Int32 m_nFieldType; sal_Int16 m_nKeyType; sal_Bool m_bOriginalNumeric : 1, m_bNumeric : 1; // analog fuer TreatAsNumeric-Property protected: ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcDefaultFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormatsSupplier() const; sal_Int32 calcFormatKey() const; DECLARE_DEFAULT_LEAF_XTOR( OFormattedModel ); friend InterfaceRef SAL_CALL OFormattedModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); friend class OFormattedFieldWrapper; protected: // XInterface DECLARE_UNO3_AGG_DEFAULTS( OFormattedModel, OEditBaseModel ); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // XAggregation virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(); // XServiceInfo IMPLEMENTATION_NAME(OFormattedModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // XPersistObject virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception); // XLoadListener virtual void SAL_CALL loaded(const ::com::sun::star::lang::EventObject& rEvent) throw ( ::com::sun::star::uno::RuntimeException); // XPropertyState void setPropertyToDefaultByHandle(sal_Int32 nHandle); ::com::sun::star::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const; void SAL_CALL setPropertyToDefault(const ::rtl::OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; virtual void describeAggregateProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; // XPropertyChangeListener virtual void _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw(::com::sun::star::uno::RuntimeException); // prevent method hiding using OEditBaseModel::disposing; using OEditBaseModel::getFastPropertyValue; protected: virtual sal_uInt16 getPersistenceFlags() const; // as we have an own version handling for persistence // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ) const; virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ) const; virtual void onConnectedExternalValue( ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual void onDisconnectedDbColumn(); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: /** retrieves the type which should be used to communicate with the current external binding The type depends on the current number format, and the types which are supported by the current external binding. As a least fallback, |double|'s type is returned. (In approveValueBinding, we ensure that only bindings supporting |double|'s are accepted.) @precond hasExternalValueBinding returns <TRUE/> */ ::com::sun::star::uno::Type getExternalValueType() const; private: DECLARE_XCLONEABLE(); void implConstruct(); void updateFormatterNullDate(); }; //================================================================== //= OFormattedControl //================================================================== typedef ::cppu::ImplHelper1< ::com::sun::star::awt::XKeyListener> OFormattedControl_BASE; class OFormattedControl : public OBoundControl ,public OFormattedControl_BASE { sal_uInt32 m_nKeyEvent; public: OFormattedControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OFormattedControl(); DECLARE_UNO3_AGG_DEFAULTS(OFormattedControl, OBoundControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OFormattedControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XKeyListener virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XControl virtual void SAL_CALL setDesignMode(sal_Bool bOn) throw ( ::com::sun::star::uno::RuntimeException); // disambiguation using OBoundControl::disposing; private: DECL_LINK( OnKeyPressed, void* ); }; //......................................................................... } //......................................................................... #endif // _FORMS_FORMATTEDFIELD_HXX_ <commit_msg>INTEGRATION: CWS dba30b (1.17.76); FILE MERGED 2008/04/15 21:52:44 fs 1.17.76.2: RESYNC: (1.17-1.18); FILE MERGED 2008/02/26 08:28:58 fs 1.17.76.1: remove unused code Issue number: #i86305# Submitted by: [email protected] Reviewed by: [email protected]<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: FormattedField.hxx,v $ * $Revision: 1.19 $ * * 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 _FORMS_FORMATTEDFIELD_HXX_ #define _FORMS_FORMATTEDFIELD_HXX_ #include "EditBase.hxx" #include <comphelper/propmultiplex.hxx> #include <cppuhelper/implbase1.hxx> #include "errorbroadcaster.hxx" //......................................................................... namespace frm { //================================================================== //= OFormattedModel //================================================================== class OFormattedModel :public OEditBaseModel ,public OErrorBroadcaster { // das Original, falls ich die Format-Properties meines aggregierten Models gefaket, d.h. von dem Feld, an das // ich gebunden bin, weitergereicht habe (nur gueltig wenn loaded) ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> m_xOriginalFormatter; ::com::sun::star::util::Date m_aNullDate; ::com::sun::star::uno::Any m_aSaveValue; sal_Int32 m_nFieldType; sal_Int16 m_nKeyType; sal_Bool m_bOriginalNumeric : 1, m_bNumeric : 1; // analog fuer TreatAsNumeric-Property protected: ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcDefaultFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormFormatsSupplier() const; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier> calcFormatsSupplier() const; DECLARE_DEFAULT_LEAF_XTOR( OFormattedModel ); friend class OFormattedFieldWrapper; protected: // XInterface DECLARE_UNO3_AGG_DEFAULTS( OFormattedModel, OEditBaseModel ); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // XAggregation virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(); // XServiceInfo IMPLEMENTATION_NAME(OFormattedModel); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // XPersistObject virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException); // XPropertySet virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw(::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception); // XLoadListener virtual void SAL_CALL loaded(const ::com::sun::star::lang::EventObject& rEvent) throw ( ::com::sun::star::uno::RuntimeException); // XPropertyState void setPropertyToDefaultByHandle(sal_Int32 nHandle); ::com::sun::star::uno::Any getPropertyDefaultByHandle(sal_Int32 nHandle) const; void SAL_CALL setPropertyToDefault(const ::rtl::OUString& aPropertyName) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); // OControlModel's property handling virtual void describeFixedProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps ) const; virtual void describeAggregateProperties( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps ) const; // XPropertyChangeListener virtual void _propertyChanged(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw(::com::sun::star::uno::RuntimeException); // prevent method hiding using OEditBaseModel::disposing; using OEditBaseModel::getFastPropertyValue; protected: virtual sal_uInt16 getPersistenceFlags() const; // as we have an own version handling for persistence // OBoundControlModel overridables virtual ::com::sun::star::uno::Any translateDbColumnToControlValue( ); virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset ); virtual ::com::sun::star::uno::Any translateExternalValueToControlValue( ) const; virtual ::com::sun::star::uno::Any translateControlValueToExternalValue( ) const; virtual void onConnectedExternalValue( ); virtual ::com::sun::star::uno::Any getDefaultForReset() const; virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm ); virtual void onDisconnectedDbColumn(); virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding ); protected: /** retrieves the type which should be used to communicate with the current external binding The type depends on the current number format, and the types which are supported by the current external binding. As a least fallback, |double|'s type is returned. (In approveValueBinding, we ensure that only bindings supporting |double|'s are accepted.) @precond hasExternalValueBinding returns <TRUE/> */ ::com::sun::star::uno::Type getExternalValueType() const; private: DECLARE_XCLONEABLE(); void implConstruct(); void updateFormatterNullDate(); }; //================================================================== //= OFormattedControl //================================================================== typedef ::cppu::ImplHelper1< ::com::sun::star::awt::XKeyListener> OFormattedControl_BASE; class OFormattedControl : public OBoundControl ,public OFormattedControl_BASE { sal_uInt32 m_nKeyEvent; public: OFormattedControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); virtual ~OFormattedControl(); DECLARE_UNO3_AGG_DEFAULTS(OFormattedControl, OBoundControl); virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes(); // ::com::sun::star::lang::XServiceInfo IMPLEMENTATION_NAME(OFormattedControl); virtual StringSequence SAL_CALL getSupportedServiceNames() throw(); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XKeyListener virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException); // ::com::sun::star::awt::XControl virtual void SAL_CALL setDesignMode(sal_Bool bOn) throw ( ::com::sun::star::uno::RuntimeException); // disambiguation using OBoundControl::disposing; private: DECL_LINK( OnKeyPressed, void* ); }; //......................................................................... } //......................................................................... #endif // _FORMS_FORMATTEDFIELD_HXX_ <|endoftext|>
<commit_before>#include <iostream> #include <memory> #include <vector> #include <unordered_map> #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> using namespace std; template<typename T> T clamp(T val, T from, T to) { return std::max(from, std::min(to, val)); } struct Color3 { float r, g, b; }; class Size { public: Size(int pixels) : _pixels(pixels) {} Size(float percents) : _percents(percents), _is_pixels(false) {} static Size All() { return Size(1.0f); } static Size Nth(int n) { return Size(1.0f / n); } int to_pixels(int base_pixels) const { if (_is_pixels) return clamp(_pixels, 0, base_pixels); else return (int) (_percents * base_pixels); } bool is_const() const { return _is_pixels; } float get_percents() const { return _percents; } int get_pixels() const { return _pixels; } private: int _pixels; float _percents; bool _is_pixels = true; }; struct Size2 { Size x, y; }; struct Int2 { int x, y; }; struct Rect { Int2 position, size; }; struct Margin { int left, right, top, bottom; Margin(int v) : left(v), right(v), top(v), bottom(v) {} Margin(int x, int y) : left(x), right(x), top(y), bottom(y) {} Margin(int left, int right, int top, int bottom) : left(left), right(right), top(top), bottom(bottom) {} Margin operator-() { return { -left, -right, -top, -bottom }; } Rect apply(const Rect& r) const { return { { r.position.x + left, r.position.y + top }, { r.size.x + left + right, r.size.y + top + bottom } }; } }; enum class MouseButton { left, middle, right }; enum class MouseState { down, up }; class IVisualElement { public: virtual Rect arrange(const Rect& origin) = 0; virtual void render(const Rect& origin) = 0; virtual const Margin& get_margin() const = 0; virtual const Size2& get_size() const = 0; virtual void UpdateMousePosition(Int2 cursor) = 0; virtual void UpdateMouseState(MouseButton button, MouseState state) = 0; virtual void UpdateMouseScroll(Int2 scroll) = 0; virtual ~IVisualElement() {} }; class MouseEventsHandler : public virtual IVisualElement { public: virtual void UpdateMousePosition(Int2 cursor) {}; virtual void UpdateMouseState(MouseButton button, MouseState state) {}; virtual void UpdateMouseScroll(Int2 scroll) {}; }; class ControlBase : public virtual IVisualElement, public MouseEventsHandler { public: ControlBase(const Size2& position, const Size2& size, const Margin& margin) : _position(position), _size(size), _margin(margin) {} Rect arrange(const Rect& origin) override { auto x0 = _position.x.to_pixels(origin.size.x) + _margin.left; auto y0 = _position.y.to_pixels(origin.size.y) + _margin.top; auto w = std::min(_size.x.to_pixels(origin.size.x), origin.size.x - _margin.right - _margin.left); auto h = std::min(_size.y.to_pixels(origin.size.y), origin.size.y - _margin.bottom - _margin.top); x0 += origin.position.x; y0 += origin.position.y; return { { x0, y0 }, { w, h } }; } const Margin& get_margin() const override { return _margin; } const Size2& get_size() const override { return _size; } private: Size2 _position; Size2 _size; Margin _margin; }; class Button : public ControlBase { public: Button(const Size2& position, const Size2& size, const Margin& margin, const Color3& color) : ControlBase(position, size, margin), _color(color) {} void render(const Rect& origin) override { glBegin(GL_QUADS); glColor3f(_color.r, _color.g, _color.b); auto rect = arrange(origin); glVertex2i(rect.position.x, rect.position.y); glVertex2i(rect.position.x, rect.position.y + rect.size.y); glVertex2i(rect.position.x + rect.size.x, rect.position.y + rect.size.y); glVertex2i(rect.position.x + rect.size.x, rect.position.y); glEnd(); } private: Color3 _color; }; enum class Orientation { vertical, horizontal }; class Container : public ControlBase { public: Container(const Size2& position, const Size2& size, const Margin& margin, Orientation orientation = Orientation::vertical) : ControlBase(position, size, margin), _orientation(orientation) {} void add_item(std::unique_ptr<IVisualElement> item) { _content.push_back(std::move(item)); } void render(const Rect& origin) override { auto rect = arrange(origin); Size Size2::* field; int Int2::* ifield; if (_orientation == Orientation::vertical) { field = &Size2::y; ifield = &Int2::y; } else { field = &Size2::x; ifield = &Int2::x; } // first, scan items, map the "greedy" ones wanting relative portion std::vector<IVisualElement*> greedy; std::unordered_map<IVisualElement*, int> sizes; auto sum = 0; for (auto& p : _content) { auto p_rect = p->arrange(rect); auto p_total = p->get_margin().apply(p_rect); if ((p->get_size().*field).is_const()) { auto pixels = (p->get_size().*field).get_pixels(); sum += pixels; sizes[p.get()] = pixels; } else { greedy.push_back(p.get()); } } auto rest = std::max(rect.size.*ifield - sum, 0); float total_parts = 0; for (auto ptr : greedy) { total_parts += (ptr->get_size().*field).get_percents(); } for (auto ptr : greedy) { auto f = ((ptr->get_size().*field).get_percents() / total_parts); sizes[ptr] = (int) (rest * f); } sum = rect.position.*ifield; for (auto& p : _content) { auto new_origin = rect; (new_origin.position.*ifield) = sum; (new_origin.size.*ifield) = sizes[p.get()]; sum += sizes[p.get()]; p->render(new_origin); } } private: std::vector<std::unique_ptr<IVisualElement>> _content; Orientation _orientation; }; int main(int argc, char * argv[]) try { glfwInit(); GLFWwindow * win = glfwCreateWindow(1280, 960, "main", 0, 0); glfwMakeContextCurrent(win); Color3 redish { 0.8f, 0.5f, 0.6f }; Container c( { 0, 0 }, { 300, 1.0f }, { 5, 5, 5, 5 } ); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 1.0f }, { 5, 5, 5, 5 }, redish ))); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); glfwSetWindowUserPointer(win, &c); glfwSetCursorPosCallback(win, [](GLFWwindow * w, double x, double y) { auto ui_element = (IVisualElement*)glfwGetWindowUserPointer(w); ui_element->UpdateMousePosition({ (int)x, (int)y }); }); glfwSetScrollCallback(win, [](GLFWwindow * w, double x, double y) { auto ui_element = (IVisualElement*)glfwGetWindowUserPointer(w); ui_element->UpdateMouseScroll({ (int)x, (int)y }); }); glfwSetMouseButtonCallback(win, [](GLFWwindow * w, int button, int action, int mods) { auto ui_element = (IVisualElement*)glfwGetWindowUserPointer(w); MouseButton button_type; switch(button) { case GLFW_MOUSE_BUTTON_RIGHT: button_type = MouseButton::right; break; case GLFW_MOUSE_BUTTON_LEFT: button_type = MouseButton::left; break; case GLFW_MOUSE_BUTTON_MIDDLE: button_type = MouseButton::middle; break; default: button_type = MouseButton::left; }; MouseState mouse_state; switch(action) { case GLFW_PRESS: mouse_state = MouseState::up; break; case GLFW_RELEASE: mouse_state = MouseState::down; break; default: mouse_state = MouseState::up; }; ui_element->UpdateMouseState(button_type, mouse_state); }); while (!glfwWindowShouldClose(win)) { glfwPollEvents(); int w,h; glfwGetFramebufferSize(win, &w, &h); glViewport(0, 0, w, h); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glfwGetWindowSize(win, &w, &h); glOrtho(0, w, h, 0, -1, +1); Rect origin { { 0, 0 }, { w, h } }; c.render(origin); glPopMatrix(); glfwSwapBuffers(win); } glfwDestroyWindow(win); glfwTerminate(); return 0; } catch(const std::exception & e) { std::cerr << e.what() << std::endl; return -1; } <commit_msg>adding support for basic clicking and double-clicking<commit_after>#include <iostream> #include <memory> #include <vector> #include <unordered_map> #include <chrono> #include <map> #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> using namespace std; template<typename T> T clamp(T val, T from, T to) { return std::max(from, std::min(to, val)); } struct Color3 { float r, g, b; }; class Size { public: Size(int pixels) : _pixels(pixels) {} Size(float percents) : _percents(percents), _is_pixels(false) {} static Size All() { return Size(1.0f); } static Size Nth(int n) { return Size(1.0f / n); } int to_pixels(int base_pixels) const { if (_is_pixels) return clamp(_pixels, 0, base_pixels); else return (int) (_percents * base_pixels); } bool is_const() const { return _is_pixels; } float get_percents() const { return _percents; } int get_pixels() const { return _pixels; } private: int _pixels; float _percents; bool _is_pixels = true; }; struct Size2 { Size x, y; }; struct Int2 { int x, y; }; struct Rect { Int2 position, size; }; struct Margin { int left, right, top, bottom; Margin(int v) : left(v), right(v), top(v), bottom(v) {} Margin(int x, int y) : left(x), right(x), top(y), bottom(y) {} Margin(int left, int right, int top, int bottom) : left(left), right(right), top(top), bottom(bottom) {} Margin operator-() { return { -left, -right, -top, -bottom }; } Rect apply(const Rect& r) const { return { { r.position.x + left, r.position.y + top }, { r.size.x + left + right, r.size.y + top + bottom } }; } }; enum class MouseButton { left, middle, right }; enum class MouseState { down, up }; class IVisualElement { public: virtual Rect arrange(const Rect& origin) = 0; virtual void render(const Rect& origin) = 0; virtual const Margin& get_margin() const = 0; virtual const Size2& get_size() const = 0; virtual void update_mouse_position(Int2 cursor) = 0; virtual void update_mouse_state(MouseButton button, MouseState state) = 0; virtual void update_mouse_scroll(Int2 scroll) = 0; virtual ~IVisualElement() {} }; typedef std::chrono::time_point<std::chrono::high_resolution_clock> TimePoint; class MouseEventsHandler : public virtual IVisualElement { public: MouseEventsHandler() : _on_double_click([](){}) { _state[MouseButton::left] = _state[MouseButton::right] = _state[MouseButton::middle] = MouseState::up; _on_click[MouseButton::left] = _on_click[MouseButton::right] = _on_click[MouseButton::middle] = [](){}; auto now = std::chrono::high_resolution_clock::now(); _last_update[MouseButton::left] = _last_update[MouseButton::right] = _last_update[MouseButton::middle] = now; _last_click[MouseButton::left] = _last_click[MouseButton::right] = _last_click[MouseButton::middle] = now; } void update_mouse_position(Int2 cursor) override {}; void update_mouse_state(MouseButton button, MouseState state) override { auto now = std::chrono::high_resolution_clock::now(); auto curr = _state[button]; if (curr != state) { auto ms = std::chrono::duration_cast<std::chrono::milliseconds> (now - _last_update[button]).count(); if (ms < CLICK_TIME_MS) { if (state == MouseState::up) { ms = std::chrono::duration_cast<std::chrono::milliseconds> (now - _last_click[button]).count(); _last_click[button] = now; if (ms < CLICK_TIME_MS && button == MouseButton::left) { _on_double_click(); } else { _on_click[button](); } } } _state[button] = state; } _last_update[button] = now; }; void update_mouse_scroll(Int2 scroll) override {}; void set_on_click(std::function<void()> on_click, MouseButton button = MouseButton::left) { _on_click[button] = on_click; } void set_on_double_click(std::function<void()> on_click){ _on_double_click = on_click; } private: std::map<MouseButton, MouseState> _state; std::map<MouseButton, TimePoint> _last_update; std::map<MouseButton, TimePoint> _last_click; std::map<MouseButton, std::function<void()>> _on_click; std::function<void()> _on_double_click; const int CLICK_TIME_MS = 200; }; class ControlBase : public virtual IVisualElement, public MouseEventsHandler { public: ControlBase(const Size2& position, const Size2& size, const Margin& margin) : _position(position), _size(size), _margin(margin) {} Rect arrange(const Rect& origin) override { auto x0 = _position.x.to_pixels(origin.size.x) + _margin.left; auto y0 = _position.y.to_pixels(origin.size.y) + _margin.top; auto w = std::min(_size.x.to_pixels(origin.size.x), origin.size.x - _margin.right - _margin.left); auto h = std::min(_size.y.to_pixels(origin.size.y), origin.size.y - _margin.bottom - _margin.top); x0 += origin.position.x; y0 += origin.position.y; return { { x0, y0 }, { w, h } }; } const Margin& get_margin() const override { return _margin; } const Size2& get_size() const override { return _size; } private: Size2 _position; Size2 _size; Margin _margin; }; class Button : public ControlBase { public: Button(const Size2& position, const Size2& size, const Margin& margin, const Color3& color) : ControlBase(position, size, margin), _color(color) {} void render(const Rect& origin) override { glBegin(GL_QUADS); glColor3f(_color.r, _color.g, _color.b); auto rect = arrange(origin); glVertex2i(rect.position.x, rect.position.y); glVertex2i(rect.position.x, rect.position.y + rect.size.y); glVertex2i(rect.position.x + rect.size.x, rect.position.y + rect.size.y); glVertex2i(rect.position.x + rect.size.x, rect.position.y); glEnd(); } private: Color3 _color; }; enum class Orientation { vertical, horizontal }; class Container : public ControlBase { public: Container(const Size2& position, const Size2& size, const Margin& margin, Orientation orientation = Orientation::vertical) : ControlBase(position, size, margin), _orientation(orientation) {} void add_item(std::unique_ptr<IVisualElement> item) { _content.push_back(std::move(item)); } void render(const Rect& origin) override { auto rect = arrange(origin); Size Size2::* field; int Int2::* ifield; if (_orientation == Orientation::vertical) { field = &Size2::y; ifield = &Int2::y; } else { field = &Size2::x; ifield = &Int2::x; } // first, scan items, map the "greedy" ones wanting relative portion std::vector<IVisualElement*> greedy; std::unordered_map<IVisualElement*, int> sizes; auto sum = 0; for (auto& p : _content) { auto p_rect = p->arrange(rect); auto p_total = p->get_margin().apply(p_rect); if ((p->get_size().*field).is_const()) { auto pixels = (p->get_size().*field).get_pixels(); sum += pixels; sizes[p.get()] = pixels; } else { greedy.push_back(p.get()); } } auto rest = std::max(rect.size.*ifield - sum, 0); float total_parts = 0; for (auto ptr : greedy) { total_parts += (ptr->get_size().*field).get_percents(); } for (auto ptr : greedy) { auto f = ((ptr->get_size().*field).get_percents() / total_parts); sizes[ptr] = (int) (rest * f); } sum = rect.position.*ifield; for (auto& p : _content) { auto new_origin = rect; (new_origin.position.*ifield) = sum; (new_origin.size.*ifield) = sizes[p.get()]; sum += sizes[p.get()]; p->render(new_origin); } } private: std::vector<std::unique_ptr<IVisualElement>> _content; Orientation _orientation; }; int main(int argc, char * argv[]) try { glfwInit(); GLFWwindow * win = glfwCreateWindow(1280, 960, "main", 0, 0); glfwMakeContextCurrent(win); Color3 redish { 0.8f, 0.5f, 0.6f }; Container c( { 0, 0 }, { 300, 1.0f }, { 5, 5, 5, 5 } ); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 1.0f }, { 5, 5, 5, 5 }, redish ))); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); c.set_on_double_click([&](){ c.add_item(std::unique_ptr<Button>(new Button( { 0, 0 }, { 1.0f, 35 }, { 5, 5, 5, 5 }, redish ))); }); glfwSetWindowUserPointer(win, &c); glfwSetCursorPosCallback(win, [](GLFWwindow * w, double x, double y) { auto ui_element = (IVisualElement*)glfwGetWindowUserPointer(w); ui_element->update_mouse_position({ (int)x, (int)y }); }); glfwSetScrollCallback(win, [](GLFWwindow * w, double x, double y) { auto ui_element = (IVisualElement*)glfwGetWindowUserPointer(w); ui_element->update_mouse_scroll({ (int)x, (int)y }); }); glfwSetMouseButtonCallback(win, [](GLFWwindow * w, int button, int action, int mods) { auto ui_element = (IVisualElement*)glfwGetWindowUserPointer(w); MouseButton button_type; switch(button) { case GLFW_MOUSE_BUTTON_RIGHT: button_type = MouseButton::right; break; case GLFW_MOUSE_BUTTON_LEFT: button_type = MouseButton::left; break; case GLFW_MOUSE_BUTTON_MIDDLE: button_type = MouseButton::middle; break; default: button_type = MouseButton::left; }; MouseState mouse_state; switch(action) { case GLFW_PRESS: mouse_state = MouseState::down; break; case GLFW_RELEASE: mouse_state = MouseState::up; break; default: mouse_state = MouseState::up; }; ui_element->update_mouse_state(button_type, mouse_state); }); while (!glfwWindowShouldClose(win)) { glfwPollEvents(); int w,h; glfwGetFramebufferSize(win, &w, &h); glViewport(0, 0, w, h); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glfwGetWindowSize(win, &w, &h); glOrtho(0, w, h, 0, -1, +1); Rect origin { { 0, 0 }, { w, h } }; c.render(origin); glPopMatrix(); glfwSwapBuffers(win); } glfwDestroyWindow(win); glfwTerminate(); return 0; } catch(const std::exception & e) { std::cerr << e.what() << std::endl; return -1; } <|endoftext|>
<commit_before>#include <stdio.h> #include "Scanner.h" int main(int argc, const char *argv[]) { Scanner scanner; return 0; } <commit_msg>something changes in main.cpp<commit_after>#include <stdio.h> #include "Scanner.h" int main(int argc, const char *argv[]) { printf("Before\r\n"); Scanner scanner; printf("After\r\n"); return 0; } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosComm.inl */ #ifndef ADIOS2_HELPER_ADIOSCOMM_INL_ #define ADIOS2_HELPER_ADIOSCOMM_INL_ #ifndef ADIOS2_HELPER_ADIOSCOMM_H_ #error "Inline file should only be included from it's header, never on it's own" #endif #include <numeric> //std::accumulate #include <stdexcept> //std::runtime_error #include <utility> //std::pair namespace adios2 { namespace helper { // GatherArrays full specializations implemented in 'adiosComm.tcc'. template <> void Comm::GatherArrays(const char *source, size_t sourceCount, char *destination, int rankDestination) const; template <> void Comm::GatherArrays(const size_t *source, size_t sourceCount, size_t *destination, int rankDestination) const; template <class T> std::vector<T> Comm::GatherValues(T source, int rankDestination) const { int rank = this->Rank(); int size = this->Size(); std::vector<T> output; if (rank == rankDestination) // pre-allocate in destination rank { output.resize(size); } T sourceCopy = source; // so we can have an address for rvalues this->GatherArrays(&sourceCopy, 1, output.data(), rankDestination); return output; } // GathervArrays full specializations implemented in 'adiosComm.tcc'. template <> void Comm::GathervArrays(const char *source, size_t sourceCount, const size_t *counts, size_t countsSize, char *destination, int rankDestination) const; template <> void Comm::GathervArrays(const size_t *source, size_t sourceCount, const size_t *counts, size_t countsSize, size_t *destination, int rankDestination) const; template <class T> void Comm::GathervVectors(const std::vector<T> &in, std::vector<T> &out, size_t &position, int rankDestination, size_t extraSize) const { const size_t inSize = in.size(); const std::vector<size_t> counts = this->GatherValues(inSize, rankDestination); size_t gatheredSize = 0; int rank = this->Rank(); if (rank == rankDestination) // pre-allocate vector { gatheredSize = std::accumulate(counts.begin(), counts.end(), size_t(0)); const size_t newSize = position + gatheredSize; try { out.reserve(newSize + extraSize); // to avoid power of 2 growth out.resize(newSize + extraSize); } catch (...) { std::throw_with_nested( std::runtime_error("ERROR: buffer overflow when resizing to " + std::to_string(newSize) + " bytes, in call to GathervVectors\n")); } } this->GathervArrays(in.data(), in.size(), counts.data(), counts.size(), out.data() + position); position += gatheredSize; } template <class T> std::vector<T> Comm::AllGatherValues(const T source) const { int size; SMPI_Comm_size(m_MPIComm, &size); std::vector<T> output(size); T sourceCopy = source; // so we can have an address for rvalues this->AllGatherArrays(&sourceCopy, 1, output.data()); return output; } // AllGatherArrays full specializations implemented in 'adiosComm.tcc'. template <> void Comm::AllGatherArrays(const size_t *source, const size_t sourceCount, size_t *destination) const; // ReduceValues full specializations implemented in 'adiosComm.tcc'. template <> unsigned int Comm::ReduceValues(const unsigned int source, MPI_Op operation, const int rankDestination) const; template <> unsigned long int Comm::ReduceValues(const unsigned long int source, MPI_Op operation, const int rankDestination) const; template <> unsigned long long int Comm::ReduceValues(const unsigned long long int source, MPI_Op operation, const int rankDestination) const; // BroadcastValue full specializations implemented in 'adiosComm.tcc'. template <> size_t Comm::BroadcastValue(const size_t &input, const int rankSource) const; template <> std::string Comm::BroadcastValue(const std::string &input, const int rankSource) const; // BroadcastVector full specializations implemented in 'adiosComm.tcc'. template <> void Comm::BroadcastVector(std::vector<char> &vector, const int rankSource) const; template <> void Comm::BroadcastVector(std::vector<size_t> &vector, const int rankSource) const; template <typename TSend, typename TRecv> void Comm::Allgather(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, size_t recvcount, const std::string &hint) const { return AllgatherImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcount, Datatype<TRecv>(), hint); } template <typename T> void Comm::Allreduce(const T *sendbuf, T *recvbuf, size_t count, MPI_Op op, const std::string &hint) const { return AllreduceImpl(sendbuf, recvbuf, count, Datatype<T>(), op, hint); } template <typename T> void Comm::Bcast(T *buffer, const size_t count, int root, const std::string &hint) const { return BcastImpl(buffer, count, Datatype<T>(), root, hint); } template <typename TSend, typename TRecv> void Comm::Gather(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, size_t recvcount, int root, const std::string &hint) const { return GatherImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcount, Datatype<TRecv>(), root, hint); } template <typename TSend, typename TRecv> void Comm::Gatherv(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, const size_t *recvcounts, const size_t *displs, int root, const std::string &hint) const { return GathervImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcounts, displs, Datatype<TRecv>(), root, hint); } template <typename T> void Comm::Reduce(const T *sendbuf, T *recvbuf, size_t count, MPI_Op op, int root, const std::string &hint) const { return ReduceImpl(sendbuf, recvbuf, count, Datatype<T>(), op, root, hint); } template <typename T> void Comm::ReduceInPlace(T *buf, size_t count, MPI_Op op, int root, const std::string &hint) const { return ReduceInPlaceImpl(buf, count, Datatype<T>(), op, root, hint); } template <typename T> void Comm::Send(const T *buf, size_t count, int dest, int tag, const std::string &hint) const { return SendImpl(buf, count, Datatype<T>(), dest, tag, hint); } template <typename T> Comm::Status Comm::Recv(T *buf, size_t count, int source, int tag, const std::string &hint) const { return RecvImpl(buf, count, Datatype<T>(), source, tag, hint); } template <typename TSend, typename TRecv> void Comm::Scatter(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, size_t recvcount, int root, const std::string &hint) const { return ScatterImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcount, Datatype<TRecv>(), root, hint); } template <typename T> Comm::Req Comm::Isend(const T *buffer, const size_t count, int dest, int tag, const std::string &hint) const { return IsendImpl(buffer, count, Datatype<T>(), dest, tag, hint); } template <typename T> Comm::Req Comm::Irecv(T *buffer, const size_t count, int source, int tag, const std::string &hint) const { return IrecvImpl(buffer, count, Datatype<T>(), source, tag, hint); } // Datatype full specializations implemented in 'adiosComm.tcc'. template <> MPI_Datatype Comm::Datatype<signed char>(); template <> MPI_Datatype Comm::Datatype<char>(); template <> MPI_Datatype Comm::Datatype<short>(); template <> MPI_Datatype Comm::Datatype<int>(); template <> MPI_Datatype Comm::Datatype<long>(); template <> MPI_Datatype Comm::Datatype<unsigned char>(); template <> MPI_Datatype Comm::Datatype<unsigned short>(); template <> MPI_Datatype Comm::Datatype<unsigned int>(); template <> MPI_Datatype Comm::Datatype<unsigned long>(); template <> MPI_Datatype Comm::Datatype<unsigned long long>(); template <> MPI_Datatype Comm::Datatype<long long>(); template <> MPI_Datatype Comm::Datatype<double>(); template <> MPI_Datatype Comm::Datatype<long double>(); template <> MPI_Datatype Comm::Datatype<std::pair<int, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<float, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<double, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<long double, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<short, int>>(); } // end namespace helper } // end namespace adios2 #endif /* ADIOS2_HELPER_ADIOSCOMM_INL_ */ <commit_msg>helper: Implement Comm::AllGatherValues in terms of our encapsulation<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * adiosComm.inl */ #ifndef ADIOS2_HELPER_ADIOSCOMM_INL_ #define ADIOS2_HELPER_ADIOSCOMM_INL_ #ifndef ADIOS2_HELPER_ADIOSCOMM_H_ #error "Inline file should only be included from it's header, never on it's own" #endif #include <numeric> //std::accumulate #include <stdexcept> //std::runtime_error #include <utility> //std::pair namespace adios2 { namespace helper { // GatherArrays full specializations implemented in 'adiosComm.tcc'. template <> void Comm::GatherArrays(const char *source, size_t sourceCount, char *destination, int rankDestination) const; template <> void Comm::GatherArrays(const size_t *source, size_t sourceCount, size_t *destination, int rankDestination) const; template <class T> std::vector<T> Comm::GatherValues(T source, int rankDestination) const { int rank = this->Rank(); int size = this->Size(); std::vector<T> output; if (rank == rankDestination) // pre-allocate in destination rank { output.resize(size); } T sourceCopy = source; // so we can have an address for rvalues this->GatherArrays(&sourceCopy, 1, output.data(), rankDestination); return output; } // GathervArrays full specializations implemented in 'adiosComm.tcc'. template <> void Comm::GathervArrays(const char *source, size_t sourceCount, const size_t *counts, size_t countsSize, char *destination, int rankDestination) const; template <> void Comm::GathervArrays(const size_t *source, size_t sourceCount, const size_t *counts, size_t countsSize, size_t *destination, int rankDestination) const; template <class T> void Comm::GathervVectors(const std::vector<T> &in, std::vector<T> &out, size_t &position, int rankDestination, size_t extraSize) const { const size_t inSize = in.size(); const std::vector<size_t> counts = this->GatherValues(inSize, rankDestination); size_t gatheredSize = 0; int rank = this->Rank(); if (rank == rankDestination) // pre-allocate vector { gatheredSize = std::accumulate(counts.begin(), counts.end(), size_t(0)); const size_t newSize = position + gatheredSize; try { out.reserve(newSize + extraSize); // to avoid power of 2 growth out.resize(newSize + extraSize); } catch (...) { std::throw_with_nested( std::runtime_error("ERROR: buffer overflow when resizing to " + std::to_string(newSize) + " bytes, in call to GathervVectors\n")); } } this->GathervArrays(in.data(), in.size(), counts.data(), counts.size(), out.data() + position); position += gatheredSize; } template <class T> std::vector<T> Comm::AllGatherValues(const T source) const { int size = this->Size(); std::vector<T> output(size); T sourceCopy = source; // so we can have an address for rvalues this->AllGatherArrays(&sourceCopy, 1, output.data()); return output; } // AllGatherArrays full specializations implemented in 'adiosComm.tcc'. template <> void Comm::AllGatherArrays(const size_t *source, const size_t sourceCount, size_t *destination) const; // ReduceValues full specializations implemented in 'adiosComm.tcc'. template <> unsigned int Comm::ReduceValues(const unsigned int source, MPI_Op operation, const int rankDestination) const; template <> unsigned long int Comm::ReduceValues(const unsigned long int source, MPI_Op operation, const int rankDestination) const; template <> unsigned long long int Comm::ReduceValues(const unsigned long long int source, MPI_Op operation, const int rankDestination) const; // BroadcastValue full specializations implemented in 'adiosComm.tcc'. template <> size_t Comm::BroadcastValue(const size_t &input, const int rankSource) const; template <> std::string Comm::BroadcastValue(const std::string &input, const int rankSource) const; // BroadcastVector full specializations implemented in 'adiosComm.tcc'. template <> void Comm::BroadcastVector(std::vector<char> &vector, const int rankSource) const; template <> void Comm::BroadcastVector(std::vector<size_t> &vector, const int rankSource) const; template <typename TSend, typename TRecv> void Comm::Allgather(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, size_t recvcount, const std::string &hint) const { return AllgatherImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcount, Datatype<TRecv>(), hint); } template <typename T> void Comm::Allreduce(const T *sendbuf, T *recvbuf, size_t count, MPI_Op op, const std::string &hint) const { return AllreduceImpl(sendbuf, recvbuf, count, Datatype<T>(), op, hint); } template <typename T> void Comm::Bcast(T *buffer, const size_t count, int root, const std::string &hint) const { return BcastImpl(buffer, count, Datatype<T>(), root, hint); } template <typename TSend, typename TRecv> void Comm::Gather(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, size_t recvcount, int root, const std::string &hint) const { return GatherImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcount, Datatype<TRecv>(), root, hint); } template <typename TSend, typename TRecv> void Comm::Gatherv(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, const size_t *recvcounts, const size_t *displs, int root, const std::string &hint) const { return GathervImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcounts, displs, Datatype<TRecv>(), root, hint); } template <typename T> void Comm::Reduce(const T *sendbuf, T *recvbuf, size_t count, MPI_Op op, int root, const std::string &hint) const { return ReduceImpl(sendbuf, recvbuf, count, Datatype<T>(), op, root, hint); } template <typename T> void Comm::ReduceInPlace(T *buf, size_t count, MPI_Op op, int root, const std::string &hint) const { return ReduceInPlaceImpl(buf, count, Datatype<T>(), op, root, hint); } template <typename T> void Comm::Send(const T *buf, size_t count, int dest, int tag, const std::string &hint) const { return SendImpl(buf, count, Datatype<T>(), dest, tag, hint); } template <typename T> Comm::Status Comm::Recv(T *buf, size_t count, int source, int tag, const std::string &hint) const { return RecvImpl(buf, count, Datatype<T>(), source, tag, hint); } template <typename TSend, typename TRecv> void Comm::Scatter(const TSend *sendbuf, size_t sendcount, TRecv *recvbuf, size_t recvcount, int root, const std::string &hint) const { return ScatterImpl(sendbuf, sendcount, Datatype<TSend>(), recvbuf, recvcount, Datatype<TRecv>(), root, hint); } template <typename T> Comm::Req Comm::Isend(const T *buffer, const size_t count, int dest, int tag, const std::string &hint) const { return IsendImpl(buffer, count, Datatype<T>(), dest, tag, hint); } template <typename T> Comm::Req Comm::Irecv(T *buffer, const size_t count, int source, int tag, const std::string &hint) const { return IrecvImpl(buffer, count, Datatype<T>(), source, tag, hint); } // Datatype full specializations implemented in 'adiosComm.tcc'. template <> MPI_Datatype Comm::Datatype<signed char>(); template <> MPI_Datatype Comm::Datatype<char>(); template <> MPI_Datatype Comm::Datatype<short>(); template <> MPI_Datatype Comm::Datatype<int>(); template <> MPI_Datatype Comm::Datatype<long>(); template <> MPI_Datatype Comm::Datatype<unsigned char>(); template <> MPI_Datatype Comm::Datatype<unsigned short>(); template <> MPI_Datatype Comm::Datatype<unsigned int>(); template <> MPI_Datatype Comm::Datatype<unsigned long>(); template <> MPI_Datatype Comm::Datatype<unsigned long long>(); template <> MPI_Datatype Comm::Datatype<long long>(); template <> MPI_Datatype Comm::Datatype<double>(); template <> MPI_Datatype Comm::Datatype<long double>(); template <> MPI_Datatype Comm::Datatype<std::pair<int, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<float, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<double, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<long double, int>>(); template <> MPI_Datatype Comm::Datatype<std::pair<short, int>>(); } // end namespace helper } // end namespace adios2 #endif /* ADIOS2_HELPER_ADIOSCOMM_INL_ */ <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX64M/RX71M/RX651/RX65N/RX66T/RX72T/RX72N/RX72M グループ・システム制御 @n ※RX24T は構成が大きく異なるので、RX24T/system_io.hpp に分離しています。@n ※ USB を使う場合:96MHz, 144MHz, 192MHz, 240MHz のいづれか @n RX72x 系では、内部 PLL 回路が追加され、Ethernet などに必要な 25MHz を得る為 @n 16MHz を使います。@n (16MHz x 12.5 -> 200MHz, 16MHz x 15 -> 240MHz) @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017, 2021 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "RX600/system.hpp" #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX66T) || defined(SIG_RX65N) || defined(SIG_RX72T) || defined(SIG_RX72N) || defined(SIG_RX72M) #elif #error "system_io.hpp: Not available on RX24T" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_base クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct system_base { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 発信器タイプ @n HOCO を使う場合、同時に、BASE_CLOCK_ に周波数(16,18,20 MHz)を設定します。 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class OSC_TYPE { XTAL, ///< クリスタル接続 EXT, ///< クロック入力 HOCO, ///< 高速オンチップオシレーター LOCO, ///< 低速オンチップオシレーター (240KHz) }; }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_io クラス @n INTR_CLOCK は、内部 PLL で扱える最大速度です、@n 外部クリスタルを微妙な周波数にする場合、その整数倍にしなければなりません。 @n RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 @n RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 @param[in] OSC_TYPE 発信器タイプを設定(通常、XTAL) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <auto OSC_TYPE_ = system_base::OSC_TYPE::XTAL> struct system_io : public system_base { static uint8_t clock_div_(uint32_t clk) noexcept { uint8_t div = 0; while(clk < clock_profile::PLL_BASE) { ++div; clk <<= 1; } if(div > 0b0110) div = 0b0110; return div; } //-------------------------------------------------------------// /*! @brief マスター・クロックのブースト @n インストラクション・クロックを最大速度にブーストする。 */ //-------------------------------------------------------------// static void boost_master_clock() noexcept { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MOSCWTCR = 9; // 1ms wait // メインクロック強制発振とドライブ能力設定 if(OSC_TYPE_ == OSC_TYPE::XTAL) { uint8_t modrv2 = 0b11; if(clock_profile::BASE > 20'000'000) modrv2 = 0b00; else if(clock_profile::BASE > 16'000'000) modrv2 = 0b01; else if(clock_profile::BASE > 8'000'000) modrv2 = 0b10; device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); } } else if(OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::MOSCCR.MOSTP = 1; // メインクロック発振器停止 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MOSEL.b(); } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { // 高速オンチップオシレータ uint8_t frq; if(clock_profile::BASE == 16'000'000) frq = 0b00; else if(clock_profile::BASE == 18'000'000) frq = 0b01; else if(clock_profile::BASE == 20'000'000) frq = 0b10; else frq = 0b00; device::SYSTEM::HOCOCR2.HCFRQ = frq; device::SYSTEM::HOCOCR.HCSTP = 0; // 動作 while(device::SYSTEM::OSCOVFSR.HCOVF() == 0) { asm("nop"); } device::SYSTEM::PLLCR.PLLSRCSEL = 1; } else { device::SYSTEM::PRCR = 0xA500; return; } #if defined(SIG_RX65N) if(clock_profile::ICLK >= 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::ROMWT = 0b10; } else if(clock_profile::ICLK >= 100'000'000) { device::SYSTEM::ROMWT = 0b01; } else if(clock_profile::ICLK >= 50'000'000) { device::SYSTEM::ROMWT = 0b00; } #endif // RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 // RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 #if defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) if(clock_profile::ICLK > 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::MEMWAIT = 1; volatile auto tmp = device::SYSTEM::MEMWAIT(); // 読み出しを行う } #endif // (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110 // ... MAX x30.0 uint32_t n = clock_profile::PLL_BASE * 2 / clock_profile::BASE; if(n < 20) n = 20; else if(n > 60) n = 60; n -= 20; device::SYSTEM::PLLCR.STC = n + 0b010011; // base x10 device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); } device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(clock_profile::FCLK)) | device::SYSTEM::SCKCR.ICK.b(clock_div_(clock_profile::ICLK)) | device::SYSTEM::SCKCR.BCK.b(clock_div_(clock_profile::BCLK)) | device::SYSTEM::SCKCR.PCKA.b(clock_div_(clock_profile::PCLKA)) | device::SYSTEM::SCKCR.PCKB.b(clock_div_(clock_profile::PCLKB)) | device::SYSTEM::SCKCR.PCKC.b(clock_div_(clock_profile::PCLKC)) | device::SYSTEM::SCKCR.PCKD.b(clock_div_(clock_profile::PCLKD)); { // USB Master Clock の設定 auto usb_div = clock_profile::PLL_BASE / 48'000'000; if(usb_div >= 2 && usb_div <= 5) { // 1/2, 1/3, 1/4, 1/5 device::SYSTEM::SCKCR2.UCK = usb_div - 1; } } device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 if(OSC_TYPE_ == OSC_TYPE::XTAL || OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 device::SYSTEM::HOCOCR.HCSTP = 1; ///< 高速オンチップオシレータ停止 device::SYSTEM::HOCOPCR.HOCOPCNT = 1; ///< 高速オンチップオシレーター電源 OFF } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 } // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; #if defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) // ROM キャッシュを有効(標準) device::SYSTEM::ROMCE = 1; #endif #if defined(__TFU) __init_tfu(); #endif } #if defined(SIG_RX72M) || defined(SIG_RX72N) //-------------------------------------------------------------// /*! @brief PPLL 制御を使って PHY 向け 25MHz を出力する。 @return 成功なら「true」 */ //-------------------------------------------------------------// static bool setup_phy25() noexcept { if(clock_profile::BASE != 16'000'000) { // ベースクロックが 16MHz 以外は、生成不可とする。 return false; } bool ret = true; device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::PACKCR.OUTCKSEL = 1; // PPLIDIV: 1/2, PPLSTC: x12.5 (100MHz) device::SYSTEM::PPLLCR = device::SYSTEM::PPLLCR.PPLIDIV.b(0b01) | device::SYSTEM::PPLLCR.PPLSTC.b(0b011000); device::SYSTEM::PPLLCR2 = device::SYSTEM::PPLLCR2.PPLLEN.b(1); // 発信許可 // PPLL 安定待ち while(device::SYSTEM::OSCOVFSR.PPLOVF() == 0) { asm("nop"); } // PPLLCR3: 1/4 (25MHz) device::SYSTEM::PPLLCR3 = device::SYSTEM::PPLLCR3.PPLCK.b(0b0011); // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; // ポート・マッピングを行う必要があるが、あえて、ここでは許可しない。 // ※このヘッダーに、port_map.hpp の依存を無くす為。 // deveice::port_map::turn_CLKOUT25M(); return true; } #endif }; //-------------------------------------------------------------// /*! @brief ソフト・リセットの起動 */ //-------------------------------------------------------------// inline void assert_soft_reset() { device::SYSTEM::PRCR = 0xA502; device::SYSTEM::SWRR = 0xA501; device::SYSTEM::PRCR = 0xA500; } } <commit_msg>Update: setting flash clock value register<commit_after>#pragma once //=====================================================================// /*! @file @brief RX64M/RX71M/RX651/RX65N/RX66T/RX72T/RX72N/RX72M グループ・システム制御 @n ※RX24T は構成が大きく異なるので、RX24T/system_io.hpp に分離しています。@n ※ USB を使う場合:96MHz, 144MHz, 192MHz, 240MHz のいづれか @n RX72x 系では、内部 PLL 回路が追加され、Ethernet などに必要な 25MHz を得る為 @n 16MHz を使います。@n (16MHz x 12.5 -> 200MHz, 16MHz x 15 -> 240MHz) @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017, 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "RX600/system.hpp" #if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX66T) || defined(SIG_RX65N) || defined(SIG_RX72T) || defined(SIG_RX72N) || defined(SIG_RX72M) #elif #error "system_io.hpp: Not available on RX24T" #endif #if defined(SIG_RX72N) || defined(SIG_RX72M) #include "RX600/flash.hpp" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_base クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct system_base { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 発信器タイプ @n HOCO を使う場合、同時に、BASE_CLOCK_ に周波数(16,18,20 MHz)を設定します。 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class OSC_TYPE { XTAL, ///< クリスタル接続 EXT, ///< クロック入力 HOCO, ///< 高速オンチップオシレーター LOCO, ///< 低速オンチップオシレーター (240KHz) }; }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief systen_io クラス @n INTR_CLOCK は、内部 PLL で扱える最大速度です、@n 外部クリスタルを微妙な周波数にする場合、その整数倍にしなければなりません。 @n RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 @n RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 @param[in] OSC_TYPE 発信器タイプを設定(通常、XTAL) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <auto OSC_TYPE_ = system_base::OSC_TYPE::XTAL> struct system_io : public system_base { static uint8_t clock_div_(uint32_t clk) noexcept { uint8_t div = 0; while(clk < clock_profile::PLL_BASE) { ++div; clk <<= 1; } if(div > 0b0110) div = 0b0110; return div; } //-------------------------------------------------------------// /*! @brief マスター・クロックのブースト @n インストラクション・クロックを最大速度にブーストする。 */ //-------------------------------------------------------------// static void boost_master_clock() noexcept { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MOSCWTCR = 9; // 1ms wait // メインクロック強制発振とドライブ能力設定 if(OSC_TYPE_ == OSC_TYPE::XTAL) { uint8_t modrv2 = 0b11; if(clock_profile::BASE > 20'000'000) modrv2 = 0b00; else if(clock_profile::BASE > 16'000'000) modrv2 = 0b01; else if(clock_profile::BASE > 8'000'000) modrv2 = 0b10; device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); } } else if(OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::MOSCCR.MOSTP = 1; // メインクロック発振器停止 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MOSEL.b(); } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { // 高速オンチップオシレータ uint8_t frq; if(clock_profile::BASE == 16'000'000) frq = 0b00; else if(clock_profile::BASE == 18'000'000) frq = 0b01; else if(clock_profile::BASE == 20'000'000) frq = 0b10; else frq = 0b00; device::SYSTEM::HOCOCR2.HCFRQ = frq; device::SYSTEM::HOCOCR.HCSTP = 0; // 動作 while(device::SYSTEM::OSCOVFSR.HCOVF() == 0) { asm("nop"); } device::SYSTEM::PLLCR.PLLSRCSEL = 1; } else { device::SYSTEM::PRCR = 0xA500; return; } #if defined(SIG_RX65N) if(clock_profile::ICLK >= 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::ROMWT = 0b10; } else if(clock_profile::ICLK >= 100'000'000) { device::SYSTEM::ROMWT = 0b01; } else if(clock_profile::ICLK >= 50'000'000) { device::SYSTEM::ROMWT = 0b00; } #endif // RX71M はスーパーバイザモードでの変更が必要なので、「start.s」内で行う。 // RX71M の場合、アセンブラにオプション「--defsym MEMWAIT=1」を渡す。 #if defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) if(clock_profile::ICLK > 120'000'000) { // 120MHz 以上の場合設定 device::SYSTEM::MEMWAIT = 1; volatile auto tmp = device::SYSTEM::MEMWAIT(); // 読み出しを行う } #endif // (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110 // ... MAX x30.0 uint32_t n = clock_profile::PLL_BASE * 2 / clock_profile::BASE; if(n < 20) n = 20; else if(n > 60) n = 60; n -= 20; device::SYSTEM::PLLCR.STC = n + 0b010011; // base x10 device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); } device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(clock_profile::FCLK)) | device::SYSTEM::SCKCR.ICK.b(clock_div_(clock_profile::ICLK)) | device::SYSTEM::SCKCR.BCK.b(clock_div_(clock_profile::BCLK)) | device::SYSTEM::SCKCR.PCKA.b(clock_div_(clock_profile::PCLKA)) | device::SYSTEM::SCKCR.PCKB.b(clock_div_(clock_profile::PCLKB)) | device::SYSTEM::SCKCR.PCKC.b(clock_div_(clock_profile::PCLKC)) | device::SYSTEM::SCKCR.PCKD.b(clock_div_(clock_profile::PCLKD)); { // USB Master Clock の設定 auto usb_div = clock_profile::PLL_BASE / 48'000'000; if(usb_div >= 2 && usb_div <= 5) { // 1/2, 1/3, 1/4, 1/5 device::SYSTEM::SCKCR2.UCK = usb_div - 1; } } #if defined(SIG_RX72N) || defined(SIG_RX72M) { // Set for DataFlash memory access clocks uint32_t clk = ((static_cast<uint32_t>(clock_profile::FCLK) / 500'000) + 1) >> 1; if(clk > 60) { clk = 60; } device::FLASH::EEPFCLK = clk; while(device::FLASH::EEPFCLK() != clk) { asm("nop"); } } #endif device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 if(OSC_TYPE_ == OSC_TYPE::XTAL || OSC_TYPE_ == OSC_TYPE::EXT) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 device::SYSTEM::HOCOCR.HCSTP = 1; ///< 高速オンチップオシレータ停止 device::SYSTEM::HOCOPCR.HOCOPCNT = 1; ///< 高速オンチップオシレーター電源 OFF } else if(OSC_TYPE_ == OSC_TYPE::HOCO) { device::SYSTEM::LOCOCR.LCSTP = 1; ///< 低速オンチップオシレータ停止 } // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; #if defined(SIG_RX65N) || defined(SIG_RX66T) || defined(SIG_RX72M) || defined(SIG_RX72T) || defined(SIG_RX72N) // ROM キャッシュを有効(標準) device::SYSTEM::ROMCE = 1; #endif #if defined(__TFU) __init_tfu(); #endif } #if defined(SIG_RX72M) || defined(SIG_RX72N) //-------------------------------------------------------------// /*! @brief PPLL 制御を使って PHY 向け 25MHz を出力する。 @return 成功なら「true」 */ //-------------------------------------------------------------// static bool setup_phy25() noexcept { if(clock_profile::BASE != 16'000'000) { // ベースクロックが 16MHz 以外は、生成不可とする。 return false; } bool ret = true; device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::PACKCR.OUTCKSEL = 1; // PPLIDIV: 1/2, PPLSTC: x12.5 (100MHz) device::SYSTEM::PPLLCR = device::SYSTEM::PPLLCR.PPLIDIV.b(0b01) | device::SYSTEM::PPLLCR.PPLSTC.b(0b011000); device::SYSTEM::PPLLCR2 = device::SYSTEM::PPLLCR2.PPLLEN.b(1); // 発信許可 // PPLL 安定待ち while(device::SYSTEM::OSCOVFSR.PPLOVF() == 0) { asm("nop"); } // PPLLCR3: 1/4 (25MHz) device::SYSTEM::PPLLCR3 = device::SYSTEM::PPLLCR3.PPLCK.b(0b0011); // クロック関係書き込み不許可 device::SYSTEM::PRCR = 0xA500; // ポート・マッピングを行う必要があるが、あえて、ここでは許可しない。 // ※このヘッダーに、port_map.hpp の依存を無くす為。 // deveice::port_map::turn_CLKOUT25M(); return true; } #endif }; //-------------------------------------------------------------// /*! @brief ソフト・リセットの起動 */ //-------------------------------------------------------------// inline void assert_soft_reset() { device::SYSTEM::PRCR = 0xA502; device::SYSTEM::SWRR = 0xA501; device::SYSTEM::PRCR = 0xA500; } } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "RestartableDataIO.h" #include "MooseUtils.h" #include "RestartableData.h" #include "FEProblem.h" #include <stdio.h> RestartableDataIO::RestartableDataIO(FEProblem & fe_problem) : _fe_problem(fe_problem) { } void RestartableDataIO::writeRestartableData(std::string base_file_name) { unsigned int n_threads = libMesh::n_threads(); unsigned int n_procs = libMesh::n_processors(); for(unsigned int tid=0; tid<n_threads; tid++) { std::map<std::string, RestartableDataValue *> restartable_data = _fe_problem._restartable_data[tid]; if(restartable_data.size()) { const unsigned int file_version = 1; std::ofstream out; std::ostringstream file_name_stream; file_name_stream << base_file_name; if(n_threads > 1) file_name_stream << "-" << tid; std::string file_name = file_name_stream.str(); if (libMesh::processor_id() == 0) { out.open(file_name.c_str(), std::ios::out | std::ios::binary); char id[2]; // header id[0] = 'R'; id[1] = 'D'; out.write(id, 2); out.write((const char *)&file_version, sizeof(file_version)); out.write((const char *)&n_procs, sizeof(n_procs)); out.write((const char *)&n_threads, sizeof(n_threads)); // number of RestartableData unsigned int n_data = restartable_data.size(); out.write((const char *) &n_data, sizeof(n_data)); // data names for(std::map<std::string, RestartableDataValue *>::iterator it = restartable_data.begin(); it != restartable_data.end(); ++it) { std::string name = it->second->name(); out.write(name.c_str(), name.length() + 1); // trailing 0! } out.close(); } // now each process dump its part, appending into the file for (unsigned int proc = 0; proc < n_procs; proc++) { if (libMesh::processor_id() == proc) { out.open(file_name.c_str(), std::ios::app | std::ios::binary); std::ostringstream data_blk; for(std::map<std::string, RestartableDataValue *>::iterator it = restartable_data.begin(); it != restartable_data.end(); ++it) { // std::cout<<"Storing "<<it->first<<std::endl; std::ostringstream data; it->second->store(data); // Store the size of the data then the data unsigned int data_size = data.tellp(); data_blk.write((const char *) &data_size, sizeof(data_size)); data_blk << data.str(); } // Write out this proc's block size unsigned int data_blk_size = data_blk.tellp(); out.write((const char *) &data_blk_size, sizeof(data_blk_size)); // Write out the values out << data_blk.str(); out.close(); } libMesh::Parallel::barrier(libMesh::CommWorld); } } } } void RestartableDataIO::readRestartableData(std::string base_file_name) { unsigned int n_threads = libMesh::n_threads(); unsigned int n_procs = libMesh::n_processors(); std::vector<std::string> ignored_data; for(unsigned int tid=0; tid<n_threads; tid++) { std::map<std::string, RestartableDataValue *> restartable_data = _fe_problem._restartable_data[tid]; if(restartable_data.size()) { std::ostringstream file_name_stream; file_name_stream << base_file_name; if(n_threads > 1) file_name_stream << "-" << tid; std::string file_name = file_name_stream.str(); MooseUtils::checkFileReadable(file_name); const unsigned int file_version = 1; std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary); // header char id[2]; in.read(id, 2); unsigned int this_file_version; in.read((char *)&this_file_version, sizeof(this_file_version)); unsigned int this_n_procs = 0; unsigned int this_n_threads = 0; in.read((char *)&this_n_procs, sizeof(this_n_procs)); in.read((char *)&this_n_threads, sizeof(this_n_threads)); // check the header if(id[0] != 'R' || id[1] != 'D') mooseError("Corrupted restartable data file!"); // check the file version if(this_file_version > file_version) mooseError("Trying to restart from a newer file version - you need to update MOOSE"); if(this_file_version < file_version) mooseError("Trying to restart from an older file version - you need to checkout an older version of MOOSE."); if(this_n_procs != n_procs) mooseError("Cannot restart using a different number of processors!"); if(this_n_threads != n_threads) mooseError("Cannot restart using a different number of threads!"); // number of data unsigned int n_data = 0; in.read((char *) &n_data, sizeof(n_data)); // data names std::vector<std::string> data_names(n_data); for(unsigned int i=0; i < n_data; i++) { std::string data_name; char ch = 0; do { in.read(&ch, 1); if (ch != '\0') data_name += ch; } while (ch != '\0'); data_names[i] = data_name; } // Read each data value for (unsigned int proc = 0; proc < libMesh::n_processors(); proc++) { // Grab this processor's block size unsigned int data_blk_size = 0; in.read((char *) &data_blk_size, sizeof(data_blk_size)); if (libMesh::processor_id() == proc) { for(unsigned int i=0; i < n_data; i++) { std::string current_name = data_names[i]; unsigned int data_size = 0; in.read((char *) &data_size, sizeof(data_size)); if(restartable_data.find(current_name) != restartable_data.end()) // Only restore values if they're currently being used { // std::cout<<"Loading "<<current_name<<std::endl; RestartableDataValue * current_data = restartable_data[current_name]; current_data->load(in); } else { // Skip this piece of data in.seekg(data_size, std::ios_base::cur); ignored_data.push_back(current_name); } } } else // Skip this block in.seekg(data_blk_size, std::ios_base::cur); libMesh::Parallel::barrier(libMesh::CommWorld); } in.close(); } } if(ignored_data.size()) { std::ostringstream names; for(unsigned int i=0; i<ignored_data.size(); i++) names << ignored_data[i] << "\n"; mooseWarning("The following RestorableData was found in restart file but is being ignored:\n" << names.str()); } } <commit_msg>move to restartable data being written separately on each processor refs #1169<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "RestartableDataIO.h" #include "MooseUtils.h" #include "RestartableData.h" #include "FEProblem.h" #include <stdio.h> RestartableDataIO::RestartableDataIO(FEProblem & fe_problem) : _fe_problem(fe_problem) { } void RestartableDataIO::writeRestartableData(std::string base_file_name) { unsigned int n_threads = libMesh::n_threads(); unsigned int n_procs = libMesh::n_processors(); unsigned int proc_id = libMesh::processor_id(); for(unsigned int tid=0; tid<n_threads; tid++) { std::map<std::string, RestartableDataValue *> restartable_data = _fe_problem._restartable_data[tid]; if(restartable_data.size()) { const unsigned int file_version = 1; std::ofstream out; std::ostringstream file_name_stream; file_name_stream << base_file_name; file_name_stream << "-" << proc_id; if(n_threads > 1) file_name_stream << "-" << tid; std::string file_name = file_name_stream.str(); { // Write out header out.open(file_name.c_str(), std::ios::out | std::ios::binary); char id[2]; // header id[0] = 'R'; id[1] = 'D'; out.write(id, 2); out.write((const char *)&file_version, sizeof(file_version)); out.write((const char *)&n_procs, sizeof(n_procs)); out.write((const char *)&n_threads, sizeof(n_threads)); // number of RestartableData unsigned int n_data = restartable_data.size(); out.write((const char *) &n_data, sizeof(n_data)); // data names for(std::map<std::string, RestartableDataValue *>::iterator it = restartable_data.begin(); it != restartable_data.end(); ++it) { std::string name = it->second->name(); out.write(name.c_str(), name.length() + 1); // trailing 0! } } { std::ostringstream data_blk; for(std::map<std::string, RestartableDataValue *>::iterator it = restartable_data.begin(); it != restartable_data.end(); ++it) { // std::cout<<"Storing "<<it->first<<std::endl; std::ostringstream data; it->second->store(data); // Store the size of the data then the data unsigned int data_size = data.tellp(); data_blk.write((const char *) &data_size, sizeof(data_size)); data_blk << data.str(); } // Write out this proc's block size unsigned int data_blk_size = data_blk.tellp(); out.write((const char *) &data_blk_size, sizeof(data_blk_size)); // Write out the values out << data_blk.str(); out.close(); } } } } void RestartableDataIO::readRestartableData(std::string base_file_name) { unsigned int n_threads = libMesh::n_threads(); unsigned int n_procs = libMesh::n_processors(); unsigned int proc_id = libMesh::processor_id(); std::vector<std::string> ignored_data; for(unsigned int tid=0; tid<n_threads; tid++) { std::map<std::string, RestartableDataValue *> restartable_data = _fe_problem._restartable_data[tid]; if(restartable_data.size()) { std::ostringstream file_name_stream; file_name_stream << base_file_name; file_name_stream << "-" << proc_id; if(n_threads > 1) file_name_stream << "-" << tid; std::string file_name = file_name_stream.str(); MooseUtils::checkFileReadable(file_name); const unsigned int file_version = 1; std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary); // header char id[2]; in.read(id, 2); unsigned int this_file_version; in.read((char *)&this_file_version, sizeof(this_file_version)); unsigned int this_n_procs = 0; unsigned int this_n_threads = 0; in.read((char *)&this_n_procs, sizeof(this_n_procs)); in.read((char *)&this_n_threads, sizeof(this_n_threads)); // check the header if(id[0] != 'R' || id[1] != 'D') mooseError("Corrupted restartable data file!"); // check the file version if(this_file_version > file_version) mooseError("Trying to restart from a newer file version - you need to update MOOSE"); if(this_file_version < file_version) mooseError("Trying to restart from an older file version - you need to checkout an older version of MOOSE."); if(this_n_procs != n_procs) mooseError("Cannot restart using a different number of processors!"); if(this_n_threads != n_threads) mooseError("Cannot restart using a different number of threads!"); // number of data unsigned int n_data = 0; in.read((char *) &n_data, sizeof(n_data)); // data names std::vector<std::string> data_names(n_data); for(unsigned int i=0; i < n_data; i++) { std::string data_name; char ch = 0; do { in.read(&ch, 1); if (ch != '\0') data_name += ch; } while (ch != '\0'); data_names[i] = data_name; } // Grab this processor's block size unsigned int data_blk_size = 0; in.read((char *) &data_blk_size, sizeof(data_blk_size)); for(unsigned int i=0; i < n_data; i++) { std::string current_name = data_names[i]; unsigned int data_size = 0; in.read((char *) &data_size, sizeof(data_size)); if(restartable_data.find(current_name) != restartable_data.end()) // Only restore values if they're currently being used { // std::cout<<"Loading "<<current_name<<std::endl; RestartableDataValue * current_data = restartable_data[current_name]; current_data->load(in); } else { // Skip this piece of data in.seekg(data_size, std::ios_base::cur); ignored_data.push_back(current_name); } } in.close(); } } if(ignored_data.size()) { std::ostringstream names; for(unsigned int i=0; i<ignored_data.size(); i++) names << ignored_data[i] << "\n"; mooseWarning("The following RestorableData was found in restart file but is being ignored:\n" << names.str()); } } <|endoftext|>
<commit_before> #include <gloperate/stages/base/MixerStage.h> #include <glbinding/gl/gl.h> #include <globjects/base/File.h> #include <globjects/base/StringTemplate.h> #include <globjects/Framebuffer.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/Texture.h> #include <gloperate/base/Environment.h> #include <gloperate/base/ResourceManager.h> #include <gloperate/gloperate.h> namespace gloperate { CPPEXPOSE_COMPONENT(MixerStage, gloperate::Stage) MixerStage::MixerStage(Environment * environment, const std::string & name) : Stage(environment, "MixerStage", name) , viewport ("viewport", this) , targetFBO ("targetFBO", this) , texture ("texture", this) , vertexShader ("vertexShader", this) , geometryShader("geometryShader", this) , fragmentShader("fragmentShader", this) , rendered ("rendered", this) , fboOut ("fboOut", this) , m_rebuildProgram(false) { // Get data path std::string dataPath = gloperate::dataPath(); // Set default values vertexShader .setValue(dataPath + "/gloperate/shaders/Mixer/Mixer.vert"); fragmentShader.setValue(dataPath + "/gloperate/shaders/Mixer/Mixer.frag"); } MixerStage::~MixerStage() { } void MixerStage::onContextInit(AbstractGLContext *) { } void MixerStage::onContextDeinit(AbstractGLContext *) { m_vao = nullptr; m_buffer = nullptr; m_vertexShader = nullptr; m_geometryShader = nullptr; m_fragmentShader = nullptr; m_program = nullptr; } void MixerStage::onProcess(AbstractGLContext *) { // Check if geometry needs to be built if (!m_vao.get()) { buildGeometry(); } // Check if program needs to be (re-)built if (!m_program.get() || m_rebuildProgram) { buildProgram(); } // Activate FBO globjects::Framebuffer * fbo = *targetFBO; assert(fbo); fbo->bind(gl::GL_FRAMEBUFFER); // Set viewport gl::glViewport(viewport->x, viewport->y, viewport->z, viewport->w); // Disable depth test for screen-aligned quad gl::glDisable(gl::GL_DEPTH_TEST); // Enable blending gl::glEnable(gl::GL_BLEND); // Restore OpenGL states gl::glEnable(gl::GL_DEPTH_TEST); // Bind texture if (*texture) { gl::glActiveTexture(gl::GL_TEXTURE0 + 0); texture->bind(); } // Draw screen-aligned quad m_program->use(); m_vao->drawArrays(gl::GL_TRIANGLE_STRIP, 0, 4); m_vao->unbind(); m_program->release(); // Unbind texture if (*texture) { texture->unbind(); } // Unbind FBO, bind default FBO if (*targetFBO) { targetFBO->unbind(gl::GL_FRAMEBUFFER); globjects::Framebuffer::defaultFBO()->bind(gl::GL_FRAMEBUFFER); } // Indicate change to the output FBO fboOut.setValue(fbo); // Signal that output is valid rendered.setValue(true); } void MixerStage::onInputValueChanged(AbstractSlot * slot) { // Rebuild program when shader files have changed if (slot == &vertexShader || slot == &fragmentShader) { m_rebuildProgram = true; } // Invalidate all outputs invalidateOutputs(); } void MixerStage::buildGeometry() { // Static vertices static const std::array<glm::vec2, 4> vertices { { glm::vec2( +1.f, -1.f ) , glm::vec2( +1.f, +1.f ) , glm::vec2( -1.f, -1.f ) , glm::vec2( -1.f, +1.f ) } }; // Create vertex buffer m_buffer = cppassist::make_unique<globjects::Buffer>(); m_buffer->setData(vertices, gl::GL_STATIC_DRAW); // needed for some drivers // Create VAO m_vao = cppassist::make_unique<globjects::VertexArray>(); auto binding = m_vao->binding(0); binding->setAttribute(0); binding->setBuffer(m_buffer.get(), 0, sizeof(glm::vec2)); binding->setFormat(2, gl::GL_FLOAT, gl::GL_FALSE, 0); m_vao->enable(0); } void MixerStage::buildProgram() { // Create program and load shaders m_program = cppassist::make_unique<globjects::Program>(); if (auto shader = environment()->resourceManager()->load<globjects::Shader>(vertexShader.value())) { m_vertexShader = std::unique_ptr<globjects::Shader>(shader); m_program->attach(m_vertexShader.get()); } if (auto shader = environment()->resourceManager()->load<globjects::Shader>(geometryShader.value())) { m_geometryShader = std::unique_ptr<globjects::Shader>(shader); m_program->attach(m_geometryShader.get()); } if (auto shader = environment()->resourceManager()->load<globjects::Shader>(fragmentShader.value())) { m_fragmentShader = std::unique_ptr<globjects::Shader>(shader); m_program->attach(m_fragmentShader.get()); } // Set uniforms m_program->setUniform("texColor", 0); // Program has been built m_rebuildProgram = false; } } // namespace gloperate <commit_msg>MixerStage: Disable backface culling (fixes rendering on Windows)<commit_after> #include <gloperate/stages/base/MixerStage.h> #include <glbinding/gl/gl.h> #include <globjects/base/File.h> #include <globjects/base/StringTemplate.h> #include <globjects/Framebuffer.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/Texture.h> #include <gloperate/base/Environment.h> #include <gloperate/base/ResourceManager.h> #include <gloperate/gloperate.h> namespace gloperate { CPPEXPOSE_COMPONENT(MixerStage, gloperate::Stage) MixerStage::MixerStage(Environment * environment, const std::string & name) : Stage(environment, "MixerStage", name) , viewport ("viewport", this) , targetFBO ("targetFBO", this) , texture ("texture", this) , vertexShader ("vertexShader", this) , geometryShader("geometryShader", this) , fragmentShader("fragmentShader", this) , rendered ("rendered", this) , fboOut ("fboOut", this) , m_rebuildProgram(false) { // Get data path std::string dataPath = gloperate::dataPath(); // Set default values vertexShader .setValue(dataPath + "/gloperate/shaders/Mixer/Mixer.vert"); fragmentShader.setValue(dataPath + "/gloperate/shaders/Mixer/Mixer.frag"); } MixerStage::~MixerStage() { } void MixerStage::onContextInit(AbstractGLContext *) { } void MixerStage::onContextDeinit(AbstractGLContext *) { m_vao = nullptr; m_buffer = nullptr; m_vertexShader = nullptr; m_geometryShader = nullptr; m_fragmentShader = nullptr; m_program = nullptr; } void MixerStage::onProcess(AbstractGLContext *) { // Check if geometry needs to be built if (!m_vao.get()) { buildGeometry(); } // Check if program needs to be (re-)built if (!m_program.get() || m_rebuildProgram) { buildProgram(); } // Activate FBO globjects::Framebuffer * fbo = *targetFBO; assert(fbo); fbo->bind(gl::GL_FRAMEBUFFER); // Set viewport gl::glViewport(viewport->x, viewport->y, viewport->z, viewport->w); // Set OpenGL states gl::glDisable(gl::GL_CULL_FACE); gl::glDisable(gl::GL_DEPTH_TEST); gl::glEnable(gl::GL_BLEND); // Bind texture if (*texture) { gl::glActiveTexture(gl::GL_TEXTURE0 + 0); texture->bind(); } // Draw screen-aligned quad m_program->use(); m_vao->drawArrays(gl::GL_TRIANGLE_STRIP, 0, 4); m_vao->unbind(); m_program->release(); // Unbind texture if (*texture) { texture->unbind(); } // Unbind FBO, bind default FBO if (*targetFBO) { targetFBO->unbind(gl::GL_FRAMEBUFFER); globjects::Framebuffer::defaultFBO()->bind(gl::GL_FRAMEBUFFER); } // Indicate change to the output FBO fboOut.setValue(fbo); // Signal that output is valid rendered.setValue(true); } void MixerStage::onInputValueChanged(AbstractSlot * slot) { // Rebuild program when shader files have changed if (slot == &vertexShader || slot == &fragmentShader) { m_rebuildProgram = true; } // Invalidate all outputs invalidateOutputs(); } void MixerStage::buildGeometry() { // Static vertices static const std::array<glm::vec2, 4> vertices { { glm::vec2( +1.f, -1.f ) , glm::vec2( +1.f, +1.f ) , glm::vec2( -1.f, -1.f ) , glm::vec2( -1.f, +1.f ) } }; // Create vertex buffer m_buffer = cppassist::make_unique<globjects::Buffer>(); m_buffer->setData(vertices, gl::GL_STATIC_DRAW); // needed for some drivers // Create VAO m_vao = cppassist::make_unique<globjects::VertexArray>(); auto binding = m_vao->binding(0); binding->setAttribute(0); binding->setBuffer(m_buffer.get(), 0, sizeof(glm::vec2)); binding->setFormat(2, gl::GL_FLOAT, gl::GL_FALSE, 0); m_vao->enable(0); } void MixerStage::buildProgram() { // Create program and load shaders m_program = cppassist::make_unique<globjects::Program>(); if (auto shader = environment()->resourceManager()->load<globjects::Shader>(vertexShader.value())) { m_vertexShader = std::unique_ptr<globjects::Shader>(shader); m_program->attach(m_vertexShader.get()); } if (auto shader = environment()->resourceManager()->load<globjects::Shader>(geometryShader.value())) { m_geometryShader = std::unique_ptr<globjects::Shader>(shader); m_program->attach(m_geometryShader.get()); } if (auto shader = environment()->resourceManager()->load<globjects::Shader>(fragmentShader.value())) { m_fragmentShader = std::unique_ptr<globjects::Shader>(shader); m_program->attach(m_fragmentShader.get()); } // Set uniforms m_program->setUniform("texColor", 0); // Program has been built m_rebuildProgram = false; } } // namespace gloperate <|endoftext|>
<commit_before>// // PROJECT: Aspia // FILE: client/ui/desktop_widget.cc // LICENSE: GNU General Public License 3 // PROGRAMMERS: Dmitry Chapyshev ([email protected]) // #include "client/ui/desktop_widget.h" #include <QDebug> #include <QPainter> #include <QWheelEvent> #if defined(Q_OS_WIN) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // defined(Q_OS_WIN) #include "base/keycode_converter.h" #include "desktop_capture/desktop_frame_qimage.h" #include "protocol/desktop_session.pb.h" namespace aspia { namespace { constexpr quint32 kWheelMask = proto::desktop::PointerEvent::WHEEL_DOWN | proto::desktop::PointerEvent::WHEEL_UP; bool isNumLockActivated() { #if defined(Q_OS_WIN) return GetKeyState(VK_NUMLOCK) != 0; #else #error Platform support not implemented #endif // defined(Q_OS_WIN) } bool isCapsLockActivated() { #if defined(Q_OS_WIN) return GetKeyState(VK_CAPITAL) != 0; #else #error Platform support not implemented #endif // defined(Q_OS_WIN) } } // namespace DesktopWidget::DesktopWidget(QWidget* parent) : QWidget(parent) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setFocusPolicy(Qt::StrongFocus); setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_NoSystemBackground); setMouseTracking(true); } void DesktopWidget::resizeDesktopFrame(const QSize& screen_size) { frame_ = DesktopFrameQImage::create(screen_size); resize(screen_size); } DesktopFrame* DesktopWidget::desktopFrame() { return frame_.get(); } void DesktopWidget::doMouseEvent(QEvent::Type event_type, const Qt::MouseButtons& buttons, const QPoint& pos, const QPoint& delta) { if (!frame_ || !frame_->contains(pos.x(), pos.y())) return; quint32 mask; if (event_type == QMouseEvent::MouseMove) { mask = prev_mask_; } else { mask = 0; if (buttons & Qt::LeftButton) mask |= proto::desktop::PointerEvent::LEFT_BUTTON; if (buttons & Qt::MiddleButton) mask |= proto::desktop::PointerEvent::MIDDLE_BUTTON; if (buttons & Qt::RightButton) mask |= proto::desktop::PointerEvent::RIGHT_BUTTON; } int wheel_steps = 0; if (event_type == QEvent::Wheel) { if (delta.y() < 0) { mask |= proto::desktop::PointerEvent::WHEEL_DOWN; wheel_steps = -delta.y() / QWheelEvent::DefaultDeltasPerStep; } else { mask |= proto::desktop::PointerEvent::WHEEL_UP; wheel_steps = delta.y() / QWheelEvent::DefaultDeltasPerStep; } if (!wheel_steps) wheel_steps = 1; } if (prev_pos_ != pos || prev_mask_ != mask) { prev_pos_ = pos; prev_mask_ = mask & ~kWheelMask; if (mask & kWheelMask) { for (int i = 0; i < wheel_steps; ++i) { emit sendPointerEvent(pos, mask); emit sendPointerEvent(pos, mask & ~kWheelMask); } } else { emit sendPointerEvent(pos, mask); } } } void DesktopWidget::doKeyEvent(QKeyEvent* event) { int key = event->key(); if (key == Qt::Key_CapsLock || key == Qt::Key_NumLock) return; quint32 flags = ((event->type() == QEvent::KeyPress) ? proto::desktop::KeyEvent::PRESSED : 0); flags |= (isCapsLockActivated() ? proto::desktop::KeyEvent::CAPSLOCK : 0); flags |= (isNumLockActivated() ? proto::desktop::KeyEvent::NUMLOCK : 0); quint32 usb_keycode = KeycodeConverter::nativeKeycodeToUsbKeycode(event->nativeScanCode()); if (usb_keycode == KeycodeConverter::invalidUsbKeycode()) return; emit sendKeyEvent(usb_keycode, flags); } void DesktopWidget::executeKeySequense(int key_sequence) { const quint32 kUsbCodeLeftAlt = 0x0700e2; const quint32 kUsbCodeLeftCtrl = 0x0700e0; const quint32 kUsbCodeLeftShift = 0x0700e1; const quint32 kUsbCodeLeftMeta = 0x0700e3; QVector<int> keys; if (key_sequence & Qt::AltModifier) keys.push_back(kUsbCodeLeftAlt); if (key_sequence & Qt::ControlModifier) keys.push_back(kUsbCodeLeftCtrl); if (key_sequence & Qt::ShiftModifier) keys.push_back(kUsbCodeLeftShift); if (key_sequence & Qt::MetaModifier) keys.push_back(kUsbCodeLeftMeta); quint32 key = KeycodeConverter::qtKeycodeToUsbKeycode(key_sequence & ~Qt::KeyboardModifierMask); if (key == KeycodeConverter::invalidUsbKeycode()) return; keys.push_back(key); quint32 flags = proto::desktop::KeyEvent::PRESSED; flags |= (isCapsLockActivated() ? proto::desktop::KeyEvent::CAPSLOCK : 0); flags |= (isNumLockActivated() ? proto::desktop::KeyEvent::NUMLOCK : 0); for (auto it = keys.begin(); it != keys.end(); ++it) emit sendKeyEvent(*it, flags); flags ^= proto::desktop::KeyEvent::PRESSED; for (auto it = keys.rbegin(); it != keys.rend(); ++it) emit sendKeyEvent(*it, flags); } void DesktopWidget::paintEvent(QPaintEvent* /* event */) { if (frame_) { QPainter painter(this); painter.drawImage(rect(), frame_->constImage()); } } void DesktopWidget::mouseMoveEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::mousePressEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::mouseReleaseEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::mouseDoubleClickEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::wheelEvent(QWheelEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos(), event->angleDelta()); } void DesktopWidget::keyPressEvent(QKeyEvent* event) { doKeyEvent(event); } void DesktopWidget::keyReleaseEvent(QKeyEvent* event) { doKeyEvent(event); } void DesktopWidget::leaveEvent(QEvent* event) { // When the mouse cursor leaves the widget area, release all the mouse buttons. if (prev_mask_ != 0) { emit sendPointerEvent(prev_pos_, 0); prev_mask_ = 0; } QWidget::leaveEvent(event); } } // namespace aspia <commit_msg>- Using const iterators.<commit_after>// // PROJECT: Aspia // FILE: client/ui/desktop_widget.cc // LICENSE: GNU General Public License 3 // PROGRAMMERS: Dmitry Chapyshev ([email protected]) // #include "client/ui/desktop_widget.h" #include <QDebug> #include <QPainter> #include <QWheelEvent> #if defined(Q_OS_WIN) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // defined(Q_OS_WIN) #include "base/keycode_converter.h" #include "desktop_capture/desktop_frame_qimage.h" #include "protocol/desktop_session.pb.h" namespace aspia { namespace { constexpr quint32 kWheelMask = proto::desktop::PointerEvent::WHEEL_DOWN | proto::desktop::PointerEvent::WHEEL_UP; bool isNumLockActivated() { #if defined(Q_OS_WIN) return GetKeyState(VK_NUMLOCK) != 0; #else #error Platform support not implemented #endif // defined(Q_OS_WIN) } bool isCapsLockActivated() { #if defined(Q_OS_WIN) return GetKeyState(VK_CAPITAL) != 0; #else #error Platform support not implemented #endif // defined(Q_OS_WIN) } } // namespace DesktopWidget::DesktopWidget(QWidget* parent) : QWidget(parent) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setFocusPolicy(Qt::StrongFocus); setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_NoSystemBackground); setMouseTracking(true); } void DesktopWidget::resizeDesktopFrame(const QSize& screen_size) { frame_ = DesktopFrameQImage::create(screen_size); resize(screen_size); } DesktopFrame* DesktopWidget::desktopFrame() { return frame_.get(); } void DesktopWidget::doMouseEvent(QEvent::Type event_type, const Qt::MouseButtons& buttons, const QPoint& pos, const QPoint& delta) { if (!frame_ || !frame_->contains(pos.x(), pos.y())) return; quint32 mask; if (event_type == QMouseEvent::MouseMove) { mask = prev_mask_; } else { mask = 0; if (buttons & Qt::LeftButton) mask |= proto::desktop::PointerEvent::LEFT_BUTTON; if (buttons & Qt::MiddleButton) mask |= proto::desktop::PointerEvent::MIDDLE_BUTTON; if (buttons & Qt::RightButton) mask |= proto::desktop::PointerEvent::RIGHT_BUTTON; } int wheel_steps = 0; if (event_type == QEvent::Wheel) { if (delta.y() < 0) { mask |= proto::desktop::PointerEvent::WHEEL_DOWN; wheel_steps = -delta.y() / QWheelEvent::DefaultDeltasPerStep; } else { mask |= proto::desktop::PointerEvent::WHEEL_UP; wheel_steps = delta.y() / QWheelEvent::DefaultDeltasPerStep; } if (!wheel_steps) wheel_steps = 1; } if (prev_pos_ != pos || prev_mask_ != mask) { prev_pos_ = pos; prev_mask_ = mask & ~kWheelMask; if (mask & kWheelMask) { for (int i = 0; i < wheel_steps; ++i) { emit sendPointerEvent(pos, mask); emit sendPointerEvent(pos, mask & ~kWheelMask); } } else { emit sendPointerEvent(pos, mask); } } } void DesktopWidget::doKeyEvent(QKeyEvent* event) { int key = event->key(); if (key == Qt::Key_CapsLock || key == Qt::Key_NumLock) return; quint32 flags = ((event->type() == QEvent::KeyPress) ? proto::desktop::KeyEvent::PRESSED : 0); flags |= (isCapsLockActivated() ? proto::desktop::KeyEvent::CAPSLOCK : 0); flags |= (isNumLockActivated() ? proto::desktop::KeyEvent::NUMLOCK : 0); quint32 usb_keycode = KeycodeConverter::nativeKeycodeToUsbKeycode(event->nativeScanCode()); if (usb_keycode == KeycodeConverter::invalidUsbKeycode()) return; emit sendKeyEvent(usb_keycode, flags); } void DesktopWidget::executeKeySequense(int key_sequence) { const quint32 kUsbCodeLeftAlt = 0x0700e2; const quint32 kUsbCodeLeftCtrl = 0x0700e0; const quint32 kUsbCodeLeftShift = 0x0700e1; const quint32 kUsbCodeLeftMeta = 0x0700e3; QVector<int> keys; if (key_sequence & Qt::AltModifier) keys.push_back(kUsbCodeLeftAlt); if (key_sequence & Qt::ControlModifier) keys.push_back(kUsbCodeLeftCtrl); if (key_sequence & Qt::ShiftModifier) keys.push_back(kUsbCodeLeftShift); if (key_sequence & Qt::MetaModifier) keys.push_back(kUsbCodeLeftMeta); quint32 key = KeycodeConverter::qtKeycodeToUsbKeycode(key_sequence & ~Qt::KeyboardModifierMask); if (key == KeycodeConverter::invalidUsbKeycode()) return; keys.push_back(key); quint32 flags = proto::desktop::KeyEvent::PRESSED; flags |= (isCapsLockActivated() ? proto::desktop::KeyEvent::CAPSLOCK : 0); flags |= (isNumLockActivated() ? proto::desktop::KeyEvent::NUMLOCK : 0); for (auto it = keys.cbegin(); it != keys.cend(); ++it) emit sendKeyEvent(*it, flags); flags ^= proto::desktop::KeyEvent::PRESSED; for (auto it = keys.crbegin(); it != keys.crend(); ++it) emit sendKeyEvent(*it, flags); } void DesktopWidget::paintEvent(QPaintEvent* /* event */) { if (frame_) { QPainter painter(this); painter.drawImage(rect(), frame_->constImage()); } } void DesktopWidget::mouseMoveEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::mousePressEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::mouseReleaseEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::mouseDoubleClickEvent(QMouseEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos()); } void DesktopWidget::wheelEvent(QWheelEvent* event) { doMouseEvent(event->type(), event->buttons(), event->pos(), event->angleDelta()); } void DesktopWidget::keyPressEvent(QKeyEvent* event) { doKeyEvent(event); } void DesktopWidget::keyReleaseEvent(QKeyEvent* event) { doKeyEvent(event); } void DesktopWidget::leaveEvent(QEvent* event) { // When the mouse cursor leaves the widget area, release all the mouse buttons. if (prev_mask_ != 0) { emit sendPointerEvent(prev_pos_, 0); prev_mask_ = 0; } QWidget::leaveEvent(event); } } // namespace aspia <|endoftext|>
<commit_before>#include "details/pass/build-ast-to-ir/scope.h" #include "details/grammar/nany.h" #include "libnanyc-config.h" using namespace Yuni; namespace Nany { namespace IR { namespace Producer { void Scope::emitDebugpos(AST::Node& node) { if (node.offset > 0) { auto it = context.offsetToLine.lower_bound(node.offset); if (it != context.offsetToLine.end()) { if (it->first == node.offset or (--it != context.offsetToLine.end())) addDebugCurrentPosition(it->second, node.offset - it->first); } } } void Scope::doEmitTmplParameters() { if (!!lastPushedTmplParams) { if (not lastPushedTmplParams->empty()) { auto& outIR = sequence(); for (auto& pair: *lastPushedTmplParams) { if (pair.second.empty()) outIR.emitTPush(pair.first); else outIR.emitTPush(pair.first, pair.second); } } // clear lastPushedTmplParams = nullptr; } } AnyString Scope::getSymbolNameFromASTNode(AST::Node& node) { assert(node.rule == AST::rgSymbolName); assert(node.children.size() == 1); auto& identifier = node.children.front(); if (unlikely(identifier.rule != AST::rgIdentifier)) { unexpectedNode(node, "expected identifier"); return AnyString{}; } if (unlikely(identifier.text.size() > Config::maxSymbolNameLength)) { auto err = error(node) << "identifier name too long"; err.message.origins.location.pos.offsetEnd = err.message.origins.location.pos.offset + identifier.text.size(); return AnyString{}; } return identifier.text; } void Scope::checkForUnknownAttributes() const { assert(!!attributes); if (unlikely(not attributes->flags.empty())) { if (unlikely(context.ignoreAtoms)) return; auto& attrs = *attributes; auto& node = attrs.node; if (unlikely(attrs.flags(Attributes::Flag::pushSynthetic))) error(node, "invalid use of expr attribute '__nanyc_synthetic'"); if (attrs.flags(Attributes::Flag::shortcircuit)) error(node, "invalid use of func attribute 'shortcircuit'"); if (attrs.flags(Attributes::Flag::doNotSuggest)) error(node, "invalid use of func attribute 'nosuggest'"); if (attrs.flags(Attributes::Flag::builtinAlias)) error(node, "invalid use of func attribute 'builtinalias'"); if (attrs.flags(Attributes::Flag::threadproc)) error(node, "invalid use of func attribute 'thread'"); } } } // namespace Producer } // namespace IR } // namespace Nany <commit_msg>ast2ir: fixed crash when the iterator is already at the begining (clang)<commit_after>#include "details/pass/build-ast-to-ir/scope.h" #include "details/grammar/nany.h" #include "libnanyc-config.h" using namespace Yuni; namespace Nany { namespace IR { namespace Producer { void Scope::emitDebugpos(AST::Node& node) { if (node.offset > 0) { auto it = context.offsetToLine.lower_bound(node.offset); if (it != context.offsetToLine.end()) { bool emit = (it->first == node.offset); if (not emit and context.offsetToLine.begin() != it) emit = (--it != context.offsetToLine.end()); if (emit) addDebugCurrentPosition(it->second, node.offset - it->first); } } } void Scope::doEmitTmplParameters() { if (!!lastPushedTmplParams) { if (not lastPushedTmplParams->empty()) { auto& outIR = sequence(); for (auto& pair: *lastPushedTmplParams) { if (pair.second.empty()) outIR.emitTPush(pair.first); else outIR.emitTPush(pair.first, pair.second); } } // clear lastPushedTmplParams = nullptr; } } AnyString Scope::getSymbolNameFromASTNode(AST::Node& node) { assert(node.rule == AST::rgSymbolName); assert(node.children.size() == 1); auto& identifier = node.children.front(); if (unlikely(identifier.rule != AST::rgIdentifier)) { unexpectedNode(node, "expected identifier"); return AnyString{}; } if (unlikely(identifier.text.size() > Config::maxSymbolNameLength)) { auto err = error(node) << "identifier name too long"; err.message.origins.location.pos.offsetEnd = err.message.origins.location.pos.offset + identifier.text.size(); return AnyString{}; } return identifier.text; } void Scope::checkForUnknownAttributes() const { assert(!!attributes); if (unlikely(not attributes->flags.empty())) { if (unlikely(context.ignoreAtoms)) return; auto& attrs = *attributes; auto& node = attrs.node; if (unlikely(attrs.flags(Attributes::Flag::pushSynthetic))) error(node, "invalid use of expr attribute '__nanyc_synthetic'"); if (attrs.flags(Attributes::Flag::shortcircuit)) error(node, "invalid use of func attribute 'shortcircuit'"); if (attrs.flags(Attributes::Flag::doNotSuggest)) error(node, "invalid use of func attribute 'nosuggest'"); if (attrs.flags(Attributes::Flag::builtinAlias)) error(node, "invalid use of func attribute 'builtinalias'"); if (attrs.flags(Attributes::Flag::threadproc)) error(node, "invalid use of func attribute 'thread'"); } } } // namespace Producer } // namespace IR } // namespace Nany <|endoftext|>
<commit_before>/* * * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017 GAMS Software GmbH <[email protected]> * Copyright (c) 2017 GAMS Development Corp. <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QVariant> #include <vector> #include "gams.h" #include <iostream> using namespace std; using namespace gams; string getModelText() { return " Sets \n" " i canning plants \n" " j markets \n" " \n" " Parameters \n" " a(i) capacity of plant i in cases \n" " b(j) demand at market j in cases \n" " d(i,j) distance in thousands of miles \n" " Scalar f freight in dollars per case per thousand miles /90/; \n" " \n" "$if not set gdxincname $abort 'no include file name for data file provided' \n" "$gdxin %gdxincname% \n" "$load i j a b d \n" "$gdxin \n" " \n" " Parameter c(i,j) transport cost in thousands of dollars per case ; \n" " \n" " c(i,j) = f * d(i,j) / 1000 ; \n" " \n" " Variables \n" " x(i,j) shipment quantities in cases \n" " z total transportation costs in thousands of dollars ; \n" " \n" " Positive Variable x ; \n" " \n" " Equations \n" " cost define objective function \n" " supply(i) observe supply limit at plant i \n" " demand(j) satisfy demand at market j ; \n" " \n" " cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \n" " \n" " supply(i) .. sum(j, x(i,j)) =l= a(i) ; \n" " \n" " demand(j) .. sum(i, x(i,j)) =g= b(j) ; \n" " \n" " Model transport /all/ ; \n" " \n" " Solve transport using lp minimizing z ; \n" " \n" " Display x.l, x.m ; \n" " \n"; } void readSet(QSqlDatabase sqlDb, GAMSDatabase db, string strAccessSelect, string setName, int setDim, string setExp = "") { QSqlQuery query(sqlDb); if (!query.exec(strAccessSelect.c_str())) { cout << "Error executing query on set '" << setName << "'" << endl; cout << query.lastError().text().toStdString() << endl; exit(1); } if (query.size() && (query.record().count() != setDim)) { cout << "Number of fields in select statement does not match setDim" << endl; exit(1); } GAMSSet i = db.addSet(setName, setDim, setExp); vector<string> keys = vector<string>(setDim); while (query.next()) { for (int idx = 0; idx < setDim; idx++) keys[idx] = query.value(idx).toString().toStdString(); i.addRecord(keys); } } void readParameter(QSqlDatabase sqlDb, GAMSDatabase db, string strAccessSelect, string parName, int parDim, string parExp = "") { QSqlQuery query(sqlDb); if (!query.exec(strAccessSelect.c_str())) { cout << "Error executing query on parameter '" << parName << "'" << endl; cout << query.lastError().text().toStdString() << endl; exit(1); } if (query.size() && (query.record().count() != parDim+1)) { cout << "Number of fields in select statement does not match parDim" << endl; exit(1); } GAMSParameter a = db.addParameter(parName, parDim, parExp); vector<string> keys = vector<string>(parDim); while (query.next()) { for (int idx = 0; idx < parDim; idx++) keys[idx] = query.value(idx).toString().toStdString(); a.addRecord(keys).setValue(query.value(parDim).toDouble()); } } GAMSDatabase readFromAccess(GAMSWorkspace ws) { GAMSDatabase db = ws.addDatabase(); QSqlDatabase sqlDb = QSqlDatabase::addDatabase("QODBC", "readConnection"); QString strAccessConn = ("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=" + ws.systemDirectory() \ + cPathSep + "apifiles" + cPathSep + "Data" + cPathSep + "transport.accdb").c_str(); sqlDb.setDatabaseName(strAccessConn); if(sqlDb.open()) { // read GAMS sets readSet(sqlDb, db, "SELECT Plant FROM Plant", "i", 1, "canning plants"); readSet(sqlDb, db, "SELECT Market FROM Market", "j", 1, "markets"); // read GAMS parameters readParameter(sqlDb, db, "SELECT Plant,Capacity FROM Plant", "a", 1, "capacity of plant i in cases"); readParameter(sqlDb, db, "SELECT Market,Demand FROM Market", "b", 1, "demand at market j in cases"); readParameter(sqlDb, db, "SELECT Plant,Market,Distance FROM Distance", "d", 2, "distance in thousands of miles"); sqlDb.close(); } else { cout << "Error: Failed to create a database connection. " << sqlDb.lastError().text().toStdString() << endl; exit(1); } return db; } void writeVariable(QSqlDatabase sqlDb, GAMSDatabase db, string varName, vector<string> domains) { GAMSVariable var = db.getVariable(varName); if(domains.size() != var.dim()) { cout << "Number of column names does not match the dimension of the variable." << endl; exit(1); } // delete table varName if it exists already QSqlQuery query(sqlDb); query.exec(("drop table " + varName).c_str()); string queryStr = "create table " + varName + "("; for (string dom : domains) queryStr += dom + " varchar(64), "; queryStr += "lvl double)"; query.exec(queryStr.c_str()); for (GAMSVariableRecord rec : var) { queryStr = "insert into " + varName + "("; for (string dom : domains) queryStr += dom + ", "; queryStr += "lvl) values ("; for (string key : rec.keys()) queryStr += "'" + key + "', "; queryStr += std::to_string(rec.level()) + ")"; if(!query.exec(queryStr.c_str())) { cout << "Error: Failed to write variable to the database" << endl; cout << sqlDb.lastError().text().toStdString() << endl; exit(1); } } } void writeToAccess(GAMSWorkspace ws, GAMSDatabase db) { // connect to database QSqlDatabase sqlDb = QSqlDatabase::addDatabase("QODBC", "writeConnection"); QString strAccessConn = ("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=" + ws.systemDirectory() \ + cPathSep + "apifiles" + cPathSep + "Data" + cPathSep + "transport.accdb").c_str(); sqlDb.setDatabaseName(strAccessConn); if(sqlDb.open()) { // write levels of variable x vector<string> domains{"i", "j"}; writeVariable(sqlDb, db, "x", domains); sqlDb.close(); } else { cout << "Error: Failed to create a database connection. " << sqlDb.lastError().text().toStdString() << endl; exit(1); } } int main(int argc, char* argv[]) { cout << "---------- Transport 9 --------------" << endl; GAMSWorkspaceInfo wsInfo; if (argc > 1) wsInfo.setSystemDirectory(argv[1]); GAMSWorkspace ws(wsInfo); // fill GAMSDatabase by reading from Access GAMSDatabase db = readFromAccess(ws); // run job GAMSOptions opt = ws.addOptions(); GAMSJob t9 = ws.addJobFromString(getModelText()); opt.setDefine("gdxincname", db.name()); opt.setAllModelTypes("xpress"); t9.run(opt, db); for (GAMSVariableRecord rec : t9.outDB().getVariable("x")) cout << "x(" << rec.key(0) << "," << rec.key(1) << "):" << " level=" << rec.level() << " marginal=" << rec.marginal() << endl; // write results into Access file writeToAccess(ws, t9.outDB()); return 0; } <commit_msg>=include QtSql indead of including the used classes separately<commit_after>/* * * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017 GAMS Software GmbH <[email protected]> * Copyright (c) 2017 GAMS Development Corp. <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <QtSql> #include <vector> #include "gams.h" #include <iostream> using namespace std; using namespace gams; string getModelText() { return " Sets \n" " i canning plants \n" " j markets \n" " \n" " Parameters \n" " a(i) capacity of plant i in cases \n" " b(j) demand at market j in cases \n" " d(i,j) distance in thousands of miles \n" " Scalar f freight in dollars per case per thousand miles /90/; \n" " \n" "$if not set gdxincname $abort 'no include file name for data file provided' \n" "$gdxin %gdxincname% \n" "$load i j a b d \n" "$gdxin \n" " \n" " Parameter c(i,j) transport cost in thousands of dollars per case ; \n" " \n" " c(i,j) = f * d(i,j) / 1000 ; \n" " \n" " Variables \n" " x(i,j) shipment quantities in cases \n" " z total transportation costs in thousands of dollars ; \n" " \n" " Positive Variable x ; \n" " \n" " Equations \n" " cost define objective function \n" " supply(i) observe supply limit at plant i \n" " demand(j) satisfy demand at market j ; \n" " \n" " cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \n" " \n" " supply(i) .. sum(j, x(i,j)) =l= a(i) ; \n" " \n" " demand(j) .. sum(i, x(i,j)) =g= b(j) ; \n" " \n" " Model transport /all/ ; \n" " \n" " Solve transport using lp minimizing z ; \n" " \n" " Display x.l, x.m ; \n" " \n"; } void readSet(QSqlDatabase sqlDb, GAMSDatabase db, string strAccessSelect, string setName, int setDim, string setExp = "") { QSqlQuery query(sqlDb); if (!query.exec(strAccessSelect.c_str())) { cout << "Error executing query on set '" << setName << "'" << endl; cout << query.lastError().text().toStdString() << endl; exit(1); } if (query.size() && (query.record().count() != setDim)) { cout << "Number of fields in select statement does not match setDim" << endl; exit(1); } GAMSSet i = db.addSet(setName, setDim, setExp); vector<string> keys = vector<string>(setDim); while (query.next()) { for (int idx = 0; idx < setDim; idx++) keys[idx] = query.value(idx).toString().toStdString(); i.addRecord(keys); } } void readParameter(QSqlDatabase sqlDb, GAMSDatabase db, string strAccessSelect, string parName, int parDim, string parExp = "") { QSqlQuery query(sqlDb); if (!query.exec(strAccessSelect.c_str())) { cout << "Error executing query on parameter '" << parName << "'" << endl; cout << query.lastError().text().toStdString() << endl; exit(1); } if (query.size() && (query.record().count() != parDim+1)) { cout << "Number of fields in select statement does not match parDim" << endl; exit(1); } GAMSParameter a = db.addParameter(parName, parDim, parExp); vector<string> keys = vector<string>(parDim); while (query.next()) { for (int idx = 0; idx < parDim; idx++) keys[idx] = query.value(idx).toString().toStdString(); a.addRecord(keys).setValue(query.value(parDim).toDouble()); } } GAMSDatabase readFromAccess(GAMSWorkspace ws) { GAMSDatabase db = ws.addDatabase(); QSqlDatabase sqlDb = QSqlDatabase::addDatabase("QODBC", "readConnection"); QString strAccessConn = ("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=" + ws.systemDirectory() \ + cPathSep + "apifiles" + cPathSep + "Data" + cPathSep + "transport.accdb").c_str(); sqlDb.setDatabaseName(strAccessConn); if(sqlDb.open()) { // read GAMS sets readSet(sqlDb, db, "SELECT Plant FROM Plant", "i", 1, "canning plants"); readSet(sqlDb, db, "SELECT Market FROM Market", "j", 1, "markets"); // read GAMS parameters readParameter(sqlDb, db, "SELECT Plant,Capacity FROM Plant", "a", 1, "capacity of plant i in cases"); readParameter(sqlDb, db, "SELECT Market,Demand FROM Market", "b", 1, "demand at market j in cases"); readParameter(sqlDb, db, "SELECT Plant,Market,Distance FROM Distance", "d", 2, "distance in thousands of miles"); sqlDb.close(); } else { cout << "Error: Failed to create a database connection. " << sqlDb.lastError().text().toStdString() << endl; exit(1); } return db; } void writeVariable(QSqlDatabase sqlDb, GAMSDatabase db, string varName, vector<string> domains) { GAMSVariable var = db.getVariable(varName); if(domains.size() != var.dim()) { cout << "Number of column names does not match the dimension of the variable." << endl; exit(1); } // delete table varName if it exists already QSqlQuery query(sqlDb); query.exec(("drop table " + varName).c_str()); string queryStr = "create table " + varName + "("; for (string dom : domains) queryStr += dom + " varchar(64), "; queryStr += "lvl double)"; query.exec(queryStr.c_str()); for (GAMSVariableRecord rec : var) { queryStr = "insert into " + varName + "("; for (string dom : domains) queryStr += dom + ", "; queryStr += "lvl) values ("; for (string key : rec.keys()) queryStr += "'" + key + "', "; queryStr += std::to_string(rec.level()) + ")"; if(!query.exec(queryStr.c_str())) { cout << "Error: Failed to write variable to the database" << endl; cout << sqlDb.lastError().text().toStdString() << endl; exit(1); } } } void writeToAccess(GAMSWorkspace ws, GAMSDatabase db) { // connect to database QSqlDatabase sqlDb = QSqlDatabase::addDatabase("QODBC", "writeConnection"); QString strAccessConn = ("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=" + ws.systemDirectory() \ + cPathSep + "apifiles" + cPathSep + "Data" + cPathSep + "transport.accdb").c_str(); sqlDb.setDatabaseName(strAccessConn); if(sqlDb.open()) { // write levels of variable x vector<string> domains{"i", "j"}; writeVariable(sqlDb, db, "x", domains); sqlDb.close(); } else { cout << "Error: Failed to create a database connection. " << sqlDb.lastError().text().toStdString() << endl; exit(1); } } int main(int argc, char* argv[]) { cout << "---------- Transport 9 --------------" << endl; GAMSWorkspaceInfo wsInfo; if (argc > 1) wsInfo.setSystemDirectory(argv[1]); GAMSWorkspace ws(wsInfo); // fill GAMSDatabase by reading from Access GAMSDatabase db = readFromAccess(ws); // run job GAMSOptions opt = ws.addOptions(); GAMSJob t9 = ws.addJobFromString(getModelText()); opt.setDefine("gdxincname", db.name()); opt.setAllModelTypes("xpress"); t9.run(opt, db); for (GAMSVariableRecord rec : t9.outDB().getVariable("x")) cout << "x(" << rec.key(0) << "," << rec.key(1) << "):" << " level=" << rec.level() << " marginal=" << rec.marginal() << endl; // write results into Access file writeToAccess(ws, t9.outDB()); return 0; } <|endoftext|>
<commit_before>#include <franka_hw/franka_state_controller.h> #include <cmath> #include <mutex> #include <string> #include <controller_interface/controller_base.h> #include <hardware_interface/hardware_interface.h> #include <pluginlib/class_list_macros.h> #include <ros/ros.h> #include <tf/tf.h> #include <tf/transform_datatypes.h> #include <xmlrpcpp/XmlRpcValue.h> #include <franka_hw/Errors.h> #include <franka_hw/franka_cartesian_command_interface.h> namespace { tf::Transform convertArrayToTf(const std::array<double, 16>& transform) { tf::Matrix3x3 rotation(transform[0], transform[4], transform[8], transform[1], transform[5], transform[9], transform[2], transform[6], transform[10]); tf::Vector3 translation(transform[12], transform[13], transform[14]); return tf::Transform(rotation, translation); } franka_hw::Errors errorsToMessage(const franka::Errors& error) { franka_hw::Errors message; message.cartesian_motion_generator_acceleration_discontinuity = error.cartesian_motion_generator_acceleration_discontinuity; message.cartesian_motion_generator_elbow_limit_violation = error.cartesian_motion_generator_elbow_limit_violation; message.cartesian_motion_generator_elbow_sign_inconsistent = error.cartesian_motion_generator_elbow_sign_inconsistent; message.cartesian_motion_generator_start_elbow_invalid = error.cartesian_motion_generator_start_elbow_invalid; message.cartesian_motion_generator_velocity_discontinuity = error.cartesian_motion_generator_velocity_discontinuity; message.cartesian_motion_generator_velocity_limits_violation = error.cartesian_motion_generator_velocity_limits_violation; message.cartesian_position_limits_violation = error.cartesian_position_limits_violation; message.cartesian_position_motion_generator_start_pose_invalid = error.cartesian_position_motion_generator_start_pose_invalid; message.cartesian_reflex = error.cartesian_reflex; message.cartesian_velocity_profile_safety_violation = error.cartesian_velocity_profile_safety_violation; message.cartesian_velocity_violation = error.cartesian_velocity_violation; message.force_controller_desired_force_tolerance_violation = error.force_controller_desired_force_tolerance_violation; message.force_control_safety_violation = error.force_control_safety_violation; message.joint_motion_generator_acceleration_discontinuity = error.joint_motion_generator_acceleration_discontinuity; message.joint_motion_generator_position_limits_violation = error.joint_motion_generator_position_limits_violation; message.joint_motion_generator_velocity_discontinuity = error.joint_motion_generator_velocity_discontinuity; message.joint_motion_generator_velocity_limits_violation = message.joint_motion_generator_velocity_limits_violation; message.joint_position_limits_violation = error.joint_position_limits_violation; message.joint_position_motion_generator_start_pose_invalid = error.joint_position_motion_generator_start_pose_invalid; message.joint_reflex = error.joint_reflex; message.joint_velocity_violation = error.joint_velocity_violation; message.max_goal_pose_deviation_violation = error.max_goal_pose_deviation_violation; message.max_path_pose_deviation_violation = error.max_path_pose_deviation_violation; message.self_collision_avoidance_violation = error.self_collision_avoidance_violation; return message; } } // anonymous namespace namespace franka_hw { FrankaStateController::FrankaStateController() : franka_state_interface_(nullptr), franka_state_handle_(nullptr), publisher_transforms_(), publisher_franka_states_(), publisher_joint_states_(), publisher_external_wrench_(), trigger_publish_(30.0) {} bool FrankaStateController::init(hardware_interface::RobotHW* robot_hardware, ros::NodeHandle& root_node_handle, ros::NodeHandle& controller_node_handle) { franka_state_interface_ = robot_hardware->get<franka_hw::FrankaStateInterface>(); if (franka_state_interface_ == nullptr) { ROS_ERROR("FrankaStateController: Could not get Franka state interface from hardware"); return false; } if (!root_node_handle.getParam("arm_id", arm_id_)) { ROS_ERROR("FrankaStateController: Could not get parameter arm_id"); return false; } double publish_rate(30.0); if (controller_node_handle.getParam("publish_rate", publish_rate)) { trigger_publish_ = franka_hw::TriggerRate(publish_rate); } else { ROS_INFO_STREAM("FrankaStateController: Did not find publish_rate. Using default " << publish_rate << " [Hz]."); } if (!root_node_handle.getParam("joint_names", joint_names_) || joint_names_.size() != 7) { ROS_ERROR( "FrankaStateController: Invalid or no joint_names parameters provided, aborting " "controller init!"); return false; } try { franka_state_handle_.reset( new franka_hw::FrankaStateHandle(franka_state_interface_->getHandle(arm_id_ + "_robot"))); } catch (const hardware_interface::HardwareInterfaceException& ex) { ROS_ERROR_STREAM("FrankaStateController: Exception getting cartesian handle: " << ex.what()); return false; } publisher_transforms_.init(root_node_handle, "/tf", 1); publisher_franka_states_.init(controller_node_handle, "franka_states", 1); publisher_joint_states_.init(controller_node_handle, "joint_states", 1); publisher_external_wrench_.init(controller_node_handle, "F_ext", 1); { std::lock_guard<realtime_tools::RealtimePublisher<sensor_msgs::JointState> > lock( publisher_joint_states_); publisher_joint_states_.msg_.name.resize(7); publisher_joint_states_.msg_.position.resize(robot_state_.q.size()); publisher_joint_states_.msg_.velocity.resize(robot_state_.dq.size()); publisher_joint_states_.msg_.effort.resize(robot_state_.tau_J.size()); } { std::lock_guard<realtime_tools::RealtimePublisher<tf2_msgs::TFMessage> > lock( publisher_transforms_); publisher_transforms_.msg_.transforms.resize(2); tf::Quaternion quaternion(0.0, 0.0, 0.0, 1.0); tf::Vector3 translation(0.0, 0.0, 0.05); tf::Transform transform(quaternion, translation); tf::StampedTransform trafo(transform, ros::Time::now(), arm_id_ + "_link8", arm_id_ + "_EE"); geometry_msgs::TransformStamped transform_message; transformStampedTFToMsg(trafo, transform_message); publisher_transforms_.msg_.transforms[0] = transform_message; translation = tf::Vector3(0.0, 0.0, 0.0); transform = tf::Transform(quaternion, translation); trafo = tf::StampedTransform(transform, ros::Time::now(), arm_id_ + "_EE", arm_id_ + "_K"); transformStampedTFToMsg(trafo, transform_message); publisher_transforms_.msg_.transforms[1] = transform_message; } { std::lock_guard<realtime_tools::RealtimePublisher<geometry_msgs::WrenchStamped> > lock( publisher_external_wrench_); publisher_external_wrench_.msg_.header.frame_id = arm_id_ + "_K"; publisher_external_wrench_.msg_.wrench.force.x = 0.0; publisher_external_wrench_.msg_.wrench.force.y = 0.0; publisher_external_wrench_.msg_.wrench.force.z = 0.0; publisher_external_wrench_.msg_.wrench.torque.x = 0.0; publisher_external_wrench_.msg_.wrench.torque.y = 0.0; publisher_external_wrench_.msg_.wrench.torque.z = 0.0; } return true; } void FrankaStateController::update(const ros::Time& time, const ros::Duration& /*period*/) { if (trigger_publish_()) { robot_state_ = franka_state_handle_->getRobotState(); publishFrankaStates(time); publishTransforms(time); publishExternalWrench(time); publishJointStates(time); sequence_number_++; } } void FrankaStateController::publishFrankaStates(const ros::Time& time) { if (publisher_franka_states_.trylock()) { for (size_t i = 0; i < robot_state_.cartesian_collision.size(); ++i) { publisher_franka_states_.msg_.cartesian_collision[i] = robot_state_.cartesian_collision[i]; publisher_franka_states_.msg_.cartesian_contact[i] = robot_state_.cartesian_contact[i]; publisher_franka_states_.msg_.K_F_ext_hat_K[i] = robot_state_.K_F_ext_hat_K[i]; publisher_franka_states_.msg_.O_F_ext_hat_K[i] = robot_state_.O_F_ext_hat_K[i]; } for (size_t i = 0; i < robot_state_.q.size(); ++i) { publisher_franka_states_.msg_.q[i] = robot_state_.q[i]; publisher_franka_states_.msg_.dq[i] = robot_state_.dq[i]; publisher_franka_states_.msg_.tau_J[i] = robot_state_.tau_J[i]; publisher_franka_states_.msg_.dtau_J[i] = robot_state_.dtau_J[i]; publisher_franka_states_.msg_.joint_collision[i] = robot_state_.joint_collision[i]; publisher_franka_states_.msg_.joint_contact[i] = robot_state_.joint_contact[i]; publisher_franka_states_.msg_.q_d[i] = robot_state_.q_d[i]; publisher_franka_states_.msg_.tau_ext_hat_filtered[i] = robot_state_.tau_ext_hat_filtered[i]; } for (size_t i = 0; i < robot_state_.elbow.size(); ++i) { publisher_franka_states_.msg_.elbow[i] = robot_state_.elbow[i]; } for (size_t i = 0; i < robot_state_.elbow_d.size(); ++i) { publisher_franka_states_.msg_.elbow_d[i] = robot_state_.elbow_d[i]; } for (size_t i = 0; i < 16; ++i) { publisher_franka_states_.msg_.O_T_EE[i] = robot_state_.O_T_EE[i]; publisher_franka_states_.msg_.F_T_EE[i] = robot_state_.F_T_EE[i]; publisher_franka_states_.msg_.EE_T_K[i] = robot_state_.EE_T_K[i]; publisher_franka_states_.msg_.O_T_EE_d[i] = robot_state_.O_T_EE_d[i]; } publisher_franka_states_.msg_.m_load = robot_state_.m_load; for (size_t i = 0; i < 9; ++i) { publisher_franka_states_.msg_.I_load[i] = robot_state_.I_load[i]; } for (size_t i = 0; i < 3; ++i) { publisher_franka_states_.msg_.F_x_Cload[i] = robot_state_.F_x_Cload[i]; } publisher_franka_states_.msg_.time = robot_state_.time.s(); publisher_franka_states_.msg_.current_errors = errorsToMessage(robot_state_.current_errors); publisher_franka_states_.msg_.last_motion_errors = errorsToMessage(robot_state_.last_motion_errors); publisher_franka_states_.msg_.header.seq = sequence_number_; publisher_franka_states_.msg_.header.stamp = time; publisher_franka_states_.unlockAndPublish(); } } void FrankaStateController::publishJointStates(const ros::Time& time) { if (publisher_joint_states_.trylock()) { for (size_t i = 0; i < 7; ++i) { publisher_joint_states_.msg_.name[i] = joint_names_[i]; publisher_joint_states_.msg_.position[i] = robot_state_.q[i]; publisher_joint_states_.msg_.velocity[i] = robot_state_.dq[i]; publisher_joint_states_.msg_.effort[i] = robot_state_.tau_J[i]; } publisher_joint_states_.msg_.header.stamp = time; publisher_joint_states_.msg_.header.seq = sequence_number_; publisher_joint_states_.unlockAndPublish(); } } void FrankaStateController::publishTransforms(const ros::Time& time) { if (publisher_transforms_.trylock()) { tf::StampedTransform trafo(convertArrayToTf(robot_state_.F_T_EE), time, arm_id_ + "_link8", arm_id_ + "_EE"); geometry_msgs::TransformStamped transform_message; transformStampedTFToMsg(trafo, transform_message); publisher_transforms_.msg_.transforms[0] = transform_message; trafo = tf::StampedTransform(convertArrayToTf(robot_state_.EE_T_K), time, arm_id_ + "_EE", arm_id_ + "_K"); transformStampedTFToMsg(trafo, transform_message); publisher_transforms_.msg_.transforms[1] = transform_message; publisher_transforms_.unlockAndPublish(); } } void FrankaStateController::publishExternalWrench(const ros::Time& time) { if (publisher_external_wrench_.trylock()) { publisher_external_wrench_.msg_.header.frame_id = arm_id_ + "_K"; publisher_external_wrench_.msg_.header.stamp = time; publisher_external_wrench_.msg_.wrench.force.x = robot_state_.K_F_ext_hat_K[0]; publisher_external_wrench_.msg_.wrench.force.y = robot_state_.K_F_ext_hat_K[1]; publisher_external_wrench_.msg_.wrench.force.z = robot_state_.K_F_ext_hat_K[2]; publisher_external_wrench_.msg_.wrench.torque.x = robot_state_.K_F_ext_hat_K[3]; publisher_external_wrench_.msg_.wrench.torque.y = robot_state_.K_F_ext_hat_K[4]; publisher_external_wrench_.msg_.wrench.torque.z = robot_state_.K_F_ext_hat_K[5]; publisher_external_wrench_.unlockAndPublish(); } } } // namespace franka_hw PLUGINLIB_EXPORT_CLASS(franka_hw::FrankaStateController, controller_interface::ControllerBase) <commit_msg>Change name from trafo to stamped_transform<commit_after>#include <franka_hw/franka_state_controller.h> #include <cmath> #include <mutex> #include <string> #include <controller_interface/controller_base.h> #include <hardware_interface/hardware_interface.h> #include <pluginlib/class_list_macros.h> #include <ros/ros.h> #include <tf/tf.h> #include <tf/transform_datatypes.h> #include <xmlrpcpp/XmlRpcValue.h> #include <franka_hw/Errors.h> #include <franka_hw/franka_cartesian_command_interface.h> namespace { tf::Transform convertArrayToTf(const std::array<double, 16>& transform) { tf::Matrix3x3 rotation(transform[0], transform[4], transform[8], transform[1], transform[5], transform[9], transform[2], transform[6], transform[10]); tf::Vector3 translation(transform[12], transform[13], transform[14]); return tf::Transform(rotation, translation); } franka_hw::Errors errorsToMessage(const franka::Errors& error) { franka_hw::Errors message; message.cartesian_motion_generator_acceleration_discontinuity = error.cartesian_motion_generator_acceleration_discontinuity; message.cartesian_motion_generator_elbow_limit_violation = error.cartesian_motion_generator_elbow_limit_violation; message.cartesian_motion_generator_elbow_sign_inconsistent = error.cartesian_motion_generator_elbow_sign_inconsistent; message.cartesian_motion_generator_start_elbow_invalid = error.cartesian_motion_generator_start_elbow_invalid; message.cartesian_motion_generator_velocity_discontinuity = error.cartesian_motion_generator_velocity_discontinuity; message.cartesian_motion_generator_velocity_limits_violation = error.cartesian_motion_generator_velocity_limits_violation; message.cartesian_position_limits_violation = error.cartesian_position_limits_violation; message.cartesian_position_motion_generator_start_pose_invalid = error.cartesian_position_motion_generator_start_pose_invalid; message.cartesian_reflex = error.cartesian_reflex; message.cartesian_velocity_profile_safety_violation = error.cartesian_velocity_profile_safety_violation; message.cartesian_velocity_violation = error.cartesian_velocity_violation; message.force_controller_desired_force_tolerance_violation = error.force_controller_desired_force_tolerance_violation; message.force_control_safety_violation = error.force_control_safety_violation; message.joint_motion_generator_acceleration_discontinuity = error.joint_motion_generator_acceleration_discontinuity; message.joint_motion_generator_position_limits_violation = error.joint_motion_generator_position_limits_violation; message.joint_motion_generator_velocity_discontinuity = error.joint_motion_generator_velocity_discontinuity; message.joint_motion_generator_velocity_limits_violation = message.joint_motion_generator_velocity_limits_violation; message.joint_position_limits_violation = error.joint_position_limits_violation; message.joint_position_motion_generator_start_pose_invalid = error.joint_position_motion_generator_start_pose_invalid; message.joint_reflex = error.joint_reflex; message.joint_velocity_violation = error.joint_velocity_violation; message.max_goal_pose_deviation_violation = error.max_goal_pose_deviation_violation; message.max_path_pose_deviation_violation = error.max_path_pose_deviation_violation; message.self_collision_avoidance_violation = error.self_collision_avoidance_violation; return message; } } // anonymous namespace namespace franka_hw { FrankaStateController::FrankaStateController() : franka_state_interface_(nullptr), franka_state_handle_(nullptr), publisher_transforms_(), publisher_franka_states_(), publisher_joint_states_(), publisher_external_wrench_(), trigger_publish_(30.0) {} bool FrankaStateController::init(hardware_interface::RobotHW* robot_hardware, ros::NodeHandle& root_node_handle, ros::NodeHandle& controller_node_handle) { franka_state_interface_ = robot_hardware->get<franka_hw::FrankaStateInterface>(); if (franka_state_interface_ == nullptr) { ROS_ERROR("FrankaStateController: Could not get Franka state interface from hardware"); return false; } if (!root_node_handle.getParam("arm_id", arm_id_)) { ROS_ERROR("FrankaStateController: Could not get parameter arm_id"); return false; } double publish_rate(30.0); if (controller_node_handle.getParam("publish_rate", publish_rate)) { trigger_publish_ = franka_hw::TriggerRate(publish_rate); } else { ROS_INFO_STREAM("FrankaStateController: Did not find publish_rate. Using default " << publish_rate << " [Hz]."); } if (!root_node_handle.getParam("joint_names", joint_names_) || joint_names_.size() != 7) { ROS_ERROR( "FrankaStateController: Invalid or no joint_names parameters provided, aborting " "controller init!"); return false; } try { franka_state_handle_.reset( new franka_hw::FrankaStateHandle(franka_state_interface_->getHandle(arm_id_ + "_robot"))); } catch (const hardware_interface::HardwareInterfaceException& ex) { ROS_ERROR_STREAM("FrankaStateController: Exception getting cartesian handle: " << ex.what()); return false; } publisher_transforms_.init(root_node_handle, "/tf", 1); publisher_franka_states_.init(controller_node_handle, "franka_states", 1); publisher_joint_states_.init(controller_node_handle, "joint_states", 1); publisher_external_wrench_.init(controller_node_handle, "F_ext", 1); { std::lock_guard<realtime_tools::RealtimePublisher<sensor_msgs::JointState> > lock( publisher_joint_states_); publisher_joint_states_.msg_.name.resize(7); publisher_joint_states_.msg_.position.resize(robot_state_.q.size()); publisher_joint_states_.msg_.velocity.resize(robot_state_.dq.size()); publisher_joint_states_.msg_.effort.resize(robot_state_.tau_J.size()); } { std::lock_guard<realtime_tools::RealtimePublisher<tf2_msgs::TFMessage> > lock( publisher_transforms_); publisher_transforms_.msg_.transforms.resize(2); tf::Quaternion quaternion(0.0, 0.0, 0.0, 1.0); tf::Vector3 translation(0.0, 0.0, 0.05); tf::Transform transform(quaternion, translation); tf::StampedTransform stamped_transform(transform, ros::Time::now(), arm_id_ + "_link8", arm_id_ + "_EE"); geometry_msgs::TransformStamped transform_message; transformStampedTFToMsg(stamped_transform, transform_message); publisher_transforms_.msg_.transforms[0] = transform_message; translation = tf::Vector3(0.0, 0.0, 0.0); transform = tf::Transform(quaternion, translation); stamped_transform = tf::StampedTransform(transform, ros::Time::now(), arm_id_ + "_EE", arm_id_ + "_K"); transformStampedTFToMsg(stamped_transform, transform_message); publisher_transforms_.msg_.transforms[1] = transform_message; } { std::lock_guard<realtime_tools::RealtimePublisher<geometry_msgs::WrenchStamped> > lock( publisher_external_wrench_); publisher_external_wrench_.msg_.header.frame_id = arm_id_ + "_K"; publisher_external_wrench_.msg_.wrench.force.x = 0.0; publisher_external_wrench_.msg_.wrench.force.y = 0.0; publisher_external_wrench_.msg_.wrench.force.z = 0.0; publisher_external_wrench_.msg_.wrench.torque.x = 0.0; publisher_external_wrench_.msg_.wrench.torque.y = 0.0; publisher_external_wrench_.msg_.wrench.torque.z = 0.0; } return true; } void FrankaStateController::update(const ros::Time& time, const ros::Duration& /*period*/) { if (trigger_publish_()) { robot_state_ = franka_state_handle_->getRobotState(); publishFrankaStates(time); publishTransforms(time); publishExternalWrench(time); publishJointStates(time); sequence_number_++; } } void FrankaStateController::publishFrankaStates(const ros::Time& time) { if (publisher_franka_states_.trylock()) { for (size_t i = 0; i < robot_state_.cartesian_collision.size(); ++i) { publisher_franka_states_.msg_.cartesian_collision[i] = robot_state_.cartesian_collision[i]; publisher_franka_states_.msg_.cartesian_contact[i] = robot_state_.cartesian_contact[i]; publisher_franka_states_.msg_.K_F_ext_hat_K[i] = robot_state_.K_F_ext_hat_K[i]; publisher_franka_states_.msg_.O_F_ext_hat_K[i] = robot_state_.O_F_ext_hat_K[i]; } for (size_t i = 0; i < robot_state_.q.size(); ++i) { publisher_franka_states_.msg_.q[i] = robot_state_.q[i]; publisher_franka_states_.msg_.dq[i] = robot_state_.dq[i]; publisher_franka_states_.msg_.tau_J[i] = robot_state_.tau_J[i]; publisher_franka_states_.msg_.dtau_J[i] = robot_state_.dtau_J[i]; publisher_franka_states_.msg_.joint_collision[i] = robot_state_.joint_collision[i]; publisher_franka_states_.msg_.joint_contact[i] = robot_state_.joint_contact[i]; publisher_franka_states_.msg_.q_d[i] = robot_state_.q_d[i]; publisher_franka_states_.msg_.tau_ext_hat_filtered[i] = robot_state_.tau_ext_hat_filtered[i]; } for (size_t i = 0; i < robot_state_.elbow.size(); ++i) { publisher_franka_states_.msg_.elbow[i] = robot_state_.elbow[i]; } for (size_t i = 0; i < robot_state_.elbow_d.size(); ++i) { publisher_franka_states_.msg_.elbow_d[i] = robot_state_.elbow_d[i]; } for (size_t i = 0; i < 16; ++i) { publisher_franka_states_.msg_.O_T_EE[i] = robot_state_.O_T_EE[i]; publisher_franka_states_.msg_.F_T_EE[i] = robot_state_.F_T_EE[i]; publisher_franka_states_.msg_.EE_T_K[i] = robot_state_.EE_T_K[i]; publisher_franka_states_.msg_.O_T_EE_d[i] = robot_state_.O_T_EE_d[i]; } publisher_franka_states_.msg_.m_load = robot_state_.m_load; for (size_t i = 0; i < 9; ++i) { publisher_franka_states_.msg_.I_load[i] = robot_state_.I_load[i]; } for (size_t i = 0; i < 3; ++i) { publisher_franka_states_.msg_.F_x_Cload[i] = robot_state_.F_x_Cload[i]; } publisher_franka_states_.msg_.time = robot_state_.time.s(); publisher_franka_states_.msg_.current_errors = errorsToMessage(robot_state_.current_errors); publisher_franka_states_.msg_.last_motion_errors = errorsToMessage(robot_state_.last_motion_errors); publisher_franka_states_.msg_.header.seq = sequence_number_; publisher_franka_states_.msg_.header.stamp = time; publisher_franka_states_.unlockAndPublish(); } } void FrankaStateController::publishJointStates(const ros::Time& time) { if (publisher_joint_states_.trylock()) { for (size_t i = 0; i < 7; ++i) { publisher_joint_states_.msg_.name[i] = joint_names_[i]; publisher_joint_states_.msg_.position[i] = robot_state_.q[i]; publisher_joint_states_.msg_.velocity[i] = robot_state_.dq[i]; publisher_joint_states_.msg_.effort[i] = robot_state_.tau_J[i]; } publisher_joint_states_.msg_.header.stamp = time; publisher_joint_states_.msg_.header.seq = sequence_number_; publisher_joint_states_.unlockAndPublish(); } } void FrankaStateController::publishTransforms(const ros::Time& time) { if (publisher_transforms_.trylock()) { tf::StampedTransform stamped_transform(convertArrayToTf(robot_state_.F_T_EE), time, arm_id_ + "_link8", arm_id_ + "_EE"); geometry_msgs::TransformStamped transform_message; transformStampedTFToMsg(stamped_transform, transform_message); publisher_transforms_.msg_.transforms[0] = transform_message; stamped_transform = tf::StampedTransform(convertArrayToTf(robot_state_.EE_T_K), time, arm_id_ + "_EE", arm_id_ + "_K"); transformStampedTFToMsg(stamped_transform, transform_message); publisher_transforms_.msg_.transforms[1] = transform_message; publisher_transforms_.unlockAndPublish(); } } void FrankaStateController::publishExternalWrench(const ros::Time& time) { if (publisher_external_wrench_.trylock()) { publisher_external_wrench_.msg_.header.frame_id = arm_id_ + "_K"; publisher_external_wrench_.msg_.header.stamp = time; publisher_external_wrench_.msg_.wrench.force.x = robot_state_.K_F_ext_hat_K[0]; publisher_external_wrench_.msg_.wrench.force.y = robot_state_.K_F_ext_hat_K[1]; publisher_external_wrench_.msg_.wrench.force.z = robot_state_.K_F_ext_hat_K[2]; publisher_external_wrench_.msg_.wrench.torque.x = robot_state_.K_F_ext_hat_K[3]; publisher_external_wrench_.msg_.wrench.torque.y = robot_state_.K_F_ext_hat_K[4]; publisher_external_wrench_.msg_.wrench.torque.z = robot_state_.K_F_ext_hat_K[5]; publisher_external_wrench_.unlockAndPublish(); } } } // namespace franka_hw PLUGINLIB_EXPORT_CLASS(franka_hw::FrankaStateController, controller_interface::ControllerBase) <|endoftext|>
<commit_before>// // main.cpp // thermaleraser // // Created by Mark Larus on 9/8/12. // Copyright (c) 2012 Kenyon College. All rights reserved. // #include <iostream> #include <algorithm> #include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> /*! Fix a namespace issue with boost library. This lets us use both cpu_timer and progress */ #define timer timer_class #include <boost/progress.hpp> #undef timer #include "clangomp.h" #include "Stochastic.h" #include "Ising.h" #include "System.h" #include "Utilities.h" #include "ReservoirFactory.h" #define print(x) std::cout<<#x <<": " <<x<<std::endl; namespace opt = boost::program_options; enum OutputType { CommaSeparated, PrettyPrint, Mathematica, NoOutput }; enum ReservoirType { Ising, Stoch }; void simulate_and_print(Constants constants, int iterations, OutputType type, ReservoirFactory *factory, bool verbose = false); int main(int argc, char * argv[]) { /*! Initialize options list. */ bool verbose = false; const int default_iterations = 1<<16; opt::options_description desc("Allowed options"); desc.add_options() ("iterations,n",opt::value<int>(), "Number of iterations.") ("help","Show help message") ("verbose,v", "Show extensive debugging info") ("benchmark", "Test evaluation speed") ("ising", opt::value<bool>()->default_value(false), "Use Ising reservoir. Requires -d. Overrides --stoch") ("stoch", opt::value<bool>()->default_value(true), "Use Stochastic reservoir. This is set by default, and overridden by" " --ising") ("dimension,d", opt::value<int>()->default_value(100), "Set the dimension of the Ising reservoir") ; opt::variables_map vmap; opt::store(opt::parse_command_line(argc,argv,desc),vmap); opt::notify(vmap); if (vmap.count("help")) { std::cout << desc << "\n"; return 1; } verbose = vmap.count("verbose"); int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations; if (verbose) { print(iterations); #pragma omp parallel #pragma omp single print(omp_get_num_threads()); } OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated; /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is represented by an object with pointers to the next states and the bit-flip states. */ setupStates(); Constants constants; /*! The delta used here is NOT, at this point, the delta used in the paper. This is the ratio of ones to zeroes in the bit stream. Probably worth changing the name, but calculating this at runtime is just an invitation for bugs. */ constants.delta = .5; constants.epsilon = .7; constants.tau = 20; int dimension = 50; if(vmap.count("benchmark")) { std::cout<<"Benchmarking speed.\n"; int benchmark_size = 1000; boost::timer::cpu_timer timer; boost::progress_display display(benchmark_size); timer.start(); #pragma omp parallel for private(constants) for (int k=0; k<benchmark_size; k++) { simulate_and_print(constants,iterations,NoOutput,false); ++display; } timer.stop(); double time_elapsed = timer.elapsed().wall; print(benchmark_size); print(timer.format(3,"%ws")); print(benchmark_size/time_elapsed); exit(0); } ReservoirFactory *rFactory = NULL; if ( vmap["ising"].as<bool>() ) { if (!vmap.count("dimension")) { std::clog << "Option --ising requires -d\n"; exit(1); } int dim = vmap["dimension"].as<int>(); rFactory = new IsingReservoir::IsingFactory(dim); } else { //Assume stochastic rFactory = new DefaultArgsReservoirFactory<StochasticReservoir>; } assert(rFactory); #pragma omp parallel for private(constants) for (int k=dimension*dimension; k>=0; k--) { constants.epsilon = (k % dimension)/(double)(dimension); constants.delta = .5 + .5*(k / dimension)/(double)(dimension); simulate_and_print(constants, iterations, output_style, rFactory, verbose); } delete rFactory; } void simulate_and_print(Constants constants, int iterations, OutputType type, \ ReservoirFactory *factory, bool verbose) { /*! Use this to change the length of the tape. */ const int BIT_STREAM_LENGTH = 8; int first_pass_iterations = iterations; int *histogram = new int[1<<BIT_STREAM_LENGTH]; std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0); long double *p = new long double[1<<BIT_STREAM_LENGTH]; long double *p_prime = new long double[1<<BIT_STREAM_LENGTH]; long double sum = 0; const long double beta = log((1+constants.epsilon)/(1-constants.epsilon)); long double max_surprise = 0; long double min_surprise = LONG_MAX; gsl_rng *localRNG = GSLRandomNumberGenerator(); for (int k=0; k<first_pass_iterations; ++k) { System *currentSystem = new System(localRNG, constants,BIT_STREAM_LENGTH); StochasticReservoir *reservoir = new StochasticReservoir(localRNG,constants); currentSystem->evolveWithReservoir(reservoir); histogram[currentSystem->endingBitString]++; delete currentSystem; delete reservoir; } for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) { int setBits = bitCount(k,BIT_STREAM_LENGTH); p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits); p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations); } delete [] histogram; for(int k=0; k<iterations; k++) { System *currentSystem = new System(localRNG, constants, BIT_STREAM_LENGTH); StochasticReservoir *reservoir = new StochasticReservoir(localRNG,constants); currentSystem->evolveWithReservoir(reservoir); long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString]; max_surprise = surprise > max_surprise ? surprise : max_surprise; min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise; sum = sum + surprise; delete currentSystem; delete reservoir; } delete [] p_prime; delete [] p; #pragma omp critical { if(type==CommaSeparated) { static int once = 0; if (!once) { std::cout<<"delta,epsilon,avg,max_surprise\n"; once=1; } std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl; } if(type==PrettyPrint) { print(beta); print(constants.delta); print(constants.epsilon); print(sum/iterations); print(max_surprise); print(sum); std::cout<<std::endl; } if (type==Mathematica) { exit(1); } } gsl_rng_free(localRNG); } <commit_msg>Fix an issue with default values for boost options.<commit_after>// // main.cpp // thermaleraser // // Created by Mark Larus on 9/8/12. // Copyright (c) 2012 Kenyon College. All rights reserved. // #include <iostream> #include <algorithm> #include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> /*! Fix a namespace issue with boost library. This lets us use both cpu_timer and progress */ #define timer timer_class #include <boost/progress.hpp> #undef timer #include "clangomp.h" #include "Stochastic.h" #include "Ising.h" #include "System.h" #include "Utilities.h" #include "ReservoirFactory.h" #define print(x) std::cout<<#x <<": " <<x<<std::endl; namespace opt = boost::program_options; enum OutputType { CommaSeparated, PrettyPrint, Mathematica, NoOutput }; enum ReservoirType { Ising, Stoch }; void simulate_and_print(Constants constants, int iterations, OutputType type, ReservoirFactory *factory, bool verbose = false); int main(int argc, char * argv[]) { /*! Initialize options list. */ bool verbose = false; const int default_iterations = 1<<16; opt::options_description desc("Allowed options"); desc.add_options() ("iterations,n",opt::value<int>(), "Number of iterations.") ("help","Show help message") ("verbose,v", "Show extensive debugging info") ("benchmark", "Test evaluation speed") ("ising", "Use Ising reservoir. Requires -d. Overrides --stoch") ("stoch", "Use Stochastic reservoir. This is set by default, and overridden" " by --ising.") ("dimension,d", opt::value<int>()->default_value(100), "Set the dimension of the Ising reservoir") ; opt::variables_map vmap; opt::store(opt::parse_command_line(argc,argv,desc),vmap); opt::notify(vmap); if (vmap.count("help")) { std::cout << desc << "\n"; return 1; } verbose = vmap.count("verbose"); int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations; if (verbose) { print(iterations); #pragma omp parallel #pragma omp single print(omp_get_num_threads()); } OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated; /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is represented by an object with pointers to the next states and the bit-flip states. */ setupStates(); Constants constants; /*! The delta used here is NOT, at this point, the delta used in the paper. This is the ratio of ones to zeroes in the bit stream. Probably worth changing the name, but calculating this at runtime is just an invitation for bugs. */ constants.delta = .5; constants.epsilon = .7; constants.tau = 20; int dimension = 50; if(vmap.count("benchmark")) { std::cout<<"Benchmarking speed.\n"; int benchmark_size = 1000; boost::timer::cpu_timer timer; boost::progress_display display(benchmark_size); timer.start(); #pragma omp parallel for private(constants) for (int k=0; k<benchmark_size; k++) { simulate_and_print(constants,iterations,NoOutput,false); ++display; } timer.stop(); double time_elapsed = timer.elapsed().wall; print(benchmark_size); print(timer.format(3,"%ws")); print(benchmark_size/time_elapsed); exit(0); } ReservoirFactory *rFactory = NULL; if ( vmap["ising"].as<bool>() ) { if (!vmap.count("dimension")) { std::clog << "Option --ising requires -d\n"; exit(1); } int dim = vmap["dimension"].as<int>(); rFactory = new IsingReservoir::IsingFactory(dim); } else { //Assume stochastic rFactory = new DefaultArgsReservoirFactory<StochasticReservoir>; } assert(rFactory); #pragma omp parallel for private(constants) for (int k=dimension*dimension; k>=0; k--) { constants.epsilon = (k % dimension)/(double)(dimension); constants.delta = .5 + .5*(k / dimension)/(double)(dimension); simulate_and_print(constants, iterations, output_style, rFactory, verbose); } delete rFactory; } void simulate_and_print(Constants constants, int iterations, OutputType type, \ ReservoirFactory *factory, bool verbose) { /*! Use this to change the length of the tape. */ const int BIT_STREAM_LENGTH = 8; int first_pass_iterations = iterations; int *histogram = new int[1<<BIT_STREAM_LENGTH]; std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0); long double *p = new long double[1<<BIT_STREAM_LENGTH]; long double *p_prime = new long double[1<<BIT_STREAM_LENGTH]; long double sum = 0; const long double beta = log((1+constants.epsilon)/(1-constants.epsilon)); long double max_surprise = 0; long double min_surprise = LONG_MAX; gsl_rng *localRNG = GSLRandomNumberGenerator(); for (int k=0; k<first_pass_iterations; ++k) { System *currentSystem = new System(localRNG, constants,BIT_STREAM_LENGTH); StochasticReservoir *reservoir = new StochasticReservoir(localRNG,constants); currentSystem->evolveWithReservoir(reservoir); histogram[currentSystem->endingBitString]++; delete currentSystem; delete reservoir; } for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) { int setBits = bitCount(k,BIT_STREAM_LENGTH); p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits); p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations); } delete [] histogram; for(int k=0; k<iterations; k++) { System *currentSystem = new System(localRNG, constants, BIT_STREAM_LENGTH); StochasticReservoir *reservoir = new StochasticReservoir(localRNG,constants); currentSystem->evolveWithReservoir(reservoir); long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString]; max_surprise = surprise > max_surprise ? surprise : max_surprise; min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise; sum = sum + surprise; delete currentSystem; delete reservoir; } delete [] p_prime; delete [] p; #pragma omp critical { if(type==CommaSeparated) { static int once = 0; if (!once) { std::cout<<"delta,epsilon,avg,max_surprise\n"; once=1; } std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl; } if(type==PrettyPrint) { print(beta); print(constants.delta); print(constants.epsilon); print(sum/iterations); print(max_surprise); print(sum); std::cout<<std::endl; } if (type==Mathematica) { exit(1); } } gsl_rng_free(localRNG); } <|endoftext|>
<commit_before>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9"; static const char* pszTestKey = "048b75ab041ee9965f6f57ee299395c02daf5105f208fc49e908804aad3ace5a77c7f87b3aae74d6698124f20c3d1bea31c9fcdd350c9c61c0113fd988ecfb5c09"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <commit_msg>Update alert.cpp<commit_after>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "03eb63e8fe22172205bcdd4a92932a778b41e1fa21e16321ac67487d039b255690"; static const char* pszTestKey = "048b75ab041ee9965f6f57ee299395c02daf5105f208fc49e908804aad3ace5a77c7f87b3aae74d6698124f20c3d1bea31c9fcdd350c9c61c0113fd988ecfb5c09"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <|endoftext|>
<commit_before>/* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp [email protected] Josef Weinbub [email protected] (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #ifdef _MSC_VER //Visual Studio complains about potentially dangerous things, which are perfectly legal in our context #pragma warning( disable : 4355 ) //use of this in member initializer list #pragma warning( disable : 4503 ) //truncated name decoration #endif #include "viennagrid/forwards.h" #include "viennagrid/element.hpp" #include "viennagrid/point.hpp" #include "viennagrid/domain.hpp" #include "viennagrid/segment.hpp" #include "viennagrid/config/simplex.hpp" template <typename CellType, typename DomainType> void setup_cell(CellType & cell, DomainType & domain, std::size_t id0, std::size_t id1, std::size_t id2) { typedef typename DomainType::config_type ConfigType; typedef typename viennagrid::result_of::ncell<ConfigType, 0>::type VertexType; VertexType * cell_vertices[3]; //holds pointers to the respective vertices in the domain cell_vertices[0] = &(viennagrid::ncells<0>(domain)[id0]); cell_vertices[1] = &(viennagrid::ncells<0>(domain)[id1]); cell_vertices[2] = &(viennagrid::ncells<0>(domain)[id2]); cell.vertices(cell_vertices); } // // Let us construct the following input domain: // // 5---------4---------3 // | \ | \ | // | \ | \ | y // | \ | \ | ^ // | \ | \ | | // 0---------1---------2 *--> x // // Segment 1 | Segment 2 // int main() { // // Define the necessary types: // typedef viennagrid::config::triangular_2d ConfigType; typedef viennagrid::result_of::domain<ConfigType>::type Domain; typedef viennagrid::result_of::segment<ConfigType>::type Segment; typedef ConfigType::cell_tag CellTag; typedef viennagrid::result_of::point<ConfigType>::type PointType; typedef viennagrid::result_of::ncell<ConfigType, 0>::type VertexType; typedef viennagrid::result_of::ncell<ConfigType, CellTag::dim>::type CellType; typedef viennagrid::result_of::ncell_range<Segment, CellTag::dim>::type CellRange; typedef viennagrid::result_of::iterator<CellRange>::type CellIterator; std::cout << "-------------------------------------------------------------- " << std::endl; std::cout << "-- ViennaGrid tutorial: Setup of a domain with two segments -- " << std::endl; std::cout << "-------------------------------------------------------------- " << std::endl; std::cout << std::endl; // // Step 1: Instantiate the domain and create two segments: // Domain domain; domain.segments().resize(2); Segment seg0 = domain.segments()[0]; Segment seg1 = domain.segments()[1]; // // Step 2: Add vertices to the domain. // Note that vertices with IDs are enumerated in the order they are pushed to the domain. // domain.push_back(PointType(0,0)); domain.push_back(PointType(1,0)); domain.push_back(PointType(2,0)); domain.push_back(PointType(2,1)); domain.push_back(PointType(1,1)); domain.push_back(PointType(0,1)); // // Step 3: Fill the two segments with cells. // To do so, each cell must be linked with the defining vertices from the domain (not v0, v1, ...!) // CellType cell; VertexType * cell_vertices[3]; //holds pointers to the respective vertices in the domain // First triangle: (do not use v0, v1, etc. for vertex setup!) cell_vertices[0] = &(viennagrid::ncells<0>(domain)[0]); //get vertex with ID 0 from domain cell_vertices[1] = &(viennagrid::ncells<0>(domain)[1]); //get vertex with ID 1 from domain cell_vertices[2] = &(viennagrid::ncells<0>(domain)[5]); //get vertex with ID 5 from domain cell.vertices(cell_vertices); //set cell vertices. //Note that vertices are rearranged internally if they are not supplied in mathematically positive order. seg0.push_back(cell); //copies 'cell' to the domain. 'cell' can be reused for setting up the other cells. // Second triangle: setup_cell(cell, domain, 1, 4, 5); //use the shortcut function defined at the beginning of this tutorial seg0.push_back(cell); // Third triangle: setup_cell(cell, domain, 1, 2, 4); seg1.push_back(cell); // Note that we push to 'seg1' now. // Fourth triangle: setup_cell(cell, domain, 2, 3, 4); seg1.push_back(cell); // // That's it. The domain consisting of two segments is now set up. // If no segments are required, one can also directly write domain.push_back(cell); // // // Step 4: Output the cells for each segment: // std::cout << "Cells in segment 0:" << std::endl; CellRange cells_seg0 = viennagrid::ncells(seg0); for (CellIterator cit0 = cells_seg0.begin(); cit0 != cells_seg0.end(); ++cit0) { std::cout << *cit0 << std::endl; } std::cout << std::endl; std::cout << "Cells in segment 1:" << std::endl; CellRange cells_seg1 = viennagrid::ncells(seg1); for (CellIterator cit1 = cells_seg1.begin(); cit1 != cells_seg1.end(); ++cit1) { std::cout << *cit1 << std::endl; } std::cout << std::endl; std::cout << "-----------------------------------------------" << std::endl; std::cout << " \\o/ Tutorial finished successfully! \\o/ " << std::endl; std::cout << "-----------------------------------------------" << std::endl; return EXIT_SUCCESS; } <commit_msg>adapted to new domain/storage layer<commit_after>/* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp [email protected] Josef Weinbub [email protected] (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #ifdef _MSC_VER //Visual Studio complains about potentially dangerous things, which are perfectly legal in our context #pragma warning( disable : 4355 ) //use of this in member initializer list #pragma warning( disable : 4503 ) //truncated name decoration #endif #include "viennagrid/forwards.hpp" #include "viennagrid/domain/geometric_domain.hpp" #include "viennagrid/point.hpp" #include "viennagrid/domain.hpp" #include "viennagrid/segment.hpp" #include "viennagrid/config/simplex.hpp" template <typename CellType, typename DomainType, typename SegmentType> void setup_cell(DomainType & domain, SegmentType & segment, std::size_t id0, std::size_t id1, std::size_t id2) { typedef typename viennagrid::result_of::element_hook<DomainType, viennagrid::vertex_tag>::type VertexHookType; viennagrid::storage::static_array<VertexHookType, 3> vertices; vertices[0] = viennagrid::elements<viennagrid::vertex_tag>(domain).hook_at( id0 ); vertices[1] = viennagrid::elements<viennagrid::vertex_tag>(domain).hook_at( id1 ); vertices[2] = viennagrid::elements<viennagrid::vertex_tag>(domain).hook_at( id2 ); viennagrid::create_element<CellType>(segment, vertices); } // // Let us construct the following input domain: // // 5---------4---------3 // | \ | \ | // | \ | \ | y // | \ | \ | ^ // | \ | \ | | // 0---------1---------2 *--> x // // Segment 1 | Segment 2 // int main() { // // Define the necessary types: // typedef viennagrid::point_t<double, viennagrid::cartesian_cs<2> > PointType; typedef viennagrid::result_of::geometric_domain_config< viennagrid::triangle_tag, PointType, viennagrid::storage::id_hook_tag >::type DomainConfig; //typedef viennagrid::config::triangular_2d ConfigType; //typedef viennagrid::result_of::domain<ConfigType>::type Domain; //typedef viennagrid::result_of::segment<ConfigType>::type Segment; typedef viennagrid::result_of::geometric_domain< DomainConfig >::type Domain; typedef viennagrid::result_of::geometric_view<Domain>::type Segment; typedef viennagrid::triangle_tag CellTag; //typedef viennagrid::result_of::point<ConfigType>::type PointType; typedef viennagrid::result_of::element<Domain, viennagrid::vertex_tag>::type VertexType; typedef viennagrid::result_of::element_hook<Domain, viennagrid::vertex_tag>::type VertexHookType; typedef viennagrid::result_of::element<Domain, CellTag>::type CellType; typedef viennagrid::result_of::element_range<Segment, CellTag>::type CellRange; typedef viennagrid::result_of::iterator<CellRange>::type CellIterator; std::cout << "-------------------------------------------------------------- " << std::endl; std::cout << "-- ViennaGrid tutorial: Setup of a domain with two segments -- " << std::endl; std::cout << "-------------------------------------------------------------- " << std::endl; std::cout << std::endl; // // Step 1: Instantiate the domain and create two segments: // Domain domain; // std::vector<Segment> segments; // // segments.resize(2); // segments[0] = viennagrid::create_view<Segment>(domain); // segments[1] = viennagrid::create_view<Segment>(domain); // //domain.segments().resize(2); Segment seg0 = viennagrid::create_view<Segment>(domain); Segment seg1 = viennagrid::create_view<Segment>(domain); // // Step 2: Add vertices to the domain. // Note that vertices with IDs are enumerated in the order they are pushed to the domain. // viennagrid::point( domain, viennagrid::create_element<VertexType>(domain) ) = PointType(0,0); viennagrid::point( domain, viennagrid::create_element<VertexType>(domain) ) = PointType(1,0); viennagrid::point( domain, viennagrid::create_element<VertexType>(domain) ) = PointType(2,0); viennagrid::point( domain, viennagrid::create_element<VertexType>(domain) ) = PointType(2,1); viennagrid::point( domain, viennagrid::create_element<VertexType>(domain) ) = PointType(1,1); viennagrid::point( domain, viennagrid::create_element<VertexType>(domain) ) = PointType(0,1); // // Step 3: Fill the two segments with cells. // To do so, each cell must be linked with the defining vertices from the domain (not v0, v1, ...!) // viennagrid::storage::static_array<VertexHookType, 3> vertices; //CellType cell; //VertexType * cell_vertices[3]; //holds pointers to the respective vertices in the domain // First triangle: (do not use v0, v1, etc. for vertex setup!) vertices[0] = viennagrid::elements<viennagrid::vertex_tag>(domain).hook_at(0); vertices[1] = viennagrid::elements<viennagrid::vertex_tag>(domain).hook_at(1); vertices[2] = viennagrid::elements<viennagrid::vertex_tag>(domain).hook_at(5); //Note that vertices are rearranged internally if they are not supplied in mathematically positive order. viennagrid::create_element<CellType>(seg0, vertices); //copies 'cell' to the domain. 'cell' can be reused for setting up the other cells. // Second triangle: setup_cell<CellType>(domain, seg0, 1, 4, 5); //use the shortcut function defined at the beginning of this tutorial // Third triangle: setup_cell<CellType>(domain, seg1, 1, 2, 4); // Note that we push to 'seg1' now. // Fourth triangle: setup_cell<CellType>(domain, seg1, 2, 3, 4); // // That's it. The domain consisting of two segments is now set up. // If no segments are required, one can also directly write domain.push_back(cell); // // // Step 4: Output the cells for each segment: // std::cout << "Cells in segment 0:" << std::endl; CellRange cells_seg0 = viennagrid::elements<CellType>(seg0); for (CellIterator cit0 = cells_seg0.begin(); cit0 != cells_seg0.end(); ++cit0) { std::cout << *cit0 << std::endl; } std::cout << std::endl; std::cout << "Cells in segment 1:" << std::endl; CellRange cells_seg1 = viennagrid::elements<CellType>(seg1); for (CellIterator cit1 = cells_seg1.begin(); cit1 != cells_seg1.end(); ++cit1) { std::cout << *cit1 << std::endl; } std::cout << std::endl; std::cout << "-----------------------------------------------" << std::endl; std::cout << " \\o/ Tutorial finished successfully! \\o/ " << std::endl; std::cout << "-----------------------------------------------" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "0486bce1bac0d543f104cbff2bd23680056a3b9ea05e1137d2ff90eeb5e08472eb500322593a2cb06fbf8297d7beb6cd30cb90f98153b5b7cce1493749e41e0284"; // TestNet alerts pubKey static const char* pszTestKey = "0471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496"; // TestNet alerts private key // "308201130201010420b665cff1884e53da26376fd1b433812c9a5a8a4d5221533b15b9629789bb7e42a081a53081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a1440342000471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496" void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRId64"\n" " nExpiration = %"PRId64"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything // even possibly remotely dangerous like & or > std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@"); std::string safeStatus; for (std::string::size_type i = 0; i < strStatusBar.size(); i++) { if (safeChars.find(strStatusBar[i]) != std::string::npos) safeStatus.push_back(strStatusBar[i]); } safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <commit_msg>Add new alert key.<commit_after>// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "04d2045ae17f45675e7c0eaa19d47fca3462defec5a713a7eda2bd04b86fafc8a2eece56562025fc131cf03bd96f3501dfb0ac0f2faa5557d69f7a7778711994f1"; // TestNet alerts pubKey static const char* pszTestKey = "0471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496"; // TestNet alerts private key // "308201130201010420b665cff1884e53da26376fd1b433812c9a5a8a4d5221533b15b9629789bb7e42a081a53081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a1440342000471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496" void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRId64"\n" " nExpiration = %"PRId64"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything // even possibly remotely dangerous like & or > std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@"); std::string safeStatus; for (std::string::size_type i = 0; i < strStatusBar.size(); i++) { if (safeChars.find(strStatusBar[i]) != std::string::npos) safeStatus.push_back(strStatusBar[i]); } safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } <|endoftext|>
<commit_before>#include <iostream> #include <thread> #include <chrono> #include <atomic> #include <string> #include <iomanip> #include <memory> #include <sys/ioctl.h> #include <linux/serial.h> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/asio/steady_timer.hpp> void sendTest(const boost::system::error_code &ec); static const uint32_t DEFAULT_BAUD_RATE = 115200; static const auto DEFAULT_FLOW_CONTROL = boost::asio::serial_port_base::flow_control::none; static const auto DEFAULT_STOP_BITS = boost::asio::serial_port_base::stop_bits::one; static const auto DEFAULT_PARITY = boost::asio::serial_port_base::parity::even; static boost::asio::io_service io_service; static boost::asio::steady_timer timer(io_service); struct TestData { std::size_t send_size = 0; std::size_t rec_size = 0; std::vector<uint8_t> send_data; std::vector<uint8_t> rec_data; }; typedef std::shared_ptr<TestData> TestDataPtr; class Port { public: Port(boost::asio::io_service &io_service, const std::string & device) : serial_port_(io_service, device) { boost::asio::serial_port_base::baud_rate br(DEFAULT_BAUD_RATE); boost::asio::serial_port_base::flow_control fc(DEFAULT_FLOW_CONTROL); boost::asio::serial_port_base::stop_bits sb(DEFAULT_STOP_BITS); boost::asio::serial_port_base::parity p(DEFAULT_PARITY); serial_port_.set_option(br); serial_port_.set_option(fc); serial_port_.set_option(sb); serial_port_.set_option(p); auto nativeHandler = serial_port_.lowest_layer().native_handle(); serial_rs485 rs485conf; rs485conf.flags = (!SER_RS485_ENABLED) | (!SER_RS485_RTS_ON_SEND); rs485conf.delay_rts_before_send = 0; rs485conf.delay_rts_after_send = 0; // set rs485 settings on given tty if (ioctl(nativeHandler, TIOCSRS485, &rs485conf) < 0) { std::cout << "SerialPort ioctl() ERROR" << std::endl; } } void echo() { std::cout << "echo()" << std::endl; std::shared_ptr<std::vector<uint8_t> > buffer = std::make_shared<std::vector<uint8_t> >(1); serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()), boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void send_test(const std::vector<uint8_t>& pattern) { TestDataPtr data = std::make_shared<TestData>(); data->send_data = std::vector<uint8_t>(pattern); serial_port_.async_write_some(boost::asio::buffer(data->send_data, data->send_data.size()), boost::bind(&Port::handler_send_test, this, data, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } /* void send_test_pattern(const std::vector<uint8_t>& pattern) { serial_port_.async_write_some(boost::asio::buffer(pattern, pattern.size()), boost::bind(&Port::handler_send_test_pattern, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handler_send_test_pattern(const boost::system::error_code &ec, const std::size_t bytes_recived) { if (!ec) { std::cout << "handler_send_test_pattern send" << std::to_string(bytes_recived) << std::endl; std::chrono::milliseconds dura(500); std::this_thread::sleep_for(dura); send_test_pattern (test_pattern); } else { std::cout << "handler_send_test_pattern() " << ec.message() << std::endl; } } void rec_test_pattern(const std::vector<uint8_t>& pattern) { } */ private: void handler_echo_read(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_recived) { if (!ec) { std::cout << "handler_echo_read() msg:" << ec.message() << "\t bytes_read " << std::to_string(bytes_recived) << "\t"; for (int i = 0; i < bytes_recived; i++) { int value = (int) (*buffer)[i]; std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << value; } std::cout << std::endl; serial_port_.async_write_some(boost::asio::buffer(*buffer, bytes_recived), boost::bind(&Port::handler_echo_write, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { std::cout << "handler_echo_read() " << ec.message() << std::endl; } } void handler_echo_write(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_transferd) { if (!ec) { //buffer.reset(); //buffer = std::make_shared < std::vector<uint8_t> > (BUFFER_SIZE); std::cout << "handler_echo_write() \t written " << std::to_string(bytes_transferd) << std::endl; serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()), boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { std::cout << "handler_echo_write() " << ec.message() << std::endl; } } void handler_send_test(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_transferd) { if (!ec) { testData->send_size = bytes_transferd; std::cout << "handler_send_test(): bytes_send: \t" << std::to_string(bytes_transferd) << std::endl; global_read_buffer = std::vector<uint8_t>(bytes_transferd); ///* serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, bytes_transferd), boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // */ /* boost::asio::async_read(serial_port_, boost::asio::buffer(*receive_buffer, bytes_transferd), boost::bind(&Port::handler_receive_test, this, send_buffer, bytes_transferd, receive_buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // */ } } void handler_read_all(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_recived) { if (!ec) { std::cout << "handler_read_all(): bytes_recived: \t" << std::to_string(bytes_recived) << std::endl; testData->rec_size += bytes_recived; for (int i = 0; i < bytes_recived; i++) { testData->rec_data.push_back(global_read_buffer[i]); } if (testData->send_size > testData->rec_size) { std::size_t missing = testData->send_size - testData->rec_size; global_read_buffer = std::vector<uint8_t>(missing); serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, missing), boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { handler_receive_test(testData); } } else { std::cout << "handler_read_all() " << ec.message() << std::endl; } } void handler_receive_test(TestDataPtr testData) { std::cout << "handler_receive_test()" << std::endl; bool error = false; if (testData->send_size != testData->rec_size) { std::cout << "snd: \t" << std::to_string(testData->send_size) << std::endl; std::cout << "rec: \t" << std::to_string(testData->rec_size) << std::endl; } for (int i = 0; i < testData->send_size; i++) { uint8_t sendByte = testData->send_data[i]; uint8_t recivedByte = testData->rec_data[i]; if (sendByte != recivedByte || error) { error = true; std::cout << "snd: " << std::hex << std::setfill('0') << std::setw(2) << (int) sendByte; std::cout << "\trec: " << std::hex << std::setfill('0') << std::setw(2) << (int) recivedByte; std::cout << std::endl; } else { } } if (!error) { std::cout << "OK "; std::cout << "snd: " << std::to_string(testData->send_size); std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl; std::cout << std::endl; } else { std::cout << "ERROR "; std::cout << "snd: " << std::to_string(testData->send_size); std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl; std::cout << std::endl; } timer.expires_from_now(std::chrono::milliseconds(50)); timer.async_wait(sendTest); } boost::asio::serial_port serial_port_; std::vector<uint8_t> global_read_buffer; }; static std::vector<uint8_t> basic_pattern; //6 bytes static std::vector<uint8_t> test_pattern; static Port* port; void sendTest(const boost::system::error_code &ec) { //apennd new testpatterm for (int i = 0; i < 7; i++) { int8_t v = test_pattern[test_pattern.size() - 1]; test_pattern.push_back((v - 1)); } //test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end()); //if to long reset to basic size if (test_pattern.size() > 250) { test_pattern = basic_pattern; } if (!ec && port != 0) { port->send_test(test_pattern); } else { std::cout << "sendTest() " << ec.message() << std::endl; } } int main(int argc, char** argv) { if (std::strcmp(argv[1], "echo") == 0) { std::string port_name_a(argv[2]); port = new Port(io_service, port_name_a); port->echo(); } /* else if (std::strcmp(argv[1], "send") == 0) { std::string port_name_a(argv[2]); port = new Port(io_service, port_name_a); test_pattern.push_back(0xFF); for (int i = 0; i < 64; i++) { int8_t v = test_pattern[test_pattern.size() - 1]; test_pattern.push_back((v - 1)); } port->send_test_pattern(test_pattern); } else if (std::strcmp(argv[1], "rec") == 0) { std::string port_name_a(argv[2]); port = new Port(io_service, port_name_a); test_pattern.push_back(0xFF); for (int i = 0; i < 64; i++) { int8_t v = test_pattern[test_pattern.size() - 1]; test_pattern.push_back((v - 1)); } port->rec_test_pattern(test_pattern); } // */ else { std::string port_name_a(argv[1]); port = new Port(io_service, port_name_a); basic_pattern.push_back(0xFF); basic_pattern.push_back(0xFE); basic_pattern.push_back(0xFD); basic_pattern.push_back(0xFC); basic_pattern.push_back(0xFB); basic_pattern.push_back(0xFA); basic_pattern.push_back(0xF9); test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end()); std::cout << "send_test()" << std::endl; std::cout << std::endl; for (auto i : (test_pattern)) { std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << (int) i; } std::cout << std::endl; timer.expires_from_now(std::chrono::seconds(1)); timer.async_wait(sendTest); } io_service.run(); return 0; } <commit_msg>FETAURE: set timing to 10ms<commit_after>#include <iostream> #include <thread> #include <chrono> #include <atomic> #include <string> #include <iomanip> #include <memory> #include <sys/ioctl.h> #include <linux/serial.h> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/asio/steady_timer.hpp> void sendTest(const boost::system::error_code &ec); static const uint32_t DEFAULT_BAUD_RATE = 115200; static const auto DEFAULT_FLOW_CONTROL = boost::asio::serial_port_base::flow_control::none; static const auto DEFAULT_STOP_BITS = boost::asio::serial_port_base::stop_bits::one; static const auto DEFAULT_PARITY = boost::asio::serial_port_base::parity::even; static boost::asio::io_service io_service; static boost::asio::steady_timer timer(io_service); struct TestData { std::size_t send_size = 0; std::size_t rec_size = 0; std::vector<uint8_t> send_data; std::vector<uint8_t> rec_data; }; typedef std::shared_ptr<TestData> TestDataPtr; class Port { public: Port(boost::asio::io_service &io_service, const std::string & device) : serial_port_(io_service, device) { boost::asio::serial_port_base::baud_rate br(DEFAULT_BAUD_RATE); boost::asio::serial_port_base::flow_control fc(DEFAULT_FLOW_CONTROL); boost::asio::serial_port_base::stop_bits sb(DEFAULT_STOP_BITS); boost::asio::serial_port_base::parity p(DEFAULT_PARITY); serial_port_.set_option(br); serial_port_.set_option(fc); serial_port_.set_option(sb); serial_port_.set_option(p); auto nativeHandler = serial_port_.lowest_layer().native_handle(); serial_rs485 rs485conf; rs485conf.flags = (!SER_RS485_ENABLED) | (!SER_RS485_RTS_ON_SEND); rs485conf.delay_rts_before_send = 0; rs485conf.delay_rts_after_send = 0; // set rs485 settings on given tty if (ioctl(nativeHandler, TIOCSRS485, &rs485conf) < 0) { std::cout << "SerialPort ioctl() ERROR" << std::endl; } } void echo() { std::cout << "echo()" << std::endl; std::shared_ptr<std::vector<uint8_t> > buffer = std::make_shared<std::vector<uint8_t> >(1); serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()), boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void send_test(const std::vector<uint8_t>& pattern) { TestDataPtr data = std::make_shared<TestData>(); data->send_data = std::vector<uint8_t>(pattern); serial_port_.async_write_some(boost::asio::buffer(data->send_data, data->send_data.size()), boost::bind(&Port::handler_send_test, this, data, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } /* void send_test_pattern(const std::vector<uint8_t>& pattern) { serial_port_.async_write_some(boost::asio::buffer(pattern, pattern.size()), boost::bind(&Port::handler_send_test_pattern, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handler_send_test_pattern(const boost::system::error_code &ec, const std::size_t bytes_recived) { if (!ec) { std::cout << "handler_send_test_pattern send" << std::to_string(bytes_recived) << std::endl; std::chrono::milliseconds dura(500); std::this_thread::sleep_for(dura); send_test_pattern (test_pattern); } else { std::cout << "handler_send_test_pattern() " << ec.message() << std::endl; } } void rec_test_pattern(const std::vector<uint8_t>& pattern) { } */ private: void handler_echo_read(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_recived) { if (!ec) { std::cout << "handler_echo_read() msg:" << ec.message() << "\t bytes_read " << std::to_string(bytes_recived) << "\t"; for (int i = 0; i < bytes_recived; i++) { int value = (int) (*buffer)[i]; std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << value; } std::cout << std::endl; serial_port_.async_write_some(boost::asio::buffer(*buffer, bytes_recived), boost::bind(&Port::handler_echo_write, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { std::cout << "handler_echo_read() " << ec.message() << std::endl; } } void handler_echo_write(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_transferd) { if (!ec) { //buffer.reset(); //buffer = std::make_shared < std::vector<uint8_t> > (BUFFER_SIZE); std::cout << "handler_echo_write() \t written " << std::to_string(bytes_transferd) << std::endl; serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()), boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { std::cout << "handler_echo_write() " << ec.message() << std::endl; } } void handler_send_test(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_transferd) { if (!ec) { testData->send_size = bytes_transferd; std::cout << "handler_send_test(): bytes_send: \t" << std::to_string(bytes_transferd) << std::endl; global_read_buffer = std::vector<uint8_t>(bytes_transferd); ///* serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, bytes_transferd), boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // */ /* boost::asio::async_read(serial_port_, boost::asio::buffer(*receive_buffer, bytes_transferd), boost::bind(&Port::handler_receive_test, this, send_buffer, bytes_transferd, receive_buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // */ } } void handler_read_all(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_recived) { if (!ec) { std::cout << "handler_read_all(): bytes_recived: \t" << std::to_string(bytes_recived) << std::endl; testData->rec_size += bytes_recived; for (int i = 0; i < bytes_recived; i++) { testData->rec_data.push_back(global_read_buffer[i]); } if (testData->send_size > testData->rec_size) { std::size_t missing = testData->send_size - testData->rec_size; global_read_buffer = std::vector<uint8_t>(missing); serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, missing), boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { handler_receive_test(testData); } } else { std::cout << "handler_read_all() " << ec.message() << std::endl; } } void handler_receive_test(TestDataPtr testData) { std::cout << "handler_receive_test()" << std::endl; bool error = false; if (testData->send_size != testData->rec_size) { std::cout << "snd: \t" << std::to_string(testData->send_size) << std::endl; std::cout << "rec: \t" << std::to_string(testData->rec_size) << std::endl; } for (int i = 0; i < testData->send_size; i++) { uint8_t sendByte = testData->send_data[i]; uint8_t recivedByte = testData->rec_data[i]; if (sendByte != recivedByte || error) { error = true; std::cout << "snd: " << std::hex << std::setfill('0') << std::setw(2) << (int) sendByte; std::cout << "\trec: " << std::hex << std::setfill('0') << std::setw(2) << (int) recivedByte; std::cout << std::endl; } else { } } if (!error) { std::cout << "OK "; std::cout << "snd: " << std::to_string(testData->send_size); std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl; std::cout << std::endl; } else { std::cout << "ERROR "; std::cout << "snd: " << std::to_string(testData->send_size); std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl; std::cout << std::endl; } timer.expires_from_now(std::chrono::milliseconds(10)); timer.async_wait(sendTest); } boost::asio::serial_port serial_port_; std::vector<uint8_t> global_read_buffer; }; static std::vector<uint8_t> basic_pattern; //6 bytes static std::vector<uint8_t> test_pattern; static Port* port; void sendTest(const boost::system::error_code &ec) { //apennd new testpatterm for (int i = 0; i < 7; i++) { int8_t v = test_pattern[test_pattern.size() - 1]; test_pattern.push_back((v - 1)); } //test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end()); //if to long reset to basic size if (test_pattern.size() > 250) { test_pattern = basic_pattern; } if (!ec && port != 0) { port->send_test(test_pattern); } else { std::cout << "sendTest() " << ec.message() << std::endl; } } int main(int argc, char** argv) { if (std::strcmp(argv[1], "echo") == 0) { std::string port_name_a(argv[2]); port = new Port(io_service, port_name_a); port->echo(); } /* else if (std::strcmp(argv[1], "send") == 0) { std::string port_name_a(argv[2]); port = new Port(io_service, port_name_a); test_pattern.push_back(0xFF); for (int i = 0; i < 64; i++) { int8_t v = test_pattern[test_pattern.size() - 1]; test_pattern.push_back((v - 1)); } port->send_test_pattern(test_pattern); } else if (std::strcmp(argv[1], "rec") == 0) { std::string port_name_a(argv[2]); port = new Port(io_service, port_name_a); test_pattern.push_back(0xFF); for (int i = 0; i < 64; i++) { int8_t v = test_pattern[test_pattern.size() - 1]; test_pattern.push_back((v - 1)); } port->rec_test_pattern(test_pattern); } // */ else { std::string port_name_a(argv[1]); port = new Port(io_service, port_name_a); basic_pattern.push_back(0xFF); basic_pattern.push_back(0xFE); basic_pattern.push_back(0xFD); basic_pattern.push_back(0xFC); basic_pattern.push_back(0xFB); basic_pattern.push_back(0xFA); basic_pattern.push_back(0xF9); test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end()); std::cout << "send_test()" << std::endl; std::cout << std::endl; for (auto i : (test_pattern)) { std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << (int) i; } std::cout << std::endl; timer.expires_from_now(std::chrono::seconds(1)); timer.async_wait(sendTest); } io_service.run(); return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * GATB : Genome Assembly Tool Box * Copyright (C) 2014 INRIA * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ // We include the header file for the tool #include <kmerinshort.hpp> /********************************************************************************/ int main (int argc, char* argv[]) { if(argc==2 && strcmp(argv[1],"--version")==0 || strcmp(argv[1],"-v")==0 ){ printf("KmerInShort version 1.0.1\n"); return EXIT_SUCCESS; } try { // We run the tool with the provided command line arguments. kis().run (argc, argv); } catch (Exception& e) { std::cout << "EXCEPTION: " << e.getMessage() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Update main.cpp<commit_after>/***************************************************************************** * GATB : Genome Assembly Tool Box * Copyright (C) 2014 INRIA * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ // We include the header file for the tool #include <kmerinshort.hpp> /********************************************************************************/ int main (int argc, char* argv[]) { if(argc==2 && (strcmp(argv[1],"--version")==0 || strcmp(argv[1],"-v")==0) ){ printf("KmerInShort version 1.0.1\n"); return EXIT_SUCCESS; } try { // We run the tool with the provided command line arguments. kis().run (argc, argv); } catch (Exception& e) { std::cout << "EXCEPTION: " << e.getMessage() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef ORIGEN_SITE_HPP_ #define ORIGEN_SITE_HPP_ #include <string> using namespace std; namespace Origen { class Site { string _lotid; bool lotidSet; int _wafer; bool waferSet; int _x; bool xSet; int _y; bool ySet; int _number; int _bin; int _softbin; bool binSet; bool softbinSet; public: Site(int); virtual ~Site(); string lotid(); uint64_t lotidInt(); void lotid(string); void lotid(uint64_t); int wafer(); void wafer(int); int x(); void x(int); int y(); void y(int); int bin(); void bin(int); void bin(int, bool); int softbin(); void softbin(int); void softbin(int, bool); /// Returns the site number associated with the given site object int number() { return _number; } }; } /* namespace Origen */ #endif <commit_msg>Added support for RHEL7 compile.<commit_after>#ifndef ORIGEN_SITE_HPP_ #define ORIGEN_SITE_HPP_ #include <string> #include <inttypes.h> using namespace std; namespace Origen { class Site { string _lotid; bool lotidSet; int _wafer; bool waferSet; int _x; bool xSet; int _y; bool ySet; int _number; int _bin; int _softbin; bool binSet; bool softbinSet; public: Site(int); virtual ~Site(); string lotid(); uint64_t lotidInt(); void lotid(string); void lotid(uint64_t); int wafer(); void wafer(int); int x(); void x(int); int y(); void y(int); int bin(); void bin(int); void bin(int, bool); int softbin(); void softbin(int); void softbin(int, bool); /// Returns the site number associated with the given site object int number() { return _number; } }; } /* namespace Origen */ #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright 2014-2015 David Simmons-Duffin. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "SDP_Solver_Parameters.hxx" #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; int solve(const std::vector<boost::filesystem::path> &sdp_files, const boost::filesystem::path &out_file, const boost::filesystem::path &checkpoint_file_in, const boost::filesystem::path &checkpoint_file_out, SDP_Solver_Parameters parameters); int main(int argc, char **argv) { std::vector<boost::filesystem::path> sdp_files; boost::filesystem::path out_file; boost::filesystem::path checkpoint_file_in; boost::filesystem::path checkpoint_file_out; boost::filesystem::path param_file; SDP_Solver_Parameters parameters; po::options_description basicOptions("Basic options"); basicOptions.add_options()("help,h", "Show this helpful message.")( "sdpFile,s", po::value<std::vector<boost::filesystem::path>>(&sdp_files)->required(), "SDP data file(s) in XML format. Use this option repeatedly to specify " "multiple data files.")( "paramFile,p", po::value<boost::filesystem::path>(&param_file), "Any parameter can optionally be set via this file in key=value " "format. Command line arguments override values in the parameter " "file.")("outFile,o", po::value<boost::filesystem::path>(&out_file), "The optimal solution is saved to this file in Mathematica " "format. Defaults to sdpFile with '.out' extension.")( "checkpointFile,c", po::value<boost::filesystem::path>(&checkpoint_file_out), "Checkpoints are saved to this file every checkpointInterval. Defaults " "to sdpFile with '.ck' extension.")( "initialCheckpointFile,i", po::value<boost::filesystem::path>(&checkpoint_file_in), "The initial checkpoint to load. Defaults to checkpointFile."); po::options_description solverParamsOptions("Solver parameters"); solverParamsOptions.add_options()( "precision", po::value<int>(&parameters.precision)->default_value(400), "Precision in binary digits. GMP will round up to the nearest " "multiple of 64 (or 32 on older systems).")( "maxThreads", po::value<int>(&parameters.maxThreads)->default_value(4), "Maximum number of threads to use for parallel calculation.")( "checkpointInterval", po::value<int>(&parameters.checkpointInterval)->default_value(3600), "Save checkpoints to checkpointFile every checkpointInterval seconds.")( "noFinalCheckpoint", po::bool_switch(&parameters.noFinalCheckpoint)->default_value(false), "Don't save a final checkpoint after terminating (useful when debugging).")( "findPrimalFeasible", po::bool_switch(&parameters.findPrimalFeasible)->default_value(false), "Terminate once a primal feasible solution is found.")( "findDualFeasible", po::bool_switch(&parameters.findDualFeasible)->default_value(false), "Terminate once a dual feasible solution is found.")( "detectPrimalFeasibleJump", po::bool_switch(&parameters.detectPrimalFeasibleJump)->default_value(false), "Terminate if a primal-step of 1 is taken. This often indicates that a " "primal feasible solution would be found if the precision were high " "enough. Try increasing either primalErrorThreshold or precision " "and run from the latest checkpoint.")( "detectDualFeasibleJump", po::bool_switch(&parameters.detectDualFeasibleJump)->default_value(false), "Terminate if a dual-step of 1 is taken. This often indicates that a " "dual feasible solution would be found if the precision were high " "enough. Try increasing either dualErrorThreshold or precision " "and run from the latest checkpoint.")( "maxIterations", po::value<int>(&parameters.maxIterations)->default_value(500), "Maximum number of iterations to run the solver.")( "maxRuntime", po::value<int>(&parameters.maxRuntime)->default_value(86400), "Maximum amount of time to run the solver in seconds.")( "dualityGapThreshold", po::value<Real>(&parameters.dualityGapThreshold) ->default_value(Real("1e-30")), "Threshold for duality gap (roughly the difference in primal and dual " "objective) at which the solution is considered " "optimal. Corresponds to SDPA's epsilonStar.")( "primalErrorThreshold", po::value<Real>(&parameters.primalErrorThreshold) ->default_value(Real("1e-30")), "Threshold for feasibility of the primal problem. Corresponds to SDPA's " "epsilonBar.")( "dualErrorThreshold", po::value<Real>(&parameters.dualErrorThreshold)->default_value(Real("1e-30")), "Threshold for feasibility of the dual problem. Corresponds to SDPA's " "epsilonBar.")( "initialMatrixScalePrimal", po::value<Real>(&parameters.initialMatrixScalePrimal) ->default_value(Real("1e20")), "The primal matrix X begins at initialMatrixScalePrimal times the " "identity matrix. Corresponds to SDPA's lambdaStar.")( "initialMatrixScaleDual", po::value<Real>(&parameters.initialMatrixScaleDual) ->default_value(Real("1e20")), "The dual matrix Y begins at initialMatrixScaleDual times the " "identity matrix. Corresponds to SDPA's lambdaStar.")( "feasibleCenteringParameter", po::value<Real>(&parameters.feasibleCenteringParameter) ->default_value(Real("0.1")), "Shrink the complementarity X Y by this factor when the primal and dual " "problems are feasible. Corresponds to SDPA's betaStar.")( "infeasibleCenteringParameter", po::value<Real>(&parameters.infeasibleCenteringParameter) ->default_value(Real("0.3")), "Shrink the complementarity X Y by this factor when either the primal " "or dual problems are infeasible. Corresponds to SDPA's betaBar.")( "stepLengthReduction", po::value<Real>(&parameters.stepLengthReduction)->default_value(Real("0.7")), "Shrink each newton step by this factor (smaller means slower, more " "stable convergence). Corresponds to SDPA's gammaStar.")( "choleskyStabilizeThreshold", po::value<Real>(&parameters.choleskyStabilizeThreshold) ->default_value(Real("1e-40")), "Adds stabilizing terms to the cholesky decomposition of the schur " "complement " "matrix for diagonal entries which are smaller than this threshold times " "the " "geometric mean of other diagonal entries. Somewhat higher " "choleskyStabilizeThreshold " "can improve numerical stability but if the threshold is large enough that " "a high " "proportion of eigenvalues are being stabilized, the computation will slow " "substantially.")( "maxComplementarity", po::value<Real>(&parameters.maxComplementarity)->default_value(Real("1e100")), "Terminate if the complementarity mu = Tr(X Y)/dim(X) exceeds this value."); po::options_description cmdLineOptions; cmdLineOptions.add(basicOptions).add(solverParamsOptions); po::variables_map variablesMap; try { po::store(po::parse_command_line(argc, argv, cmdLineOptions), variablesMap); if(variablesMap.count("help")) { std::cout << cmdLineOptions << '\n'; return 0; } if(variablesMap.count("paramFile")) { param_file = variablesMap["paramFile"].as<boost::filesystem::path>(); std::ifstream ifs(param_file.string().c_str()); po::store(po::parse_config_file(ifs, solverParamsOptions), variablesMap); } po::notify(variablesMap); if(!variablesMap.count("outFile")) { out_file = sdp_files[0]; out_file.replace_extension("out"); } if(!variablesMap.count("checkpointFile")) { checkpoint_file_out = sdp_files[0]; checkpoint_file_out.replace_extension("ck"); } if(!variablesMap.count("initialCheckpointFile")) { checkpoint_file_in = checkpoint_file_out; } std::ofstream ofs(out_file.string().c_str()); ofs.close(); if(!ofs) { std::cerr << "Cannot write to outFile." << '\n'; return 1; } } catch(po::error &e) { std::cerr << "ERROR: " << e.what() << '\n'; std::cerr << cmdLineOptions << '\n'; return 1; } return solve(sdp_files, out_file, checkpoint_file_in, checkpoint_file_out, parameters); } <commit_msg>camelCase -> snake_case<commit_after>//======================================================================= // Copyright 2014-2015 David Simmons-Duffin. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "SDP_Solver_Parameters.hxx" #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; int solve(const std::vector<boost::filesystem::path> &sdp_files, const boost::filesystem::path &out_file, const boost::filesystem::path &checkpoint_file_in, const boost::filesystem::path &checkpoint_file_out, SDP_Solver_Parameters parameters); int main(int argc, char **argv) { std::vector<boost::filesystem::path> sdp_files; boost::filesystem::path out_file; boost::filesystem::path checkpoint_file_in; boost::filesystem::path checkpoint_file_out; boost::filesystem::path param_file; SDP_Solver_Parameters parameters; po::options_description basic_options("Basic options"); basic_options.add_options()("help,h", "Show this helpful message.")( "sdpFile,s", po::value<std::vector<boost::filesystem::path>>(&sdp_files)->required(), "SDP data file(s) in XML format. Use this option repeatedly to specify " "multiple data files.")( "paramFile,p", po::value<boost::filesystem::path>(&param_file), "Any parameter can optionally be set via this file in key=value " "format. Command line arguments override values in the parameter " "file.")("outFile,o", po::value<boost::filesystem::path>(&out_file), "The optimal solution is saved to this file in Mathematica " "format. Defaults to sdpFile with '.out' extension.")( "checkpointFile,c", po::value<boost::filesystem::path>(&checkpoint_file_out), "Checkpoints are saved to this file every checkpointInterval. Defaults " "to sdpFile with '.ck' extension.")( "initialCheckpointFile,i", po::value<boost::filesystem::path>(&checkpoint_file_in), "The initial checkpoint to load. Defaults to checkpointFile."); po::options_description solver_params_options("Solver parameters"); solver_params_options.add_options()( "precision", po::value<int>(&parameters.precision)->default_value(400), "Precision in binary digits. GMP will round up to the nearest " "multiple of 64 (or 32 on older systems).")( "maxThreads", po::value<int>(&parameters.maxThreads)->default_value(4), "Maximum number of threads to use for parallel calculation.")( "checkpointInterval", po::value<int>(&parameters.checkpointInterval)->default_value(3600), "Save checkpoints to checkpointFile every checkpointInterval seconds.")( "noFinalCheckpoint", po::bool_switch(&parameters.noFinalCheckpoint)->default_value(false), "Don't save a final checkpoint after terminating (useful when debugging).")( "findPrimalFeasible", po::bool_switch(&parameters.findPrimalFeasible)->default_value(false), "Terminate once a primal feasible solution is found.")( "findDualFeasible", po::bool_switch(&parameters.findDualFeasible)->default_value(false), "Terminate once a dual feasible solution is found.")( "detectPrimalFeasibleJump", po::bool_switch(&parameters.detectPrimalFeasibleJump)->default_value(false), "Terminate if a primal-step of 1 is taken. This often indicates that a " "primal feasible solution would be found if the precision were high " "enough. Try increasing either primalErrorThreshold or precision " "and run from the latest checkpoint.")( "detectDualFeasibleJump", po::bool_switch(&parameters.detectDualFeasibleJump)->default_value(false), "Terminate if a dual-step of 1 is taken. This often indicates that a " "dual feasible solution would be found if the precision were high " "enough. Try increasing either dualErrorThreshold or precision " "and run from the latest checkpoint.")( "maxIterations", po::value<int>(&parameters.maxIterations)->default_value(500), "Maximum number of iterations to run the solver.")( "maxRuntime", po::value<int>(&parameters.maxRuntime)->default_value(86400), "Maximum amount of time to run the solver in seconds.")( "dualityGapThreshold", po::value<Real>(&parameters.dualityGapThreshold) ->default_value(Real("1e-30")), "Threshold for duality gap (roughly the difference in primal and dual " "objective) at which the solution is considered " "optimal. Corresponds to SDPA's epsilonStar.")( "primalErrorThreshold", po::value<Real>(&parameters.primalErrorThreshold) ->default_value(Real("1e-30")), "Threshold for feasibility of the primal problem. Corresponds to SDPA's " "epsilonBar.")( "dualErrorThreshold", po::value<Real>(&parameters.dualErrorThreshold)->default_value(Real("1e-30")), "Threshold for feasibility of the dual problem. Corresponds to SDPA's " "epsilonBar.")( "initialMatrixScalePrimal", po::value<Real>(&parameters.initialMatrixScalePrimal) ->default_value(Real("1e20")), "The primal matrix X begins at initialMatrixScalePrimal times the " "identity matrix. Corresponds to SDPA's lambdaStar.")( "initialMatrixScaleDual", po::value<Real>(&parameters.initialMatrixScaleDual) ->default_value(Real("1e20")), "The dual matrix Y begins at initialMatrixScaleDual times the " "identity matrix. Corresponds to SDPA's lambdaStar.")( "feasibleCenteringParameter", po::value<Real>(&parameters.feasibleCenteringParameter) ->default_value(Real("0.1")), "Shrink the complementarity X Y by this factor when the primal and dual " "problems are feasible. Corresponds to SDPA's betaStar.")( "infeasibleCenteringParameter", po::value<Real>(&parameters.infeasibleCenteringParameter) ->default_value(Real("0.3")), "Shrink the complementarity X Y by this factor when either the primal " "or dual problems are infeasible. Corresponds to SDPA's betaBar.")( "stepLengthReduction", po::value<Real>(&parameters.stepLengthReduction)->default_value(Real("0.7")), "Shrink each newton step by this factor (smaller means slower, more " "stable convergence). Corresponds to SDPA's gammaStar.")( "choleskyStabilizeThreshold", po::value<Real>(&parameters.choleskyStabilizeThreshold) ->default_value(Real("1e-40")), "Adds stabilizing terms to the cholesky decomposition of the schur " "complement " "matrix for diagonal entries which are smaller than this threshold times " "the " "geometric mean of other diagonal entries. Somewhat higher " "choleskyStabilizeThreshold " "can improve numerical stability but if the threshold is large enough that " "a high " "proportion of eigenvalues are being stabilized, the computation will slow " "substantially.")( "maxComplementarity", po::value<Real>(&parameters.maxComplementarity)->default_value(Real("1e100")), "Terminate if the complementarity mu = Tr(X Y)/dim(X) exceeds this value."); po::options_description cmd_line_options; cmd_line_options.add(basic_options).add(solver_params_options); po::variables_map variables_map; try { po::store(po::parse_command_line(argc, argv, cmd_line_options), variables_map); if(variables_map.count("help")) { std::cout << cmd_line_options << '\n'; return 0; } if(variables_map.count("paramFile")) { param_file = variables_map["paramFile"].as<boost::filesystem::path>(); std::ifstream ifs(param_file.string().c_str()); po::store(po::parse_config_file(ifs, solver_params_options), variables_map); } po::notify(variables_map); if(!variables_map.count("outFile")) { out_file = sdp_files[0]; out_file.replace_extension("out"); } if(!variables_map.count("checkpointFile")) { checkpoint_file_out = sdp_files[0]; checkpoint_file_out.replace_extension("ck"); } if(!variables_map.count("initialCheckpointFile")) { checkpoint_file_in = checkpoint_file_out; } std::ofstream ofs(out_file.string().c_str()); ofs.close(); if(!ofs) { std::cerr << "Cannot write to outFile." << '\n'; return 1; } } catch(po::error &e) { std::cerr << "ERROR: " << e.what() << '\n'; std::cerr << cmd_line_options << '\n'; return 1; } return solve(sdp_files, out_file, checkpoint_file_in, checkpoint_file_out, parameters); } <|endoftext|>
<commit_before>#include "../../../shared/generated/cpp/WebViewBase.h" #include "../../../shared/System.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "rubyext/WebView.h" //extern "C" HWND getMainWnd(); extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal(); extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName); namespace rho { using namespace apiGenerator; using namespace common; class CWebViewImpl: public CWebViewSingletonBase { int m_nNavigationTimeout; double m_dZoomPage; int m_nTextZoom; public: CWebViewImpl(): m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase() { convertFromStringW( rho_wmimpl_getNavTimeOutVal(), m_nNavigationTimeout ); } virtual void getFramework(rho::apiGenerator::CMethodResult& oResult) { oResult.set(System::getWebviewFramework()); } virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult) { oResult.set(rho_webview_get_full_screen() != 0 ? true : false ); } virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(value ? 1 : 0); } //Android only virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){} virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult) { //oResult.set(false); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult) { //Do nothing. It can be set only in config.xml } virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){} // virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_nNavigationTimeout); } virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult) { m_nNavigationTimeout = value; rho_webview_setNavigationTimeout(m_nNavigationTimeout); } virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.scrollTechnique") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) ); } virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("Webview.fontFamily") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) ); } virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.userAgent") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) ); } virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getInt("WebView.viewportWidth") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue ); oResult.set( nValue ); } virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult) { int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue ); oResult.set( nValue ); //oResult.set( RHOCONF().getInt("WebView.cacheSize") ); } //TODO: EnableCache - does it supported by Moto Webkit ? virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){} virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){} //TODO: AcceptLanguage - does it supported by Moto Webkit ? virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){} virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){} virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_dZoomPage); } virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult) { m_dZoomPage = value; RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage); } virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult) { oResult.set( m_nTextZoom ); } virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult) { m_nTextZoom = value; RHODESAPP().getExtManager().zoomText( m_nTextZoom ); } virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_refresh(tabIndex); } virtual void navigate( const rho::String& url, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate(url.c_str(), tabIndex); } virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate_back_with_tab(tabIndex); } virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_current_location(tabIndex) ); } //iOS, Android only virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){} virtual void executeJavascript( const rho::String& javascriptText, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_execute_js( javascriptText.c_str(), tabIndex ); } virtual void active_tab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(enable ? 1 : 0); } virtual void setCookie( const rho::String& url, const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult) { rho_webview_set_cookie( url.c_str(), cookie.c_str() ); } //Android only virtual void save( const rho::String& format, const rho::String& path, int tabIndex, rho::apiGenerator::CMethodResult& oResult){} // }; //////////////////////////////////////////////////////////////////////// class CWebViewFactory: public CWebViewFactoryBase { public: ~CWebViewFactory(){} IWebViewSingleton* createModuleSingleton() { return new CWebViewImpl(); } }; } extern "C" void Init_WebView() { rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() ); rho::Init_WebView_API(); RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi"); } <commit_msg>Update WebViewImpl.cpp<commit_after>#include "../../../shared/generated/cpp/WebViewBase.h" #include "../../../shared/System.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "rubyext/WebView.h" //extern "C" HWND getMainWnd(); extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal(); extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName); namespace rho { using namespace apiGenerator; using namespace common; class CWebViewImpl: public CWebViewSingletonBase { int m_nNavigationTimeout; double m_dZoomPage; int m_nTextZoom; public: CWebViewImpl(): m_nNavigationTimeout(45000), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase() { convertFromStringW( rho_wmimpl_getNavTimeOutVal(), m_nNavigationTimeout ); if(m_nNavigationTimeout<=0) { LOG(WARNING)+" NavigationTimeout value from config.xml not correct "+m_nNavigationTimeout; m_nNavigationTimeout=45000; } } virtual void getFramework(rho::apiGenerator::CMethodResult& oResult) { oResult.set(System::getWebviewFramework()); } virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult) { oResult.set(rho_webview_get_full_screen() != 0 ? true : false ); } virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(value ? 1 : 0); } //Android only virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){} virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult) { //oResult.set(false); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult) { //Do nothing. It can be set only in config.xml } virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){} // virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_nNavigationTimeout); } virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult) { m_nNavigationTimeout = value; rho_webview_setNavigationTimeout(m_nNavigationTimeout); } virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.scrollTechnique") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) ); } virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("Webview.fontFamily") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) ); } virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.userAgent") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) ); } virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getInt("WebView.viewportWidth") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue ); oResult.set( nValue ); } virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult) { int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue ); oResult.set( nValue ); //oResult.set( RHOCONF().getInt("WebView.cacheSize") ); } //TODO: EnableCache - does it supported by Moto Webkit ? virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){} virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){} //TODO: AcceptLanguage - does it supported by Moto Webkit ? virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){} virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){} virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_dZoomPage); } virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult) { m_dZoomPage = value; RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage); } virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult) { oResult.set( m_nTextZoom ); } virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult) { m_nTextZoom = value; RHODESAPP().getExtManager().zoomText( m_nTextZoom ); } virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_refresh(tabIndex); } virtual void navigate( const rho::String& url, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate(url.c_str(), tabIndex); } virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate_back_with_tab(tabIndex); } virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_current_location(tabIndex) ); } //iOS, Android only virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){} virtual void executeJavascript( const rho::String& javascriptText, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_execute_js( javascriptText.c_str(), tabIndex ); } virtual void active_tab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(enable ? 1 : 0); } virtual void setCookie( const rho::String& url, const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult) { rho_webview_set_cookie( url.c_str(), cookie.c_str() ); } //Android only virtual void save( const rho::String& format, const rho::String& path, int tabIndex, rho::apiGenerator::CMethodResult& oResult){} // }; //////////////////////////////////////////////////////////////////////// class CWebViewFactory: public CWebViewFactoryBase { public: ~CWebViewFactory(){} IWebViewSingleton* createModuleSingleton() { return new CWebViewImpl(); } }; } extern "C" void Init_WebView() { rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() ); rho::Init_WebView_API(); RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi"); } <|endoftext|>
<commit_before>#include "../../../shared/generated/cpp/WebViewBase.h" #include "../../../shared/System.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "rubyext/WebView.h" //extern "C" HWND getMainWnd(); extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal(const wchar_t* szName); extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName); namespace rho { using namespace apiGenerator; using namespace common; class CWebViewImpl: public CWebViewSingletonBase { int m_nNavigationTimeout; double m_dZoomPage; int m_nTextZoom; public: CWebViewImpl(): m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase() { convertFromStringW( rho_wmimpl_getNavTimeOutVal( L"Navigation\\NavTimeout" ), m_nNavigationTimeout ); } virtual void getFramework(rho::apiGenerator::CMethodResult& oResult) { oResult.set(System::getWebviewFramework()); } virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult) { oResult.set(rho_webview_get_full_screen() != 0 ? true : false ); } virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(value ? 1 : 0); } //Android only virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){} virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult) { //oResult.set(false); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult) { //Do nothing. It can be set only in config.xml } virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){} // virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_nNavigationTimeout); } virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult) { m_nNavigationTimeout = value; rho_webview_setNavigationTimeout(m_nNavigationTimeout); } virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.scrollTechnique") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) ); } virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("Webview.fontFamily") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) ); } virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.userAgent") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) ); } virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getInt("WebView.viewportWidth") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue ); oResult.set( nValue ); } virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult) { int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue ); oResult.set( nValue ); //oResult.set( RHOCONF().getInt("WebView.cacheSize") ); } //TODO: EnableCache - does it supported by Moto Webkit ? virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){} virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){} //TODO: AcceptLanguage - does it supported by Moto Webkit ? virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){} virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){} virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_dZoomPage); } virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult) { m_dZoomPage = value; RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage); } virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult) { oResult.set( m_nTextZoom ); } virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult) { m_nTextZoom = value; RHODESAPP().getExtManager().zoomText( m_nTextZoom ); } virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_refresh(tabIndex); } virtual void navigate( const rho::String& url, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate(url.c_str(), tabIndex); } virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate_back_with_tab(tabIndex); } virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_current_location(tabIndex) ); } //iOS, Android only virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){} virtual void executeJavascript( const rho::String& javascriptText, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_execute_js( javascriptText.c_str(), tabIndex ); } virtual void active_tab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(enable ? 1 : 0); } virtual void setCookie( const rho::String& url, const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult) { rho_webview_set_cookie( url.c_str(), cookie.c_str() ); } //Android only virtual void save( const rho::String& format, const rho::String& path, int tabIndex, rho::apiGenerator::CMethodResult& oResult){} // }; //////////////////////////////////////////////////////////////////////// class CWebViewFactory: public CWebViewFactoryBase { public: ~CWebViewFactory(){} IWebViewSingleton* createModuleSingleton() { return new CWebViewImpl(); } }; } extern "C" void Init_WebView() { rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() ); rho::Init_WebView_API(); RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi"); } <commit_msg>Update WebViewImpl.cpp<commit_after>#include "../../../shared/generated/cpp/WebViewBase.h" #include "../../../shared/System.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "rubyext/WebView.h" //extern "C" HWND getMainWnd(); extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal(); extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName); namespace rho { using namespace apiGenerator; using namespace common; class CWebViewImpl: public CWebViewSingletonBase { int m_nNavigationTimeout; double m_dZoomPage; int m_nTextZoom; public: CWebViewImpl(): m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase() { convertFromStringW( rho_wmimpl_getNavTimeOutVal(), m_nNavigationTimeout ); } virtual void getFramework(rho::apiGenerator::CMethodResult& oResult) { oResult.set(System::getWebviewFramework()); } virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult) { oResult.set(rho_webview_get_full_screen() != 0 ? true : false ); } virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(value ? 1 : 0); } //Android only virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){} virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult) { //oResult.set(false); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult) { //Do nothing. It can be set only in config.xml } virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult) { oResult.set(true); } virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){} // virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_nNavigationTimeout); } virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult) { m_nNavigationTimeout = value; rho_webview_setNavigationTimeout(m_nNavigationTimeout); } virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.scrollTechnique") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) ); } virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("Webview.fontFamily") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) ); } virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getString("WebView.userAgent") ); oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) ); } virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue ); oResult.set( nValue ? true : false ); } virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult) { //oResult.set( RHOCONF().getInt("WebView.viewportWidth") ); int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue ); oResult.set( nValue ); } virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult) { int nValue = 0; convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue ); oResult.set( nValue ); //oResult.set( RHOCONF().getInt("WebView.cacheSize") ); } //TODO: EnableCache - does it supported by Moto Webkit ? virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){} virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){} //TODO: AcceptLanguage - does it supported by Moto Webkit ? virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){} virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){} virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_dZoomPage); } virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult) { m_dZoomPage = value; RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage); } virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult) { oResult.set( m_nTextZoom ); } virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult) { m_nTextZoom = value; RHODESAPP().getExtManager().zoomText( m_nTextZoom ); } virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_refresh(tabIndex); } virtual void navigate( const rho::String& url, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate(url.c_str(), tabIndex); } virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_navigate_back_with_tab(tabIndex); } virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_current_location(tabIndex) ); } //iOS, Android only virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){} virtual void executeJavascript( const rho::String& javascriptText, int tabIndex, rho::apiGenerator::CMethodResult& oResult) { rho_webview_execute_js( javascriptText.c_str(), tabIndex ); } virtual void active_tab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult) { oResult.set( rho_webview_active_tab() ); } virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult) { rho_webview_full_screen_mode(enable ? 1 : 0); } virtual void setCookie( const rho::String& url, const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult) { rho_webview_set_cookie( url.c_str(), cookie.c_str() ); } //Android only virtual void save( const rho::String& format, const rho::String& path, int tabIndex, rho::apiGenerator::CMethodResult& oResult){} // }; //////////////////////////////////////////////////////////////////////// class CWebViewFactory: public CWebViewFactoryBase { public: ~CWebViewFactory(){} IWebViewSingleton* createModuleSingleton() { return new CWebViewImpl(); } }; } extern "C" void Init_WebView() { rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() ); rho::Init_WebView_API(); RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi"); } <|endoftext|>
<commit_before>#ifndef BOOST_THREAD_PTHREAD_MUTEX_HPP #define BOOST_THREAD_PTHREAD_MUTEX_HPP // (C) Copyright 2007-8 Anthony Williams // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <pthread.h> #include <boost/utility.hpp> #include <boost/thread/exceptions.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/thread_time.hpp> #include <boost/thread/xtime.hpp> #include <boost/assert.hpp> #include <errno.h> #include "timespec.hpp" #include "pthread_mutex_scoped_lock.hpp" #ifdef _POSIX_TIMEOUTS #if _POSIX_TIMEOUTS >= 0 #define BOOST_PTHREAD_HAS_TIMEDLOCK #endif #endif #include <boost/config/abi_prefix.hpp> namespace boost { class mutex: boost::noncopyable { private: pthread_mutex_t m; public: mutex() { int const res=pthread_mutex_init(&m,NULL); if(res) { throw thread_resource_error("Cannot initialize a mutex", res); } } ~mutex() { BOOST_VERIFY(!pthread_mutex_destroy(&m)); } void lock() { BOOST_VERIFY(!pthread_mutex_lock(&m)); } void unlock() { BOOST_VERIFY(!pthread_mutex_unlock(&m)); } bool try_lock() { int const res=pthread_mutex_trylock(&m); BOOST_ASSERT(!res || res==EBUSY); return !res; } typedef pthread_mutex_t* native_handle_type; native_handle_type native_handle() { return &m; } typedef unique_lock<mutex> scoped_lock; typedef detail::try_lock_wrapper<mutex> scoped_try_lock; }; typedef mutex try_mutex; class timed_mutex: boost::noncopyable { private: pthread_mutex_t m; #ifndef BOOST_PTHREAD_HAS_TIMEDLOCK pthread_cond_t cond; bool is_locked; #endif public: timed_mutex() { int const res=pthread_mutex_init(&m,NULL); if(res) { throw thread_resource_error("Cannot initialize a mutex", res); } #ifndef BOOST_PTHREAD_HAS_TIMEDLOCK int const res2=pthread_cond_init(&cond,NULL); if(res2) { BOOST_VERIFY(!pthread_mutex_destroy(&m)); throw thread_resource_error("Cannot initialize a condition variable", res2); } is_locked=false; #endif } ~timed_mutex() { BOOST_VERIFY(!pthread_mutex_destroy(&m)); #ifndef BOOST_PTHREAD_HAS_TIMEDLOCK BOOST_VERIFY(!pthread_cond_destroy(&cond)); #endif } template<typename TimeDuration> bool timed_lock(TimeDuration const & relative_time) { return timed_lock(get_system_time()+relative_time); } bool timed_lock(boost::xtime const & absolute_time) { return timed_lock(system_time(absolute_time)); } #ifdef BOOST_PTHREAD_HAS_TIMEDLOCK void lock() { BOOST_VERIFY(!pthread_mutex_lock(&m)); } void unlock() { BOOST_VERIFY(!pthread_mutex_unlock(&m)); } bool try_lock() { int const res=pthread_mutex_trylock(&m); BOOST_ASSERT(!res || res==EBUSY); return !res; } bool timed_lock(system_time const & abs_time) { struct timespec const timeout=detail::get_timespec(abs_time); int const res=pthread_mutex_timedlock(&m,&timeout); BOOST_ASSERT(!res || res==ETIMEDOUT); return !res; } typedef pthread_mutex_t* native_handle_type; native_handle_type native_handle() { return &m; } #else void lock() { boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); while(is_locked) { BOOST_VERIFY(!pthread_cond_wait(&cond,&m)); } is_locked=true; } void unlock() { boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); is_locked=false; BOOST_VERIFY(!pthread_cond_signal(&cond)); } bool try_lock() { boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); if(is_locked) { return false; } is_locked=true; return true; } bool timed_lock(system_time const & abs_time) { struct timespec const timeout=detail::get_timespec(abs_time); boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); while(is_locked) { int const cond_res=pthread_cond_timedwait(&cond,&m,&timeout); if(cond_res==ETIMEDOUT) { return false; } BOOST_ASSERT(!cond_res); } is_locked=true; return true; } #endif typedef unique_lock<timed_mutex> scoped_timed_lock; typedef detail::try_lock_wrapper<timed_mutex> scoped_try_lock; typedef scoped_timed_lock scoped_lock; }; } #include <boost/config/abi_suffix.hpp> #endif <commit_msg>Make boost::mutex handle EINTR gracefully.<commit_after>#ifndef BOOST_THREAD_PTHREAD_MUTEX_HPP #define BOOST_THREAD_PTHREAD_MUTEX_HPP // (C) Copyright 2007-8 Anthony Williams // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <pthread.h> #include <boost/utility.hpp> #include <boost/thread/exceptions.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/thread_time.hpp> #include <boost/thread/xtime.hpp> #include <boost/assert.hpp> #include <errno.h> #include "timespec.hpp" #include "pthread_mutex_scoped_lock.hpp" #ifdef _POSIX_TIMEOUTS #if _POSIX_TIMEOUTS >= 0 #define BOOST_PTHREAD_HAS_TIMEDLOCK #endif #endif #include <boost/config/abi_prefix.hpp> namespace boost { class mutex: boost::noncopyable { private: pthread_mutex_t m; public: mutex() { int const res=pthread_mutex_init(&m,NULL); if(res) { throw thread_resource_error("Cannot initialize a mutex", res); } } ~mutex() { int ret; do { ret = pthread_mutex_destroy(&m); } while (ret == EINTR); BOOST_VERIFY(!ret); } void lock() { int ret; do { ret = pthread_mutex_lock(&m); } while (ret == EINTR); BOOST_VERIFY(!ret); } void unlock() { int ret; do { ret = pthread_mutex_unlock(&m); } while (ret == EINTR); BOOST_VERIFY(!ret); } bool try_lock() { int res; do { res = pthread_mutex_trylock(&m); } while (res == EINTR); BOOST_ASSERT(!res || res==EBUSY); return !res; } typedef pthread_mutex_t* native_handle_type; native_handle_type native_handle() { return &m; } typedef unique_lock<mutex> scoped_lock; typedef detail::try_lock_wrapper<mutex> scoped_try_lock; }; typedef mutex try_mutex; class timed_mutex: boost::noncopyable { private: pthread_mutex_t m; #ifndef BOOST_PTHREAD_HAS_TIMEDLOCK pthread_cond_t cond; bool is_locked; #endif public: timed_mutex() { int const res=pthread_mutex_init(&m,NULL); if(res) { throw thread_resource_error("Cannot initialize a mutex", res); } #ifndef BOOST_PTHREAD_HAS_TIMEDLOCK int const res2=pthread_cond_init(&cond,NULL); if(res2) { BOOST_VERIFY(!pthread_mutex_destroy(&m)); throw thread_resource_error("Cannot initialize a condition variable", res2); } is_locked=false; #endif } ~timed_mutex() { BOOST_VERIFY(!pthread_mutex_destroy(&m)); #ifndef BOOST_PTHREAD_HAS_TIMEDLOCK BOOST_VERIFY(!pthread_cond_destroy(&cond)); #endif } template<typename TimeDuration> bool timed_lock(TimeDuration const & relative_time) { return timed_lock(get_system_time()+relative_time); } bool timed_lock(boost::xtime const & absolute_time) { return timed_lock(system_time(absolute_time)); } #ifdef BOOST_PTHREAD_HAS_TIMEDLOCK void lock() { BOOST_VERIFY(!pthread_mutex_lock(&m)); } void unlock() { BOOST_VERIFY(!pthread_mutex_unlock(&m)); } bool try_lock() { int const res=pthread_mutex_trylock(&m); BOOST_ASSERT(!res || res==EBUSY); return !res; } bool timed_lock(system_time const & abs_time) { struct timespec const timeout=detail::get_timespec(abs_time); int const res=pthread_mutex_timedlock(&m,&timeout); BOOST_ASSERT(!res || res==ETIMEDOUT); return !res; } typedef pthread_mutex_t* native_handle_type; native_handle_type native_handle() { return &m; } #else void lock() { boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); while(is_locked) { BOOST_VERIFY(!pthread_cond_wait(&cond,&m)); } is_locked=true; } void unlock() { boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); is_locked=false; BOOST_VERIFY(!pthread_cond_signal(&cond)); } bool try_lock() { boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); if(is_locked) { return false; } is_locked=true; return true; } bool timed_lock(system_time const & abs_time) { struct timespec const timeout=detail::get_timespec(abs_time); boost::pthread::pthread_mutex_scoped_lock const local_lock(&m); while(is_locked) { int const cond_res=pthread_cond_timedwait(&cond,&m,&timeout); if(cond_res==ETIMEDOUT) { return false; } BOOST_ASSERT(!cond_res); } is_locked=true; return true; } #endif typedef unique_lock<timed_mutex> scoped_timed_lock; typedef detail::try_lock_wrapper<timed_mutex> scoped_try_lock; typedef scoped_timed_lock scoped_lock; }; } #include <boost/config/abi_suffix.hpp> #endif <|endoftext|>
<commit_before>#include "fastlib/fastlib.h" #define A 1 #define epsilon 1e-4 void save_correctly(const char *filename, Matrix a) { Matrix a_transpose; la::TransposeInit(a, &a_transpose); data::Save(filename, a_transpose); } void rand_vector(Vector &v) { index_t d = v.length(); v.SetZero(); for(index_t i = 0; i+1 < d; i+=2) { double a = drand48(); double b = drand48(); double first_term = sqrt(-2 * log(a)); double second_term = 2 * M_PI * b; v[i] = first_term * cos(second_term); v[i+1] = first_term * sin(second_term); } if((d % 2) == 1) { v[d - 1] = sqrt(-2 * log(drand48())) * cos(2 * M_PI * drand48()); } la::Scale(1/sqrt(la::Dot(v, v)), &v); } void center(Matrix X, Matrix &X_centered) { Vector col_vector_sum; col_vector_sum.Init(X.n_rows()); col_vector_sum.SetZero(); index_t n = X.n_cols(); for(index_t i = 0; i < n; i++) { Vector cur_col_vector; X.MakeColumnVector(i, &cur_col_vector); la::AddTo(cur_col_vector, &col_vector_sum); } la::Scale(1/(double)n, &col_vector_sum); X_centered.CopyValues(X); for(index_t i = 0; i < n; i++) { Vector cur_col_vector; X_centered.MakeColumnVector(i, &cur_col_vector); la::SubFrom(col_vector_sum, &cur_col_vector); } } void whiten(Matrix X, Matrix &whitening, Matrix &X_whitened) { Matrix X_transpose, X_cov, D, E, E_times_D; Vector D_vector; la::TransposeInit(X, &X_transpose); la::MulInit(X, X_transpose, &X_cov); la::Scale(1 / (double) (X.n_cols() - 1), &X_cov); X_cov.PrintDebug("X_cov"); la::EigenvectorsInit(X_cov, &D_vector, &E); D.InitDiagonal(D_vector); index_t d = D.n_rows(); for(index_t i = 0; i < d; i++) { D.set(i, i, pow(D.get(i, i), -.5)); } la::MulInit(E, D, &E_times_D); la::MulTransBOverwrite(E_times_D, E, &whitening); la::MulOverwrite(whitening, X, &X_whitened); } void univariate_FastICA(Matrix X, double (*contrast_function)(double), Matrix fixed_subspace, index_t dim_num, double tolerance, Vector &w) { index_t n_fixed = dim_num; Vector w_old; index_t d = X.n_rows(); index_t n = X.n_cols(); rand_vector(w); w_old.Init(d); w_old.SetZero(); bool converged = false; for(index_t epoch = 0; !converged; epoch++) { w.PrintDebug("w at beginning of epoch"); printf("epoch %d\n", epoch); Vector first_sum; first_sum.Init(d); first_sum.SetZero(); Vector tanh_dots; tanh_dots.Init(n); for(index_t i = 0; i < n; i++) { Vector x; X.MakeColumnVector(i, &x); tanh_dots[i] = contrast_function(la::Dot(w, x)); //printf("%f\t", tanh_dots[i]); la::AddExpert(tanh_dots[i], x, &first_sum); } //first_sum.PrintDebug("first_sum"); la::Scale((double)1/(double)n, &first_sum); printf("first_sum: %f %f\n", first_sum[0], first_sum[1]); double second_sum = 0; for(index_t i = 0; i < n; i++) { second_sum += A * (1 - (tanh_dots[i] * tanh_dots[i])); } la::Scale(-second_sum/(double)n, &w); printf("second_sum: %f\n", second_sum / (double)n); w.PrintDebug("w before adding first_sum"); la::AddTo(first_sum, &w); w.PrintDebug("w after adding first_sum"); // normalize la::Scale(1/sqrt(la::Dot(w, w)), &w); w.PrintDebug("before correction"); // make orthogonal to fixed_subspace for(index_t i = 0; i < n_fixed; i++) { Vector w_i; fixed_subspace.MakeColumnVector(i, &w_i); la::AddExpert(-la::Dot(w_i, w), w_i, &w); } // normalize la::Scale(1/sqrt(la::Dot(w, w)), &w); w.PrintDebug("after correction"); // check for convergence Vector w_diff; la::SubInit(w_old, w, &w_diff); if(la::Dot(w_diff, w_diff) < epsilon) { converged = true; } else { la::AddOverwrite(w_old, w, &w_diff); if(la::Dot(w_diff, w_diff) < epsilon) { converged = true; } } w_old.CopyValues(w); } } void deflationICA(Matrix X, double (*contrast_function)(double), double tolerance, Matrix &fixed_subspace) { index_t d = X.n_rows(); printf("d = %d\n", d); for(index_t i = 0; i < d; i++) { printf("i = %d\n", i); Vector w; w.Init(d); univariate_FastICA(X, contrast_function, fixed_subspace, i, tolerance, w); Vector fixed_subspace_vector_i; fixed_subspace.MakeColumnVector(i, &fixed_subspace_vector_i); fixed_subspace_vector_i.CopyValues(w); } // fixed_subspace is the transpose of the postwhitening unmixing matrix W~ // saving fixed_subspace really saves the transpose, so we simply save data::Save("fixed_subspace.dat", fixed_subspace); } double d_logcosh(double u) { return tanh(A * u); } double d_exp(double u) { return u * exp(-u*u/2); } int main(int argc, char *argv[]) { fx_init(argc, argv); srand48(time(0)); const char *data = fx_param_str(NULL, "data", NULL); Matrix X, X_centered, whitening, X_whitened; data::Load(data, &X); index_t d = X.n_rows(); // number of dimensions index_t n = X.n_cols(); // number of points X_centered.Init(d, n); X_whitened.Init(d, n); whitening.Init(d, d); printf("%d,%d\n", X.n_rows(), X.n_cols()); printf("centering\n"); center(X, X_centered); printf("whitening\n"); whiten(X_centered, whitening, X_whitened); double tolerance = 1e-4; Matrix post_whitening_W_transpose; post_whitening_W_transpose.Init(d, d); printf("deflationICA\n"); deflationICA(X_whitened, &d_logcosh, tolerance, post_whitening_W_transpose); Matrix post_whitening_W; la::TransposeInit(post_whitening_W_transpose, &post_whitening_W); Matrix W; la::MulInit(post_whitening_W, whitening, &W); Matrix Y; la::MulInit(post_whitening_W, X_whitened, &Y); save_correctly("post_whitening_W.dat", post_whitening_W); save_correctly("whitening.dat", whitening); save_correctly("W.dat", W); save_correctly("X_centered.dat", X_centered); save_correctly("X_whitened.dat", X_whitened); save_correctly("Y.dat", Y); // fx_done(); return 0; } <commit_msg>updated niche/fastica<commit_after>#include "fastlib/fastlib.h" #define A 1 #define epsilon 1e-4 #define LOGCOSH 0 #define EXP 1 // n indicates number of points // d indicates number of dimensions (number of components or variables) namespace { void SaveCorrectly(const char *filename, Matrix a) { Matrix a_transpose; la::TransposeInit(a, &a_transpose); data::Save(filename, a_transpose); } void RandVector(Vector &v) { index_t d = v.length(); v.SetZero(); for(index_t i = 0; i+1 < d; i+=2) { double a = drand48(); double b = drand48(); double first_term = sqrt(-2 * log(a)); double second_term = 2 * M_PI * b; v[i] = first_term * cos(second_term); v[i+1] = first_term * sin(second_term); } if((d % 2) == 1) { v[d - 1] = sqrt(-2 * log(drand48())) * cos(2 * M_PI * drand48()); } la::Scale(1/sqrt(la::Dot(v, v)), &v); } void Center(Matrix X, Matrix &X_centered) { Vector col_vector_sum; col_vector_sum.Init(X.n_rows()); col_vector_sum.SetZero(); index_t n = X.n_cols(); for(index_t i = 0; i < n; i++) { Vector cur_col_vector; X.MakeColumnVector(i, &cur_col_vector); la::AddTo(cur_col_vector, &col_vector_sum); } la::Scale(1/(double)n, &col_vector_sum); X_centered.CopyValues(X); for(index_t i = 0; i < n; i++) { Vector cur_col_vector; X_centered.MakeColumnVector(i, &cur_col_vector); la::SubFrom(col_vector_sum, &cur_col_vector); } } void Whiten(Matrix X, Matrix &whitening, Matrix &X_whitened) { Matrix X_transpose, X_cov, D, E, E_times_D; Vector D_vector; la::TransposeInit(X, &X_transpose); la::MulInit(X, X_transpose, &X_cov); la::Scale(1 / (double) (X.n_cols() - 1), &X_cov); X_cov.PrintDebug("X_cov"); la::EigenvectorsInit(X_cov, &D_vector, &E); D.InitDiagonal(D_vector); index_t d = D.n_rows(); for(index_t i = 0; i < d; i++) { D.set(i, i, pow(D.get(i, i), -.5)); } la::MulInit(E, D, &E_times_D); la::MulTransBOverwrite(E_times_D, E, &whitening); la::MulOverwrite(whitening, X, &X_whitened); } void UnivariateFastICA(Matrix X, int contrast_type, Matrix fixed_subspace, index_t dim_num, double tolerance, Vector &w) { index_t d = X.n_rows(); index_t n = X.n_cols(); RandVector(w); Vector w_old; w_old.Init(d); w_old.SetZero(); bool converged = false; for(index_t epoch = 0; !converged; epoch++) { printf("\nEPOCH %"LI"d\n", epoch); w.PrintDebug("w at beginning of epoch"); Vector first_sum; first_sum.Init(d); first_sum.SetZero(); double second_sum = 0; if(contrast_type == LOGCOSH) { Vector first_deriv_dots; first_deriv_dots.Init(n); for(index_t i = 0; i < n; i++) { Vector x; X.MakeColumnVector(i, &x); first_deriv_dots[i] = tanh(A * la::Dot(w, x)); la::AddExpert(first_deriv_dots[i], x, &first_sum); } la::Scale(1/(double)n, &first_sum); for(index_t i = 0; i < n; i++) { second_sum += first_deriv_dots[i] * first_deriv_dots[i]; } second_sum *= A / (double) n; second_sum -= A; } else if(contrast_type == EXP) { Vector dots; Vector exp_dots; dots.Init(n); exp_dots.Init(n); for(index_t i = 0; i < n; i++) { Vector x; X.MakeColumnVector(i, &x); double dot = la::Dot(w, x); dots[i] = dot; exp_dots[i] = exp(-dot * dot/2); la::AddExpert(dot * exp_dots[i], x, &first_sum); } la::Scale(1/(double)n, &first_sum); for(index_t i = 0; i < n; i++) { second_sum += exp_dots[i] * (dots[i] * dots[i] - 1); } second_sum /= (double) n; } else { printf("ERROR: invalid contrast function: contrast_type = %d\n", contrast_type); exit(SUCCESS_FAIL); } la::Scale(second_sum, &w); la::AddTo(first_sum, &w); first_sum.PrintDebug("first_sum"); printf("second_sum = %f\n", second_sum); // normalize la::Scale(1/sqrt(la::Dot(w, w)), &w); w.PrintDebug("before correction"); // make orthogonal to fixed_subspace for(index_t i = 0; i < dim_num; i++) { Vector w_i; fixed_subspace.MakeColumnVector(i, &w_i); la::AddExpert(-la::Dot(w_i, w), w_i, &w); } // normalize la::Scale(1/sqrt(la::Dot(w, w)), &w); w.PrintDebug("after correction"); // check for convergence Vector w_diff; la::SubInit(w_old, w, &w_diff); if(la::Dot(w_diff, w_diff) < epsilon) { converged = true; } else { la::AddOverwrite(w_old, w, &w_diff); if(la::Dot(w_diff, w_diff) < epsilon) { converged = true; } } w_old.CopyValues(w); } } void DeflationICA(Matrix X, int contrast_type, double tolerance, Matrix &fixed_subspace) { index_t d = X.n_rows(); printf("%"LI"d Components\n", d); for(index_t i = 0; i < d; i++) { printf("\n\nExtracting component %"LI"d\n", i); Vector w; w.Init(d); UnivariateFastICA(X, contrast_type, fixed_subspace, i, tolerance, w); Vector fixed_subspace_vector_i; fixed_subspace.MakeColumnVector(i, &fixed_subspace_vector_i); fixed_subspace_vector_i.CopyValues(w); } } double DLogCosh(double u) { return tanh(A * u); } double DExp(double u) { return u * exp(-u*u/2); } } int main(int argc, char *argv[]) { fx_init(argc, argv); srand48(time(0)); const char *data = fx_param_str(NULL, "data", NULL); Matrix X, X_centered, whitening, X_whitened; data::Load(data, &X); index_t d = X.n_rows(); // number of dimensions index_t n = X.n_cols(); // number of points printf("d = %d, n = %d\n", d, n); X_centered.Init(d, n); X_whitened.Init(d, n); whitening.Init(d, d); printf("centering\n"); Center(X, X_centered); printf("whitening\n"); Whiten(X_centered, whitening, X_whitened); double tolerance = 1e-4; Matrix post_whitening_W_transpose; post_whitening_W_transpose.Init(d, d); printf("deflation ICA\n"); DeflationICA(X_whitened, EXP, tolerance, post_whitening_W_transpose); Matrix post_whitening_W; la::TransposeInit(post_whitening_W_transpose, &post_whitening_W); Matrix W; la::MulInit(post_whitening_W, whitening, &W); Matrix Y; la::MulInit(post_whitening_W, X_whitened, &Y); SaveCorrectly("post_whitening_W.dat", post_whitening_W); SaveCorrectly("whitening.dat", whitening); SaveCorrectly("W.dat", W); SaveCorrectly("X_centered.dat", X_centered); SaveCorrectly("X_whitened.dat", X_whitened); SaveCorrectly("Y.dat", Y); // fx_done(); return 0; } <|endoftext|>
<commit_before>#pragma once #include <memory> #include "MatrixData.h" namespace smurff { template<typename YType> class MatrixDataTempl : public MatrixData { public: MatrixDataTempl(YType Y) : Y(Y) { } //init and center void init_pre() override { assert(nrow() > 0 && ncol() > 0); Ycentered = std::shared_ptr<std::vector<YType> >(new std::vector<YType>()); Ycentered->push_back(Y.transpose()); Ycentered->push_back(Y); init_cwise_mean(); } PVec<> dim() const override { return PVec<>({ static_cast<int>(Y.rows()), static_cast<int>(Y.cols()) }); } int nnz() const override { return Y.nonZeros(); } double sum() const override { return Y.sum(); } double offset_to_mean(const PVec<>& pos) const override { if (getCenterMode() == CenterModeTypes::CENTER_GLOBAL) return getGlobalMean(); else if (getCenterMode() == CenterModeTypes::CENTER_VIEW) return getCwiseMean(); else if (getCenterMode() == CenterModeTypes::CENTER_ROWS) return getModeMeanItem(1,pos.at(1)); else if (getCenterMode() == CenterModeTypes::CENTER_COLS) return getModeMeanItem(0,pos.at(0)); else if (getCenterMode() == CenterModeTypes::CENTER_NONE) return .0; assert(false); return .0; } double var_total() const override; double sumsq(const SubModel& model) const override; YType Y; // eigen matrix with the data private: std::shared_ptr<std::vector<YType> > Ycentered; // centered versions of original matrix (transposed, original) public: const std::vector<YType>& getYc() const { assert(Ycentered); return *Ycentered.get(); } std::shared_ptr<std::vector<YType> > getYcPtr() const { assert(Ycentered); return Ycentered; } }; template<> double MatrixDataTempl<Eigen::MatrixXd>::var_total() const; template<> double MatrixDataTempl<Eigen::SparseMatrix<double> >::var_total() const; template<> double MatrixDataTempl<Eigen::MatrixXd>::sumsq(const SubModel &model) const; template<> double MatrixDataTempl<Eigen::SparseMatrix<double> >::sumsq(const SubModel &model) const; } <commit_msg>Fix order of modes in offset_to_mean<commit_after>#pragma once #include <memory> #include "MatrixData.h" namespace smurff { template<typename YType> class MatrixDataTempl : public MatrixData { public: MatrixDataTempl(YType Y) : Y(Y) { } //init and center void init_pre() override { assert(nrow() > 0 && ncol() > 0); Ycentered = std::shared_ptr<std::vector<YType> >(new std::vector<YType>()); Ycentered->push_back(Y.transpose()); Ycentered->push_back(Y); init_cwise_mean(); } PVec<> dim() const override { return PVec<>({ static_cast<int>(Y.rows()), static_cast<int>(Y.cols()) }); } int nnz() const override { return Y.nonZeros(); } double sum() const override { return Y.sum(); } double offset_to_mean(const PVec<>& pos) const override { if (getCenterMode() == CenterModeTypes::CENTER_GLOBAL) return getGlobalMean(); else if (getCenterMode() == CenterModeTypes::CENTER_VIEW) return getCwiseMean(); else if (getCenterMode() == CenterModeTypes::CENTER_ROWS) return getModeMeanItem(0,pos.at(0)); else if (getCenterMode() == CenterModeTypes::CENTER_COLS) return getModeMeanItem(1,pos.at(1)); else if (getCenterMode() == CenterModeTypes::CENTER_NONE) return .0; assert(false); return .0; } double var_total() const override; double sumsq(const SubModel& model) const override; YType Y; // eigen matrix with the data private: std::shared_ptr<std::vector<YType> > Ycentered; // centered versions of original matrix (transposed, original) public: const std::vector<YType>& getYc() const { assert(Ycentered); return *Ycentered.get(); } std::shared_ptr<std::vector<YType> > getYcPtr() const { assert(Ycentered); return Ycentered; } }; template<> double MatrixDataTempl<Eigen::MatrixXd>::var_total() const; template<> double MatrixDataTempl<Eigen::SparseMatrix<double> >::var_total() const; template<> double MatrixDataTempl<Eigen::MatrixXd>::sumsq(const SubModel &model) const; template<> double MatrixDataTempl<Eigen::SparseMatrix<double> >::sumsq(const SubModel &model) const; } <|endoftext|>
<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/AutoParameter.h> #include <limits.h> class AutoParameterTest: public testing::Test {}; struct MyParamClass1 { struct MyIntParam1 { static constexpr int Default() { return 15; } }; AutoParameter<int, MyIntParam1> m_param; }; TEST_F(AutoParameterTest, VerifyCorrectDeconstruction) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; EXPECT_STREQ("AutoParam.MyParamClass1::MyIntParam1", param.m_key.c_str()) << "Configuration variable name was not correctly extracted"; } TEST_F(AutoParameterTest, VerifyDefaultValue) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; ASSERT_EQ(*param, 15) << "Default value was not properly set"; ASSERT_FALSE(param.IsConfigured()) << "Using the default value does not mean the parameter should be configured/set"; } TEST_F(AutoParameterTest, VerifySetShouldCallConfigure) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; ASSERT_TRUE(param.Set(MyParamClass1::MyIntParam1::Default()) && param.IsConfigured()) << "Settung the variable should configure it in the auto config manager"; } TEST_F(AutoParameterTest, VerifyResetToDefaultValue) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; ASSERT_TRUE(param.Set(30) && *param == 30) << "Could not set the parameter to another value"; // Reset param.Set(MyParamClass1::MyIntParam1::Default()); ASSERT_EQ(*param, 15) << "Parameter was not properly reset to its default value"; } struct MyParamClass2 { struct MyIntParam2 { static constexpr int Default() { return 15; } static bool Validate(const int& value) { return 10 <= value && value <= 20; } }; AutoParameter<int, MyIntParam2> m_param; }; TEST_F(AutoParameterTest, VerifyValidationFunction) { AutoRequired<MyParamClass2> mpc; auto& param = mpc->m_param; ASSERT_FALSE(param.Set(9)) << "Set() should return false when setting invalid value"; ASSERT_EQ(*param, 15) << "Failed set attempts should not have altered the previous state"; ASSERT_TRUE(param.Set(10) && *param == 10) << "Should be able to set values that are valid according to the validation function"; } struct MyParamClass4 { struct MyIntParam4 { static constexpr int Default() { return 0; } static bool Validate(const int& value) { return 10 <= value && value <= 20; } }; AutoParameter<int, MyIntParam4> m_param; }; TEST_F(AutoParameterTest, VerifyInvalidDefaultValue) { ASSERT_ANY_THROW(AutoRequired<MyParamClass4>()) << "Cannot construct a parameter where default value is invalid"; } <commit_msg>name change<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/AutoParameter.h> #include <limits.h> class AutoParameterTest: public testing::Test {}; struct MyParamClass1 { struct MyIntParam1 { static constexpr int Default() { return 15; } }; AutoParameter<int, MyIntParam1> m_param; }; TEST_F(AutoParameterTest, VerifyCorrectDeconstruction) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; EXPECT_STREQ("AutoParam.MyParamClass1::MyIntParam1", param.m_key.c_str()) << "Configuration variable name was not correctly extracted"; } TEST_F(AutoParameterTest, VerifyDefaultValue) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; ASSERT_EQ(*param, 15) << "Default value was not properly set"; ASSERT_FALSE(param.IsConfigured()) << "Using the default value does not mean the parameter should be configured/set"; } TEST_F(AutoParameterTest, VerifySetShouldCallConfigure) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; ASSERT_TRUE(param.Set(MyParamClass1::MyIntParam1::Default()) && param.IsConfigured()) << "Settung the variable should configure it in the auto config manager"; } TEST_F(AutoParameterTest, VerifyResetToDefaultValue) { AutoRequired<MyParamClass1> mpc; auto& param = mpc->m_param; ASSERT_TRUE(param.Set(30) && *param == 30) << "Could not set the parameter to another value"; // Reset param.Set(MyParamClass1::MyIntParam1::Default()); ASSERT_EQ(*param, 15) << "Parameter was not properly reset to its default value"; } struct MyParamClass2 { struct MyIntParam2 { static constexpr int Default() { return 15; } static bool Validate(const int& value) { return 10 <= value && value <= 20; } }; AutoParameter<int, MyIntParam2> m_param; }; TEST_F(AutoParameterTest, VerifyValidationFunction) { AutoRequired<MyParamClass2> mpc; auto& param = mpc->m_param; ASSERT_FALSE(param.Set(9)) << "Set() should return false when setting invalid value"; ASSERT_EQ(*param, 15) << "Failed set attempts should not have altered the previous state"; ASSERT_TRUE(param.Set(10) && *param == 10) << "Should be able to set values that are valid according to the validation function"; } struct MyParamClass3 { struct MyIntParam3 { static constexpr int Default() { return 0; } static bool Validate(const int& value) { return 10 <= value && value <= 20; } }; AutoParameter<int, MyIntParam3> m_param; }; TEST_F(AutoParameterTest, VerifyInvalidDefaultValue) { ASSERT_ANY_THROW(AutoRequired<MyParamClass3>()) << "Cannot construct a parameter where default value is invalid"; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Pattern.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:52:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_forms.hxx" #ifndef _FORMS_PATTERN_HXX_ #include "Pattern.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::form; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; //================================================================== // OPatternControl //================================================================== //------------------------------------------------------------------ OPatternControl::OPatternControl(const Reference<XMultiServiceFactory>& _rxFactory) :OBoundControl(_rxFactory, VCL_CONTROL_PATTERNFIELD) { } //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternControl(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternControl::_getTypes() { return OBoundControl::_getTypes(); } //------------------------------------------------------------------------------ StringSequence OPatternControl::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControl::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 1); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_PATTERNFIELD; return aSupported; } //================================================================== // OPatternModel //================================================================== //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternModel(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternModel::_getTypes() { return OEditBaseModel::_getTypes(); } //------------------------------------------------------------------ DBG_NAME( OPatternModel ) //------------------------------------------------------------------ OPatternModel::OPatternModel(const Reference<XMultiServiceFactory>& _rxFactory) :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_PATTERNFIELD, FRM_SUN_CONTROL_PATTERNFIELD, sal_False, sal_False ) // use the old control name for compytibility reasons { DBG_CTOR( OPatternModel, NULL ); m_nClassId = FormComponentType::PATTERNFIELD; initValueProperty( PROPERTY_TEXT, PROPERTY_ID_TEXT ); } //------------------------------------------------------------------ OPatternModel::OPatternModel( const OPatternModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory ) :OEditBaseModel( _pOriginal, _rxFactory ) { DBG_CTOR( OPatternModel, NULL ); } //------------------------------------------------------------------ OPatternModel::~OPatternModel() { DBG_DTOR( OPatternModel, NULL ); } // XCloneable //------------------------------------------------------------------------------ IMPLEMENT_DEFAULT_CLONING( OPatternModel ) // XServiceInfo //------------------------------------------------------------------------------ StringSequence SAL_CALL OPatternModel::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControlModel::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 2); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-2] = FRM_SUN_COMPONENT_DATABASE_PATTERNFIELD; pArray[aSupported.getLength()-1] = FRM_SUN_COMPONENT_PATTERNFIELD; return aSupported; } //------------------------------------------------------------------------------ Reference<XPropertySetInfo> SAL_CALL OPatternModel::getPropertySetInfo() throw( RuntimeException ) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------------ void OPatternModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const { BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel ) DECL_PROP2(DEFAULT_TEXT, ::rtl::OUString, BOUND, MAYBEDEFAULT); DECL_BOOL_PROP1(EMPTY_IS_NULL, BOUND); DECL_PROP1(TABINDEX, sal_Int16, BOUND); DECL_PROP2(FILTERPROPOSAL, sal_Bool, BOUND, MAYBEDEFAULT); END_DESCRIBE_PROPERTIES(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& OPatternModel::getInfoHelper() { return *const_cast<OPatternModel*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL OPatternModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException) { return FRM_COMPONENT_PATTERNFIELD; // old (non-sun) name for compatibility ! } //------------------------------------------------------------------------------ sal_Bool OPatternModel::commitControlValueToDbColumn( bool /*_bPostReset*/ ) { ::rtl::OUString sNewValue; m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) >>= sNewValue; if ( sNewValue != m_aSaveValue ) { if ( !sNewValue.getLength() && !isRequired() && m_bEmptyIsNull ) m_xColumnUpdate->updateNull(); else { try { m_xColumnUpdate->updateString( sNewValue ); } catch(Exception&) { return sal_False; } } m_aSaveValue = sNewValue; } return sal_True; } // XPropertyChangeListener //------------------------------------------------------------------------------ Any OPatternModel::translateDbColumnToControlValue() { m_aSaveValue = m_xColumn->getString(); return makeAny( m_aSaveValue ); } // XReset //------------------------------------------------------------------------------ Any OPatternModel::getDefaultForReset() const { return makeAny( m_aDefaultText ); } //......................................................................... } // namespace frm //......................................................................... <commit_msg>INTEGRATION: CWS hb02 (1.15.52); FILE MERGED 2007/02/01 12:09:40 fs 1.15.52.2: #i74051# split describeFixedProperties in describeFixedProperties and describeAggregateProperties 2007/01/31 10:55:29 fs 1.15.52.1: changed handling of properties in the course of #i74051#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Pattern.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: obo $ $Date: 2007-03-09 13:30: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_forms.hxx" #ifndef _FORMS_PATTERN_HXX_ #include "Pattern.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::form; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; //================================================================== // OPatternControl //================================================================== //------------------------------------------------------------------ OPatternControl::OPatternControl(const Reference<XMultiServiceFactory>& _rxFactory) :OBoundControl(_rxFactory, VCL_CONTROL_PATTERNFIELD) { } //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternControl(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternControl::_getTypes() { return OBoundControl::_getTypes(); } //------------------------------------------------------------------------------ StringSequence OPatternControl::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControl::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 1); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_PATTERNFIELD; return aSupported; } //================================================================== // OPatternModel //================================================================== //------------------------------------------------------------------ InterfaceRef SAL_CALL OPatternModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new OPatternModel(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> OPatternModel::_getTypes() { return OEditBaseModel::_getTypes(); } //------------------------------------------------------------------ DBG_NAME( OPatternModel ) //------------------------------------------------------------------ OPatternModel::OPatternModel(const Reference<XMultiServiceFactory>& _rxFactory) :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_PATTERNFIELD, FRM_SUN_CONTROL_PATTERNFIELD, sal_False, sal_False ) // use the old control name for compytibility reasons { DBG_CTOR( OPatternModel, NULL ); m_nClassId = FormComponentType::PATTERNFIELD; initValueProperty( PROPERTY_TEXT, PROPERTY_ID_TEXT ); } //------------------------------------------------------------------ OPatternModel::OPatternModel( const OPatternModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory ) :OEditBaseModel( _pOriginal, _rxFactory ) { DBG_CTOR( OPatternModel, NULL ); } //------------------------------------------------------------------ OPatternModel::~OPatternModel() { DBG_DTOR( OPatternModel, NULL ); } // XCloneable //------------------------------------------------------------------------------ IMPLEMENT_DEFAULT_CLONING( OPatternModel ) // XServiceInfo //------------------------------------------------------------------------------ StringSequence SAL_CALL OPatternModel::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControlModel::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 2); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-2] = FRM_SUN_COMPONENT_DATABASE_PATTERNFIELD; pArray[aSupported.getLength()-1] = FRM_SUN_COMPONENT_PATTERNFIELD; return aSupported; } //------------------------------------------------------------------------------ void OPatternModel::describeFixedProperties( Sequence< Property >& _rProps ) const { BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel ) DECL_PROP2(DEFAULT_TEXT, ::rtl::OUString, BOUND, MAYBEDEFAULT); DECL_BOOL_PROP1(EMPTY_IS_NULL, BOUND); DECL_PROP1(TABINDEX, sal_Int16, BOUND); DECL_PROP2(FILTERPROPOSAL, sal_Bool, BOUND, MAYBEDEFAULT); END_DESCRIBE_PROPERTIES(); } //------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL OPatternModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException) { return FRM_COMPONENT_PATTERNFIELD; // old (non-sun) name for compatibility ! } //------------------------------------------------------------------------------ sal_Bool OPatternModel::commitControlValueToDbColumn( bool /*_bPostReset*/ ) { ::rtl::OUString sNewValue; m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) >>= sNewValue; if ( sNewValue != m_aSaveValue ) { if ( !sNewValue.getLength() && !isRequired() && m_bEmptyIsNull ) m_xColumnUpdate->updateNull(); else { try { m_xColumnUpdate->updateString( sNewValue ); } catch(Exception&) { return sal_False; } } m_aSaveValue = sNewValue; } return sal_True; } // XPropertyChangeListener //------------------------------------------------------------------------------ Any OPatternModel::translateDbColumnToControlValue() { m_aSaveValue = m_xColumn->getString(); return makeAny( m_aSaveValue ); } // XReset //------------------------------------------------------------------------------ Any OPatternModel::getDefaultForReset() const { return makeAny( m_aDefaultText ); } //......................................................................... } // namespace frm //......................................................................... <|endoftext|>
<commit_before>/* * BloscPlugin.cpp * * Created on: 22 Jan 2018 * Author: Ulrik Pedersen */ #include <cstdlib> #include <blosc.h> #include <version.h> #include <BloscPlugin.h> #include <DebugLevelLogger.h> namespace FrameProcessor { /** * cd_values[7] meaning (see blosc.h): * 0: reserved * 1: reserved * 2: type size * 3: uncompressed size * 4: compression level * 5: 0: shuffle not active, 1: byte shuffle, 2: bit shuffle * 6: the actual Blosc compressor to use. See blosc.h * * @param settings * @return */ void create_cd_values(const BloscCompressionSettings& settings, std::vector<unsigned int>& cd_values) { if (cd_values.size() < 7) cd_values.resize(7); cd_values[0] = 0; cd_values[1] = 0; cd_values[2] = static_cast<unsigned int>(settings.type_size); cd_values[3] = static_cast<unsigned int>(settings.uncompressed_size); cd_values[4] = settings.compression_level; cd_values[5] = settings.shuffle; cd_values[6] = settings.blosc_compressor; } /** * The constructor sets up logging used within the class. */ BloscPlugin::BloscPlugin() : current_acquisition_("") { this->commanded_compression_settings_.blosc_compressor = BLOSC_LZ4; this->commanded_compression_settings_.shuffle = BLOSC_BITSHUFFLE; this->commanded_compression_settings_.compression_level = 1; this->commanded_compression_settings_.type_size = 0; this->commanded_compression_settings_.uncompressed_size = 0; this->compression_settings_ = this->commanded_compression_settings_; // Setup logging for the class logger_ = Logger::getLogger("FP.BloscPlugin"); logger_->setLevel(Level::getAll()); LOG4CXX_TRACE(logger_, "BloscPlugin constructor"); //blosc_init(); // not required for blosc >= v1.9 int ret = 0; ret = blosc_set_compressor(BLOSC_LZ4_COMPNAME); if (ret < 0) LOG4CXX_ERROR(logger_, "Blosc unable to set compressor: " << BLOSC_LZ4_COMPNAME); LOG4CXX_TRACE(logger_, "Blosc Version: " << blosc_get_version_string()); LOG4CXX_TRACE(logger_, "Blosc list available compressors: " << blosc_list_compressors()); LOG4CXX_TRACE(logger_, "Blosc current compressor: " << blosc_get_compressor()); } /** * Destructor. */ BloscPlugin::~BloscPlugin() { LOG4CXX_DEBUG_LEVEL(3, logger_, "BloscPlugin destructor."); } /** * Compress one frame, return compressed frame. */ boost::shared_ptr<Frame> BloscPlugin::compress_frame(boost::shared_ptr<Frame> src_frame) { int compressed_size = 0; BloscCompressionSettings c_settings; boost::shared_ptr <Frame> dest_frame; const void* src_data_ptr = static_cast<const void*>( static_cast<const char*>(src_frame->get_data()) ); this->update_compression_settings(src_frame->get_acquisition_id()); c_settings = this->compression_settings_; if (src_frame->get_data_type() >= 0) { c_settings.type_size = src_frame->get_data_type_size(); } else { // TODO: This if/else is a hack to work around Frame::data_type_ not being set. See https://jira.diamond.ac.uk/browse/BC-811 c_settings.type_size = 2; // hack: just default to 16bit per pixel as Excalibur use that } c_settings.uncompressed_size = src_frame->get_data_size(); size_t dest_data_size = c_settings.uncompressed_size + BLOSC_MAX_OVERHEAD; // TODO: is this malloc really necessary? Can't we get writable DataBlocks somehow? void *dest_data_ptr = malloc(dest_data_size); if (dest_data_ptr == NULL) {throw std::runtime_error("Failed to malloc buffer for Blosc compression output");} try { std::stringstream ss_blosc_settings; ss_blosc_settings << " compressor=" << blosc_get_compressor() << " threads=" << blosc_get_nthreads() << " clevel=" << c_settings.compression_level << " doshuffle=" << c_settings.shuffle << " typesize=" << c_settings.type_size << " nbytes=" << c_settings.uncompressed_size << " destsize=" << dest_data_size; LOG4CXX_DEBUG_LEVEL(2, logger_, "Blosc compression: frame=" << src_frame->get_frame_number() << " acquisition=\"" << src_frame->get_acquisition_id() << "\"" << ss_blosc_settings.str() << " src=" << src_data_ptr << " dest=" << dest_data_ptr); compressed_size = blosc_compress(c_settings.compression_level, c_settings.shuffle, c_settings.type_size, c_settings.uncompressed_size, src_data_ptr, dest_data_ptr, dest_data_size); if (compressed_size < 0) { std::stringstream ss; ss << "blosc_compress failed. error=" << compressed_size << ss_blosc_settings.str(); LOG4CXX_ERROR(logger_, ss.str()); throw std::runtime_error(ss.str()); } double factor = 0.; if (compressed_size > 0) { factor = (double)src_frame->get_data_size() / (double)compressed_size; } LOG4CXX_DEBUG_LEVEL(2, logger_, "Blosc compression complete: frame=" << src_frame->get_frame_number() << " compressed_size=" << compressed_size << " factor=" << factor); dest_frame = boost::shared_ptr<Frame>(new Frame(src_frame->get_dataset_name())); LOG4CXX_DEBUG_LEVEL(3, logger_, "Copying compressed data to output frame. (" << compressed_size << " bytes)"); // I wish we had a pointer swap feature on the Frame class and avoid this unnecessary copy... dest_frame->copy_data(dest_data_ptr, compressed_size); if (dest_data_ptr != NULL) {free(dest_data_ptr); dest_data_ptr = NULL;} // I wish we had a shallow-copy feature on the Frame class... dest_frame->set_data_type(src_frame->get_data_type()); dest_frame->set_frame_number(src_frame->get_frame_number()); dest_frame->set_acquisition_id(src_frame->get_acquisition_id()); // TODO: is this the correct way to get and set dimensions? dest_frame->set_dimensions(src_frame->get_dimensions()); } catch (const std::exception& e) { LOG4CXX_ERROR(logger_, "Serious error in Blosc compression: " << e.what()); if (dest_data_ptr != NULL) {free(dest_data_ptr); dest_data_ptr = NULL;} } return dest_frame; } /** * Update the compression settings used if the acquisition ID differs from the current one. * i.e. if a new acquisition has been started. * * @param acquisition_id */ void BloscPlugin::update_compression_settings(const std::string &acquisition_id) { if (acquisition_id != this->current_acquisition_){ LOG4CXX_DEBUG_LEVEL(1, logger_, "New acquisition detected: "<< acquisition_id); this->compression_settings_ = this->commanded_compression_settings_; this->current_acquisition_ = acquisition_id; int ret = 0; const char * p_compressor_name; ret = blosc_compcode_to_compname(this->compression_settings_.blosc_compressor, &p_compressor_name); LOG4CXX_DEBUG_LEVEL(1, logger_, "Blosc compression new acquisition=\"" << acquisition_id << "\":" << " compressor=" << p_compressor_name << " threads=" << blosc_get_nthreads() << " clevel=" << this->compression_settings_.compression_level << " doshuffle=" << this->compression_settings_.shuffle << " typesize=" << this->compression_settings_.type_size << " nbytes=" << this->compression_settings_.uncompressed_size); ret = blosc_set_compressor(p_compressor_name); if (ret < 0) { LOG4CXX_ERROR(logger_, "Blosc failed to set compressor: " << " " << this->compression_settings_.blosc_compressor << " " << *p_compressor_name) throw std::runtime_error("Blosc failed to set compressor"); } } } /** * Perform compression on the frame and output a new, compressed Frame. * * \param[in] frame - Pointer to a Frame object. */ void BloscPlugin::process_frame(boost::shared_ptr<Frame> src_frame) { LOG4CXX_DEBUG_LEVEL(3, logger_, "Received a new frame..."); boost::shared_ptr <Frame> compressed_frame = this->compress_frame(src_frame); LOG4CXX_DEBUG_LEVEL(3, logger_, "Pushing compressed frame"); this->push(compressed_frame); } int BloscPlugin::get_version_major() { return ODIN_DATA_VERSION_MAJOR; } int BloscPlugin::get_version_minor() { return ODIN_DATA_VERSION_MINOR; } int BloscPlugin::get_version_patch() { return ODIN_DATA_VERSION_PATCH; } std::string BloscPlugin::get_version_short() { return ODIN_DATA_VERSION_STR_SHORT; } std::string BloscPlugin::get_version_long() { return ODIN_DATA_VERSION_STR; } } /* namespace FrameProcessor */ <commit_msg>BloscPlugin: removing large try/catch section<commit_after>/* * BloscPlugin.cpp * * Created on: 22 Jan 2018 * Author: Ulrik Pedersen */ #include <cstdlib> #include <blosc.h> #include <version.h> #include <BloscPlugin.h> #include <DebugLevelLogger.h> namespace FrameProcessor { /** * cd_values[7] meaning (see blosc.h): * 0: reserved * 1: reserved * 2: type size * 3: uncompressed size * 4: compression level * 5: 0: shuffle not active, 1: byte shuffle, 2: bit shuffle * 6: the actual Blosc compressor to use. See blosc.h * * @param settings * @return */ void create_cd_values(const BloscCompressionSettings& settings, std::vector<unsigned int>& cd_values) { if (cd_values.size() < 7) cd_values.resize(7); cd_values[0] = 0; cd_values[1] = 0; cd_values[2] = static_cast<unsigned int>(settings.type_size); cd_values[3] = static_cast<unsigned int>(settings.uncompressed_size); cd_values[4] = settings.compression_level; cd_values[5] = settings.shuffle; cd_values[6] = settings.blosc_compressor; } /** * The constructor sets up logging used within the class. */ BloscPlugin::BloscPlugin() : current_acquisition_("") { this->commanded_compression_settings_.blosc_compressor = BLOSC_LZ4; this->commanded_compression_settings_.shuffle = BLOSC_BITSHUFFLE; this->commanded_compression_settings_.compression_level = 1; this->commanded_compression_settings_.type_size = 0; this->commanded_compression_settings_.uncompressed_size = 0; this->compression_settings_ = this->commanded_compression_settings_; // Setup logging for the class logger_ = Logger::getLogger("FP.BloscPlugin"); logger_->setLevel(Level::getAll()); LOG4CXX_TRACE(logger_, "BloscPlugin constructor"); //blosc_init(); // not required for blosc >= v1.9 int ret = 0; ret = blosc_set_compressor(BLOSC_LZ4_COMPNAME); if (ret < 0) LOG4CXX_ERROR(logger_, "Blosc unable to set compressor: " << BLOSC_LZ4_COMPNAME); LOG4CXX_TRACE(logger_, "Blosc Version: " << blosc_get_version_string()); LOG4CXX_TRACE(logger_, "Blosc list available compressors: " << blosc_list_compressors()); LOG4CXX_TRACE(logger_, "Blosc current compressor: " << blosc_get_compressor()); } /** * Destructor. */ BloscPlugin::~BloscPlugin() { LOG4CXX_DEBUG_LEVEL(3, logger_, "BloscPlugin destructor."); } /** * Compress one frame, return compressed frame. */ boost::shared_ptr<Frame> BloscPlugin::compress_frame(boost::shared_ptr<Frame> src_frame) { int compressed_size = 0; BloscCompressionSettings c_settings; boost::shared_ptr <Frame> dest_frame; const void* src_data_ptr = static_cast<const void*>( static_cast<const char*>(src_frame->get_data()) ); this->update_compression_settings(src_frame->get_acquisition_id()); c_settings = this->compression_settings_; if (src_frame->get_data_type() >= 0) { c_settings.type_size = src_frame->get_data_type_size(); } else { // TODO: This if/else is a hack to work around Frame::data_type_ not being set. See https://jira.diamond.ac.uk/browse/BC-811 c_settings.type_size = 2; // hack: just default to 16bit per pixel as Excalibur use that } c_settings.uncompressed_size = src_frame->get_data_size(); size_t dest_data_size = c_settings.uncompressed_size + BLOSC_MAX_OVERHEAD; // TODO: is this malloc really necessary? Can't we get writable DataBlocks somehow? void *dest_data_ptr = malloc(dest_data_size); if (dest_data_ptr == NULL) {throw std::runtime_error("Failed to malloc buffer for Blosc compression output");} std::stringstream ss_blosc_settings; ss_blosc_settings << " compressor=" << blosc_get_compressor() << " threads=" << blosc_get_nthreads() << " clevel=" << c_settings.compression_level << " doshuffle=" << c_settings.shuffle << " typesize=" << c_settings.type_size << " nbytes=" << c_settings.uncompressed_size << " destsize=" << dest_data_size; LOG4CXX_DEBUG_LEVEL(2, logger_, "Blosc compression: frame=" << src_frame->get_frame_number() << " acquisition=\"" << src_frame->get_acquisition_id() << "\"" << ss_blosc_settings.str() << " src=" << src_data_ptr << " dest=" << dest_data_ptr); compressed_size = blosc_compress(c_settings.compression_level, c_settings.shuffle, c_settings.type_size, c_settings.uncompressed_size, src_data_ptr, dest_data_ptr, dest_data_size); if (compressed_size < 0) { std::stringstream ss; ss << "blosc_compress failed. error=" << compressed_size << ss_blosc_settings.str(); LOG4CXX_ERROR(logger_, ss.str()); throw std::runtime_error(ss.str()); } double factor = 0.; if (compressed_size > 0) { factor = (double)src_frame->get_data_size() / (double)compressed_size; } LOG4CXX_DEBUG_LEVEL(2, logger_, "Blosc compression complete: frame=" << src_frame->get_frame_number() << " compressed_size=" << compressed_size << " factor=" << factor); dest_frame = boost::shared_ptr<Frame>(new Frame(src_frame->get_dataset_name())); LOG4CXX_DEBUG_LEVEL(3, logger_, "Copying compressed data to output frame. (" << compressed_size << " bytes)"); // I wish we had a pointer swap feature on the Frame class and avoid this unnecessary copy... dest_frame->copy_data(dest_data_ptr, compressed_size); if (dest_data_ptr != NULL) {free(dest_data_ptr); dest_data_ptr = NULL;} // I wish we had a shallow-copy feature on the Frame class... dest_frame->set_data_type(src_frame->get_data_type()); dest_frame->set_frame_number(src_frame->get_frame_number()); dest_frame->set_acquisition_id(src_frame->get_acquisition_id()); // TODO: is this the correct way to get and set dimensions? dest_frame->set_dimensions(src_frame->get_dimensions()); return dest_frame; } /** * Update the compression settings used if the acquisition ID differs from the current one. * i.e. if a new acquisition has been started. * * @param acquisition_id */ void BloscPlugin::update_compression_settings(const std::string &acquisition_id) { if (acquisition_id != this->current_acquisition_){ LOG4CXX_DEBUG_LEVEL(1, logger_, "New acquisition detected: "<< acquisition_id); this->compression_settings_ = this->commanded_compression_settings_; this->current_acquisition_ = acquisition_id; int ret = 0; const char * p_compressor_name; ret = blosc_compcode_to_compname(this->compression_settings_.blosc_compressor, &p_compressor_name); LOG4CXX_DEBUG_LEVEL(1, logger_, "Blosc compression new acquisition=\"" << acquisition_id << "\":" << " compressor=" << p_compressor_name << " threads=" << blosc_get_nthreads() << " clevel=" << this->compression_settings_.compression_level << " doshuffle=" << this->compression_settings_.shuffle << " typesize=" << this->compression_settings_.type_size << " nbytes=" << this->compression_settings_.uncompressed_size); ret = blosc_set_compressor(p_compressor_name); if (ret < 0) { LOG4CXX_ERROR(logger_, "Blosc failed to set compressor: " << " " << this->compression_settings_.blosc_compressor << " " << *p_compressor_name) throw std::runtime_error("Blosc failed to set compressor"); } } } /** * Perform compression on the frame and output a new, compressed Frame. * * \param[in] frame - Pointer to a Frame object. */ void BloscPlugin::process_frame(boost::shared_ptr<Frame> src_frame) { LOG4CXX_DEBUG_LEVEL(3, logger_, "Received a new frame..."); boost::shared_ptr <Frame> compressed_frame = this->compress_frame(src_frame); LOG4CXX_DEBUG_LEVEL(3, logger_, "Pushing compressed frame"); this->push(compressed_frame); } int BloscPlugin::get_version_major() { return ODIN_DATA_VERSION_MAJOR; } int BloscPlugin::get_version_minor() { return ODIN_DATA_VERSION_MINOR; } int BloscPlugin::get_version_patch() { return ODIN_DATA_VERSION_PATCH; } std::string BloscPlugin::get_version_short() { return ODIN_DATA_VERSION_STR_SHORT; } std::string BloscPlugin::get_version_long() { return ODIN_DATA_VERSION_STR; } } /* namespace FrameProcessor */ <|endoftext|>
<commit_before>/*========================================================================= Program: T2 Relaxation Map Module: Compute T2 Relaxation Map Filter Language: C++ Copyright (c) University of North Carolina at Chapel Hill (UNC-CH) All Rights Reserved. See License.txt for details. ==========================================================================*/ #ifndef __itkT2RelaxationMapFilter_hxx #define __itkT2RelaxationMapFilter_hxx #include "itkT2RelaxationMapFilter.h" using namespace std; namespace itk { template <class TInputImage, class TOutputImage> T2RelaxationMapFilter<TInputImage, TOutputImage> ::T2RelaxationMapFilter() { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfRequiredOutputs( 1 ); m_M0 = 1; } template <class TInput, class TOutput> void T2RelaxationMapFilter<TInput, TOutput> ::BeforeThreadedGenerateData(){ InputImageConstPointer inputImage = this->GetInput(); int numComponents = inputImage->GetNumberOfComponentsPerPixel(); m_EchoTimes = vnl_vector<double>(numComponents); double echotime = this->GetEchoTime(); for(int i = 0; i < numComponents; i++){ m_EchoTimes[i] = echotime*(i+1); } } template <class TInput, class TOutput> void T2RelaxationMapFilter<TInput, TOutput> ::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType itkNotUsed(threadId)){ InputImageConstPointer inputImage = this->GetInput(); InputImageIteratorType init( inputImage, outputRegionForThread ); OutputImagePointerType outputImagePtr = this->GetOutput( 0 ); OutputImageIteratorType outit( outputImagePtr, outputRegionForThread ); init.GoToBegin(); outit.GoToBegin(); int numComponents = inputImage->GetNumberOfComponentsPerPixel(); vnl_vector<double> Y = vnl_vector<double>(numComponents); t2Fitting t2fit(numComponents); t2fit.SetX(m_EchoTimes); t2fit.SetM0(m_M0); while(!init.IsAtEnd()){ InputImagePixelType t2values = init.Get(); for(int i = 0; i < numComponents; i++){ Y[i] = t2values[i] + 1; } t2fit.SetY(Y); vnl_vector<double> b(1, 1); vnl_levenberg_marquardt optimizer(t2fit); optimizer.minimize(b); if(b[0] != 0 && !isnan(b[0])){ outit.Set(-1.0/b[0]); } ++init; ++outit; } } } #endif<commit_msg>BUG: Initialize map when wrong value<commit_after>/*========================================================================= Program: T2 Relaxation Map Module: Compute T2 Relaxation Map Filter Language: C++ Copyright (c) University of North Carolina at Chapel Hill (UNC-CH) All Rights Reserved. See License.txt for details. ==========================================================================*/ #ifndef __itkT2RelaxationMapFilter_hxx #define __itkT2RelaxationMapFilter_hxx #include "itkT2RelaxationMapFilter.h" using namespace std; namespace itk { template <class TInputImage, class TOutputImage> T2RelaxationMapFilter<TInputImage, TOutputImage> ::T2RelaxationMapFilter() { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfRequiredOutputs( 1 ); m_M0 = 1; } template <class TInput, class TOutput> void T2RelaxationMapFilter<TInput, TOutput> ::BeforeThreadedGenerateData(){ InputImageConstPointer inputImage = this->GetInput(); int numComponents = inputImage->GetNumberOfComponentsPerPixel(); m_EchoTimes = vnl_vector<double>(numComponents); double echotime = this->GetEchoTime(); for(int i = 0; i < numComponents; i++){ m_EchoTimes[i] = echotime*(i+1); } } template <class TInput, class TOutput> void T2RelaxationMapFilter<TInput, TOutput> ::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType itkNotUsed(threadId)){ InputImageConstPointer inputImage = this->GetInput(); InputImageIteratorType init( inputImage, outputRegionForThread ); OutputImagePointerType outputImagePtr = this->GetOutput( 0 ); OutputImageIteratorType outit( outputImagePtr, outputRegionForThread ); init.GoToBegin(); outit.GoToBegin(); int numComponents = inputImage->GetNumberOfComponentsPerPixel(); vnl_vector<double> Y = vnl_vector<double>(numComponents); t2Fitting t2fit(numComponents); t2fit.SetX(m_EchoTimes); t2fit.SetM0(m_M0); while(!init.IsAtEnd()){ InputImagePixelType t2values = init.Get(); for(int i = 0; i < numComponents; i++){ Y[i] = t2values[i] + 1; } t2fit.SetY(Y); vnl_vector<double> b(1, 1); vnl_levenberg_marquardt optimizer(t2fit); optimizer.minimize(b); if(b[0] != 0 && !isnan(b[0])){ outit.Set(-1.0/b[0]); }else{ outit.Set(0); } ++init; ++outit; } } } #endif <|endoftext|>
<commit_before>/** * elf_parser.cpp - Implementation of ELF binary perser * @author Alexander Titov <[email protected]> * Copyright 2012 uArchSim iLab project */ // Genereic C #include <libelf.h> #include <cstdio> #include <unistd.h> #include <cstring> #include <fcntl.h> #include <gelf.h> #include <cstdlib> #include <cerrno> #include <cassert> // Generic C++ #include <iostream> #include <string> #include <sstream> // uArchSim modules #include <elf_parser.h> using namespace std; ElfSection::ElfSection( const char* elf_file_name, const char* section_name) { // open the binary file, we have to use C-style open, // because it is required by elf_begin function int file_descr = open( elf_file_name, O_RDONLY); if ( file_descr < 0) { cerr << "ERROR: Could not open file " << elf_file_name << ": " << strerror( errno) << endl; exit( EXIT_FAILURE); } // set ELF library operating version if ( elf_version( EV_CURRENT) == EV_NONE) { cerr << "ERROR: Could not set ELF library operating version:" << elf_errmsg( elf_errno()) << endl; exit( EXIT_FAILURE); } // open the file in ELF format Elf* elf = elf_begin( file_descr, ELF_C_READ, NULL); if ( !elf) { cerr << "ERROR: Could not open file " << elf_file_name << " as ELF file: " << elf_errmsg( elf_errno()) << endl; exit( EXIT_FAILURE); } // set the name of the sections this->name = new char[ strlen( section_name) + 1]; strcpy( this->name, section_name); // set the size, start address and offset uint64 offset = NO_VAL64; this->extractSectionParams( elf, section_name, offset, this->size, this->start_addr); // allocate place for the content this->content = new uint8[ this->size + 1]; lseek( file_descr, offset, SEEK_SET); FILE *file = fdopen( file_descr, "r"); if ( !file ) { cerr << "ERROR: Could not open file " << elf_file_name << ": " << strerror(errno) << endl; exit( EXIT_FAILURE); } // fill the content by the section data fread( this->content, sizeof( uint8), this->size, file); // close all used files fclose( file); elf_end( elf); close( file_descr); } ElfSection::~ElfSection() { delete [] this->name; delete [] this->content; } void ElfSection::extractSectionParams( Elf* elf, const char* section_name, uint64& offset, uint64& size, uint64& start_addr) { size_t shstrndx; elf_getshdrstrndx( elf, &shstrndx); // look through all sections and try to find the desired one Elf_Scn *section = NULL; while ( ( section = elf_nextscn( elf, section)) != NULL) { GElf_Shdr shdr; gelf_getshdr( section, &shdr); char* name = elf_strptr( elf, shstrndx, shdr.sh_name); // if a section with the decired name // then set its start address, size and offset // and return back from the function. if ( !strcmp( name, section_name)) { offset = ( uint64)shdr.sh_offset; size = ( uint64)shdr.sh_size; start_addr = ( uint64)shdr.sh_addr; return; } } cerr << "ERROR: Could not find section " << section_name << " in ELF file!" << endl; exit( EXIT_FAILURE); } uint64 ElfSection::read( uint64 addr, short num_of_bytes) const { assert( num_of_bytes < sizeof( uint64)); assert( isInside( addr, num_of_bytes)); uint64 data = 0; for ( short i = num_of_bytes; i > 0; --i) { short the_num_of_byte = addr - this->start_addr + i - 1; data <<= 8; data |= this->content[the_num_of_byte]; } cout << "\n\nit my debug print!\ndata=" << hex << data << endl; return data; } bool ElfSection::isInside( uint64 addr, short num_of_bytes) const { cout << "\nstart_addr = " << start_addr << "\naddr = " << addr << endl; assert( num_of_bytes); if (this->start_addr > addr) { return false; } if ( this->start_addr + this->size >= addr + num_of_bytes) { return true; } return false; } uint64 ElfSection::startAddr() const { assert(start_addr); return start_addr; } string ElfSection::dump( string indent) const { ostringstream oss; oss << indent << "Dump ELF section \"" << this->name << "\"" << endl << indent << " size = " << this->size << " Bytes" << endl << indent << " start_addr = 0x" << hex << this->start_addr << dec << endl << indent << " Content:" << endl; string str = this->strByBytes(); // split the contents into words of 4 bytes for ( size_t offset = 0; offset < this->size; offset += sizeof( uint32)) { oss << indent << " 0x" << hex << ( this->start_addr + offset) << indent << ": " << str.substr( 2 * offset, // 2 hex digits is need per byte sizeof( uint64)) << endl; } return oss.str(); } string ElfSection::strByBytes() const { // temp stream is used to convert numbers into the output string ostringstream oss; oss << hex; // convert each byte into 2 hex digits for( size_t i = 0; i < this->size; ++i) { oss.width( 2); // because we need two hex symbols to print a byte (e.g. "ff") oss.fill( '0'); // thus, number 8 will be printed as "08" // print a value of oss << (uint16) *( this->content + i); // need converting to uint16 // to be not preinted as an alphabet symbol } return oss.str(); } string ElfSection::strByWords() const { // temp stream is used to convert numbers into the output string ostringstream oss; oss << hex; // convert each words of 4 bytes into 8 hex digits for( size_t i = 0; i < this->size/sizeof( uint32); ++i) { oss.width( 8); // because we need 8 hex symbols to print a word (e.g. "ffffffff") oss.fill( '0'); // thus, number a44f will be printed as "0000a44f" oss << *( ( uint32*)this->content + i); } return oss.str(); } <commit_msg>[trunk] revert changes of Yuri Samarin<commit_after>/** * elf_parser.cpp - Implementation of ELF binary perser * @author Alexander Titov <[email protected]> * Copyright 2012 uArchSim iLab project */ // Genereic C #include <libelf.h> #include <cstdio> #include <unistd.h> #include <cstring> #include <fcntl.h> #include <gelf.h> #include <cstdlib> #include <cerrno> #include <cassert> // Generic C++ #include <iostream> #include <string> #include <sstream> // uArchSim modules #include <elf_parser.h> using namespace std; ElfSection::ElfSection( const char* elf_file_name, const char* section_name) { // open the binary file, we have to use C-style open, // because it is required by elf_begin function int file_descr = open( elf_file_name, O_RDONLY); if ( file_descr < 0) { cerr << "ERROR: Could not open file " << elf_file_name << ": " << strerror( errno) << endl; exit( EXIT_FAILURE); } // set ELF library operating version if ( elf_version( EV_CURRENT) == EV_NONE) { cerr << "ERROR: Could not set ELF library operating version:" << elf_errmsg( elf_errno()) << endl; exit( EXIT_FAILURE); } // open the file in ELF format Elf* elf = elf_begin( file_descr, ELF_C_READ, NULL); if ( !elf) { cerr << "ERROR: Could not open file " << elf_file_name << " as ELF file: " << elf_errmsg( elf_errno()) << endl; exit( EXIT_FAILURE); } // set the name of the sections this->name = new char[ strlen( section_name) + 1]; strcpy( this->name, section_name); // set the size, start address and offset uint64 offset = NO_VAL64; this->extractSectionParams( elf, section_name, offset, this->size, this->start_addr); // allocate place for the content this->content = new uint8[ this->size + 1]; lseek( file_descr, offset, SEEK_SET); FILE *file = fdopen( file_descr, "r"); if ( !file ) { cerr << "ERROR: Could not open file " << elf_file_name << ": " << strerror(errno) << endl; exit( EXIT_FAILURE); } // fill the content by the section data fread( this->content, sizeof( uint8), this->size, file); // close all used files fclose( file); elf_end( elf); close( file_descr); } ElfSection::~ElfSection() { delete [] this->name; delete [] this->content; } void ElfSection::extractSectionParams( Elf* elf, const char* section_name, uint64& offset, uint64& size, uint64& start_addr) { size_t shstrndx; elf_getshdrstrndx( elf, &shstrndx); // look through all sections and try to find the desired one Elf_Scn *section = NULL; while ( ( section = elf_nextscn( elf, section)) != NULL) { GElf_Shdr shdr; gelf_getshdr( section, &shdr); char* name = elf_strptr( elf, shstrndx, shdr.sh_name); // if a section with the decired name // then set its start address, size and offset // and return back from the function. if ( !strcmp( name, section_name)) { offset = ( uint64)shdr.sh_offset; size = ( uint64)shdr.sh_size; start_addr = ( uint64)shdr.sh_addr; return; } } cerr << "ERROR: Could not find section " << section_name << " in ELF file!" << endl; exit( EXIT_FAILURE); } uint64 ElfSection::read( uint64 addr, short num_of_bytes) const { // insert here your implementation assert(0); return NO_VAL64; } bool ElfSection::isInside( uint64 addr, short num_of_bytes) const { // insert here your implementation assert(0); return false; } uint64 ElfSection::startAddr() const { // insert here your implementation assert(0); return NO_VAL64; } string ElfSection::dump( string indent) const { ostringstream oss; oss << indent << "Dump ELF section \"" << this->name << "\"" << endl << indent << " size = " << this->size << " Bytes" << endl << indent << " start_addr = 0x" << hex << this->start_addr << dec << endl << indent << " Content:" << endl; string str = this->strByBytes(); // split the contents into words of 4 bytes for ( size_t offset = 0; offset < this->size; offset += sizeof( uint32)) { oss << indent << " 0x" << hex << ( this->start_addr + offset) << indent << ": " << str.substr( 2 * offset, // 2 hex digits is need per byte sizeof( uint64)) << endl; } return oss.str(); } string ElfSection::strByBytes() const { // temp stream is used to convert numbers into the output string ostringstream oss; oss << hex; // convert each byte into 2 hex digits for( size_t i = 0; i < this->size; ++i) { oss.width( 2); // because we need two hex symbols to print a byte (e.g. "ff") oss.fill( '0'); // thus, number 8 will be printed as "08" // print a value of oss << (uint16) *( this->content + i); // need converting to uint16 // to be not preinted as an alphabet symbol } return oss.str(); } string ElfSection::strByWords() const { // temp stream is used to convert numbers into the output string ostringstream oss; oss << hex; // convert each words of 4 bytes into 8 hex digits for( size_t i = 0; i < this->size/sizeof( uint32); ++i) { oss.width( 8); // because we need 8 hex symbols to print a word (e.g. "ffffffff") oss.fill( '0'); // thus, number a44f will be printed as "0000a44f" oss << *( ( uint32*)this->content + i); } return oss.str(); } <|endoftext|>
<commit_before>#include "APS2.h" #include <sstream> using std::ostringstream; using std::endl; string APS2::printStatusRegisters(const APS_Status_Registers & status) { ostringstream ret; ret << "Host Firmware Version = " << std::hex << status.hostFirmwareVersion << endl; ret << "User Firmware Version = " << std::hex << status.userFirmwareVersion << endl; ret << "Configuration Source = " << status.configurationSource << endl; ret << "User Status = " << status.userStatus << endl; ret << "DAC 0 Status = " << status.dac0Status << endl; ret << "DAC 1 Status = " << status.dac1Status << endl; ret << "PLL Status = " << status.pllStatus << endl; ret << "VCXO Status = " << status.vcxoStatus << endl; ret << "Send Packet Count = " << status.sendPacketCount << endl; ret << "Recv Packet Count = " << status.receivePacketCount << endl; ret << "Seq Skip Count = " << status.sequenceSkipCount << endl; ret << "Seq Dup Count = " << status.sequenceDupCount << endl; ret << "Uptime = " << status.uptime << endl; ret << "Reserved 1 = " << status.reserved1 << endl; ret << "Reserved 2 = " << status.reserved2 << endl; ret << "Reserved 3 = " << status.reserved3 << endl; return ret.str(); } string APS2::printAPSCommand(APSCommand * cmd) { ostringstream ret; uint32_t * packedCmd; packedCmd = reinterpret_cast<uint32_t *>(cmd); ret << std::hex << *packedCmd << " ="; ret << " ACK: " << cmd->ack; ret << " SEQ: " << cmd->seq; ret << " SEL: " << cmd->sel; ret << " R/W: " << cmd->r_w; ret << " CMD: " << cmd->cmd; ret << " MODE/STAT: " << cmd->mode_stat; ret << std::dec << " cnt: " << cmd->cnt; return ret.str(); } void APS2::zeroAPSCommand(APSCommand * command) { uint32_t * packedCmd; packedCmd = reinterpret_cast<uint32_t *>(command); packedCmd = 0; } uint8_t * APS2::getPayloadPtr(uint8_t * packet) { uint8_t * start = reinterpret_cast<uint8_t *>(packet); start += sizeof(APSEthernetHeader); return start; } <commit_msg>Added chip config IO commands to APS2<commit_after>#include "APS2.h" #include <sstream> using std::ostringstream; using std::endl; string APS2::printStatusRegisters(const APS_Status_Registers & status) { ostringstream ret; ret << "Host Firmware Version = " << std::hex << status.hostFirmwareVersion << endl; ret << "User Firmware Version = " << std::hex << status.userFirmwareVersion << endl; ret << "Configuration Source = " << status.configurationSource << endl; ret << "User Status = " << status.userStatus << endl; ret << "DAC 0 Status = " << status.dac0Status << endl; ret << "DAC 1 Status = " << status.dac1Status << endl; ret << "PLL Status = " << status.pllStatus << endl; ret << "VCXO Status = " << status.vcxoStatus << endl; ret << "Send Packet Count = " << status.sendPacketCount << endl; ret << "Recv Packet Count = " << status.receivePacketCount << endl; ret << "Seq Skip Count = " << status.sequenceSkipCount << endl; ret << "Seq Dup Count = " << status.sequenceDupCount << endl; ret << "Uptime = " << status.uptime << endl; ret << "Reserved 1 = " << status.reserved1 << endl; ret << "Reserved 2 = " << status.reserved2 << endl; ret << "Reserved 3 = " << status.reserved3 << endl; return ret.str(); } string APS2::printAPSCommand(APSCommand_t & cmd) { ostringstream ret; ret << std::hex << cmd.packed << " ="; ret << " ACK: " << cmd.ack; ret << " SEQ: " << cmd.seq; ret << " SEL: " << cmd.sel; ret << " R/W: " << cmd.r_w; ret << " CMD: " << cmd.cmd; ret << " MODE/STAT: " << cmd.mode_stat; ret << std::dec << " cnt: " << cmd.cnt; return ret.str(); } string APS2::printAPSChipCommand(APSChipConfigCommand_t & cmd) { ostringstream ret; ret << std::hex << cmd.packed << " ="; ret << " Target: " << cmd.target; ret << " SPICNT_DATA: " << cmd.spicnt_data; ret << " INSTR: " << cmd.instr; return ret.str(); } uint32_t * APS2::getPayloadPtr(uint32_t * frame) { frame += sizeof(APSEthernetHeader) / sizeof(uint32_t); return frame; } <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file opt_array_splitting.cpp * * If an array is always dereferenced with a constant index, then * split it apart into its elements, making it more amenable to other * optimization passes. * * This skips uniform/varying arrays, which would need careful * handling due to their ir->location fields tying them to the GL API * and other shader stages. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "compiler/glsl_types.h" static bool debug = false; namespace { namespace opt_array_splitting { class variable_entry : public exec_node { public: variable_entry(ir_variable *var) { this->var = var; this->split = true; this->declaration = false; this->components = NULL; this->mem_ctx = NULL; if (var->type->is_array()) this->size = var->type->length; else this->size = var->type->matrix_columns; } ir_variable *var; /* The key: the variable's pointer. */ unsigned size; /* array length or matrix columns */ /** Whether this array should be split or not. */ bool split; /* If the variable had a decl we can work with in the instruction * stream. We can't do splitting on function arguments, which * don't get this variable set. */ bool declaration; ir_variable **components; /** ralloc_parent(this->var) -- the shader's talloc context. */ void *mem_ctx; }; } /* namespace */ using namespace opt_array_splitting; /** * This class does a walk over the tree, coming up with the set of * variables that could be split by looking to see if they are arrays * that are only ever constant-index dereferenced. */ class ir_array_reference_visitor : public ir_hierarchical_visitor { public: ir_array_reference_visitor(void) { this->mem_ctx = ralloc_context(NULL); this->variable_list.make_empty(); } ~ir_array_reference_visitor(void) { ralloc_free(mem_ctx); } bool get_split_list(exec_list *instructions, bool linked); virtual ir_visitor_status visit(ir_variable *); virtual ir_visitor_status visit(ir_dereference_variable *); virtual ir_visitor_status visit_enter(ir_dereference_array *); virtual ir_visitor_status visit_enter(ir_function_signature *); variable_entry *get_variable_entry(ir_variable *var); /* List of variable_entry */ exec_list variable_list; void *mem_ctx; }; } /* namespace */ variable_entry * ir_array_reference_visitor::get_variable_entry(ir_variable *var) { assert(var); if (var->data.mode != ir_var_auto && var->data.mode != ir_var_temporary) return NULL; if (!(var->type->is_array() || var->type->is_matrix())) return NULL; /* If the array hasn't been sized yet, we can't split it. After * linking, this should be resolved. */ if (var->type->is_unsized_array()) return NULL; foreach_in_list(variable_entry, entry, &this->variable_list) { if (entry->var == var) return entry; } variable_entry *entry = new(mem_ctx) variable_entry(var); this->variable_list.push_tail(entry); return entry; } ir_visitor_status ir_array_reference_visitor::visit(ir_variable *ir) { variable_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit(ir_dereference_variable *ir) { variable_entry *entry = this->get_variable_entry(ir->var); /* If we made it to here without seeing an ir_dereference_array, * then the dereference of this array didn't have a constant index * (see the visit_continue_with_parent below), so we can't split * the variable. */ if (entry) entry->split = false; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_dereference_array *ir) { ir_dereference_variable *deref = ir->array->as_dereference_variable(); if (!deref) return visit_continue; variable_entry *entry = this->get_variable_entry(deref->var); /* If the access to the array has a variable index, we wouldn't * know which split variable this dereference should go to. */ if (!ir->array_index->as_constant()) { if (entry) entry->split = false; /* This variable indexing could come from a different array dereference * that also has variable indexing, that is, something like a[b[a[b[0]]]]. * If we return visit_continue_with_parent here for the first appearence * of a, then we can miss that b also has indirect indexing (if this is * the only place in the program where such indirect indexing into b * happens), so keep going. */ return visit_continue; } /* If the index is also array dereference, visit index. */ if (ir->array_index->as_dereference_array()) visit_enter(ir->array_index->as_dereference_array()); return visit_continue_with_parent; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_function_signature *ir) { /* We don't have logic for array-splitting function arguments, * so just look at the body instructions and not the parameter * declarations. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } bool ir_array_reference_visitor::get_split_list(exec_list *instructions, bool linked) { visit_list_elements(this, instructions); /* If the shaders aren't linked yet, we can't mess with global * declarations, which need to be matched by name across shaders. */ if (!linked) { foreach_in_list(ir_instruction, node, instructions) { ir_variable *var = node->as_variable(); if (var) { variable_entry *entry = get_variable_entry(var); if (entry) entry->remove(); } } } /* Trim out variables we found that we can't split. */ foreach_in_list_safe(variable_entry, entry, &variable_list) { if (debug) { printf("array %s@%p: decl %d, split %d\n", entry->var->name, (void *) entry->var, entry->declaration, entry->split); } if (!(entry->declaration && entry->split)) { entry->remove(); } } return !variable_list.is_empty(); } /** * This class rewrites the dereferences of arrays that have been split * to use the newly created ir_variables for each component. */ class ir_array_splitting_visitor : public ir_rvalue_visitor { public: ir_array_splitting_visitor(exec_list *vars) { this->variable_list = vars; } virtual ~ir_array_splitting_visitor() { } virtual ir_visitor_status visit_leave(ir_assignment *); void split_deref(ir_dereference **deref); void handle_rvalue(ir_rvalue **rvalue); variable_entry *get_splitting_entry(ir_variable *var); exec_list *variable_list; }; variable_entry * ir_array_splitting_visitor::get_splitting_entry(ir_variable *var) { assert(var); foreach_in_list(variable_entry, entry, this->variable_list) { if (entry->var == var) { return entry; } } return NULL; } void ir_array_splitting_visitor::split_deref(ir_dereference **deref) { ir_dereference_array *deref_array = (*deref)->as_dereference_array(); if (!deref_array) return; ir_dereference_variable *deref_var = deref_array->array->as_dereference_variable(); if (!deref_var) return; ir_variable *var = deref_var->var; variable_entry *entry = get_splitting_entry(var); if (!entry) return; ir_constant *constant = deref_array->array_index->as_constant(); assert(constant); if (constant->value.i[0] >= 0 && constant->value.i[0] < (int)entry->size) { *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[constant->value.i[0]]); } else { /* There was a constant array access beyond the end of the * array. This might have happened due to constant folding * after the initial parse. This produces an undefined value, * but shouldn't crash. Just give them an uninitialized * variable. */ ir_variable *temp = new(entry->mem_ctx) ir_variable(deref_array->type, "undef", ir_var_temporary); entry->components[0]->insert_before(temp); *deref = new(entry->mem_ctx) ir_dereference_variable(temp); } } void ir_array_splitting_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; split_deref(&deref); *rvalue = deref; } ir_visitor_status ir_array_splitting_visitor::visit_leave(ir_assignment *ir) { /* The normal rvalue visitor skips the LHS of assignments, but we * need to process those just the same. */ ir_rvalue *lhs = ir->lhs; handle_rvalue(&lhs); ir->lhs = lhs->as_dereference(); ir->lhs->accept(this); handle_rvalue(&ir->rhs); ir->rhs->accept(this); if (ir->condition) { handle_rvalue(&ir->condition); ir->condition->accept(this); } return visit_continue; } bool optimize_split_arrays(exec_list *instructions, bool linked) { ir_array_reference_visitor refs; if (!refs.get_split_list(instructions, linked)) return false; void *mem_ctx = ralloc_context(NULL); /* Replace the decls of the arrays to be split with their split * components. */ foreach_in_list(variable_entry, entry, &refs.variable_list) { const struct glsl_type *type = entry->var->type; const struct glsl_type *subtype; if (type->is_matrix()) subtype = type->column_type(); else subtype = type->fields.array; entry->mem_ctx = ralloc_parent(entry->var); entry->components = ralloc_array(mem_ctx, ir_variable *, entry->size); for (unsigned int i = 0; i < entry->size; i++) { const char *name = ralloc_asprintf(mem_ctx, "%s_%d", entry->var->name, i); entry->components[i] = new(entry->mem_ctx) ir_variable(subtype, name, ir_var_temporary); entry->var->insert_before(entry->components[i]); } entry->var->remove(); } ir_array_splitting_visitor split(&refs.variable_list); visit_list_elements(&split, instructions); if (debug) _mesa_print_ir(stdout, instructions, NULL); ralloc_free(mem_ctx); return true; } <commit_msg>glsl: Split arrays even in the presence of whole-array copies.<commit_after>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file opt_array_splitting.cpp * * If an array is always dereferenced with a constant index, then * split it apart into its elements, making it more amenable to other * optimization passes. * * This skips uniform/varying arrays, which would need careful * handling due to their ir->location fields tying them to the GL API * and other shader stages. */ #include "ir.h" #include "ir_visitor.h" #include "ir_rvalue_visitor.h" #include "compiler/glsl_types.h" static bool debug = false; namespace { namespace opt_array_splitting { class variable_entry : public exec_node { public: variable_entry(ir_variable *var) { this->var = var; this->split = true; this->declaration = false; this->components = NULL; this->mem_ctx = NULL; if (var->type->is_array()) this->size = var->type->length; else this->size = var->type->matrix_columns; } ir_variable *var; /* The key: the variable's pointer. */ unsigned size; /* array length or matrix columns */ /** Whether this array should be split or not. */ bool split; /* If the variable had a decl we can work with in the instruction * stream. We can't do splitting on function arguments, which * don't get this variable set. */ bool declaration; ir_variable **components; /** ralloc_parent(this->var) -- the shader's talloc context. */ void *mem_ctx; }; } /* namespace */ using namespace opt_array_splitting; /** * This class does a walk over the tree, coming up with the set of * variables that could be split by looking to see if they are arrays * that are only ever constant-index dereferenced. */ class ir_array_reference_visitor : public ir_hierarchical_visitor { public: ir_array_reference_visitor(void) { this->mem_ctx = ralloc_context(NULL); this->variable_list.make_empty(); this->in_whole_array_copy = false; } ~ir_array_reference_visitor(void) { ralloc_free(mem_ctx); } bool get_split_list(exec_list *instructions, bool linked); virtual ir_visitor_status visit(ir_variable *); virtual ir_visitor_status visit(ir_dereference_variable *); virtual ir_visitor_status visit_enter(ir_assignment *); virtual ir_visitor_status visit_leave(ir_assignment *); virtual ir_visitor_status visit_enter(ir_dereference_array *); virtual ir_visitor_status visit_enter(ir_function_signature *); variable_entry *get_variable_entry(ir_variable *var); /* List of variable_entry */ exec_list variable_list; void *mem_ctx; bool in_whole_array_copy; }; } /* namespace */ variable_entry * ir_array_reference_visitor::get_variable_entry(ir_variable *var) { assert(var); if (var->data.mode != ir_var_auto && var->data.mode != ir_var_temporary) return NULL; if (!(var->type->is_array() || var->type->is_matrix())) return NULL; /* If the array hasn't been sized yet, we can't split it. After * linking, this should be resolved. */ if (var->type->is_unsized_array()) return NULL; foreach_in_list(variable_entry, entry, &this->variable_list) { if (entry->var == var) return entry; } variable_entry *entry = new(mem_ctx) variable_entry(var); this->variable_list.push_tail(entry); return entry; } ir_visitor_status ir_array_reference_visitor::visit(ir_variable *ir) { variable_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_assignment *ir) { in_whole_array_copy = ir->lhs->type->is_array() && ir->whole_variable_written(); return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit_leave(ir_assignment *ir) { in_whole_array_copy = false; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit(ir_dereference_variable *ir) { variable_entry *entry = this->get_variable_entry(ir->var); /* Allow whole-array assignments on the LHS. We can split those * by "unrolling" the assignment into component-wise assignments. */ if (in_assignee && in_whole_array_copy) return visit_continue; /* If we made it to here without seeing an ir_dereference_array, * then the dereference of this array didn't have a constant index * (see the visit_continue_with_parent below), so we can't split * the variable. */ if (entry) entry->split = false; return visit_continue; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_dereference_array *ir) { ir_dereference_variable *deref = ir->array->as_dereference_variable(); if (!deref) return visit_continue; variable_entry *entry = this->get_variable_entry(deref->var); /* If the access to the array has a variable index, we wouldn't * know which split variable this dereference should go to. */ if (!ir->array_index->as_constant()) { if (entry) entry->split = false; /* This variable indexing could come from a different array dereference * that also has variable indexing, that is, something like a[b[a[b[0]]]]. * If we return visit_continue_with_parent here for the first appearence * of a, then we can miss that b also has indirect indexing (if this is * the only place in the program where such indirect indexing into b * happens), so keep going. */ return visit_continue; } /* If the index is also array dereference, visit index. */ if (ir->array_index->as_dereference_array()) visit_enter(ir->array_index->as_dereference_array()); return visit_continue_with_parent; } ir_visitor_status ir_array_reference_visitor::visit_enter(ir_function_signature *ir) { /* We don't have logic for array-splitting function arguments, * so just look at the body instructions and not the parameter * declarations. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } bool ir_array_reference_visitor::get_split_list(exec_list *instructions, bool linked) { visit_list_elements(this, instructions); /* If the shaders aren't linked yet, we can't mess with global * declarations, which need to be matched by name across shaders. */ if (!linked) { foreach_in_list(ir_instruction, node, instructions) { ir_variable *var = node->as_variable(); if (var) { variable_entry *entry = get_variable_entry(var); if (entry) entry->remove(); } } } /* Trim out variables we found that we can't split. */ foreach_in_list_safe(variable_entry, entry, &variable_list) { if (debug) { printf("array %s@%p: decl %d, split %d\n", entry->var->name, (void *) entry->var, entry->declaration, entry->split); } if (!(entry->declaration && entry->split)) { entry->remove(); } } return !variable_list.is_empty(); } /** * This class rewrites the dereferences of arrays that have been split * to use the newly created ir_variables for each component. */ class ir_array_splitting_visitor : public ir_rvalue_visitor { public: ir_array_splitting_visitor(exec_list *vars) { this->variable_list = vars; } virtual ~ir_array_splitting_visitor() { } virtual ir_visitor_status visit_leave(ir_assignment *); void split_deref(ir_dereference **deref); void handle_rvalue(ir_rvalue **rvalue); variable_entry *get_splitting_entry(ir_variable *var); exec_list *variable_list; }; variable_entry * ir_array_splitting_visitor::get_splitting_entry(ir_variable *var) { assert(var); foreach_in_list(variable_entry, entry, this->variable_list) { if (entry->var == var) { return entry; } } return NULL; } void ir_array_splitting_visitor::split_deref(ir_dereference **deref) { ir_dereference_array *deref_array = (*deref)->as_dereference_array(); if (!deref_array) return; ir_dereference_variable *deref_var = deref_array->array->as_dereference_variable(); if (!deref_var) return; ir_variable *var = deref_var->var; variable_entry *entry = get_splitting_entry(var); if (!entry) return; ir_constant *constant = deref_array->array_index->as_constant(); assert(constant); if (constant->value.i[0] >= 0 && constant->value.i[0] < (int)entry->size) { *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[constant->value.i[0]]); } else { /* There was a constant array access beyond the end of the * array. This might have happened due to constant folding * after the initial parse. This produces an undefined value, * but shouldn't crash. Just give them an uninitialized * variable. */ ir_variable *temp = new(entry->mem_ctx) ir_variable(deref_array->type, "undef", ir_var_temporary); entry->components[0]->insert_before(temp); *deref = new(entry->mem_ctx) ir_dereference_variable(temp); } } void ir_array_splitting_visitor::handle_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; split_deref(&deref); *rvalue = deref; } ir_visitor_status ir_array_splitting_visitor::visit_leave(ir_assignment *ir) { /* The normal rvalue visitor skips the LHS of assignments, but we * need to process those just the same. */ ir_rvalue *lhs = ir->lhs; /* "Unroll" any whole array assignments, creating assignments for * each array element. Then, do splitting on each new assignment. */ if (lhs->type->is_array() && ir->whole_variable_written() && get_splitting_entry(ir->whole_variable_written())) { void *mem_ctx = ralloc_parent(ir); for (unsigned i = 0; i < lhs->type->length; i++) { ir_rvalue *lhs_i = new(mem_ctx) ir_dereference_array(ir->lhs->clone(mem_ctx, NULL), new(mem_ctx) ir_constant(i)); ir_rvalue *rhs_i = new(mem_ctx) ir_dereference_array(ir->rhs->clone(mem_ctx, NULL), new(mem_ctx) ir_constant(i)); ir_rvalue *condition_i = ir->condition ? ir->condition->clone(mem_ctx, NULL) : NULL; ir_assignment *assign_i = new(mem_ctx) ir_assignment(lhs_i, rhs_i, condition_i); ir->insert_before(assign_i); assign_i->accept(this); } ir->remove(); return visit_continue; } handle_rvalue(&lhs); ir->lhs = lhs->as_dereference(); ir->lhs->accept(this); handle_rvalue(&ir->rhs); ir->rhs->accept(this); if (ir->condition) { handle_rvalue(&ir->condition); ir->condition->accept(this); } return visit_continue; } bool optimize_split_arrays(exec_list *instructions, bool linked) { ir_array_reference_visitor refs; if (!refs.get_split_list(instructions, linked)) return false; void *mem_ctx = ralloc_context(NULL); /* Replace the decls of the arrays to be split with their split * components. */ foreach_in_list(variable_entry, entry, &refs.variable_list) { const struct glsl_type *type = entry->var->type; const struct glsl_type *subtype; if (type->is_matrix()) subtype = type->column_type(); else subtype = type->fields.array; entry->mem_ctx = ralloc_parent(entry->var); entry->components = ralloc_array(mem_ctx, ir_variable *, entry->size); for (unsigned int i = 0; i < entry->size; i++) { const char *name = ralloc_asprintf(mem_ctx, "%s_%d", entry->var->name, i); entry->components[i] = new(entry->mem_ctx) ir_variable(subtype, name, ir_var_temporary); entry->var->insert_before(entry->components[i]); } entry->var->remove(); } ir_array_splitting_visitor split(&refs.variable_list); visit_list_elements(&split, instructions); if (debug) _mesa_print_ir(stdout, instructions, NULL); ralloc_free(mem_ctx); return true; } <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "HashTable.h" #include "../condor_daemon_core.V6/condor_daemon_core.h" #include "scheduler.h" #include "proc.h" #include "MyString.h" #include "dedicated_scheduler.h" #include "grid_universe.h" #include "simplelist.h" #include "list.h" #include "schedd_api.h" #include "tdman.h" //#include "condor_crontab.h" template class SimpleList<TransferRequest*>; template class HashTable<MyString, TransferRequest*>; template class HashTable<MyString, JobFile>; template class List<FileInfo>; template class Item<FileInfo>; class Shadow; template class HashTable<int, int>; template class HashBucket<int,int>; template class HashTable<int, shadow_rec *>; template class HashBucket<int,shadow_rec *>; template class HashTable<HashKey, match_rec *>; template class HashTable<PROC_ID, match_rec *>; template class HashBucket<HashKey,match_rec *>; template class HashTable<PROC_ID, shadow_rec *>; template class HashBucket<PROC_ID,shadow_rec *>; template class HashTable<PROC_ID, ClassAd *>; template class HashBucket<PROC_ID, ClassAd *>; //template class HashTable<PROC_ID, CronTab *>; //template class HashBucket<PROC_ID, CronTab *>; template class HashTable<UserIdentity, GridJobCounts>; template class HashBucket<UserIdentity, GridJobCounts>; template class Queue<shadow_rec*>; template class Queue<ContactStartdArgs*>; template class List<shadow_rec*>; template class Item<shadow_rec*>; template class SimpleList<PROC_ID>; template class ExtArray<MyString*>; template class ExtArray<bool>; template class ExtArray<PROC_ID>; template class ExtArray<OwnerData>; template class SimpleList<Shadow*>; template class HashTable<int, ExtArray<PROC_ID> *>; template class HashTable<MyString, TransferDaemon*>; template class HashBucket<MyString, TransferDaemon*>; template class HashTable<MyString, MyString>; template class HashBucket<MyString, MyString>; template class HashTable<long, TransferDaemon*>; template class HashBucket<long, TransferDaemon*>; // for condor-G template class HashTable<MyString,GridUniverseLogic::gman_node_t *>; // for MPI (or parallel) use: template class ExtArray<match_rec*>; template class ExtArray<MRecArray*>; template class ExtArray<ClassAd*>; template class HashTable<int,AllocationNode*>; template class HashBucket<int,AllocationNode*>; template class List<ClassAd>; template class Item<ClassAd>; template class Queue<PROC_ID>; // You'd think we'd need to instantiate a HashTable and HashBucket for // <HashKey, ClassAd*> here, but those are already instantiated in // classad_log.C in the c++_util_lib (not in c++_util_instantiate.C // where you'd expect to find it *sigh*) // schedd_api template class HashTable<int, ScheddTransaction*>; template class HashTable<PROC_ID, Job*>; <commit_msg>removed redundant template instantiations. everything removed was already instantiated in c++_util_instantiate.C.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "HashTable.h" #include "../condor_daemon_core.V6/condor_daemon_core.h" #include "scheduler.h" #include "proc.h" #include "MyString.h" #include "dedicated_scheduler.h" #include "grid_universe.h" #include "simplelist.h" #include "list.h" #include "schedd_api.h" #include "tdman.h" //#include "condor_crontab.h" template class SimpleList<TransferRequest*>; template class HashTable<MyString, TransferRequest*>; template class HashTable<MyString, JobFile>; template class List<FileInfo>; template class Item<FileInfo>; class Shadow; template class HashTable<int, int>; template class HashBucket<int,int>; template class HashTable<int, shadow_rec *>; template class HashBucket<int,shadow_rec *>; template class HashTable<HashKey, match_rec *>; template class HashTable<PROC_ID, match_rec *>; template class HashBucket<HashKey,match_rec *>; template class HashTable<PROC_ID, shadow_rec *>; template class HashBucket<PROC_ID,shadow_rec *>; template class HashTable<PROC_ID, ClassAd *>; template class HashBucket<PROC_ID, ClassAd *>; //template class HashTable<PROC_ID, CronTab *>; //template class HashBucket<PROC_ID, CronTab *>; template class HashTable<UserIdentity, GridJobCounts>; template class HashBucket<UserIdentity, GridJobCounts>; template class Queue<shadow_rec*>; template class Queue<ContactStartdArgs*>; template class List<shadow_rec*>; template class Item<shadow_rec*>; template class SimpleList<PROC_ID>; template class ExtArray<MyString*>; template class ExtArray<bool>; template class ExtArray<OwnerData>; template class SimpleList<Shadow*>; template class HashTable<int, ExtArray<PROC_ID> *>; template class HashTable<MyString, TransferDaemon*>; template class HashBucket<MyString, TransferDaemon*>; template class HashTable<long, TransferDaemon*>; template class HashBucket<long, TransferDaemon*>; // for condor-G template class HashTable<MyString,GridUniverseLogic::gman_node_t *>; // for MPI (or parallel) use: template class ExtArray<match_rec*>; template class ExtArray<MRecArray*>; template class ExtArray<ClassAd*>; template class HashTable<int,AllocationNode*>; template class HashBucket<int,AllocationNode*>; template class List<ClassAd>; template class Item<ClassAd>; template class Queue<PROC_ID>; // You'd think we'd need to instantiate a HashTable and HashBucket for // <HashKey, ClassAd*> here, but those are already instantiated in // classad_log.C in the c++_util_lib (not in c++_util_instantiate.C // where you'd expect to find it *sigh*) // schedd_api template class HashTable<int, ScheddTransaction*>; template class HashTable<PROC_ID, Job*>; <|endoftext|>
<commit_before> #define _ALL_SOURCE #include <stdio.h> #include <filehdr.h> #include <aouthdr.h> #include <model.h> #include <magic.h> #include <nlist.h> #include "condor_debug.h" #include "_condor_fix_resource.h" #include "types.h" #include "proto.h" #include <fcntl.h> #include <unistd.h> #include <string.h> extern "C" { int nlist( char *FileName, struct nlist *N1 ); } int magic_check( char *a_out ) { int exec_fd = -1; struct header exec_header; struct som_exec_auxhdr hpux_header; int nbytes; if ( (exec_fd=open(a_out,O_RDONLY)) < 0) { dprintf(D_ALWAYS,"error opening executeable file %s\n",a_out); return(-1); } nbytes = read(exec_fd, (char *)&exec_header, sizeof( exec_header) ); if ( nbytes != sizeof( exec_header) ) { dprintf(D_ALWAYS,"read executeable main header error \n"); close(exec_fd); return(-1); } close(exec_fd); if ( exec_header.a_magic != SHARE_MAGIC ) { dprintf(D_ALWAYS,"EXECUTEABLE %s HAS BAD MAGIC NUMBER\n",a_out); return -1; } /**** #define MYSYS 0x20B // this is for g++ installation bug : dhruba if ( exec_header.system_id != MYSYS ) { dprintf(D_ALWAYS,"EXECUTEABLE %s NOT COMPILED FOR THIS ARCHITECTURE: system_id = %d\n",a_out,exec_header.system_id); return -1; } ***********/ return 0; } /* Check to see that the checkpoint file is linked with the Condor library by looking for the symbol "_START". */ int symbol_main_check( char *name ) { int status; struct nlist nl[2]; nl[0].n_name = "_START"; nl[1].n_name = ""; status = nlist( name, nl); /* Return TRUE even if nlist reports an error because the executeable * may have simply been stripped by the user */ if ( status < 0 ) { dprintf(D_ALWAYS,"Error: nlist returns %d, errno=%d\n",status,errno); return 0; } if ( nl[0].n_type == 0 ) { dprintf(D_ALWAYS,"No symbol _START found in executeable %s\n",name); return -1; } return 0; } int calc_hdr_blocks() { return (sizeof(struct header) + sizeof(struct som_exec_auxhdr) + 1023) / 1024; } int calc_text_blocks( char *a_out ) { int exec_fd = -1; struct header exec_header; struct som_exec_auxhdr hpux_header; int nbytes; if ( (exec_fd=open(a_out,O_RDONLY)) < 0) { printf("error opening file\n"); return(-1); } nbytes = read(exec_fd, (char *)&exec_header, sizeof( exec_header) ); if ( nbytes != sizeof( exec_header) ) { dprintf(D_ALWAYS,"reading executeable %s main header error \n",a_out); close(exec_fd); return(-1); } nbytes = read(exec_fd, (char *)&hpux_header, sizeof( hpux_header) ); if ( nbytes != sizeof( hpux_header) ) { dprintf(D_ALWAYS,"read executeable %s hpux header error \n",a_out); close(exec_fd); return(-1); } close(exec_fd); if ( hpux_header.som_auxhdr.type != HPUX_AUX_ID ) { dprintf(D_ALWAYS,"in executeable %s, hpux header does not immediately follow executeable header!\n",a_out); return(-1); } return hpux_header.exec_tsize / 1024; } <commit_msg>initial HPUX10 support<commit_after> #define _ALL_SOURCE #include <stdio.h> #include <filehdr.h> #include <aouthdr.h> #include <model.h> #include <magic.h> #include <nlist.h> #include "condor_debug.h" #include "_condor_fix_resource.h" #include "types.h" #include "proto.h" #include <fcntl.h> #include <unistd.h> #include <string.h> extern "C" { #ifdef HPUX10 int nlist( const char *FileName, struct nlist *N1 ); #else int nlist( char *FileName, struct nlist *N1 ); #endif } int magic_check( char *a_out ) { int exec_fd = -1; struct header exec_header; struct som_exec_auxhdr hpux_header; int nbytes; if ( (exec_fd=open(a_out,O_RDONLY)) < 0) { dprintf(D_ALWAYS,"error opening executeable file %s\n",a_out); return(-1); } nbytes = read(exec_fd, (char *)&exec_header, sizeof( exec_header) ); if ( nbytes != sizeof( exec_header) ) { dprintf(D_ALWAYS,"read executeable main header error \n"); close(exec_fd); return(-1); } close(exec_fd); if ( exec_header.a_magic != SHARE_MAGIC ) { dprintf(D_ALWAYS,"EXECUTEABLE %s HAS BAD MAGIC NUMBER\n",a_out); return -1; } /**** #define MYSYS 0x20B // this is for g++ installation bug : dhruba if ( exec_header.system_id != MYSYS ) { dprintf(D_ALWAYS,"EXECUTEABLE %s NOT COMPILED FOR THIS ARCHITECTURE: system_id = %d\n",a_out,exec_header.system_id); return -1; } ***********/ return 0; } /* Check to see that the checkpoint file is linked with the Condor library by looking for the symbol "_START". */ int symbol_main_check( char *name ) { int status; struct nlist nl[2]; nl[0].n_name = "_START"; nl[1].n_name = ""; status = nlist( name, nl); /* Return TRUE even if nlist reports an error because the executeable * may have simply been stripped by the user */ if ( status < 0 ) { dprintf(D_ALWAYS,"Error: nlist returns %d, errno=%d\n",status,errno); return 0; } if ( nl[0].n_type == 0 ) { dprintf(D_ALWAYS,"No symbol _START found in executeable %s\n",name); return -1; } return 0; } int calc_hdr_blocks() { return (sizeof(struct header) + sizeof(struct som_exec_auxhdr) + 1023) / 1024; } int calc_text_blocks( char *a_out ) { int exec_fd = -1; struct header exec_header; struct som_exec_auxhdr hpux_header; int nbytes; if ( (exec_fd=open(a_out,O_RDONLY)) < 0) { printf("error opening file\n"); return(-1); } nbytes = read(exec_fd, (char *)&exec_header, sizeof( exec_header) ); if ( nbytes != sizeof( exec_header) ) { dprintf(D_ALWAYS,"reading executeable %s main header error \n",a_out); close(exec_fd); return(-1); } nbytes = read(exec_fd, (char *)&hpux_header, sizeof( hpux_header) ); if ( nbytes != sizeof( hpux_header) ) { dprintf(D_ALWAYS,"read executeable %s hpux header error \n",a_out); close(exec_fd); return(-1); } close(exec_fd); if ( hpux_header.som_auxhdr.type != HPUX_AUX_ID ) { dprintf(D_ALWAYS,"in executeable %s, hpux header does not immediately follow executeable header!\n",a_out); return(-1); } return hpux_header.exec_tsize / 1024; } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_config.h" #include "match_prefix.h" #include "param_info.h" // access to default params #include "param_info_tables.h" #include "condor_version.h" #include <stdlib.h> const char * check_configif = NULL; void PREFAST_NORETURN my_exit( int status ) { fflush( stdout ); fflush( stderr ); if ( ! status ) { clear_config(); } exit( status ); } // consume the next command line argument, otherwise return an error // note that this function MAY change the value of i // static const char * use_next_arg(const char * arg, const char * argv[], int & i) { if (argv[i+1]) { return argv[++i]; } fprintf(stderr, "-%s requires an argument\n", arg); //usage(); my_exit(1); return NULL; } int do_iftest(int /*out*/ &cTests); bool dash_verbose = false; int main(int argc, const char ** argv) { bool do_test = true; int ix = 1; while (ix < argc) { if (is_dash_arg_prefix(argv[ix], "check-if", -1)) { check_configif = use_next_arg("check-if", argv, ix); do_test = false; } else if (is_dash_arg_prefix(argv[ix], "verbose", 1)) { dash_verbose = true; } else if (is_dash_arg_prefix(argv[ix], "memory-snapshot")) { #ifdef LINUX const char * filename = "tool"; if (argv[ix+1]) filename = use_next_arg("memory-shapshot", argv, ix); char copy_smaps[300]; pid_t pid = getpid(); sprintf(copy_smaps, "cat /proc/%d/smaps > %s", pid, filename); int r = system(copy_smaps); fprintf(stdout, "%s returned %d\n", copy_smaps, r); #endif } else { fprintf(stderr, "unknown argument: %s\n", argv[ix]); my_exit(1); } ++ix; } // handle check-if to valididate config's if/else parsing and help users to write // valid if conditions. if (check_configif) { std::string err_reason; bool bb = false; bool valid = config_test_if_expression(check_configif, bb, err_reason); fprintf(stdout, "# %s: \"%s\" %s\n", valid ? "ok" : "not supported", check_configif, valid ? (bb ? "\ntrue" : "\nfalse") : err_reason.c_str()); } if (do_test) { printf("running standard config if tests\n"); int cTests = 0; int cFail = do_iftest(cTests); printf("%d failures in %d tests\n", cFail, cTests); return cFail; } return 0; } static const char * const aBoolTrue[] = { "true", "True", "TRUE", "yes", "Yes", "YES", "t", "T", "1", "1.0", "0.1", ".1", "1.", "1e1", "1e10", "2.0e10", " true ", " 1 ", }; static const char * const aBoolFalse[] = { "false", "False", "FALSE", "no", "No", "NO", "f", "F ", "0", "0.0", ".0", "0.", "0e1", "0.0e10", " false ", " 0 ", }; #define CONDOR_SERIES_VERSION "8.2" static const char * const aVerTrue[] = { "version > 6.0", "!version >" CONDOR_SERIES_VERSION, "version > 8.1.1", "version > 8.1.4", "version > 7.24.29", "version >= " CONDOR_VERSION, "version == " CONDOR_SERIES_VERSION, "version != 8.0", "version == " CONDOR_VERSION, "version <= " CONDOR_SERIES_VERSION ".9", "version <= " CONDOR_SERIES_VERSION, "version < " CONDOR_SERIES_VERSION ".9", "version < " CONDOR_SERIES_VERSION ".16", "version < 8.2.99", "version < " CONDOR_SERIES_VERSION, "version < 9.0", "version < 10.0", " VERSION < 10.0 ", " Version < 10.0" }; static const char * const aVerFalse[] = { "version < 6.0", "version < " CONDOR_SERIES_VERSION, "version < " CONDOR_VERSION, "version < 8.1.4", " version < 8.1.4", "version < 8.1.4 ", " version < 8.1.4 ", "version < 7.24.29", " ! version <= " CONDOR_VERSION, "version == 8.0", "version == 8.0.6", "version <= 8.0.5", "!version >= " CONDOR_SERIES_VERSION, "version > " CONDOR_VERSION, "version > " CONDOR_SERIES_VERSION ".16", "version > " CONDOR_SERIES_VERSION ".99", "version > " CONDOR_SERIES_VERSION, "version > 9.0", "version > 10.0", }; static const char * const aDefTrue[] = { "defined true", "defined false", "defined 1", "defined 0", "defined t", "defined f", "defined release_dir", "defined log", "defined LOG", "defined $(not_a_real_param:true)", "defined use ROLE", "defined use ROLE:", "defined use ROLE:Personal", "defined use feature", "defined use Feature:VMware", }; static const char * const aDefFalse[] = { "defined", " defined ", "defined a", "defined not_a_real_param", "defined master.not_a_real_param", "defined $(not_a_real_param)", "defined use NOT", "defined use NOT:a_real_meta", "defined use", }; static const char * const aBoolError[] = { "truthy", "falsify", "true dat", "0 0", "1 0", "1b1", }; static const char * const aVerError[] = { "version", "version ", "version 99", "version <= aaa", "version =!= 8.1", "version <> 8.1", "Version < ", "version > 1.1", "version <= 1.1", " Ver < 9.9", }; static const char * const aDefError[] = { "defined a b", "defined 11 99", "defined < 1.1", "defined use foo bar", // internal whitespace (or no :) "defined use ROLE: Personal", // internal whitespace }; static const char * const aUnsupError[] = { "1 == 0", "false == false", "foo < bar", "$(foo) < $(bar)", "\"foo\" == \"bar\"", "$(foo) == $(bar)", "$(foo) != $(bar)", }; #ifndef COUNTOF #define COUNTOF(aa) (int)(sizeof(aa)/sizeof((aa)[0])) #endif #define TEST_TABLE(aa) aa, (int)COUNTOF(aa) typedef const char * PCSTR; static const struct _test_set { const char * label; bool valid; bool result; PCSTR const * aTbl; int cTbl; } aTestSets[] = { { "bool", true, true, TEST_TABLE(aBoolTrue) }, { "bool", true, false, TEST_TABLE(aBoolFalse) }, { "version", true, true, TEST_TABLE(aVerTrue) }, { "version", true, false, TEST_TABLE(aVerFalse) }, { "defined", true, true, TEST_TABLE(aDefTrue) }, { "defined", true, false, TEST_TABLE(aDefFalse) }, { "bool", false, false, TEST_TABLE(aBoolError) }, { "version", false, false, TEST_TABLE(aVerError) }, { "version", false, false, TEST_TABLE(aDefError) }, { "complex", false, false, TEST_TABLE(aUnsupError) }, }; int do_iftest(int &cTests) { int fail_count = 0; cTests = 0; std::string err_reason; bool bb = false; for (int ixSet = 0; ixSet < (int)COUNTOF(aTestSets); ++ixSet) { const struct _test_set & tset = aTestSets[ixSet]; if (dash_verbose) { fprintf(stdout, "--- %s - expecting %s %s\n", tset.label, tset.valid ? "ok" : "unsup", tset.valid ? (tset.result ? "true" : "false") : ""); } for (int ix = 0; ix < tset.cTbl; ++ix) { ++cTests; err_reason = "bogus"; const char * cond = aTestSets[ixSet].aTbl[ix]; bool valid = config_test_if_expression(cond, bb, err_reason); if ((valid != tset.valid) || (valid && (bb != tset.result))) { ++fail_count; fprintf(stdout, "Test Failure: '%s' is (%s,%s) should be (%s,%s)\n", cond, valid ? "ok" : "unsup", bb ? "true" : "false", tset.valid ? "ok" : "unsup", tset.result ? "true" : "false" ); } else if (dash_verbose) { fprintf(stdout, "# %s: \"%s\" %s\n", valid ? "ok" : "not supported", cond, valid ? (bb ? "\ntrue" : "\nfalse") : err_reason.c_str()); } } } return fail_count; } <commit_msg>more fixes for config tests that expect version to be 8.1 ===VersionHistory:None===<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_config.h" #include "match_prefix.h" #include "param_info.h" // access to default params #include "param_info_tables.h" #include "condor_version.h" #include <stdlib.h> const char * check_configif = NULL; void PREFAST_NORETURN my_exit( int status ) { fflush( stdout ); fflush( stderr ); if ( ! status ) { clear_config(); } exit( status ); } // consume the next command line argument, otherwise return an error // note that this function MAY change the value of i // static const char * use_next_arg(const char * arg, const char * argv[], int & i) { if (argv[i+1]) { return argv[++i]; } fprintf(stderr, "-%s requires an argument\n", arg); //usage(); my_exit(1); return NULL; } int do_iftest(int /*out*/ &cTests); bool dash_verbose = false; int main(int argc, const char ** argv) { bool do_test = true; int ix = 1; while (ix < argc) { if (is_dash_arg_prefix(argv[ix], "check-if", -1)) { check_configif = use_next_arg("check-if", argv, ix); do_test = false; } else if (is_dash_arg_prefix(argv[ix], "verbose", 1)) { dash_verbose = true; } else if (is_dash_arg_prefix(argv[ix], "memory-snapshot")) { #ifdef LINUX const char * filename = "tool"; if (argv[ix+1]) filename = use_next_arg("memory-shapshot", argv, ix); char copy_smaps[300]; pid_t pid = getpid(); sprintf(copy_smaps, "cat /proc/%d/smaps > %s", pid, filename); int r = system(copy_smaps); fprintf(stdout, "%s returned %d\n", copy_smaps, r); #endif } else { fprintf(stderr, "unknown argument: %s\n", argv[ix]); my_exit(1); } ++ix; } // handle check-if to valididate config's if/else parsing and help users to write // valid if conditions. if (check_configif) { std::string err_reason; bool bb = false; bool valid = config_test_if_expression(check_configif, bb, err_reason); fprintf(stdout, "# %s: \"%s\" %s\n", valid ? "ok" : "not supported", check_configif, valid ? (bb ? "\ntrue" : "\nfalse") : err_reason.c_str()); } if (do_test) { printf("running standard config if tests\n"); int cTests = 0; int cFail = do_iftest(cTests); printf("%d failures in %d tests\n", cFail, cTests); return cFail; } return 0; } static const char * const aBoolTrue[] = { "true", "True", "TRUE", "yes", "Yes", "YES", "t", "T", "1", "1.0", "0.1", ".1", "1.", "1e1", "1e10", "2.0e10", " true ", " 1 ", }; static const char * const aBoolFalse[] = { "false", "False", "FALSE", "no", "No", "NO", "f", "F ", "0", "0.0", ".0", "0.", "0e1", "0.0e10", " false ", " 0 ", }; #define CONDOR_SERIES_VERSION "8.2" #define CONDOR_NEXT_VERSION "8.3" static const char * const aVerTrue[] = { "version > 6.0", "!version >" CONDOR_SERIES_VERSION, "version > 8.1.1", "version > 8.1.4", "version > 7.24.29", "version >= " CONDOR_VERSION, "version == " CONDOR_SERIES_VERSION, "version != 8.0", "version == " CONDOR_VERSION, "version <= " CONDOR_SERIES_VERSION ".9", "version <= " CONDOR_SERIES_VERSION, "version < " CONDOR_SERIES_VERSION ".9", "version < " CONDOR_SERIES_VERSION ".16", "version < " CONDOR_SERIES_VERSION ".99", "version < " CONDOR_NEXT_VERSION, "version < 9.0", "version < 10.0", " VERSION < 10.0 ", " Version < 10.0" }; static const char * const aVerFalse[] = { "version < 6.0", "version < " CONDOR_SERIES_VERSION, "version < " CONDOR_VERSION, "version < 8.1.4", " version < 8.1.4", "version < 8.1.4 ", " version < 8.1.4 ", "version < 7.24.29", " ! version <= " CONDOR_VERSION, "version == 8.0", "version == 8.0.6", "version <= 8.0.5", "!version >= " CONDOR_SERIES_VERSION, "version > " CONDOR_VERSION, "version > " CONDOR_SERIES_VERSION ".16", "version > " CONDOR_SERIES_VERSION ".99", "version > " CONDOR_SERIES_VERSION, "version > 9.0", "version > 10.0", }; static const char * const aDefTrue[] = { "defined true", "defined false", "defined 1", "defined 0", "defined t", "defined f", "defined release_dir", "defined log", "defined LOG", "defined $(not_a_real_param:true)", "defined use ROLE", "defined use ROLE:", "defined use ROLE:Personal", "defined use feature", "defined use Feature:VMware", }; static const char * const aDefFalse[] = { "defined", " defined ", "defined a", "defined not_a_real_param", "defined master.not_a_real_param", "defined $(not_a_real_param)", "defined use NOT", "defined use NOT:a_real_meta", "defined use", }; static const char * const aBoolError[] = { "truthy", "falsify", "true dat", "0 0", "1 0", "1b1", }; static const char * const aVerError[] = { "version", "version ", "version 99", "version <= aaa", "version =!= 8.1", "version <> 8.1", "Version < ", "version > 1.1", "version <= 1.1", " Ver < 9.9", }; static const char * const aDefError[] = { "defined a b", "defined 11 99", "defined < 1.1", "defined use foo bar", // internal whitespace (or no :) "defined use ROLE: Personal", // internal whitespace }; static const char * const aUnsupError[] = { "1 == 0", "false == false", "foo < bar", "$(foo) < $(bar)", "\"foo\" == \"bar\"", "$(foo) == $(bar)", "$(foo) != $(bar)", }; #ifndef COUNTOF #define COUNTOF(aa) (int)(sizeof(aa)/sizeof((aa)[0])) #endif #define TEST_TABLE(aa) aa, (int)COUNTOF(aa) typedef const char * PCSTR; static const struct _test_set { const char * label; bool valid; bool result; PCSTR const * aTbl; int cTbl; } aTestSets[] = { { "bool", true, true, TEST_TABLE(aBoolTrue) }, { "bool", true, false, TEST_TABLE(aBoolFalse) }, { "version", true, true, TEST_TABLE(aVerTrue) }, { "version", true, false, TEST_TABLE(aVerFalse) }, { "defined", true, true, TEST_TABLE(aDefTrue) }, { "defined", true, false, TEST_TABLE(aDefFalse) }, { "bool", false, false, TEST_TABLE(aBoolError) }, { "version", false, false, TEST_TABLE(aVerError) }, { "version", false, false, TEST_TABLE(aDefError) }, { "complex", false, false, TEST_TABLE(aUnsupError) }, }; int do_iftest(int &cTests) { int fail_count = 0; cTests = 0; std::string err_reason; bool bb = false; for (int ixSet = 0; ixSet < (int)COUNTOF(aTestSets); ++ixSet) { const struct _test_set & tset = aTestSets[ixSet]; if (dash_verbose) { fprintf(stdout, "--- %s - expecting %s %s\n", tset.label, tset.valid ? "ok" : "unsup", tset.valid ? (tset.result ? "true" : "false") : ""); } for (int ix = 0; ix < tset.cTbl; ++ix) { ++cTests; err_reason = "bogus"; const char * cond = aTestSets[ixSet].aTbl[ix]; bool valid = config_test_if_expression(cond, bb, err_reason); if ((valid != tset.valid) || (valid && (bb != tset.result))) { ++fail_count; fprintf(stdout, "Test Failure: '%s' is (%s,%s) should be (%s,%s)\n", cond, valid ? "ok" : "unsup", bb ? "true" : "false", tset.valid ? "ok" : "unsup", tset.result ? "true" : "false" ); } else if (dash_verbose) { fprintf(stdout, "# %s: \"%s\" %s\n", valid ? "ok" : "not supported", cond, valid ? (bb ? "\ntrue" : "\nfalse") : err_reason.c_str()); } } } return fail_count; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mcontentitemmodel.h" void MContentItemModel::setItemPixmap(const QPixmap &itemImage) { _itemPixmap() = itemImage; memberModified(ItemPixmap); } void MContentItemModel::setOptionalPixmap(const QPixmap& pixmap) { _optionalPixmap() = pixmap; memberModified(OptionalPixmap); } const QPixmap &MContentItemModel::optionalPixmap() const { return _optionalPixmap(); } const QPixmap &MContentItemModel::itemPixmap() const { return _itemPixmap(); } void MContentItemModel::setItemImage(const QImage &itemImage) { _itemImage() = itemImage; memberModified(ItemImage); } void MContentItemModel::setOptionalImage(const QImage& image) { _optionalImage() = image; memberModified(OptionalImage); } const QImage &MContentItemModel::optionalImage() const { return _optionalImage(); } const QImage &MContentItemModel::itemImage() const { return _itemImage(); } <commit_msg>Fixes: MB#9971 - MContentItemModel doesn't provide get/set for ItemQImage<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mcontentitemmodel.h" void MContentItemModel::setItemQImage(QImage const& itemQImage) { _itemQImage() = itemQImage; memberModified(ItemQImage); } const QImage &MContentItemModel::itemQImage() const { return _itemQImage(); } void MContentItemModel::setItemPixmap(const QPixmap &itemImage) { _itemPixmap() = itemImage; memberModified(ItemPixmap); } void MContentItemModel::setOptionalPixmap(const QPixmap& pixmap) { _optionalPixmap() = pixmap; memberModified(OptionalPixmap); } const QPixmap &MContentItemModel::optionalPixmap() const { return _optionalPixmap(); } const QPixmap &MContentItemModel::itemPixmap() const { return _itemPixmap(); } void MContentItemModel::setItemImage(const QImage &itemImage) { _itemImage() = itemImage; memberModified(ItemImage); } void MContentItemModel::setOptionalImage(const QImage& image) { _optionalImage() = image; memberModified(OptionalImage); } const QImage &MContentItemModel::optionalImage() const { return _optionalImage(); } const QImage &MContentItemModel::itemImage() const { return _itemImage(); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mdetailedlistitem.h" #include "mdetailedlistitem_p.h" #include <MImageWidget> #include <MLabel> #include <MStylableWidget> #include <QGraphicsGridLayout> #include <QGraphicsLinearLayout> MDetailedListItemPrivate::MDetailedListItemPrivate(MDetailedListItem::ItemStyle style) : q_ptr(NULL), layoutGrid(NULL), image(NULL), sideTopImage(NULL), sideBottomImage(NULL), titleLabel(NULL), subtitleLabel(NULL), sideBottomLabel(NULL), isLayoutInitialized(false), listItemStyle(style), iconStyle(MDetailedListItem::Icon) { } MDetailedListItemPrivate::~MDetailedListItemPrivate() { } void MDetailedListItemPrivate::createLayout() { Q_Q(MDetailedListItem); if (!layoutGrid) { layoutGrid = new QGraphicsGridLayout(q); layoutGrid->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); layoutGrid->setContentsMargins(0, 0, 0, 0); layoutGrid->setSpacing(0); } switch (listItemStyle) { case MDetailedListItem::IconTitleSubtitleAndTwoSideIcons: { q->titleLabelWidget()->setObjectName("CommonTitle"); q->setIconStyle(MDetailedListItem::Icon); layout()->addItem(q->imageWidget(), 0, 0, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(q->titleLabelWidget(), 0, 1, Qt::AlignLeft | Qt::AlignTop); layout()->addItem(q->subtitleLabelWidget(), 1, 1, Qt::AlignLeft | Qt::AlignBottom); layout()->addItem(new QGraphicsWidget(q), 2, 1, 1, 2); layout()->addItem(q->sideTopImageWidget(), 0, 2, Qt::AlignRight | Qt::AlignBottom); layout()->addItem(q->sideBottomImageWidget(), 1, 2, Qt::AlignRight | Qt::AlignTop); break; } case MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel: { q->titleLabelWidget()->setObjectName("CommonTitle"); q->setIconStyle(MDetailedListItem::Icon); layout()->addItem(q->imageWidget(), 0, 0, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(q->titleLabelWidget(), 0, 1, 1, 3, Qt::AlignLeft | Qt::AlignTop); layout()->addItem(q->sideTopImageWidget(), 0, 4, Qt::AlignRight | Qt::AlignBottom); layout()->addItem(q->subtitleLabelWidget(), 1, 1, 1, 2); layout()->addItem(q->sideBottomLabelWidget(), 1, 3, 1, 2); layout()->addItem(new QGraphicsWidget(q), 2, 1); break; } case MDetailedListItem::ThumbnailTitleAndTwoSideIcons: { q->titleLabelWidget()->setObjectName("CommonSingleTitle"); q->setIconStyle(MDetailedListItem::Thumbnail); layout()->addItem(q->imageWidget(), 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(q->titleLabelWidget(), 0, 1, 2, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(new QGraphicsWidget(q), 2, 1, Qt::AlignRight | Qt::AlignVCenter); QGraphicsWidget * panel = new QGraphicsWidget(q); QGraphicsLinearLayout * panelLayout = new QGraphicsLinearLayout(Qt::Vertical); panelLayout->setContentsMargins(0, 0, 0, 0); panelLayout->setSpacing(0); panel->setLayout(panelLayout); q->sideTopImageWidget()->setParentItem(panel); q->sideBottomImageWidget()->setParentItem(panel); panelLayout->addItem(q->sideTopImageWidget()); panelLayout->addItem(q->sideBottomImageWidget()); layout()->addItem(panel, 0, 2, 2, 1, Qt::AlignVCenter); break; } case MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons: { q->titleLabelWidget()->setObjectName("CommonTitle"); q->setIconStyle(MDetailedListItem::Thumbnail); layout()->addItem(q->imageWidget(), 0, 0, 3, 1); layout()->addItem(q->titleLabelWidget(), 0, 1); layout()->addItem(q->subtitleLabelWidget(), 1, 1); QGraphicsWidget * panel = new QGraphicsWidget(q); QGraphicsLinearLayout * panelLayout = new QGraphicsLinearLayout(Qt::Vertical); panelLayout->setContentsMargins(0, 0, 0, 0); panelLayout->setSpacing(0); panel->setLayout(panelLayout); q->sideTopImageWidget()->setParentItem(panel); q->sideBottomImageWidget()->setParentItem(panel); panelLayout->addItem(q->sideTopImageWidget()); panelLayout->addItem(q->sideBottomImageWidget()); layout()->addItem(panel, 0, 2, 3, 1, Qt::AlignVCenter); layout()->addItem(new QGraphicsWidget(q), 2, 1); break; } default: break; } } void MDetailedListItemPrivate::clearLayout() { if (layout()) { for (int i = 0; i < layout()->count(); i++) { QGraphicsLayoutItem *item = layoutGrid->itemAt(0); layoutGrid->removeAt(0); delete item; } image = NULL; titleLabel = NULL; subtitleLabel = NULL; sideTopImage = NULL; sideBottomImage = NULL; sideBottomLabel = NULL; } } QGraphicsGridLayout *MDetailedListItemPrivate::layout() { return layoutGrid; } void MDetailedListItemPrivate::applyIconStyle() { if (!image) return; if (iconStyle == MDetailedListItem::Thumbnail) image->setObjectName("CommonThumbnail"); else if (iconStyle == MDetailedListItem::Icon) image->setObjectName("CommonMainIcon"); } MDetailedListItem::MDetailedListItem(MDetailedListItem::ItemStyle style, QGraphicsItem *parent) : MListItem(parent), d_ptr(new MDetailedListItemPrivate(style)) { Q_D(MDetailedListItem); d->q_ptr = this; setObjectName("CommonPanel"); } MDetailedListItem::~MDetailedListItem() { delete d_ptr; } void MDetailedListItem::initLayout() { Q_D(MDetailedListItem); if (d->isLayoutInitialized) return; setLayout(createLayout()); d->isLayoutInitialized = true; } QGraphicsLayout *MDetailedListItem::createLayout() { Q_D(MDetailedListItem); clearLayout(); d->createLayout(); return d->layout(); } void MDetailedListItem::clearLayout() { Q_D(MDetailedListItem); d->clearLayout(); } void MDetailedListItem::setItemStyle(ItemStyle itemStyle) { Q_D(MDetailedListItem); if (itemStyle == d->listItemStyle) return; d->listItemStyle = itemStyle; d->isLayoutInitialized = false; initLayout(); } MDetailedListItem::ItemStyle MDetailedListItem::itemStyle() const { Q_D(const MDetailedListItem); return d->listItemStyle; } void MDetailedListItem::setIconStyle(IconStyle style) { Q_D(MDetailedListItem); if(style == d->iconStyle) return; d->iconStyle = style; d->applyIconStyle(); } MDetailedListItem::IconStyle MDetailedListItem::iconStyle() const { Q_D(const MDetailedListItem); return d->iconStyle; } void MDetailedListItem::setImageWidget(MImageWidget *image) { Q_D(MDetailedListItem); if (d->image) { if (d->layout()) for (int i = 0; i < d->layout()->count(); i++) { if (d->layout()->itemAt(i) == d->image) { d->layout()->removeAt(i); break; } } delete d->image; d->image = NULL; } if (image) { d->image = image; if (d->listItemStyle == MDetailedListItem::IconTitleSubtitleAndTwoSideIcons || d->listItemStyle == MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel) { setIconStyle(Icon); if (d->layout()) d->layout()->addItem(imageWidget(), 0, 0, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); } else if (d->listItemStyle == MDetailedListItem::ThumbnailTitleAndTwoSideIcons) { setIconStyle(Thumbnail); if (d->layout()) d->layout()->addItem(imageWidget(), 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter); } else if (d->listItemStyle == MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons) { setIconStyle(Thumbnail); if (d->layout()) d->layout()->addItem(imageWidget(), 0, 0, 3, 1); } d->applyIconStyle(); } } MImageWidget *MDetailedListItem::imageWidget() { Q_D(MDetailedListItem); if (!d->image) { d->image = new MImageWidget(this); d->applyIconStyle(); } return d->image; } MImageWidget *MDetailedListItem::sideTopImageWidget() { Q_D(MDetailedListItem); if (!d->sideTopImage) { d->sideTopImage = new MImageWidget(this); d->sideTopImage->setObjectName("CommonSubIconTop"); } return d->sideTopImage; } MImageWidget *MDetailedListItem::sideBottomImageWidget() { Q_D(MDetailedListItem); if (!d->sideBottomImage) { d->sideBottomImage = new MImageWidget(this); d->sideBottomImage->setObjectName("CommonSubIconBottom"); } return d->sideBottomImage; } MLabel *MDetailedListItem::titleLabelWidget() { Q_D(MDetailedListItem); if (!d->titleLabel) { d->titleLabel = new MLabel(this); d->titleLabel->setTextElide(true); d->titleLabel->setObjectName("CommonTitle"); } return d->titleLabel; } void MDetailedListItem::setTitle(const QString &title) { titleLabelWidget()->setText(title); } QString MDetailedListItem::title() { return titleLabelWidget()->text(); } MLabel *MDetailedListItem::subtitleLabelWidget() { Q_D(MDetailedListItem); if (!d->subtitleLabel) { d->subtitleLabel = new MLabel(this); d->subtitleLabel->setTextElide(true); d->subtitleLabel->setObjectName("CommonSubTitle"); } return d->subtitleLabel; } void MDetailedListItem::setSubtitle(const QString &subtitle) { subtitleLabelWidget()->setText(subtitle); } QString MDetailedListItem::subtitle() { return subtitleLabelWidget()->text(); } MLabel *MDetailedListItem::sideBottomLabelWidget() { Q_D(MDetailedListItem); if (!d->sideBottomLabel) { d->sideBottomLabel = new MLabel(this); d->sideBottomLabel->setTextElide(true); d->sideBottomLabel->setAlignment(Qt::AlignRight); d->sideBottomLabel->setObjectName("CommonItemInfo"); d->sideBottomLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); } return d->sideBottomLabel; } void MDetailedListItem::setSideBottomTitle(const QString &text) { sideBottomLabelWidget()->setText(text); } QString MDetailedListItem::sideBottomTitle() { return sideBottomLabelWidget()->text(); } void MDetailedListItem::resizeEvent(QGraphicsSceneResizeEvent *event) { MListItem::resizeEvent(event); initLayout(); } <commit_msg>Fixes: MDetailedListItemPrivate::clearLayout() does not remove all items from gridLayout.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mdetailedlistitem.h" #include "mdetailedlistitem_p.h" #include <MImageWidget> #include <MLabel> #include <MStylableWidget> #include <QGraphicsGridLayout> #include <QGraphicsLinearLayout> MDetailedListItemPrivate::MDetailedListItemPrivate(MDetailedListItem::ItemStyle style) : q_ptr(NULL), layoutGrid(NULL), image(NULL), sideTopImage(NULL), sideBottomImage(NULL), titleLabel(NULL), subtitleLabel(NULL), sideBottomLabel(NULL), isLayoutInitialized(false), listItemStyle(style), iconStyle(MDetailedListItem::Icon) { } MDetailedListItemPrivate::~MDetailedListItemPrivate() { } void MDetailedListItemPrivate::createLayout() { Q_Q(MDetailedListItem); if (!layoutGrid) { layoutGrid = new QGraphicsGridLayout(q); layoutGrid->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); layoutGrid->setContentsMargins(0, 0, 0, 0); layoutGrid->setSpacing(0); } switch (listItemStyle) { case MDetailedListItem::IconTitleSubtitleAndTwoSideIcons: { q->titleLabelWidget()->setObjectName("CommonTitle"); q->setIconStyle(MDetailedListItem::Icon); layout()->addItem(q->imageWidget(), 0, 0, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(q->titleLabelWidget(), 0, 1, Qt::AlignLeft | Qt::AlignTop); layout()->addItem(q->subtitleLabelWidget(), 1, 1, Qt::AlignLeft | Qt::AlignBottom); layout()->addItem(new QGraphicsWidget(q), 2, 1, 1, 2); layout()->addItem(q->sideTopImageWidget(), 0, 2, Qt::AlignRight | Qt::AlignBottom); layout()->addItem(q->sideBottomImageWidget(), 1, 2, Qt::AlignRight | Qt::AlignTop); break; } case MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel: { q->titleLabelWidget()->setObjectName("CommonTitle"); q->setIconStyle(MDetailedListItem::Icon); layout()->addItem(q->imageWidget(), 0, 0, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(q->titleLabelWidget(), 0, 1, 1, 3, Qt::AlignLeft | Qt::AlignTop); layout()->addItem(q->sideTopImageWidget(), 0, 4, Qt::AlignRight | Qt::AlignBottom); layout()->addItem(q->subtitleLabelWidget(), 1, 1, 1, 2); layout()->addItem(q->sideBottomLabelWidget(), 1, 3, 1, 2); layout()->addItem(new QGraphicsWidget(q), 2, 1); break; } case MDetailedListItem::ThumbnailTitleAndTwoSideIcons: { q->titleLabelWidget()->setObjectName("CommonSingleTitle"); q->setIconStyle(MDetailedListItem::Thumbnail); layout()->addItem(q->imageWidget(), 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(q->titleLabelWidget(), 0, 1, 2, 1, Qt::AlignLeft | Qt::AlignVCenter); layout()->addItem(new QGraphicsWidget(q), 2, 1, Qt::AlignRight | Qt::AlignVCenter); QGraphicsWidget * panel = new QGraphicsWidget(q); QGraphicsLinearLayout * panelLayout = new QGraphicsLinearLayout(Qt::Vertical); panelLayout->setContentsMargins(0, 0, 0, 0); panelLayout->setSpacing(0); panel->setLayout(panelLayout); q->sideTopImageWidget()->setParentItem(panel); q->sideBottomImageWidget()->setParentItem(panel); panelLayout->addItem(q->sideTopImageWidget()); panelLayout->addItem(q->sideBottomImageWidget()); layout()->addItem(panel, 0, 2, 2, 1, Qt::AlignVCenter); break; } case MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons: { q->titleLabelWidget()->setObjectName("CommonTitle"); q->setIconStyle(MDetailedListItem::Thumbnail); layout()->addItem(q->imageWidget(), 0, 0, 3, 1); layout()->addItem(q->titleLabelWidget(), 0, 1); layout()->addItem(q->subtitleLabelWidget(), 1, 1); QGraphicsWidget * panel = new QGraphicsWidget(q); QGraphicsLinearLayout * panelLayout = new QGraphicsLinearLayout(Qt::Vertical); panelLayout->setContentsMargins(0, 0, 0, 0); panelLayout->setSpacing(0); panel->setLayout(panelLayout); q->sideTopImageWidget()->setParentItem(panel); q->sideBottomImageWidget()->setParentItem(panel); panelLayout->addItem(q->sideTopImageWidget()); panelLayout->addItem(q->sideBottomImageWidget()); layout()->addItem(panel, 0, 2, 3, 1, Qt::AlignVCenter); layout()->addItem(new QGraphicsWidget(q), 2, 1); break; } default: break; } } void MDetailedListItemPrivate::clearLayout() { if (layout()) { while (layout()->count() > 0) { QGraphicsLayoutItem *item = layoutGrid->itemAt(0); layoutGrid->removeAt(0); delete item; } image = NULL; titleLabel = NULL; subtitleLabel = NULL; sideTopImage = NULL; sideBottomImage = NULL; sideBottomLabel = NULL; } } QGraphicsGridLayout *MDetailedListItemPrivate::layout() { return layoutGrid; } void MDetailedListItemPrivate::applyIconStyle() { if (!image) return; if (iconStyle == MDetailedListItem::Thumbnail) image->setObjectName("CommonThumbnail"); else if (iconStyle == MDetailedListItem::Icon) image->setObjectName("CommonMainIcon"); } MDetailedListItem::MDetailedListItem(MDetailedListItem::ItemStyle style, QGraphicsItem *parent) : MListItem(parent), d_ptr(new MDetailedListItemPrivate(style)) { Q_D(MDetailedListItem); d->q_ptr = this; setObjectName("CommonPanel"); } MDetailedListItem::~MDetailedListItem() { delete d_ptr; } void MDetailedListItem::initLayout() { Q_D(MDetailedListItem); if (d->isLayoutInitialized) return; setLayout(createLayout()); d->isLayoutInitialized = true; } QGraphicsLayout *MDetailedListItem::createLayout() { Q_D(MDetailedListItem); clearLayout(); d->createLayout(); return d->layout(); } void MDetailedListItem::clearLayout() { Q_D(MDetailedListItem); d->clearLayout(); } void MDetailedListItem::setItemStyle(ItemStyle itemStyle) { Q_D(MDetailedListItem); if (itemStyle == d->listItemStyle) return; d->listItemStyle = itemStyle; d->isLayoutInitialized = false; initLayout(); } MDetailedListItem::ItemStyle MDetailedListItem::itemStyle() const { Q_D(const MDetailedListItem); return d->listItemStyle; } void MDetailedListItem::setIconStyle(IconStyle style) { Q_D(MDetailedListItem); if(style == d->iconStyle) return; d->iconStyle = style; d->applyIconStyle(); } MDetailedListItem::IconStyle MDetailedListItem::iconStyle() const { Q_D(const MDetailedListItem); return d->iconStyle; } void MDetailedListItem::setImageWidget(MImageWidget *image) { Q_D(MDetailedListItem); if (d->image) { if (d->layout()) for (int i = 0; i < d->layout()->count(); i++) { if (d->layout()->itemAt(i) == d->image) { d->layout()->removeAt(i); break; } } delete d->image; d->image = NULL; } if (image) { d->image = image; if (d->listItemStyle == MDetailedListItem::IconTitleSubtitleAndTwoSideIcons || d->listItemStyle == MDetailedListItem::IconTitleSubtitleAndSideIconWithLabel) { setIconStyle(Icon); if (d->layout()) d->layout()->addItem(imageWidget(), 0, 0, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); } else if (d->listItemStyle == MDetailedListItem::ThumbnailTitleAndTwoSideIcons) { setIconStyle(Thumbnail); if (d->layout()) d->layout()->addItem(imageWidget(), 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter); } else if (d->listItemStyle == MDetailedListItem::ThumbnailTitleSubtitleAndTwoSideIcons) { setIconStyle(Thumbnail); if (d->layout()) d->layout()->addItem(imageWidget(), 0, 0, 3, 1); } d->applyIconStyle(); } } MImageWidget *MDetailedListItem::imageWidget() { Q_D(MDetailedListItem); if (!d->image) { d->image = new MImageWidget(this); d->applyIconStyle(); } return d->image; } MImageWidget *MDetailedListItem::sideTopImageWidget() { Q_D(MDetailedListItem); if (!d->sideTopImage) { d->sideTopImage = new MImageWidget(this); d->sideTopImage->setObjectName("CommonSubIconTop"); } return d->sideTopImage; } MImageWidget *MDetailedListItem::sideBottomImageWidget() { Q_D(MDetailedListItem); if (!d->sideBottomImage) { d->sideBottomImage = new MImageWidget(this); d->sideBottomImage->setObjectName("CommonSubIconBottom"); } return d->sideBottomImage; } MLabel *MDetailedListItem::titleLabelWidget() { Q_D(MDetailedListItem); if (!d->titleLabel) { d->titleLabel = new MLabel(this); d->titleLabel->setTextElide(true); d->titleLabel->setObjectName("CommonTitle"); } return d->titleLabel; } void MDetailedListItem::setTitle(const QString &title) { titleLabelWidget()->setText(title); } QString MDetailedListItem::title() { return titleLabelWidget()->text(); } MLabel *MDetailedListItem::subtitleLabelWidget() { Q_D(MDetailedListItem); if (!d->subtitleLabel) { d->subtitleLabel = new MLabel(this); d->subtitleLabel->setTextElide(true); d->subtitleLabel->setObjectName("CommonSubTitle"); } return d->subtitleLabel; } void MDetailedListItem::setSubtitle(const QString &subtitle) { subtitleLabelWidget()->setText(subtitle); } QString MDetailedListItem::subtitle() { return subtitleLabelWidget()->text(); } MLabel *MDetailedListItem::sideBottomLabelWidget() { Q_D(MDetailedListItem); if (!d->sideBottomLabel) { d->sideBottomLabel = new MLabel(this); d->sideBottomLabel->setTextElide(true); d->sideBottomLabel->setAlignment(Qt::AlignRight); d->sideBottomLabel->setObjectName("CommonItemInfo"); d->sideBottomLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); } return d->sideBottomLabel; } void MDetailedListItem::setSideBottomTitle(const QString &text) { sideBottomLabelWidget()->setText(text); } QString MDetailedListItem::sideBottomTitle() { return sideBottomLabelWidget()->text(); } void MDetailedListItem::resizeEvent(QGraphicsSceneResizeEvent *event) { MListItem::resizeEvent(event); initLayout(); } <|endoftext|>
<commit_before>/* * REnvironmentPosix.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/r_util/REnvironment.hpp> #include <algorithm> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/replace.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/ConfigUtils.hpp> #include <core/system/System.hpp> namespace core { namespace r_util { namespace { FilePath scanForRScript(const std::vector<std::string>& rScriptPaths) { // iterate over paths for (std::vector<std::string>::const_iterator it = rScriptPaths.begin(); it != rScriptPaths.end(); ++it) { FilePath rScriptPath(*it); if (rScriptPath.exists()) { // verify that the alias points to a real version of R Error error = core::system::realPath(*it, &rScriptPath); if (!error) { return rScriptPath; } else { LOG_ERROR(error); continue; } } } // didn't find it return FilePath(); } // MacOS X Specific #ifdef __APPLE__ #define kLibRFileName "libR.dylib" #define kLibraryPathEnvVariable "DYLD_LIBRARY_PATH" // no extra paths on the mac std::string extraLibraryPaths(const FilePath& ldPathsScript, const std::string& rHome) { return std::string(); } FilePath systemDefaultRScript() { // define potential paths (use same order as in conventional osx PATH) std::vector<std::string> rScriptPaths; rScriptPaths.push_back("/opt/local/bin/R"); rScriptPaths.push_back("/usr/bin/R"); rScriptPaths.push_back("/usr/local/bin/R"); return scanForRScript(rScriptPaths); } bool getRHomeAndLibPath(const FilePath& rScriptPath, const config_utils::Variables& scriptVars, std::string* pRHome, std::string* pRLibPath, std::string* pErrMsg) { config_utils::Variables::const_iterator it = scriptVars.find("R_HOME_DIR"); if (it != scriptVars.end()) { // get R home *pRHome = it->second; // get R lib path (probe subdiretories if necessary) FilePath libPath = FilePath(*pRHome).complete("lib"); // check for dylib in lib and lib/x86_64 if (libPath.complete(kLibRFileName).exists()) { *pRLibPath = libPath.absolutePath(); return true; } else if (libPath.complete("x86_64/" kLibRFileName).exists()) { *pRLibPath = libPath.complete("x86_64").absolutePath(); return true; } else { *pErrMsg = "Unable to find " kLibRFileName " in expected locations" "within R Home directory " + *pRHome; LOG_ERROR_MESSAGE(*pErrMsg); return false; } } else { *pErrMsg = "Unable to find R_HOME_DIR in " + rScriptPath.absolutePath(); LOG_ERROR_MESSAGE(*pErrMsg); return false; } } // Linux specific #else #define kLibRFileName "libR.so" #define kLibraryPathEnvVariable "LD_LIBRARY_PATH" // extra paths from R (for rjava) on linux std::string extraLibraryPaths(const FilePath& ldPathsScript, const std::string& rHome) { // verify that script exists if (!ldPathsScript.exists()) { LOG_WARNING_MESSAGE("r-ldpaths script not found at " + ldPathsScript.absolutePath()); return std::string(); } // run script to capture paths std::string libraryPaths; std::string command = ldPathsScript.absolutePath() + " " + rHome; Error error = system::captureCommand(command, &libraryPaths); if (error) LOG_ERROR(error); boost::algorithm::trim(libraryPaths); return libraryPaths; } FilePath systemDefaultRScript() { // ask system which R to use std::string whichOutput; Error error = core::system::captureCommand("which R", &whichOutput); if (error) { LOG_ERROR(error); return FilePath(); } boost::algorithm::trim(whichOutput); // check for nothing returned if (whichOutput.empty()) { // try scanning known locations std::vector<std::string> rScriptPaths; rScriptPaths.push_back("/usr/local/bin/R"); rScriptPaths.push_back("/usr/bin/R"); FilePath rScriptPath = scanForRScript(rScriptPaths); if (rScriptPath.empty()) return FilePath(); else whichOutput = rScriptPath.absolutePath(); } // verify that the alias points to a real version of R FilePath rBinaryPath; error = core::system::realPath(whichOutput, &rBinaryPath); if (error) { LOG_ERROR(error); return FilePath(); } // check for real path doesn't exist if (!rBinaryPath.exists()) { LOG_ERROR_MESSAGE("Real path of R script does not exist (" + rBinaryPath.absolutePath() + ")"); return FilePath(); } // got a valid R binary return rBinaryPath; } bool getRHomeAndLibPath(const FilePath& rScriptPath, const config_utils::Variables& scriptVars, std::string* pRHome, std::string* pRLibPath, std::string* pErrMsg) { // eliminate a potentially conflicting R_HOME before calling R RHOME" // (the normal semantics of invoking the R script are that it overwrites // R_HOME and prints a warning -- this warning is co-mingled with the // output of "R RHOME" and messes up our parsing) core::system::setenv("R_HOME", ""); // run R script to detect R home std::string rHomeOutput; std::string command = rScriptPath.absolutePath() + " RHOME"; Error error = core::system::captureCommand(command, &rHomeOutput); if (error) { LOG_ERROR(error); *pErrMsg = "Error running R (" + rScriptPath.absolutePath() + "): " + error.summary(); return false; } else { boost::algorithm::trim(rHomeOutput); *pRHome = rHomeOutput; *pRLibPath = FilePath(*pRHome).complete("lib").absolutePath(); return true; } } #endif bool validateREnvironment(const EnvironmentVars& vars, const FilePath& rLibPath, std::string* pErrMsg) { // first extract paths FilePath rHomePath, rSharePath, rIncludePath, rDocPath, rLibRPath; for (EnvironmentVars::const_iterator it = vars.begin(); it != vars.end(); ++it) { if (it->first == "R_HOME") rHomePath = FilePath(it->second); else if (it->first == "R_SHARE_DIR") rSharePath = FilePath(it->second); else if (it->first == "R_INCLUDE_DIR") rIncludePath = FilePath(it->second); else if (it->first == "R_DOC_DIR") rDocPath = FilePath(it->second); } // resolve libR path rLibRPath = rLibPath.complete(kLibRFileName); // validate required paths (if these don't exist then rsession won't // be able start up) if (!rHomePath.exists()) { *pErrMsg = "R Home path (" + rHomePath.absolutePath() + ") not found"; return false; } else if (!rLibPath.exists()) { *pErrMsg = "R lib path (" + rLibPath.absolutePath() + ") not found"; return false; } else if (!rLibRPath.exists()) { *pErrMsg = "R shared library (" + rLibRPath.absolutePath() + ") " "not found. If this is a custom build of R, was it " "built with the --enable-R-shlib option?"; return false; } else if (!rDocPath.exists()) { *pErrMsg = "R doc dir (" + rDocPath.absolutePath() + ") not found."; return false; } // log warnings for other missing paths (rsession can still start but // won't be able to find these env variables) if (!rSharePath.exists()) { LOG_WARNING_MESSAGE("R share path (" + rSharePath.absolutePath() + ") not found"); } if (!rIncludePath.exists()) { LOG_WARNING_MESSAGE("R include path (" + rIncludePath.absolutePath() + ") not found"); } return true; } // resolve an R path which has been parsed from the R bash script. If // R is running out of the source directory (and was thus never installed) // then the values for R_DOC_DIR, etc. will contain unexpanded references // to the R_HOME_DIR, so we expand these if they are present. std::string resolveRPath(const FilePath& rHomePath, const std::string& path) { std::string resolvedPath = path; boost::algorithm::replace_all(resolvedPath, "${R_HOME_DIR}", rHomePath.absolutePath()); return resolvedPath; } } // anonymous namespace bool detectREnvironment(const FilePath& ldPathsScript, EnvironmentVars* pVars, std::string* pErrMsg) { return detectREnvironment(FilePath(), ldPathsScript, std::string(), pVars, pErrMsg); } bool detectREnvironment(const FilePath& whichRScript, const FilePath& ldPathsScript, const std::string& ldLibraryPath, EnvironmentVars* pVars, std::string* pErrMsg) { // if there is a which R script override then validate it (but only // log a warning then move on to the system default) FilePath rScriptPath; if (!whichRScript.empty()) { // but warn (and ignore) if it doesn't exist if (!whichRScript.exists()) { LOG_WARNING_MESSAGE("Override for which R (" + whichRScript.absolutePath() + ") does not exist (ignoring)"); } // also warn and ignore if it is a directory else if (whichRScript.isDirectory()) { LOG_WARNING_MESSAGE("Override for which R (" + whichRScript.absolutePath() + ") is a directory rather than a file (ignoring)"); } // otherwise set it else { rScriptPath = whichRScript; } } // if don't have an override (or it was invalid) then use system default if (rScriptPath.empty()) rScriptPath = systemDefaultRScript(); // bail if not found if (!rScriptPath.exists()) { LOG_ERROR(pathNotFoundError(rScriptPath.absolutePath(), ERROR_LOCATION)); *pErrMsg = "R binary (" + rScriptPath.absolutePath() + ") not found"; return false; } // scan R script for other locations and append them to our vars config_utils::Variables scriptVars; Error error = config_utils::extractVariables(rScriptPath, &scriptVars); if (error) { LOG_ERROR(error); *pErrMsg = "Error reading R script (" + rScriptPath.absolutePath() + "), " + error.summary(); return false; } // get r home path std::string rHome, rLib; if (!getRHomeAndLibPath(rScriptPath, scriptVars, &rHome, &rLib, pErrMsg)) return false; // validate: error if we got no output if (rHome.empty()) { *pErrMsg = "Unable to determine R home directory"; LOG_ERROR(systemError(boost::system::errc::not_supported, *pErrMsg, ERROR_LOCATION)); return false; } // validate: error if `R RHOME` yields file that doesn't exist FilePath rHomePath(rHome); if (!rHomePath.exists()) { *pErrMsg = "R home path (" + rHome + ") not found"; LOG_ERROR(pathNotFoundError(*pErrMsg, ERROR_LOCATION)); return false; } // set R home path pVars->push_back(std::make_pair("R_HOME", rHomePath.absolutePath())); // set other environment values pVars->push_back(std::make_pair("R_SHARE_DIR", resolveRPath(rHomePath, scriptVars["R_SHARE_DIR"]))); pVars->push_back(std::make_pair("R_INCLUDE_DIR", resolveRPath(rHomePath, scriptVars["R_INCLUDE_DIR"]))); pVars->push_back(std::make_pair("R_DOC_DIR", resolveRPath(rHomePath, scriptVars["R_DOC_DIR"]))); // determine library path (existing + r lib dir + r extra lib dirs) FilePath rLibPath(rLib); std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable); if (!libraryPath.empty()) libraryPath.append(":"); libraryPath.append(ldLibraryPath); if (!libraryPath.empty()) libraryPath.append(":"); libraryPath.append(rLibPath.absolutePath()); std::string extraPaths = extraLibraryPaths(ldPathsScript, rHomePath.absolutePath()); if (!extraPaths.empty()) libraryPath.append(":" + extraPaths); pVars->push_back(std::make_pair(kLibraryPathEnvVariable, libraryPath)); return validateREnvironment(*pVars, rLibPath, pErrMsg); } void setREnvironmentVars(const EnvironmentVars& vars) { for (EnvironmentVars::const_iterator it = vars.begin(); it != vars.end(); ++it) { core::system::setenv(it->first, it->second); } } } // namespace r_util } // namespace core <commit_msg>refactor REnvironmentPosix in preparation for detection changes<commit_after>/* * REnvironmentPosix.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/r_util/REnvironment.hpp> #include <algorithm> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/replace.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/ConfigUtils.hpp> #include <core/system/System.hpp> namespace core { namespace r_util { namespace { FilePath scanForRScript(const std::vector<std::string>& rScriptPaths) { // iterate over paths for (std::vector<std::string>::const_iterator it = rScriptPaths.begin(); it != rScriptPaths.end(); ++it) { FilePath rScriptPath(*it); if (rScriptPath.exists()) { // verify that the alias points to a real version of R Error error = core::system::realPath(*it, &rScriptPath); if (!error) { return rScriptPath; } else { LOG_ERROR(error); continue; } } } // didn't find it return FilePath(); } // MacOS X Specific #ifdef __APPLE__ #define kLibRFileName "libR.dylib" #define kLibraryPathEnvVariable "DYLD_LIBRARY_PATH" // no extra paths on the mac std::string extraLibraryPaths(const FilePath& ldPathsScript, const std::string& rHome) { return std::string(); } FilePath systemDefaultRScript() { // define potential paths (use same order as in conventional osx PATH) std::vector<std::string> rScriptPaths; rScriptPaths.push_back("/opt/local/bin/R"); rScriptPaths.push_back("/usr/bin/R"); rScriptPaths.push_back("/usr/local/bin/R"); return scanForRScript(rScriptPaths); } bool getRHomeAndLibPath(const FilePath& rScriptPath, const config_utils::Variables& scriptVars, std::string* pRHome, std::string* pRLibPath, std::string* pErrMsg) { config_utils::Variables::const_iterator it = scriptVars.find("R_HOME_DIR"); if (it != scriptVars.end()) { // get R home *pRHome = it->second; // get R lib path (probe subdiretories if necessary) FilePath libPath = FilePath(*pRHome).complete("lib"); // check for dylib in lib and lib/x86_64 if (libPath.complete(kLibRFileName).exists()) { *pRLibPath = libPath.absolutePath(); return true; } else if (libPath.complete("x86_64/" kLibRFileName).exists()) { *pRLibPath = libPath.complete("x86_64").absolutePath(); return true; } else { *pErrMsg = "Unable to find " kLibRFileName " in expected locations" "within R Home directory " + *pRHome; LOG_ERROR_MESSAGE(*pErrMsg); return false; } } else { *pErrMsg = "Unable to find R_HOME_DIR in " + rScriptPath.absolutePath(); LOG_ERROR_MESSAGE(*pErrMsg); return false; } } // Linux specific #else #define kLibRFileName "libR.so" #define kLibraryPathEnvVariable "LD_LIBRARY_PATH" // extra paths from R (for rjava) on linux std::string extraLibraryPaths(const FilePath& ldPathsScript, const std::string& rHome) { // verify that script exists if (!ldPathsScript.exists()) { LOG_WARNING_MESSAGE("r-ldpaths script not found at " + ldPathsScript.absolutePath()); return std::string(); } // run script to capture paths std::string libraryPaths; std::string command = ldPathsScript.absolutePath() + " " + rHome; Error error = system::captureCommand(command, &libraryPaths); if (error) LOG_ERROR(error); boost::algorithm::trim(libraryPaths); return libraryPaths; } FilePath systemDefaultRScript() { // ask system which R to use std::string whichOutput; Error error = core::system::captureCommand("which R", &whichOutput); if (error) { LOG_ERROR(error); return FilePath(); } boost::algorithm::trim(whichOutput); // check for nothing returned if (whichOutput.empty()) { // try scanning known locations std::vector<std::string> rScriptPaths; rScriptPaths.push_back("/usr/local/bin/R"); rScriptPaths.push_back("/usr/bin/R"); FilePath rScriptPath = scanForRScript(rScriptPaths); if (rScriptPath.empty()) return FilePath(); else whichOutput = rScriptPath.absolutePath(); } // verify that the alias points to a real version of R FilePath rBinaryPath; error = core::system::realPath(whichOutput, &rBinaryPath); if (error) { LOG_ERROR(error); return FilePath(); } // check for real path doesn't exist if (!rBinaryPath.exists()) { LOG_ERROR_MESSAGE("Real path of R script does not exist (" + rBinaryPath.absolutePath() + ")"); return FilePath(); } // got a valid R binary return rBinaryPath; } bool getRHomeAndLibPath(const FilePath& rScriptPath, const config_utils::Variables& scriptVars, std::string* pRHome, std::string* pRLibPath, std::string* pErrMsg) { // eliminate a potentially conflicting R_HOME before calling R RHOME" // (the normal semantics of invoking the R script are that it overwrites // R_HOME and prints a warning -- this warning is co-mingled with the // output of "R RHOME" and messes up our parsing) core::system::setenv("R_HOME", ""); // run R script to detect R home std::string rHomeOutput; std::string command = rScriptPath.absolutePath() + " RHOME"; Error error = core::system::captureCommand(command, &rHomeOutput); if (error) { LOG_ERROR(error); *pErrMsg = "Error running R (" + rScriptPath.absolutePath() + "): " + error.summary(); return false; } else { boost::algorithm::trim(rHomeOutput); *pRHome = rHomeOutput; *pRLibPath = FilePath(*pRHome).complete("lib").absolutePath(); return true; } } #endif bool validateREnvironment(const EnvironmentVars& vars, const FilePath& rLibPath, std::string* pErrMsg) { // first extract paths FilePath rHomePath, rSharePath, rIncludePath, rDocPath, rLibRPath; for (EnvironmentVars::const_iterator it = vars.begin(); it != vars.end(); ++it) { if (it->first == "R_HOME") rHomePath = FilePath(it->second); else if (it->first == "R_SHARE_DIR") rSharePath = FilePath(it->second); else if (it->first == "R_INCLUDE_DIR") rIncludePath = FilePath(it->second); else if (it->first == "R_DOC_DIR") rDocPath = FilePath(it->second); } // resolve libR path rLibRPath = rLibPath.complete(kLibRFileName); // validate required paths (if these don't exist then rsession won't // be able start up) if (!rHomePath.exists()) { *pErrMsg = "R Home path (" + rHomePath.absolutePath() + ") not found"; return false; } else if (!rLibPath.exists()) { *pErrMsg = "R lib path (" + rLibPath.absolutePath() + ") not found"; return false; } else if (!rLibRPath.exists()) { *pErrMsg = "R shared library (" + rLibRPath.absolutePath() + ") " "not found. If this is a custom build of R, was it " "built with the --enable-R-shlib option?"; return false; } else if (!rDocPath.exists()) { *pErrMsg = "R doc dir (" + rDocPath.absolutePath() + ") not found."; return false; } // log warnings for other missing paths (rsession can still start but // won't be able to find these env variables) if (!rSharePath.exists()) { LOG_WARNING_MESSAGE("R share path (" + rSharePath.absolutePath() + ") not found"); } if (!rIncludePath.exists()) { LOG_WARNING_MESSAGE("R include path (" + rIncludePath.absolutePath() + ") not found"); } return true; } // resolve an R path which has been parsed from the R bash script. If // R is running out of the source directory (and was thus never installed) // then the values for R_DOC_DIR, etc. will contain unexpanded references // to the R_HOME_DIR, so we expand these if they are present. std::string resolveRPath(const FilePath& rHomePath, const std::string& path) { std::string resolvedPath = path; boost::algorithm::replace_all(resolvedPath, "${R_HOME_DIR}", rHomePath.absolutePath()); return resolvedPath; } bool detectRLocations(const FilePath& rScriptPath, FilePath* pHomePath, FilePath* pLibPath, config_utils::Variables* pScriptVars, std::string* pErrMsg) { // scan R script for other locations and append them to our vars Error error = config_utils::extractVariables(rScriptPath, pScriptVars); if (error) { LOG_ERROR(error); *pErrMsg = "Error reading R script (" + rScriptPath.absolutePath() + "), " + error.summary(); return false; } // get r home path std::string rHome, rLib; if (!getRHomeAndLibPath(rScriptPath, *pScriptVars, &rHome, &rLib, pErrMsg)) return false; // validate: error if we got no output if (rHome.empty()) { *pErrMsg = "Unable to determine R home directory"; LOG_ERROR(systemError(boost::system::errc::not_supported, *pErrMsg, ERROR_LOCATION)); return false; } // validate: error if `R RHOME` yields file that doesn't exist *pHomePath = FilePath(rHome); if (!pHomePath->exists()) { *pErrMsg = "R home path (" + rHome + ") not found"; LOG_ERROR(pathNotFoundError(*pErrMsg, ERROR_LOCATION)); return false; } // get lib path *pLibPath = FilePath(rLib); return true; } } // anonymous namespace bool detectREnvironment(const FilePath& ldPathsScript, EnvironmentVars* pVars, std::string* pErrMsg) { return detectREnvironment(FilePath(), ldPathsScript, std::string(), pVars, pErrMsg); } bool detectREnvironment(const FilePath& whichRScript, const FilePath& ldPathsScript, const std::string& ldLibraryPath, EnvironmentVars* pVars, std::string* pErrMsg) { // if there is a which R script override then validate it (but only // log a warning then move on to the system default) FilePath rScriptPath; if (!whichRScript.empty()) { // but warn (and ignore) if it doesn't exist if (!whichRScript.exists()) { LOG_WARNING_MESSAGE("Override for which R (" + whichRScript.absolutePath() + ") does not exist (ignoring)"); } // also warn and ignore if it is a directory else if (whichRScript.isDirectory()) { LOG_WARNING_MESSAGE("Override for which R (" + whichRScript.absolutePath() + ") is a directory rather than a file (ignoring)"); } // otherwise set it else { rScriptPath = whichRScript; } } // if don't have an override (or it was invalid) then use system default if (rScriptPath.empty()) rScriptPath = systemDefaultRScript(); // bail if not found if (!rScriptPath.exists()) { LOG_ERROR(pathNotFoundError(rScriptPath.absolutePath(), ERROR_LOCATION)); *pErrMsg = "R binary (" + rScriptPath.absolutePath() + ") not found"; return false; } // detect R locations FilePath rHomePath, rLibPath; config_utils::Variables scriptVars; if (!detectRLocations(rScriptPath, &rHomePath, &rLibPath, &scriptVars, pErrMsg)) { return false; } // set R home path pVars->push_back(std::make_pair("R_HOME", rHomePath.absolutePath())); // set other environment values pVars->push_back(std::make_pair("R_SHARE_DIR", resolveRPath(rHomePath, scriptVars["R_SHARE_DIR"]))); pVars->push_back(std::make_pair("R_INCLUDE_DIR", resolveRPath(rHomePath, scriptVars["R_INCLUDE_DIR"]))); pVars->push_back(std::make_pair("R_DOC_DIR", resolveRPath(rHomePath, scriptVars["R_DOC_DIR"]))); // determine library path (existing + r lib dir + r extra lib dirs) std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable); if (!libraryPath.empty()) libraryPath.append(":"); libraryPath.append(ldLibraryPath); if (!libraryPath.empty()) libraryPath.append(":"); libraryPath.append(rLibPath.absolutePath()); std::string extraPaths = extraLibraryPaths(ldPathsScript, rHomePath.absolutePath()); if (!extraPaths.empty()) libraryPath.append(":" + extraPaths); pVars->push_back(std::make_pair(kLibraryPathEnvVariable, libraryPath)); return validateREnvironment(*pVars, rLibPath, pErrMsg); } void setREnvironmentVars(const EnvironmentVars& vars) { for (EnvironmentVars::const_iterator it = vars.begin(); it != vars.end(); ++it) { core::system::setenv(it->first, it->second); } } } // namespace r_util } // namespace core <|endoftext|>
<commit_before>#include <cache.h> Cache::Cache() { QString medusaHome = QDir::homePath() + "/.medusa/"; if (!QFile(medusaHome).exists()) { cerr << "\x1b[31m[Medusa Error] What?! Medusa Home folder not found or unreadable. Please Reinstall.\x1b[0m" << endl; exit(-1); } db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(medusaHome + "medusa.cache"); if (!QFile(medusaHome + "medusa.cache").exists()) { db.open(); QSqlQuery query(db); query.exec("CREATE TABLE MedusaCache (InFile TEXT UNIQUE, Hash VARCHAR(64) UNIQUE, GenCode TEXT)"); } else db.open(); } Cache::~Cache() { db.close(); } QString Cache::hashFile(QString path) { sha256_ctx ctx; FILE *inFile; char buffer[BUFFER_SIZE], output[2 * SHA256_DIGEST_SIZE + 1]; unsigned char digest[SHA256_DIGEST_SIZE]; int bytes; if (!(inFile = fopen(path.toStdString().c_str(), "rb"))) { cerr << "\x1b[31m[Medusa Error]: Couldn't read " + path.toStdString() + ". Please check if it exists and is readable.\x1b[0m" << endl; exit(-1); } sha256_init(&ctx); while ((bytes = fread(buffer, 1, BUFFER_SIZE, inFile)) != 0) sha256_update(&ctx, (const unsigned char *) buffer, bytes); sha256_final(&ctx, digest); fclose(inFile); output[2 * SHA256_DIGEST_SIZE] = 0; for (int i = 0; i < SHA256_DIGEST_SIZE ; i++) sprintf(output + 2 * i, "%02X", digest[i]); return QString(output); } bool Cache::tryInsert(QString path, QString hash) { QSqlQuery query(db); return query.exec("INSERT INTO MedusaCache VALUES ('" + path + "', '" + hash + "', '')"); } bool Cache::changed(QString path, QString hash, QString &code) { QSqlQuery query(db); query.exec("SELECT Hash, GenCode FROM MedusaCache WHERE InFile='" + path + "'"); query.next(); if (query.value(0).toString() != hash) return query.exec("UPDATE MedusaCache SET Hash='" + hash + "' WHERE InFile='" + path + "'"); code = query.value(1).toString(); return false; } bool Cache::isCached(QString path, QString &code) { QString hash = hashFile(path); QSqlQuery query(db); if (!tryInsert(path, hash)) { query.exec("SELECT GenCode FROM MedusaCache WHERE Hash='" + hash + "'"); query.next(); if ((code = query.value(0).toString()) != "") return true; else return changed(path, hash, code) ? false : true; } else return false; } <commit_msg>Fixed Cache Checks<commit_after>#include <cache.h> Cache::Cache() { QString medusaHome = QDir::homePath() + "/.medusa/"; if (!QFile(medusaHome).exists()) { cerr << "\x1b[31m[Medusa Error] What?! Medusa Home folder not found or unreadable. Please Reinstall.\x1b[0m" << endl; exit(-1); } db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(medusaHome + "medusa.cache"); if (!QFile(medusaHome + "medusa.cache").exists()) { db.open(); QSqlQuery query(db); query.exec("CREATE TABLE MedusaCache (InFile TEXT UNIQUE, Hash VARCHAR(64) UNIQUE, GenCode TEXT)"); } else db.open(); } Cache::~Cache() { db.close(); } QString Cache::hashFile(QString path) { sha256_ctx ctx; FILE *inFile; char buffer[BUFFER_SIZE], output[2 * SHA256_DIGEST_SIZE + 1]; unsigned char digest[SHA256_DIGEST_SIZE]; int bytes; if (!(inFile = fopen(path.toStdString().c_str(), "rb"))) { cerr << "\x1b[31m[Medusa Error]: Couldn't read " + path.toStdString() + ". Please check if it exists and is readable.\x1b[0m" << endl; exit(-1); } sha256_init(&ctx); while ((bytes = fread(buffer, 1, BUFFER_SIZE, inFile)) != 0) sha256_update(&ctx, (const unsigned char *) buffer, bytes); sha256_final(&ctx, digest); fclose(inFile); output[2 * SHA256_DIGEST_SIZE] = 0; for (int i = 0; i < SHA256_DIGEST_SIZE ; i++) sprintf(output + 2 * i, "%02X", digest[i]); return QString(output); } bool Cache::tryInsert(QString path, QString hash) { QSqlQuery query(db); return query.exec("INSERT INTO MedusaCache VALUES ('" + path + "', '" + hash + "', '')"); } bool Cache::changed(QString path, QString hash, QString &code) { QSqlQuery query(db); query.exec("SELECT Hash, GenCode FROM MedusaCache WHERE InFile='" + path + "'"); query.next(); if (query.value(0).toString() != hash) return query.exec("UPDATE MedusaCache SET Hash='" + hash + "' WHERE InFile='" + path + "'"); code = query.value(1).toString(); return false; } bool Cache::isCached(QString path, QString &code) { QString hash = hashFile(path); QSqlQuery query(db); if (!tryInsert(path, hash)) { query.exec("SELECT GenCode FROM MedusaCache WHERE Hash='" + hash + "'"); query.next(); if (query.isValid()) { code = query.value(0).toString(); return true; } else return changed(path, hash, code) ? false : true; } else return false; } <|endoftext|>
<commit_before>/** * Copyright (c) 2016 zScale Technology GmbH <[email protected]> * Authors: * - Paul Asmuth <[email protected]> * - Laura Schlimmer <[email protected]> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include "eventql/eventql.h" #include <eventql/util/stdtypes.h> #include <eventql/util/exception.h> #include <eventql/util/wallclock.h> #include <eventql/util/test/unittest.h> #include <eventql/config/process_config.h> using namespace eventql; UNIT_TEST(ProcessConfigTest); TEST_CASE(ProcessConfigTest, TestProcessConfigBuilder, [] () { ProcessConfigBuilder builder; builder.setProperty("evql", "host", "localhost"); builder.setProperty("evql", "port", "8080"); builder.setProperty("evql", "fuu", "bar"); auto config = builder.getConfig(); { auto p = config->getProperty("evql", "host"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "localhost"); } { auto p = config->getProperty("evql", "port"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "8080"); } { auto p = config->getProperty("evql", "fuu"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "bar"); } }); <commit_msg>ProcessConfigBuilderLoadFileTest<commit_after>/** * Copyright (c) 2016 zScale Technology GmbH <[email protected]> * Authors: * - Paul Asmuth <[email protected]> * - Laura Schlimmer <[email protected]> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include "eventql/eventql.h" #include <eventql/util/stdtypes.h> #include <eventql/util/exception.h> #include <eventql/util/wallclock.h> #include <eventql/util/test/unittest.h> #include <eventql/config/process_config.h> using namespace eventql; UNIT_TEST(ProcessConfigTest); TEST_CASE(ProcessConfigTest, TestProcessConfigBuilder, [] () { ProcessConfigBuilder builder; builder.setProperty("evql", "host", "localhost"); builder.setProperty("evql", "port", "8080"); builder.setProperty("evql", "fuu", "bar"); auto config = builder.getConfig(); { auto p = config->getProperty("evql", "host"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "localhost"); } { auto p = config->getProperty("evql", "port"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "8080"); } { auto p = config->getProperty("evql", "fuu"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "bar"); } }); TEST_CASE(ProcessConfigTest, TestProcessConfigBuilderLoadFile, [] () { auto test_file_path = "eventql/config/testdata/.process_cfg"; ProcessConfigBuilder builder; auto status = builder.loadFile(test_file_path); EXPECT_TRUE(status.isSuccess()); builder.setProperty("test", "port", "9175"); auto config = builder.getConfig(); { auto p = config->getProperty("test", "host"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "localhost"); } { auto p = config->getProperty("test", "port"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "9175"); } { auto p = config->getProperty("test", "authors"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "eventQL Authors"); } { auto p = config->getProperty("test2", "mail"); EXPECT_FALSE(p.isEmpty()); EXPECT_EQ(p.get(), "[email protected]"); } }); <|endoftext|>
<commit_before>/* * KVH 1750 IMU * Eric L. Hahn <[email protected]> * 12/5/2014 * Copyright 2014. All Rights Reserved. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include <ros/ros.h> #include <tf/tf.h> #pragma GCC diagnostic pop #include "kvh1750/tov_file.h" #include <trooper_mlc_msgs/CachedRawIMUData.h> #include <sensor_msgs/Temperature.h> #include <sensor_msgs/Imu.h> #include <sched.h> namespace { const std::string DefaultImuLink = "torso"; const std::string DefaultAddress = "/dev/ttyS4"; const size_t ImuCacheSize = 15; int Rate; bool IsDA = true; double Ahrs_gyro_x = 0; double Ahrs_gyro_y = 0; double Ahrs_gyro_z = 0; double Prev_stamp = 0; size_t CachedMsgCounter = 0; } /** * Converts KVH1750Message into the standard ROS messages corresponding * to the same set of data, namely an Imu and Temperature message. */ void to_ros(const kvh::Message& msg, sensor_msgs::Imu& imu, sensor_msgs::Temperature& temp) { msg.time(imu.header.stamp.sec, imu.header.stamp.nsec); imu.angular_velocity.x = msg.gyro_x(); imu.angular_velocity.y = msg.gyro_y(); imu.angular_velocity.z = msg.gyro_z(); imu.linear_acceleration.x = msg.accel_x(); imu.linear_acceleration.y = msg.accel_y(); imu.linear_acceleration.z = msg.accel_z(); //scale for ROS if delta angles are enabled if(IsDA) { Ahrs_gyro_x += msg.gyro_x(); Ahrs_gyro_y += msg.gyro_y(); Ahrs_gyro_z += msg.gyro_z(); imu.angular_velocity.x *= Rate; imu.angular_velocity.y *= Rate; imu.angular_velocity.z *= Rate; } else { double current_stamp = imu.header.stamp.sec + imu.header.stamp.nsec * 1E-9; double deltatime; if (Prev_stamp) { deltatime = current_stamp - Prev_stamp; } else { deltatime = 1/Rate; } Ahrs_gyro_x += msg.gyro_x()*deltatime; Ahrs_gyro_y += msg.gyro_y()*deltatime; Ahrs_gyro_z += msg.gyro_z()*deltatime; Prev_stamp = current_stamp; } imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(Ahrs_gyro_x, Ahrs_gyro_y, Ahrs_gyro_z); temp.header.stamp = imu.header.stamp; temp.temperature = msg.temp(); } /** * Adds a single IMU reading to the cached value. If the cache is full, this * resets the counter and returns true. */ bool cache_imu(const kvh::Message& msg, trooper_mlc_msgs::CachedRawIMUData& cache, size_t& counter) { if(counter >= ImuCacheSize) { counter = 0; } trooper_mlc_msgs::RawIMUData& imu = cache.data[counter]; uint32_t secs = 0; uint32_t nsecs = 0; msg.time(secs, nsecs); imu.imu_timestamp = static_cast<uint64_t>(secs * 1.0E6) + static_cast<uint64_t>(nsecs * 1.0E-3); imu.packet_count = CachedMsgCounter++; imu.dax = msg.gyro_x(); imu.day = msg.gyro_y(); imu.daz = msg.gyro_z(); imu.ddx = msg.accel_x(); imu.ddy = msg.accel_y(); imu.ddz = msg.accel_z(); //if the pre-increment sets it to 15, will be set to 0 and return true return (++counter % ImuCacheSize) == 0; } int main(int argc, char **argv) { //Name of node ros::init(argc, argv, "kvh_1750_imu"); //Node handle ros::NodeHandle nh("~"); ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 1); ros::Publisher temp_pub = nh.advertise<sensor_msgs::Temperature>("temp", 1); ros::Publisher cache_pub = nh.advertise<trooper_mlc_msgs::CachedRawIMUData>("cached", 1); std::string imu_link_name = DefaultImuLink; nh.getParam("link_name", imu_link_name); nh.param("rate", Rate, 100); bool use_delta_angles = true; nh.getParam("use_delta_angles", use_delta_angles); size_t cache_counter = 0; trooper_mlc_msgs::CachedRawIMUData cached_imu; sensor_msgs::Imu current_imu; sensor_msgs::Temperature current_temp; int priority = 99; bool use_rt = true; nh.getParam("priority", priority); nh.getParam("use_rt", use_rt); int policy = (use_rt ? SCHED_RR : SCHED_OTHER); priority = std::min(sched_get_priority_max(policy), std::max(sched_get_priority_min(policy), priority)); struct sched_param params; params.sched_priority = (use_rt ? static_cast<int>(priority) : 0); int rc = sched_setscheduler(0, policy, &params); if(rc != 0) { ROS_ERROR("Setting schedule priority produced error: \"%s\"", strerror(errno)); return 1; } std::vector<double> ahrs_cov; std::vector<double> ang_cov; std::vector<double> lin_cov; nh.param<std::vector<double>>("orientation_covariance", ahrs_cov, {1, 0, 0, 0, 1, 0, 0, 0, 1}); std::copy(ahrs_cov.begin(), ahrs_cov.end(), current_imu.orientation_covariance.begin()); if(nh.getParam("angular_covariance", ang_cov)) { std::copy(ang_cov.begin(), ang_cov.end(), current_imu.angular_velocity_covariance.begin()); } else { current_imu.angular_velocity_covariance[0] = 1; current_imu.angular_velocity_covariance[4] = 1; current_imu.angular_velocity_covariance[8] = 1; } if(nh.getParam("linear_covariance", lin_cov)) { std::copy(lin_cov.begin(), lin_cov.end(), current_imu.linear_acceleration_covariance.begin()); } else { current_imu.linear_acceleration_covariance[0] = 1; current_imu.linear_acceleration_covariance[4] = 1; current_imu.linear_acceleration_covariance[8] = 1; } //IMU link locations current_temp.header.frame_id = imu_link_name; current_imu.header.frame_id = imu_link_name; cached_imu.header.frame_id = imu_link_name; std::string addr = DefaultAddress; nh.getParam("address", addr); std::string tov_addr = ""; nh.getParam("tov_address", tov_addr); uint32_t baud = 921600; int read_baud; //Because rosparam can't provide unsigned ints nh.getParam("baudrate", read_baud); baud = static_cast<uint32_t>(read_baud); int max_temp = kvh::MaxTemp_C; nh.getParam("max_temp", max_temp); uint32_t wait = 100; std::shared_ptr<kvh::IOModule> mod(new kvh::TOVFile(addr, baud, wait, tov_addr)); kvh::IMU1750 imu(mod); imu.set_temp_limit(max_temp); if(!imu.set_angle_units(use_delta_angles)) { ROS_ERROR("Could not set angle units."); } if(Rate > 0) { if(!imu.set_data_rate(Rate)) { ROS_ERROR("Could not set data rate to %d", Rate); } } imu.query_data_rate(Rate); imu.query_angle_units(IsDA); bool keep_reading = true; while(ros::ok() && keep_reading) { kvh::Message msg; switch(imu.read(msg)) { case kvh::IMU1750::VALID: to_ros(msg, current_imu, current_temp); if(cache_imu(msg, cached_imu, cache_counter)) { msg.time(cached_imu.header.stamp.sec, cached_imu.header.stamp.nsec); cache_pub.publish(cached_imu); } imu_pub.publish(current_imu); temp_pub.publish(current_temp); break; case kvh::IMU1750::BAD_READ: case kvh::IMU1750::BAD_CRC: ROS_ERROR("Bad data from KVH, ignoring."); break; case kvh::IMU1750::FATAL_ERROR: ROS_FATAL("Lost connection to IMU!"); //should reconnect keep_reading = false; break; case kvh::IMU1750::OVER_TEMP: ROS_FATAL("IMU is overheating!"); keep_reading = false; break; case kvh::IMU1750::PARTIAL_READ: default: break; } ros::spinOnce(); } return 0; } <commit_msg>Apparently batch message is a LIFO sliding buffer of 15 elements.<commit_after>/* * KVH 1750 IMU * Eric L. Hahn <[email protected]> * 12/5/2014 * Copyright 2014. All Rights Reserved. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include <ros/ros.h> #include <tf/tf.h> #pragma GCC diagnostic pop #include "kvh1750/tov_file.h" #include <trooper_mlc_msgs/CachedRawIMUData.h> #include <sensor_msgs/Temperature.h> #include <sensor_msgs/Imu.h> #include <boost/circular_buffer.hpp> #include <sched.h> namespace { const std::string DefaultImuLink = "torso"; const std::string DefaultAddress = "/dev/ttyS4"; const size_t ImuCacheSize = 15; int Rate; bool IsDA = true; double Ahrs_gyro_x = 0; double Ahrs_gyro_y = 0; double Ahrs_gyro_z = 0; double Prev_stamp = 0; size_t CachedMsgCounter = 0; boost::circular_buffer<trooper_mlc_msgs::RawIMUData> ImuCache(ImuCacheSize); } /** * Converts KVH1750Message into the standard ROS messages corresponding * to the same set of data, namely an Imu and Temperature message. */ void to_ros(const kvh::Message& msg, sensor_msgs::Imu& imu, sensor_msgs::Temperature& temp) { msg.time(imu.header.stamp.sec, imu.header.stamp.nsec); imu.angular_velocity.x = msg.gyro_x(); imu.angular_velocity.y = msg.gyro_y(); imu.angular_velocity.z = msg.gyro_z(); imu.linear_acceleration.x = msg.accel_x(); imu.linear_acceleration.y = msg.accel_y(); imu.linear_acceleration.z = msg.accel_z(); //scale for ROS if delta angles are enabled if(IsDA) { Ahrs_gyro_x += msg.gyro_x(); Ahrs_gyro_y += msg.gyro_y(); Ahrs_gyro_z += msg.gyro_z(); imu.angular_velocity.x *= Rate; imu.angular_velocity.y *= Rate; imu.angular_velocity.z *= Rate; } else { double current_stamp = imu.header.stamp.sec + imu.header.stamp.nsec * 1E-9; double deltatime; if (Prev_stamp) { deltatime = current_stamp - Prev_stamp; } else { deltatime = 1/Rate; } Ahrs_gyro_x += msg.gyro_x()*deltatime; Ahrs_gyro_y += msg.gyro_y()*deltatime; Ahrs_gyro_z += msg.gyro_z()*deltatime; Prev_stamp = current_stamp; } imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(Ahrs_gyro_x, Ahrs_gyro_y, Ahrs_gyro_z); temp.header.stamp = imu.header.stamp; temp.temperature = msg.temp(); } /** * Adds a single IMU reading to the cached value. If the cache is full, this * resets the counter and returns true. */ void cache_imu(const kvh::Message& msg) { trooper_mlc_msgs::RawIMUData imu; uint32_t secs = 0; uint32_t nsecs = 0; msg.time(secs, nsecs); imu.imu_timestamp = static_cast<uint64_t>(secs * 1.0E6) + static_cast<uint64_t>(nsecs * 1.0E-3); imu.packet_count = CachedMsgCounter++; imu.dax = msg.gyro_x(); imu.day = msg.gyro_y(); imu.daz = msg.gyro_z(); imu.ddx = msg.accel_x(); imu.ddy = msg.accel_y(); imu.ddz = msg.accel_z(); ImuCache.push_back(imu); } int main(int argc, char **argv) { //Name of node ros::init(argc, argv, "kvh_1750_imu"); //Node handle ros::NodeHandle nh("~"); ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 1); ros::Publisher temp_pub = nh.advertise<sensor_msgs::Temperature>("temp", 1); ros::Publisher cache_pub = nh.advertise<trooper_mlc_msgs::CachedRawIMUData>("cached", 1); std::string imu_link_name = DefaultImuLink; nh.getParam("link_name", imu_link_name); nh.param("rate", Rate, 100); bool use_delta_angles = true; nh.getParam("use_delta_angles", use_delta_angles); trooper_mlc_msgs::CachedRawIMUData cached_imu; sensor_msgs::Imu current_imu; sensor_msgs::Temperature current_temp; int priority = 99; bool use_rt = true; nh.getParam("priority", priority); nh.getParam("use_rt", use_rt); int policy = (use_rt ? SCHED_RR : SCHED_OTHER); priority = std::min(sched_get_priority_max(policy), std::max(sched_get_priority_min(policy), priority)); struct sched_param params; params.sched_priority = (use_rt ? static_cast<int>(priority) : 0); int rc = sched_setscheduler(0, policy, &params); if(rc != 0) { ROS_ERROR("Setting schedule priority produced error: \"%s\"", strerror(errno)); return 1; } std::vector<double> ahrs_cov; std::vector<double> ang_cov; std::vector<double> lin_cov; nh.param<std::vector<double>>("orientation_covariance", ahrs_cov, {1, 0, 0, 0, 1, 0, 0, 0, 1}); std::copy(ahrs_cov.begin(), ahrs_cov.end(), current_imu.orientation_covariance.begin()); if(nh.getParam("angular_covariance", ang_cov)) { std::copy(ang_cov.begin(), ang_cov.end(), current_imu.angular_velocity_covariance.begin()); } else { current_imu.angular_velocity_covariance[0] = 1; current_imu.angular_velocity_covariance[4] = 1; current_imu.angular_velocity_covariance[8] = 1; } if(nh.getParam("linear_covariance", lin_cov)) { std::copy(lin_cov.begin(), lin_cov.end(), current_imu.linear_acceleration_covariance.begin()); } else { current_imu.linear_acceleration_covariance[0] = 1; current_imu.linear_acceleration_covariance[4] = 1; current_imu.linear_acceleration_covariance[8] = 1; } //IMU link locations current_temp.header.frame_id = imu_link_name; current_imu.header.frame_id = imu_link_name; cached_imu.header.frame_id = imu_link_name; std::string addr = DefaultAddress; nh.getParam("address", addr); std::string tov_addr = ""; nh.getParam("tov_address", tov_addr); uint32_t baud = 921600; int read_baud; //Because rosparam can't provide unsigned ints nh.getParam("baudrate", read_baud); baud = static_cast<uint32_t>(read_baud); int max_temp = kvh::MaxTemp_C; nh.getParam("max_temp", max_temp); uint32_t wait = 100; std::shared_ptr<kvh::IOModule> mod(new kvh::TOVFile(addr, baud, wait, tov_addr)); kvh::IMU1750 imu(mod); imu.set_temp_limit(max_temp); if(!imu.set_angle_units(use_delta_angles)) { ROS_ERROR("Could not set angle units."); } if(Rate > 0) { if(!imu.set_data_rate(Rate)) { ROS_ERROR("Could not set data rate to %d", Rate); } } imu.query_data_rate(Rate); imu.query_angle_units(IsDA); bool keep_reading = true; while(ros::ok() && keep_reading) { kvh::Message msg; switch(imu.read(msg)) { case kvh::IMU1750::VALID: to_ros(msg, current_imu, current_temp); cache_imu(msg); if(CachedMsgCounter >= ImuCacheSize) { msg.time(cached_imu.header.stamp.sec, cached_imu.header.stamp.nsec); std::reverse_copy(ImuCache.begin(), ImuCache.end(), cached_imu.data.begin()); cache_pub.publish(cached_imu); } imu_pub.publish(current_imu); temp_pub.publish(current_temp); break; case kvh::IMU1750::BAD_READ: case kvh::IMU1750::BAD_CRC: ROS_ERROR("Bad data from KVH, ignoring."); break; case kvh::IMU1750::FATAL_ERROR: ROS_FATAL("Lost connection to IMU!"); //should reconnect keep_reading = false; break; case kvh::IMU1750::OVER_TEMP: ROS_FATAL("IMU is overheating!"); keep_reading = false; break; case kvh::IMU1750::PARTIAL_READ: default: break; } ros::spinOnce(); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" using namespace std; /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } <commit_msg>[UNIFYING][CORE]Start re-implementing AUXPOW function<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" #include "auxpow.h" #include "txdb.h" using namespace std; /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } std::string CDiskBlockIndex::ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s, hashParentBlock=%s)", GetBlockHash().ToString(), hashPrev.ToString(), (auxpow.get() != NULL) ? auxpow->GetParentBlockHash().ToString() : "-"); return str; } CBlockHeader CBlockIndex::GetBlockHeader(const std::map<uint256, boost::shared_ptr<CAuxPow> >& mapDirtyAuxPow) const { CBlockHeader block; if (nVersion & BLOCK_VERSION_AUXPOW) { bool foundInDirty = false; { LOCK(cs_main); std::map<uint256, boost::shared_ptr<CAuxPow> >::const_iterator it = mapDirtyAuxPow.find(*phashBlock); if (it != mapDirtyAuxPow.end()) { block.auxpow = it->second; foundInDirty = true; } } if (!foundInDirty) { CDiskBlockIndex diskblockindex; // auxpow is not in memory, load CDiskBlockHeader // from database to get it pblocktree->ReadDiskBlockIndex(*phashBlock, diskblockindex); block.auxpow = diskblockindex.auxpow; } } block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } <|endoftext|>
<commit_before>#include "formulation/cfem_diffusion_stamper.h" #include "cfem_diffusion_stamper.h" namespace bart { namespace formulation { template<int dim> CFEM_DiffusionStamper<dim>::CFEM_DiffusionStamper( std::unique_ptr<formulation::scalar::CFEM_DiffusionI<dim>> diffusion_ptr, std::unique_ptr<domain::DefinitionI<dim>> definition_ptr) : diffusion_ptr_(std::move(diffusion_ptr)), definition_ptr_(std::move(definition_ptr)) { cells_ = definition_ptr_->Cells(); diffusion_init_token_ = diffusion_ptr_->Precalculate(cells_[0]); } template<int dim> void CFEM_DiffusionStamper<dim>::StampStreamingTerm(MPISparseMatrix &to_stamp, GroupNumber group) { auto streaming_function = [&](dealii::FullMatrix<double>& matrix, const Cell& cell_ptr) -> void { this->diffusion_ptr_->FillCellStreamingTerm(matrix, this->diffusion_init_token_, cell_ptr, group); }; StampMatrix(to_stamp, streaming_function); } template<int dim> void CFEM_DiffusionStamper<dim>::StampCollisionTerm(MPISparseMatrix &to_stamp, GroupNumber group) { auto collision_function = [&](dealii::FullMatrix<double>& matrix, const Cell& cell_ptr) -> void { this->diffusion_ptr_->FillCellCollisionTerm(matrix, this->diffusion_init_token_, cell_ptr, group); }; StampMatrix(to_stamp, collision_function); } template <int dim> void CFEM_DiffusionStamper<dim>::StampMatrix( MPISparseMatrix &to_stamp, std::function<void(dealii::FullMatrix<double>&, const Cell&)> function) { auto cell_matrix = definition_ptr_->GetCellMatrix(); std::vector<dealii::types::global_dof_index> local_dof_indices(cell_matrix.n_cols()); for (const auto& cell : cells_) { cell->get_dof_indices(local_dof_indices); function(cell_matrix, cell); to_stamp.add(local_dof_indices, local_dof_indices, cell_matrix); } to_stamp.compress(dealii::VectorOperation::add); } template class CFEM_DiffusionStamper<1>; template class CFEM_DiffusionStamper<2>; template class CFEM_DiffusionStamper<3>; } // namespace formulation } // namespace bart<commit_msg>fixed whitespace in CFEM_DiffusionStamper, added zeroing out of cell_matrix<commit_after>#include "formulation/cfem_diffusion_stamper.h" #include "cfem_diffusion_stamper.h" namespace bart { namespace formulation { template<int dim> CFEM_DiffusionStamper<dim>::CFEM_DiffusionStamper( std::unique_ptr<formulation::scalar::CFEM_DiffusionI<dim>> diffusion_ptr, std::unique_ptr<domain::DefinitionI<dim>> definition_ptr) : diffusion_ptr_(std::move(diffusion_ptr)), definition_ptr_(std::move(definition_ptr)) { cells_ = definition_ptr_->Cells(); diffusion_init_token_ = diffusion_ptr_->Precalculate(cells_[0]); } template<int dim> void CFEM_DiffusionStamper<dim>::StampStreamingTerm(MPISparseMatrix &to_stamp, GroupNumber group) { auto streaming_function = [&](dealii::FullMatrix<double>& matrix, const Cell& cell_ptr) -> void { this->diffusion_ptr_->FillCellStreamingTerm(matrix, this->diffusion_init_token_, cell_ptr, group); }; StampMatrix(to_stamp, streaming_function); } template<int dim> void CFEM_DiffusionStamper<dim>::StampCollisionTerm(MPISparseMatrix &to_stamp, GroupNumber group) { auto collision_function = [&](dealii::FullMatrix<double>& matrix, const Cell& cell_ptr) -> void { this->diffusion_ptr_->FillCellCollisionTerm(matrix, this->diffusion_init_token_, cell_ptr, group); }; StampMatrix(to_stamp, collision_function); } template <int dim> void CFEM_DiffusionStamper<dim>::StampMatrix( MPISparseMatrix &to_stamp, std::function<void(dealii::FullMatrix<double>&, const Cell&)> function) { auto cell_matrix = definition_ptr_->GetCellMatrix(); std::vector<dealii::types::global_dof_index> local_dof_indices(cell_matrix.n_cols()); for (const auto& cell : cells_) { cell_matrix = 0; cell->get_dof_indices(local_dof_indices); function(cell_matrix, cell); to_stamp.add(local_dof_indices, local_dof_indices, cell_matrix); } to_stamp.compress(dealii::VectorOperation::add); } template class CFEM_DiffusionStamper<1>; template class CFEM_DiffusionStamper<2>; template class CFEM_DiffusionStamper<3>; } // namespace formulation } // namespace bart<|endoftext|>
<commit_before>#include "nysa.hpp" #include <stdio.h> Nysa::Nysa(bool debug) { this->debug = debug; this->drt = NULL; //DRT Settings this->num_devices = 0; this->version = 0; } Nysa::~Nysa(){ if (this->drt != NULL){ delete(this->drt); } } int Nysa::open(){ return 1; } int Nysa::close(){ return 1; } int Nysa::parse_drt(){ //read the DRT Json File this->version = this->drt[0] << 8 | this->drt[1]; } //Low Level interface (These must be overridden by a subclass int Nysa::write_periph_data(uint32_t dev_addr, uint32_t addr, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::read_periph_data(uint32_t dev_addr, uint32_t addr, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::write_memory(uint32_t address, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::read_memory(uint32_t address, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::wait_for_interrupts(uint32_t timeout, uint32_t *interrupts){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::ping(){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::crash_report(uint32_t *buffer){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } //Helper Functions int Nysa::write_register(uint32_t dev_addr, uint32_t reg_addr, uint32_t data){ //write to only one address in the peripheral address space printd("Entered\n"); uint8_t d[4]; d[0] = ((data >> 24) & 0xFF); d[1] = ((data >> 16) & 0xFF); d[2] = ((data >> 8) & 0xFF); d[3] = ( data & 0xFF); return this->write_periph_data(dev_addr, reg_addr, &d[0], 4); } int Nysa::read_register(uint32_t dev_addr, uint32_t reg_addr, uint32_t *data){ //read from only one address in the peripheral address space printd("Entered\n"); uint8_t d[4]; uint32_t retval; retval = this->read_periph_data(dev_addr, reg_addr, &d[0], 4); CHECK_NYSA_ERROR("Error Reading Peripheral Data"); //printf ("%02X %02X %02X %02X\n", d[0], d[1], d[2], d[3]); *data = (d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3]); return 0; } int Nysa::set_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit){ uint32_t reg; int retval = 0; printd("Entered\n"); retval = this->read_register(dev_addr, reg_addr, &reg); CHECK_NYSA_ERROR("Error Reading Register"); reg |= 1 << bit; retval = this->write_register(dev_addr, reg_addr, reg); CHECK_NYSA_ERROR("Error Writing Register"); return 0; } int Nysa::clear_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit){ uint32_t reg; int retval = 0; printd("Entered\n"); retval = this->read_register(dev_addr, reg_addr, &reg); CHECK_NYSA_ERROR("Error Reading Register"); reg &= (~(1 << bit)); retval = this->write_register(dev_addr, reg_addr, reg); CHECK_NYSA_ERROR("Error Writing Register"); return 0; } int Nysa::read_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit, bool * value){ uint32_t reg; int retval = 0; printd("Entered\n"); retval = this->read_register(dev_addr, reg_addr, &reg); CHECK_NYSA_ERROR("Error Reading Register"); reg &= (1 << bit); if (reg > 0){ *value = true; } else { *value = false; } return 0; } //DRT int Nysa::pretty_print_drt(){ return -1; } int Nysa::read_drt(){ uint8_t * buffer = new uint8_t [32]; uint32_t len = 1 * 32; int32_t retval; //We don't know the total size of the DRT so only look at the fist Block (32 bytes) retval = this->read_periph_data(0, 0, buffer, len); if (retval < 0){ printf ("%s(): Failed to read peripheral data\n", __func__); return -1; } //Found out how many devices are in the DRT this->num_devices = buffer[4] << 24 | buffer[5] << 16 | buffer[6] << 8 | buffer[7]; printf ("There are: %d devices\n", this->num_devices); delete(buffer); //Calculate the buffer size ( + 1 to read the DRT again) len = (this->num_devices + 1) * 32; printf ("Length of read: %d\n", len); this->drt = new uint8_t [len]; retval = this->read_periph_data(0, 0, this->drt, len); this->parse_drt(); return 0; } int Nysa::get_drt_version(){ if (this->drt == NULL){ return -1; } return this->version; } int Nysa::get_drt_device_count(){ if (this->drt == NULL){ return -1; } return this->num_devices; } uint32_t Nysa::get_drt_device_type(uint32_t index){ uint32_t pos = 0; uint32_t type; if (this->drt == NULL){ //XXX: Error handling return 0; } if (index == 0){ //DRT has no type //XXX: Error handling return 0; } if (index > this->num_devices){ //Out of range //XXX: Error handling return 0; } //Start of the device in question pos = (index) * 32; //Go to the start of the type type = this->drt[pos] << 24 | this->drt[pos + 1] << 16 | this->drt[pos + 2] << 8| this->drt[pos + 3]; return type; } uint32_t Nysa::get_drt_device_size(uint32_t index){ uint32_t size = 0; uint32_t pos = 0; if (this->drt == NULL){ //XXX: Error handling return 0; } if (index == 0){ //DRT has no type //XXX: Error handling return 0; } if (index > this->num_devices){ //Out of range //XXX: Error handling return 0; } //Start of the device in question pos = (index) * 32; pos += 12; //Go to the start of the type size = this->drt[pos] << 24 | this->drt[pos + 1] << 16 | this->drt[pos + 2] << 8 | this->drt[pos + 3]; return size; } uint32_t Nysa::get_drt_device_addr(uint32_t index){ uint32_t pos = 0; uint32_t addr; if (this->drt == NULL){ //XXX: Error handling return 0; } if (index == 0){ //DRT has no type //XXX: Error handling return 0; } if (index > this->num_devices){ //Out of range //XXX: Error handling return 0; } //Start of the device in question pos = (index) * 32; pos += 8; //Go to the start of the type addr = this->drt[pos] << 24 | this->drt[pos + 1] << 16 | this->drt[pos + 2] << 8 | this->drt[pos + 3]; return addr; } int Nysa::get_drt_device_flags(uint32_t index, uint16_t *nysa_flags, uint16_t *dev_flags){ uint32_t pos = 0; if (this->drt == NULL){ return -1; } if (index == 0){ //DRT has no type return -2; } if (index > this->num_devices){ //Out of range return -3; } //Start of the device in question pos = (index) * 32; pos += 4; //Go to the start of the type *nysa_flags = (this->drt[pos] << 8) | (this->drt[pos + 1]); *dev_flags = (this->drt[pos + 2] << 8) | (this->drt[pos + 3]); } bool Nysa::is_memory_device(uint32_t index){ int retval = 0; uint16_t nysa_flags; uint16_t dev_flags; retval = this->get_drt_device_flags(index, &nysa_flags, &dev_flags); if (nysa_flags & 0x01){ return true; } return false; } int Nysa::pretty_print_crash_report(){ return -1; } <commit_msg>Added function to find a device given the specified type<commit_after>#include "nysa.hpp" #include <stdio.h> Nysa::Nysa(bool debug) { this->debug = debug; this->drt = NULL; //DRT Settings this->num_devices = 0; this->version = 0; } Nysa::~Nysa(){ if (this->drt != NULL){ delete(this->drt); } } int Nysa::open(){ return 1; } int Nysa::close(){ return 1; } int Nysa::parse_drt(){ //read the DRT Json File this->version = this->drt[0] << 8 | this->drt[1]; } //Low Level interface (These must be overridden by a subclass int Nysa::write_periph_data(uint32_t dev_addr, uint32_t addr, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::read_periph_data(uint32_t dev_addr, uint32_t addr, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::write_memory(uint32_t address, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::read_memory(uint32_t address, uint8_t *buffer, uint32_t size){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::wait_for_interrupts(uint32_t timeout, uint32_t *interrupts){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::ping(){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } int Nysa::crash_report(uint32_t *buffer){ printf ("Error: Calling function that should be subclassed!\n"); return -1; } //Helper Functions int Nysa::write_register(uint32_t dev_addr, uint32_t reg_addr, uint32_t data){ //write to only one address in the peripheral address space printd("Entered\n"); uint8_t d[4]; d[0] = ((data >> 24) & 0xFF); d[1] = ((data >> 16) & 0xFF); d[2] = ((data >> 8) & 0xFF); d[3] = ( data & 0xFF); return this->write_periph_data(dev_addr, reg_addr, &d[0], 4); } int Nysa::read_register(uint32_t dev_addr, uint32_t reg_addr, uint32_t *data){ //read from only one address in the peripheral address space printd("Entered\n"); uint8_t d[4]; uint32_t retval; retval = this->read_periph_data(dev_addr, reg_addr, &d[0], 4); CHECK_NYSA_ERROR("Error Reading Peripheral Data"); //printf ("%02X %02X %02X %02X\n", d[0], d[1], d[2], d[3]); *data = (d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3]); return 0; } int Nysa::set_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit){ uint32_t reg; int retval = 0; printd("Entered\n"); retval = this->read_register(dev_addr, reg_addr, &reg); CHECK_NYSA_ERROR("Error Reading Register"); reg |= 1 << bit; retval = this->write_register(dev_addr, reg_addr, reg); CHECK_NYSA_ERROR("Error Writing Register"); return 0; } int Nysa::clear_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit){ uint32_t reg; int retval = 0; printd("Entered\n"); retval = this->read_register(dev_addr, reg_addr, &reg); CHECK_NYSA_ERROR("Error Reading Register"); reg &= (~(1 << bit)); retval = this->write_register(dev_addr, reg_addr, reg); CHECK_NYSA_ERROR("Error Writing Register"); return 0; } int Nysa::read_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit, bool * value){ uint32_t reg; int retval = 0; printd("Entered\n"); retval = this->read_register(dev_addr, reg_addr, &reg); CHECK_NYSA_ERROR("Error Reading Register"); reg &= (1 << bit); if (reg > 0){ *value = true; } else { *value = false; } return 0; } //DRT int Nysa::pretty_print_drt(){ return -1; } int Nysa::read_drt(){ uint8_t * buffer = new uint8_t [32]; uint32_t len = 1 * 32; int32_t retval; //We don't know the total size of the DRT so only look at the fist Block (32 bytes) retval = this->read_periph_data(0, 0, buffer, len); if (retval < 0){ printf ("%s(): Failed to read peripheral data\n", __func__); return -1; } //Found out how many devices are in the DRT this->num_devices = buffer[4] << 24 | buffer[5] << 16 | buffer[6] << 8 | buffer[7]; printf ("There are: %d devices\n", this->num_devices); delete(buffer); //Calculate the buffer size ( + 1 to read the DRT again) len = (this->num_devices + 1) * 32; printf ("Length of read: %d\n", len); this->drt = new uint8_t [len]; retval = this->read_periph_data(0, 0, this->drt, len); this->parse_drt(); return 0; } int Nysa::get_drt_version(){ if (this->drt == NULL){ return -1; } return this->version; } int Nysa::get_drt_device_count(){ if (this->drt == NULL){ return -1; } return this->num_devices; } uint32_t Nysa::get_drt_device_type(uint32_t index){ uint32_t pos = 0; uint32_t type; if (this->drt == NULL){ //XXX: Error handling return 0; } if (index == 0){ //DRT has no type //XXX: Error handling return 0; } if (index > this->num_devices){ //Out of range //XXX: Error handling return 0; } //Start of the device in question pos = (index) * 32; //Go to the start of the type type = this->drt[pos] << 24 | this->drt[pos + 1] << 16 | this->drt[pos + 2] << 8| this->drt[pos + 3]; return type; } uint32_t Nysa::get_drt_device_size(uint32_t index){ uint32_t size = 0; uint32_t pos = 0; if (this->drt == NULL){ //XXX: Error handling return 0; } if (index == 0){ //DRT has no type //XXX: Error handling return 0; } if (index > this->num_devices){ //Out of range //XXX: Error handling return 0; } //Start of the device in question pos = (index) * 32; pos += 12; //Go to the start of the type size = this->drt[pos] << 24 | this->drt[pos + 1] << 16 | this->drt[pos + 2] << 8 | this->drt[pos + 3]; return size; } uint32_t Nysa::get_drt_device_addr(uint32_t index){ uint32_t pos = 0; uint32_t addr; if (this->drt == NULL){ //XXX: Error handling return 0; } if (index == 0){ //DRT has no type //XXX: Error handling return 0; } if (index > this->num_devices){ //Out of range //XXX: Error handling return 0; } //Start of the device in question pos = (index) * 32; pos += 8; //Go to the start of the type addr = this->drt[pos] << 24 | this->drt[pos + 1] << 16 | this->drt[pos + 2] << 8 | this->drt[pos + 3]; return addr; } int Nysa::get_drt_device_flags(uint32_t index, uint16_t *nysa_flags, uint16_t *dev_flags){ uint32_t pos = 0; if (this->drt == NULL){ return -1; } if (index == 0){ //DRT has no type return -2; } if (index > this->num_devices){ //Out of range return -3; } //Start of the device in question pos = (index) * 32; pos += 4; //Go to the start of the type *nysa_flags = (this->drt[pos] << 8) | (this->drt[pos + 1]); *dev_flags = (this->drt[pos + 2] << 8) | (this->drt[pos + 3]); } bool Nysa::is_memory_device(uint32_t index){ int retval = 0; uint16_t nysa_flags; uint16_t dev_flags; retval = this->get_drt_device_flags(index, &nysa_flags, &dev_flags); if (nysa_flags & 0x01){ return true; } return false; } int Nysa::pretty_print_crash_report(){ return -1; } uint32_t Nysa::find_device(uint32_t device_type, uint32_t subtype, uint32_t id){ for (int i = 1; i < this->get_drt_device_count() + 1; i ++){ if (this->get_drt_device_type(i) == device_type){ if (subtype > 0){ //User has specified a subtype ID //XXX: Not implemented yet } if (id > 0){ //User has specified an implimentation specific identification //XXX: Not implemented yet } return i; } } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Stuart Walsh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdinc.h" #include <stdarg.h> #include <iomanip> #include <list> #include "system.h" #include "client.h" #include "connection.h" #include "numeric.h" #include "server.h" #include "channel.h" using std::string; using std::setw; using std::setfill; using std::list; Event<ClientPtr> Client::connected; Event<ClientPtr> Client::registering; Event<ClientPtr> Client::disconnected; Event<ClientPtr, irc_string> Client::nick_changing; Event<ClientPtr, string> Client::nick_changed; list<ClientPtr> Client::unregistered_list; map<BaseClient *, ClientPtr> Client::client_list; uv_timer_t Client::ping_timer; Client::Client() : invisible(false), last_message(time(NULL)) { } void Client::add_channel(const ChannelPtr channel) { channels.push_back(channel); } void Client::close(const string reason) { BaseClient::close(reason); for(auto it = channels.begin(); it != channels.end(); it++) { ChannelPtr channel = *it; channel->remove_member(client_list[this]); } } void Client::remove_channel(const ChannelPtr channel) { channels.remove(channel); } void Client::send(const string arg, int numeric) { stringstream buffer; buffer << ":" << Server::get_me()->str() << " "; buffer << setw(3) << setfill('0') << numeric; buffer << " "; if(name.empty()) buffer << "*"; else buffer << name; buffer << " " << arg; BaseClient::send(buffer.str()); } void Client::send(int numeric, ...) { va_list args; va_start(args, numeric); send(Numeric::format(numeric, args), numeric); va_end(args); } void Client::send_channels_common(string message) { unordered_map<BaseClient *, ClientPtr> sent_clients; for(auto it = channels.begin(); it != channels.end(); it++) { ChannelPtr channel = *it; map<ClientPtr, Membership> members = channel->get_members(); for(auto mit = members.begin(); mit != members.end(); mit++) { Membership ms = mit->second; if(sent_clients[ms.client.get()]) continue; sent_clients[ms.client.get()] = ms.client; ms.client->send(message); } } } irc_string Client::str() const { stringstream buff; if(name.empty()) return "*"; buff << name << "!" << username << "@" << host; return irc_string(buff.str().c_str()); } bool Client::is_invisible() const { return invisible; } string Client::get_username() const { return username; } string Client::get_realname() const { return realname; } time_t Client::get_idletime() const { return time(NULL) - last_message; } void Client::set_invisible(bool invis) { invisible = invis; } void Client::set_username(const string user) { username = user; } void Client::set_realname(const string real) { realname = real; } void Client::set_last_message(time_t when) { last_message = when; } // Statics void Client::init() { uv_timer_init(uv_default_loop(), &ping_timer); uv_timer_start(&ping_timer, check_pings, 0, 5); } void Client::add(ClientPtr ptr) { shared_ptr<Client> client = dynamic_pointer_cast<Client>(ptr); if(!registering(client)) return; client_list[ptr.get()] = ptr; client->set_registered(); unregistered_list.remove(client); connected(client); client->send(001, client->str().c_str()); client->send(002, Server::get_me()->str().c_str(), "0.0.1"); client->send(003, System::get_built_date()); } void Client::add_unregistered(ClientPtr client) { unregistered_list.push_back(client); } void Client::remove(ClientPtr client) { if(client->is_registered()) client_list.erase(client.get()); else unregistered_list.remove(client); } void Client::check_pings(uv_timer_t *handle, int status) { for(auto it = client_list.begin(); it != client_list.end(); it++) { ClientPtr client = it->second; if(!client->check_timeout()) { client->close("Ping Timeout"); } } for(auto it = unregistered_list.begin(); it != unregistered_list.end(); it++) { ClientPtr client = *it; if(!client->check_timeout()) { client->close("Registration timed out"); } } } <commit_msg>send_channels_common shouldn't send to the sender<commit_after>/* Copyright (c) 2012 Stuart Walsh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdinc.h" #include <stdarg.h> #include <iomanip> #include <list> #include "system.h" #include "client.h" #include "connection.h" #include "numeric.h" #include "server.h" #include "channel.h" using std::string; using std::setw; using std::setfill; using std::list; Event<ClientPtr> Client::connected; Event<ClientPtr> Client::registering; Event<ClientPtr> Client::disconnected; Event<ClientPtr, irc_string> Client::nick_changing; Event<ClientPtr, string> Client::nick_changed; list<ClientPtr> Client::unregistered_list; map<BaseClient *, ClientPtr> Client::client_list; uv_timer_t Client::ping_timer; Client::Client() : invisible(false), last_message(time(NULL)) { } void Client::add_channel(const ChannelPtr channel) { channels.push_back(channel); } void Client::close(const string reason) { BaseClient::close(reason); for(auto it = channels.begin(); it != channels.end(); it++) { ChannelPtr channel = *it; channel->remove_member(client_list[this]); } } void Client::remove_channel(const ChannelPtr channel) { channels.remove(channel); } void Client::send(const string arg, int numeric) { stringstream buffer; buffer << ":" << Server::get_me()->str() << " "; buffer << setw(3) << setfill('0') << numeric; buffer << " "; if(name.empty()) buffer << "*"; else buffer << name; buffer << " " << arg; BaseClient::send(buffer.str()); } void Client::send(int numeric, ...) { va_list args; va_start(args, numeric); send(Numeric::format(numeric, args), numeric); va_end(args); } void Client::send_channels_common(string message) { unordered_map<BaseClient *, ClientPtr> sent_clients; for(auto it = channels.begin(); it != channels.end(); it++) { ChannelPtr channel = *it; map<ClientPtr, Membership> members = channel->get_members(); for(auto mit = members.begin(); mit != members.end(); mit++) { Membership ms = mit->second; if(sent_clients[ms.client.get()]) continue; if(ms.client.get() == this) continue; sent_clients[ms.client.get()] = ms.client; ms.client->send(message); } } } irc_string Client::str() const { stringstream buff; if(name.empty()) return "*"; buff << name << "!" << username << "@" << host; return irc_string(buff.str().c_str()); } bool Client::is_invisible() const { return invisible; } string Client::get_username() const { return username; } string Client::get_realname() const { return realname; } time_t Client::get_idletime() const { return time(NULL) - last_message; } void Client::set_invisible(bool invis) { invisible = invis; } void Client::set_username(const string user) { username = user; } void Client::set_realname(const string real) { realname = real; } void Client::set_last_message(time_t when) { last_message = when; } // Statics void Client::init() { uv_timer_init(uv_default_loop(), &ping_timer); uv_timer_start(&ping_timer, check_pings, 0, 5); } void Client::add(ClientPtr ptr) { shared_ptr<Client> client = dynamic_pointer_cast<Client>(ptr); if(!registering(client)) return; client_list[ptr.get()] = ptr; client->set_registered(); unregistered_list.remove(client); connected(client); client->send(001, client->str().c_str()); client->send(002, Server::get_me()->str().c_str(), "0.0.1"); client->send(003, System::get_built_date()); } void Client::add_unregistered(ClientPtr client) { unregistered_list.push_back(client); } void Client::remove(ClientPtr client) { if(client->is_registered()) client_list.erase(client.get()); else unregistered_list.remove(client); } void Client::check_pings(uv_timer_t *handle, int status) { for(auto it = client_list.begin(); it != client_list.end(); it++) { ClientPtr client = it->second; if(!client->check_timeout()) { client->close("Ping Timeout"); } } for(auto it = unregistered_list.begin(); it != unregistered_list.end(); it++) { ClientPtr client = *it; if(!client->check_timeout()) { client->close("Registration timed out"); } } } <|endoftext|>
<commit_before> #include "id_func.h" #include "list_graph.h" #include "multi_arc.h" #include "sort_arc.h" #include "chain.h" #include "flow_cutter.h" #include "greedy_order.h" #include "node_flow_cutter.h" #include "contraction_graph.h" #include "cch_order.h" #include "tree_decomposition.h" #include "separator.h" #include <limits> #include <signal.h> #include <stdlib.h> #include <string.h> #include <string> #include <sstream> #ifdef PARALLELIZE #include <omp.h> #endif #include <sys/time.h> #include <unistd.h> using namespace std; ArrayIDIDFunc tail, head; const char*volatile best_decomposition = 0; int best_bag_size = numeric_limits<int>::max(); void ignore_return_value(int){} int compute_max_bag_size(const ArrayIDIDFunc&order){ auto inv_order = inverse_permutation(order); int current_tail = -1; int current_tail_up_deg = 0; int max_up_deg = 0; compute_chordal_supergraph( chain(tail, inv_order), chain(head, inv_order), [&](int x, int y){ if(current_tail != x){ current_tail = x; max_to(max_up_deg, current_tail_up_deg); current_tail_up_deg = 0; } ++current_tail_up_deg; } ); return max_up_deg+1; } unsigned long long get_milli_time(){ struct timeval tv; gettimeofday(&tv, NULL); return (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000; } const char*compute_decomposition(const ArrayIDIDFunc&order){ ostringstream out; print_tree_decompostion(out, tail, head, move(order)); char*buf = new char[out.str().length()+1]; memcpy(buf, out.str().c_str(), out.str().length()+1); return buf; } void test_new_order(ArrayIDIDFunc order){ int x = compute_max_bag_size(order); #ifdef PARALLELIZE #pragma omp critical #endif { if(x < best_bag_size){ best_bag_size = x; { string msg = "c status "+to_string(best_bag_size)+" "+to_string(get_milli_time())+"\n"; ignore_return_value(write(STDOUT_FILENO, msg.data(), msg.length())); } const char*old_decomposition = best_decomposition; best_decomposition = compute_decomposition(move(order)); delete[]old_decomposition; } } } void signal_handler(int) { const char*x = best_decomposition; if(x != 0) ignore_return_value(write(STDOUT_FILENO, x, strlen(x))); exit(0); } int main(int argc, char*argv[]){ signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); signal(SIGSEGV, signal_handler); try{ { string file_name = "-"; if(argc == 2) file_name = argv[1]; auto g = uncached_load_pace_graph(file_name); tail = std::move(g.tail); head = std::move(g.head); } test_new_order(identity_permutation(tail.image_count())); test_new_order(compute_greedy_min_degree_order(tail, head)); test_new_order(compute_greedy_min_shortcut_order(tail, head)); int random_seed = 0; if(argc == 3){ if(string(argv[1]) == "-s"){ random_seed = atoi(argv[2]); } } #ifdef PARALLELIZE #pragma omp parallel #endif { try{ std::minstd_rand rand_gen; rand_gen.seed( random_seed #ifdef PARALLELIZE + omp_get_thread_num() #endif ); flow_cutter::Config config; config.cutter_count = 1; config.random_seed = rand_gen(); for(int i=0;;++i){ config.random_seed = rand_gen(); if(i % 32 == 0) ++config.cutter_count; test_new_order(cch_order::compute_cch_graph_order(tail, head, flow_cutter::ComputeSeparator(config))); } }catch(...){ signal_handler(0); } } }catch(...){ signal_handler(0); } } <commit_msg>replaced exit(0) by _Exit(0) because the former is not allowed in a signal handler<commit_after> #include "id_func.h" #include "list_graph.h" #include "multi_arc.h" #include "sort_arc.h" #include "chain.h" #include "flow_cutter.h" #include "greedy_order.h" #include "node_flow_cutter.h" #include "contraction_graph.h" #include "cch_order.h" #include "tree_decomposition.h" #include "separator.h" #include <limits> #include <signal.h> #include <stdlib.h> #include <string.h> #include <string> #include <sstream> #ifdef PARALLELIZE #include <omp.h> #endif #include <sys/time.h> #include <unistd.h> using namespace std; ArrayIDIDFunc tail, head; const char*volatile best_decomposition = 0; int best_bag_size = numeric_limits<int>::max(); void ignore_return_value(int){} int compute_max_bag_size(const ArrayIDIDFunc&order){ auto inv_order = inverse_permutation(order); int current_tail = -1; int current_tail_up_deg = 0; int max_up_deg = 0; compute_chordal_supergraph( chain(tail, inv_order), chain(head, inv_order), [&](int x, int y){ if(current_tail != x){ current_tail = x; max_to(max_up_deg, current_tail_up_deg); current_tail_up_deg = 0; } ++current_tail_up_deg; } ); return max_up_deg+1; } unsigned long long get_milli_time(){ struct timeval tv; gettimeofday(&tv, NULL); return (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000; } const char*compute_decomposition(const ArrayIDIDFunc&order){ ostringstream out; print_tree_decompostion(out, tail, head, move(order)); char*buf = new char[out.str().length()+1]; memcpy(buf, out.str().c_str(), out.str().length()+1); return buf; } void test_new_order(ArrayIDIDFunc order){ int x = compute_max_bag_size(order); #ifdef PARALLELIZE #pragma omp critical #endif { if(x < best_bag_size){ best_bag_size = x; { string msg = "c status "+to_string(best_bag_size)+" "+to_string(get_milli_time())+"\n"; ignore_return_value(write(STDOUT_FILENO, msg.data(), msg.length())); } const char*old_decomposition = best_decomposition; best_decomposition = compute_decomposition(move(order)); delete[]old_decomposition; } } } void signal_handler(int) { const char*x = best_decomposition; if(x != 0) ignore_return_value(write(STDOUT_FILENO, x, strlen(x))); _Exit(EXIT_SUCCESS); } int main(int argc, char*argv[]){ signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); signal(SIGSEGV, signal_handler); try{ { string file_name = "-"; if(argc == 2) file_name = argv[1]; auto g = uncached_load_pace_graph(file_name); tail = std::move(g.tail); head = std::move(g.head); } test_new_order(identity_permutation(tail.image_count())); test_new_order(compute_greedy_min_degree_order(tail, head)); test_new_order(compute_greedy_min_shortcut_order(tail, head)); int random_seed = 0; if(argc == 3){ if(string(argv[1]) == "-s"){ random_seed = atoi(argv[2]); } } #ifdef PARALLELIZE #pragma omp parallel #endif { try{ std::minstd_rand rand_gen; rand_gen.seed( random_seed #ifdef PARALLELIZE + omp_get_thread_num() #endif ); flow_cutter::Config config; config.cutter_count = 1; config.random_seed = rand_gen(); for(int i=0;;++i){ config.random_seed = rand_gen(); if(i % 32 == 0) ++config.cutter_count; test_new_order(cch_order::compute_cch_graph_order(tail, head, flow_cutter::ComputeSeparator(config))); } }catch(...){ signal_handler(0); } } }catch(...){ signal_handler(0); } } <|endoftext|>
<commit_before>/****************************************************************/ /* derived form NearestNodeLocator.C */ /****************************************************************/ #include "VolumeNearestNodeLocator.h" #include "MooseMesh.h" #include "SubProblem.h" #include "SlaveNeighborhoodThread.h" #include "NearestNodeThread.h" #include "Moose.h" // libMesh #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/plane.h" #include "libmesh/mesh_tools.h" std::string _boundaryBlockFuser(BoundaryID boundary, SubdomainID block) { std::stringstream ss; ss << boundary << "to" << block; return ss.str(); } VolumeNearestNodeLocator::VolumeNearestNodeLocator(SubProblem & subproblem, MooseMesh & mesh, BoundaryID boundary, SubdomainID block) : Restartable(_boundaryBlockFuser(boundary, block), "VolumeNearestNodeLocator", subproblem, 0), _subproblem(subproblem), _mesh(mesh), _block_node_range(NULL), _boundary(boundary), _block(block), _first(true) { //sanity check on ids const std::set<BoundaryID>& bids=_mesh.getBoundaryIDs(); std::set<BoundaryID>::const_iterator sit; sit=bids.find(_boundary); if (sit == bids.end()) mooseError("VolumeNearestNodeLocator being created for boundary "<<_boundary<<" and block "<<_block<<", but boundary "<<_boundary<<" does not exist"); const std::set<SubdomainID>& sids=_mesh.meshSubdomains(); std::set<SubdomainID>::const_iterator ssit; ssit=sids.find(_block); if (ssit == sids.end()) mooseError("VolumeNearestNodeLocator being created for boundary "<<_boundary<<" and block "<<_block<<", but block "<<_block<<" does not exist"); } VolumeNearestNodeLocator::~VolumeNearestNodeLocator() { delete _block_node_range; } void VolumeNearestNodeLocator::findNodes() { Moose::perf_log.push("VolumeNearestNodeLocator::findNodes()","Solve"); /** * If this is the first time through we're going to build up a "neighborhood" of nodes * surrounding each of the block nodes. This will speed searching later. */ if (_first) { _first=false; // Trial block nodes are all the nodes on the slave side // We only keep the ones that are either on this processor or are likely // to interact with elements on this processor (ie nodes owned by this processor // are in the "neighborhood" of the block node std::vector<unsigned int> trial_block_nodes; // was slave std::vector<unsigned int> trial_boundary_nodes; // was master // Build a bounding box. No reason to consider nodes outside of our inflated BB MeshTools::BoundingBox * my_inflated_box = NULL; std::vector<Real> & inflation = _mesh.getGhostedBoundaryInflation(); // This means there was a user specified inflation... so we can build a BB if (inflation.size() > 0) { MeshTools::BoundingBox my_box = MeshTools::processor_bounding_box(_mesh, _mesh.processor_id()); Real distance_x = 0; Real distance_y = 0; Real distance_z = 0; distance_x = inflation[0]; if (inflation.size() > 1) distance_y = inflation[1]; if (inflation.size() > 2) distance_z = inflation[2]; my_inflated_box = new MeshTools::BoundingBox(Point(my_box.first(0)-distance_x, my_box.first(1)-distance_y, my_box.first(2)-distance_z), Point(my_box.second(0)+distance_x, my_box.second(1)+distance_y, my_box.second(2)+distance_z)); } // Data structures to hold the Nodal Boundary conditions ConstBndNodeRange & bnd_nodes = *_mesh.getBoundaryNodeRange(); for (ConstBndNodeRange::const_iterator nd = bnd_nodes.begin() ; nd != bnd_nodes.end(); ++nd) { const BndNode * bnode = *nd; BoundaryID boundary_id = bnode->_bnd_id; unsigned int node_id = bnode->_node->id(); // If we have a BB only consider saving this node if it's in our inflated BB if (boundary_id == _boundary && (!my_inflated_box || (my_inflated_box->contains_point(*bnode->_node)))) trial_boundary_nodes.push_back(node_id); } for (libMesh::Node const *nd = *_mesh.localNodesBegin() ; nd != *_mesh.localNodesEnd(); ++nd) { const Node * node = nd; std::set<SubdomainID> sids = _mesh.getNodeBlockIds(*node); std::set<SubdomainID>::const_iterator ssit(sids.find(_block)); unsigned int node_id = node->id(); // If we have a BB only consider saving this node if it's in our inflated BB if (ssit != sids.end() && (!my_inflated_box || (my_inflated_box->contains_point(*node)))) trial_block_nodes.push_back(node_id); } // don't need the BB anymore delete my_inflated_box; std::map<unsigned int, std::vector<unsigned int> > & node_to_elem_map = _mesh.nodeToElemMap(); SlaveNeighborhoodThread snt(_mesh, trial_boundary_nodes, node_to_elem_map, _mesh.getPatchSize()); NodeIdRange trial_block_node_range(trial_block_nodes.begin(), trial_block_nodes.end(), 1); Threads::parallel_reduce(trial_block_node_range, snt); _block_nodes = snt._slave_nodes; _neighbor_nodes = snt._neighbor_nodes; for (std::set<unsigned int>::iterator it = snt._ghosted_elems.begin(); it != snt._ghosted_elems.end(); ++it) _subproblem.addGhostedElem(*it); // Cache the blocke_node_range so we don't have to build it each time _block_node_range = new NodeIdRange(_block_nodes.begin(), _block_nodes.end(), 1); } _nearest_node_info.clear(); NearestNodeThread nnt(_mesh, _neighbor_nodes); Threads::parallel_reduce(*_block_node_range, nnt); _max_patch_percentage = nnt._max_patch_percentage; _nearest_node_info = nnt._nearest_node_info; Moose::perf_log.pop("VolumeNearestNodeLocator::findNodes()","Solve"); } void VolumeNearestNodeLocator::reinit() { // Reset all data delete _block_node_range; _block_node_range = NULL; _nearest_node_info.clear(); _first = true; _block_nodes.clear(); _neighbor_nodes.clear(); // Redo the search findNodes(); } Real VolumeNearestNodeLocator::distance(unsigned int node_id) { return _nearest_node_info[node_id]._distance; } const Node * VolumeNearestNodeLocator::nearestNode(unsigned int node_id) { return _nearest_node_info[node_id]._nearest_node; } <commit_msg>fixed a segfault in VolumeNearestNodeLocator due to improper use of iterators *grmpf*<commit_after>/****************************************************************/ /* derived form NearestNodeLocator.C */ /****************************************************************/ #include "VolumeNearestNodeLocator.h" #include "MooseMesh.h" #include "SubProblem.h" #include "SlaveNeighborhoodThread.h" #include "NearestNodeThread.h" #include "Moose.h" // libMesh #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/plane.h" #include "libmesh/mesh_tools.h" std::string _boundaryBlockFuser(BoundaryID boundary, SubdomainID block) { std::stringstream ss; ss << boundary << "to" << block; return ss.str(); } VolumeNearestNodeLocator::VolumeNearestNodeLocator(SubProblem & subproblem, MooseMesh & mesh, BoundaryID boundary, SubdomainID block) : Restartable(_boundaryBlockFuser(boundary, block), "VolumeNearestNodeLocator", subproblem, 0), _subproblem(subproblem), _mesh(mesh), _block_node_range(NULL), _boundary(boundary), _block(block), _first(true) { //sanity check on ids const std::set<BoundaryID>& bids=_mesh.getBoundaryIDs(); std::set<BoundaryID>::const_iterator sit; sit=bids.find(_boundary); if (sit == bids.end()) mooseError("VolumeNearestNodeLocator being created for boundary "<<_boundary<<" and block "<<_block<<", but boundary "<<_boundary<<" does not exist"); const std::set<SubdomainID>& sids=_mesh.meshSubdomains(); std::set<SubdomainID>::const_iterator ssit; ssit=sids.find(_block); if (ssit == sids.end()) mooseError("VolumeNearestNodeLocator being created for boundary "<<_boundary<<" and block "<<_block<<", but block "<<_block<<" does not exist"); } VolumeNearestNodeLocator::~VolumeNearestNodeLocator() { delete _block_node_range; } void VolumeNearestNodeLocator::findNodes() { Moose::perf_log.push("VolumeNearestNodeLocator::findNodes()","Solve"); /** * If this is the first time through we're going to build up a "neighborhood" of nodes * surrounding each of the block nodes. This will speed searching later. */ if (_first) { _first=false; // Trial block nodes are all the nodes on the slave side // We only keep the ones that are either on this processor or are likely // to interact with elements on this processor (ie nodes owned by this processor // are in the "neighborhood" of the block node std::vector<unsigned int> trial_block_nodes; // was slave std::vector<unsigned int> trial_boundary_nodes; // was master // Build a bounding box. No reason to consider nodes outside of our inflated BB MeshTools::BoundingBox * my_inflated_box = NULL; std::vector<Real> & inflation = _mesh.getGhostedBoundaryInflation(); // This means there was a user specified inflation... so we can build a BB if (inflation.size() > 0) { MeshTools::BoundingBox my_box = MeshTools::processor_bounding_box(_mesh, _mesh.processor_id()); Real distance_x = 0; Real distance_y = 0; Real distance_z = 0; distance_x = inflation[0]; if (inflation.size() > 1) distance_y = inflation[1]; if (inflation.size() > 2) distance_z = inflation[2]; my_inflated_box = new MeshTools::BoundingBox(Point(my_box.first(0)-distance_x, my_box.first(1)-distance_y, my_box.first(2)-distance_z), Point(my_box.second(0)+distance_x, my_box.second(1)+distance_y, my_box.second(2)+distance_z)); } // Data structures to hold the Nodal Boundary conditions ConstBndNodeRange & bnd_nodes = *_mesh.getBoundaryNodeRange(); for (ConstBndNodeRange::const_iterator nd = bnd_nodes.begin() ; nd != bnd_nodes.end(); ++nd) { const BndNode * bnode = *nd; BoundaryID boundary_id = bnode->_bnd_id; unsigned int node_id = bnode->_node->id(); // If we have a BB only consider saving this node if it's in our inflated BB if (boundary_id == _boundary && (!my_inflated_box || (my_inflated_box->contains_point(*bnode->_node)))) trial_boundary_nodes.push_back(node_id); } for (MeshBase::const_node_iterator nd = _mesh.localNodesBegin(); nd != _mesh.localNodesEnd(); ++nd) { const Node * node = *nd; std::set<SubdomainID> sids = _mesh.getNodeBlockIds(*node); std::set<SubdomainID>::const_iterator ssit(sids.find(_block)); unsigned int node_id = node->id(); // If we have a BB only consider saving this node if it's in our inflated BB if (ssit != sids.end() && (!my_inflated_box || (my_inflated_box->contains_point(*node)))) trial_block_nodes.push_back(node_id); } // don't need the BB anymore delete my_inflated_box; std::map<unsigned int, std::vector<unsigned int> > & node_to_elem_map = _mesh.nodeToElemMap(); SlaveNeighborhoodThread snt(_mesh, trial_boundary_nodes, node_to_elem_map, _mesh.getPatchSize()); NodeIdRange trial_block_node_range(trial_block_nodes.begin(), trial_block_nodes.end(), 1); Threads::parallel_reduce(trial_block_node_range, snt); _block_nodes = snt._slave_nodes; _neighbor_nodes = snt._neighbor_nodes; for (std::set<unsigned int>::iterator it = snt._ghosted_elems.begin(); it != snt._ghosted_elems.end(); ++it) _subproblem.addGhostedElem(*it); // Cache the blocke_node_range so we don't have to build it each time _block_node_range = new NodeIdRange(_block_nodes.begin(), _block_nodes.end(), 1); } _nearest_node_info.clear(); NearestNodeThread nnt(_mesh, _neighbor_nodes); Threads::parallel_reduce(*_block_node_range, nnt); _max_patch_percentage = nnt._max_patch_percentage; _nearest_node_info = nnt._nearest_node_info; Moose::perf_log.pop("VolumeNearestNodeLocator::findNodes()","Solve"); } void VolumeNearestNodeLocator::reinit() { // Reset all data delete _block_node_range; _block_node_range = NULL; _nearest_node_info.clear(); _first = true; _block_nodes.clear(); _neighbor_nodes.clear(); // Redo the search findNodes(); } Real VolumeNearestNodeLocator::distance(unsigned int node_id) { return _nearest_node_info[node_id]._distance; } const Node * VolumeNearestNodeLocator::nearestNode(unsigned int node_id) { return _nearest_node_info[node_id]._nearest_node; } <|endoftext|>
<commit_before>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // CSProfileUtils.C // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** //************************* System Include Files **************************** #include <iostream> #include <fstream> #ifdef NO_STD_CHEADERS // FIXME # include <string.h> #else # include <cstring> using namespace std; // For compatibility with non-std C headers #endif //*************************** User Include Files **************************** #include "CSProfileUtils.h" #include <lib/binutils/LoadModule.h> #include <lib/binutils/PCToSrcLineMap.h> #include <lib/binutils/LoadModuleInfo.h> #include <lib/xml/xml.h> #include <lib/support/String.h> #include <lib/support/Assertion.h> #include <lib/hpcfile/hpcfile_csproflib.h> //*************************** Forward Declarations *************************** using namespace xml; extern "C" { static void* cstree_create_node_CB(void* tree, hpcfile_cstree_nodedata_t* data); static void cstree_link_parent_CB(void* tree, void* node, void* parent); static void* hpcfile_alloc_CB(size_t sz); static void hpcfile_free_CB(void* mem); } bool AddPGMToCSProfTree(CSProfTree* tree, const char* progName); void ConvertOpIPToIP(Addr opIP, Addr& ip, ushort& opIdx); //**************************************************************************** // Dump a CSProfTree and collect source file information //**************************************************************************** const char *CSPROFILEdtd = #include <lib/xml/CSPROFILE.dtd.h> void WriteCSProfile(CSProfile* prof, std::ostream& os, bool prettyPrint) { os << "<?xml version=\"1.0\"?>" << std::endl; os << "<!DOCTYPE CSPROFILE [\n" << CSPROFILEdtd << "]>" << std::endl; os.flush(); CSProfileMetric* metric = prof->GetMetric(); os << "<CSPROFILE version=\"1.0\">\n"; os << "<CSPROFILEHDR>\n</CSPROFILEHDR>\n"; os << "<CSPROFILEPARAMS>\n"; { os << "<TARGET name"; WriteAttrStr(os, prof->GetTarget()); os << "/>\n"; os << "<METRIC shortName"; WriteAttrNum(os, 0); os << " nativeName"; WriteAttrNum(os, metric->GetName()); os << " period"; WriteAttrNum(os, metric->GetPeriod()); os << "/>\n"; os << "</CSPROFILEPARAMS>\n"; } os.flush(); int dumpFlags = (CSProfTree::XML_TRUE); // CSProfTree::XML_NO_ESC_CHARS if (!prettyPrint) { dumpFlags |= CSProfTree::COMPRESSED_OUTPUT; } prof->GetTree()->Dump(os, dumpFlags); } bool AddSourceFileInfoToCSProfile(CSProfile* prof, LoadModuleInfo* lm) { bool noError = true; CSProfTree* tree = prof->GetTree(); CSProfNode* root = tree->GetRoot(); for (CSProfNodeIterator it(root); it.CurNode(); ++it) { CSProfNode* n = it.CurNode(); AddSourceFileInfoToCSTreeNode(n, lm); } return noError; } bool AddSourceFileInfoToCSTreeNode(CSProfNode* node, LoadModuleInfo* lm) { bool noError = true; CSProfCallSiteNode* n = dynamic_cast<CSProfCallSiteNode*>(node); if (n) { String func, file; SrcLineX srcLn; lm->GetSymbolicInfo(n->GetIP(), n->GetOpIndex(), func, file, srcLn); n->SetFile(file); n->SetProc(func); n->SetLine(srcLn.GetSrcLine()); } return noError; } //**************************************************************************** // Set of routines to build a scope tree while reading data file //**************************************************************************** CSProfile* ReadCSProfileFile_HCSPROFILE(const char* fnm) { hpcfile_csprof_data_t data; int ret1, ret2; CSProfile* prof = new CSProfile; // Read profile FILE* fs = hpcfile_open_for_read(fnm); ret1 = hpcfile_csprof_read(fs, &data, hpcfile_alloc_CB, hpcfile_free_CB); ret2 = hpcfile_cstree_read(fs, prof->GetTree(), cstree_create_node_CB, cstree_link_parent_CB, hpcfile_alloc_CB, hpcfile_free_CB); hpcfile_close(fs); if ( !(ret1 == HPCFILE_OK && ret2 == HPCFILE_OK) ) { delete prof; return NULL; } // Extract profiling info prof->SetTarget(data.target); CSProfileMetric* metric = prof->GetMetric(); metric->SetName(data.event); metric->SetPeriod(data.sample_period); // We must deallocate pointer-data hpcfile_free_CB(data.target); hpcfile_free_CB(data.event); // Add PGM node to tree AddPGMToCSProfTree(prof->GetTree(), prof->GetTarget()); return prof; } static void* cstree_create_node_CB(void* tree, hpcfile_cstree_nodedata_t* data) { CSProfTree* t = (CSProfTree*)tree; Addr ip; ushort opIdx; ConvertOpIPToIP((Addr)data->ip, ip, opIdx); CSProfCallSiteNode* n = new CSProfCallSiteNode(NULL, ip, opIdx, (suint)data->weight); // Initialize the tree, if necessary if (t->IsEmpty()) { t->SetRoot(n); } return n; } static void cstree_link_parent_CB(void* tree, void* node, void* parent) { CSProfCallSiteNode* p = (CSProfCallSiteNode*)parent; CSProfCallSiteNode* n = (CSProfCallSiteNode*)node; n->Link(p); } static void* hpcfile_alloc_CB(size_t sz) { return (new char[sz]); } static void hpcfile_free_CB(void* mem) { delete[] (char*)mem; } // ConvertOpIPToIP: Find the instruction pointer 'ip' and operation // index 'opIdx' from the operation pointer 'opIP'. The operation // pointer is represented by adding 0, 1, or 2 to the instruction // pointer for the first, second and third operation, respectively. void ConvertOpIPToIP(Addr opIP, Addr& ip, ushort& opIdx) { opIdx = (ushort)(opIP & 0x3); // the mask ...00011 covers 0, 1 and 2 ip = opIP - opIdx; } bool AddPGMToCSProfTree(CSProfTree* tree, const char* progName) { bool noError = true; // Add PGM node CSProfNode* n = tree->GetRoot(); if (!n || n->GetType() != CSProfNode::PGM) { CSProfNode* root = new CSProfPgmNode(progName); if (n) { n->Link(root); // 'root' is parent of 'n' } tree->SetRoot(root); } return noError; } //*************************************************************************** // Routines for normalizing the ScopeTree //*************************************************************************** bool CoalesceCallsiteLeaves(CSProfile* prof); bool NormalizeCSProfile(CSProfile* prof) { // Remove duplicate/inplied file and procedure information from tree bool pass1 = true; bool pass2 = CoalesceCallsiteLeaves(prof); return (pass1 && pass2); } // FIXME // If pc values from the leaves map to the same source file info, // coalese these leaves into one. bool CoalesceCallsiteLeaves(CSProfNode* node); bool CoalesceCallsiteLeaves(CSProfile* prof) { CSProfTree* csproftree = prof->GetTree(); if (!csproftree) { return true; } return CoalesceCallsiteLeaves(csproftree->GetRoot()); } // FIXME typedef std::map<String, CSProfCallSiteNode*, StringLt> StringToCallSiteMap; typedef std::map<String, CSProfCallSiteNode*, StringLt>::iterator StringToCallSiteMapIt; typedef std::map<String, CSProfCallSiteNode*, StringLt>::value_type StringToCallSiteMapVal; bool CoalesceCallsiteLeaves(CSProfNode* node) { bool noError = true; if (!node) { return noError; } // FIXME: Use this set to determine if we have a duplicate source line StringToCallSiteMap sourceInfoMap; // For each immediate child of this node... for (CSProfNodeChildIterator it(node); it.Current(); /* */) { CSProfCodeNode* child = dynamic_cast<CSProfCodeNode*>(it.CurNode()); BriefAssertion(child); // always true (FIXME) it++; // advance iterator -- it is pointing at 'child' bool inspect = (child->IsLeaf() && (child->GetType() == CSProfNode::CALLSITE)); if (inspect) { // This child is a leaf. Test for duplicate source line info. CSProfCallSiteNode* c = dynamic_cast<CSProfCallSiteNode*>(child); String myid = String(c->GetFile()) + String(c->GetProc()) + String(c->GetLine()); StringToCallSiteMapIt it = sourceInfoMap.find(myid); if (it != sourceInfoMap.end()) { // found -- we have a duplicate CSProfCallSiteNode* c1 = (*it).second; // add weights of 'c' and 'c1' suint newWeight = c->GetWeight() + c1->GetWeight(); c1->SetWeight(newWeight); // remove 'child' from tree child->Unlink(); delete child; } else { // no entry found -- add sourceInfoMap.insert(StringToCallSiteMapVal(myid, c)); } } else if (!child->IsLeaf()) { // Recur: noError = noError && CoalesceCallsiteLeaves(child); } } return noError; } <commit_msg>fixed CSProfileUtils.C to add </CSPROFILE> tag<commit_after>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // CSProfileUtils.C // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** //************************* System Include Files **************************** #include <iostream> #include <fstream> #ifdef NO_STD_CHEADERS // FIXME # include <string.h> #else # include <cstring> using namespace std; // For compatibility with non-std C headers #endif //*************************** User Include Files **************************** #include "CSProfileUtils.h" #include <lib/binutils/LoadModule.h> #include <lib/binutils/PCToSrcLineMap.h> #include <lib/binutils/LoadModuleInfo.h> #include <lib/xml/xml.h> #include <lib/support/String.h> #include <lib/support/Assertion.h> #include <lib/hpcfile/hpcfile_csproflib.h> //*************************** Forward Declarations *************************** using namespace xml; extern "C" { static void* cstree_create_node_CB(void* tree, hpcfile_cstree_nodedata_t* data); static void cstree_link_parent_CB(void* tree, void* node, void* parent); static void* hpcfile_alloc_CB(size_t sz); static void hpcfile_free_CB(void* mem); } bool AddPGMToCSProfTree(CSProfTree* tree, const char* progName); void ConvertOpIPToIP(Addr opIP, Addr& ip, ushort& opIdx); //**************************************************************************** // Dump a CSProfTree and collect source file information //**************************************************************************** const char *CSPROFILEdtd = #include <lib/xml/CSPROFILE.dtd.h> void WriteCSProfile(CSProfile* prof, std::ostream& os, bool prettyPrint) { os << "<?xml version=\"1.0\"?>" << std::endl; os << "<!DOCTYPE CSPROFILE [\n" << CSPROFILEdtd << "]>" << std::endl; os.flush(); CSProfileMetric* metric = prof->GetMetric(); os << "<CSPROFILE version=\"1.0\">\n"; os << "<CSPROFILEHDR>\n</CSPROFILEHDR>\n"; { os << "<CSPROFILEPARAMS>\n"; os << "<TARGET name"; WriteAttrStr(os, prof->GetTarget()); os << "/>\n"; os << "<METRIC shortName"; WriteAttrNum(os, 0); os << " nativeName"; WriteAttrNum(os, metric->GetName()); os << " period"; WriteAttrNum(os, metric->GetPeriod()); os << "/>\n"; os << "</CSPROFILEPARAMS>\n"; } os.flush(); int dumpFlags = (CSProfTree::XML_TRUE); // CSProfTree::XML_NO_ESC_CHARS if (!prettyPrint) { dumpFlags |= CSProfTree::COMPRESSED_OUTPUT; } prof->GetTree()->Dump(os, dumpFlags); os << "</CSPROFILE>\n"; os.flush(); } bool AddSourceFileInfoToCSProfile(CSProfile* prof, LoadModuleInfo* lm) { bool noError = true; CSProfTree* tree = prof->GetTree(); CSProfNode* root = tree->GetRoot(); for (CSProfNodeIterator it(root); it.CurNode(); ++it) { CSProfNode* n = it.CurNode(); AddSourceFileInfoToCSTreeNode(n, lm); } return noError; } bool AddSourceFileInfoToCSTreeNode(CSProfNode* node, LoadModuleInfo* lm) { bool noError = true; CSProfCallSiteNode* n = dynamic_cast<CSProfCallSiteNode*>(node); if (n) { String func, file; SrcLineX srcLn; lm->GetSymbolicInfo(n->GetIP(), n->GetOpIndex(), func, file, srcLn); n->SetFile(file); n->SetProc(func); n->SetLine(srcLn.GetSrcLine()); } return noError; } //**************************************************************************** // Set of routines to build a scope tree while reading data file //**************************************************************************** CSProfile* ReadCSProfileFile_HCSPROFILE(const char* fnm) { hpcfile_csprof_data_t data; int ret1, ret2; CSProfile* prof = new CSProfile; // Read profile FILE* fs = hpcfile_open_for_read(fnm); ret1 = hpcfile_csprof_read(fs, &data, hpcfile_alloc_CB, hpcfile_free_CB); ret2 = hpcfile_cstree_read(fs, prof->GetTree(), cstree_create_node_CB, cstree_link_parent_CB, hpcfile_alloc_CB, hpcfile_free_CB); hpcfile_close(fs); if ( !(ret1 == HPCFILE_OK && ret2 == HPCFILE_OK) ) { delete prof; return NULL; } // Extract profiling info prof->SetTarget(data.target); CSProfileMetric* metric = prof->GetMetric(); metric->SetName(data.event); metric->SetPeriod(data.sample_period); // We must deallocate pointer-data hpcfile_free_CB(data.target); hpcfile_free_CB(data.event); // Add PGM node to tree AddPGMToCSProfTree(prof->GetTree(), prof->GetTarget()); return prof; } static void* cstree_create_node_CB(void* tree, hpcfile_cstree_nodedata_t* data) { CSProfTree* t = (CSProfTree*)tree; Addr ip; ushort opIdx; ConvertOpIPToIP((Addr)data->ip, ip, opIdx); CSProfCallSiteNode* n = new CSProfCallSiteNode(NULL, ip, opIdx, (suint)data->weight); // Initialize the tree, if necessary if (t->IsEmpty()) { t->SetRoot(n); } return n; } static void cstree_link_parent_CB(void* tree, void* node, void* parent) { CSProfCallSiteNode* p = (CSProfCallSiteNode*)parent; CSProfCallSiteNode* n = (CSProfCallSiteNode*)node; n->Link(p); } static void* hpcfile_alloc_CB(size_t sz) { return (new char[sz]); } static void hpcfile_free_CB(void* mem) { delete[] (char*)mem; } // ConvertOpIPToIP: Find the instruction pointer 'ip' and operation // index 'opIdx' from the operation pointer 'opIP'. The operation // pointer is represented by adding 0, 1, or 2 to the instruction // pointer for the first, second and third operation, respectively. void ConvertOpIPToIP(Addr opIP, Addr& ip, ushort& opIdx) { opIdx = (ushort)(opIP & 0x3); // the mask ...00011 covers 0, 1 and 2 ip = opIP - opIdx; } bool AddPGMToCSProfTree(CSProfTree* tree, const char* progName) { bool noError = true; // Add PGM node CSProfNode* n = tree->GetRoot(); if (!n || n->GetType() != CSProfNode::PGM) { CSProfNode* root = new CSProfPgmNode(progName); if (n) { n->Link(root); // 'root' is parent of 'n' } tree->SetRoot(root); } return noError; } //*************************************************************************** // Routines for normalizing the ScopeTree //*************************************************************************** bool CoalesceCallsiteLeaves(CSProfile* prof); bool NormalizeCSProfile(CSProfile* prof) { // Remove duplicate/inplied file and procedure information from tree bool pass1 = true; bool pass2 = CoalesceCallsiteLeaves(prof); return (pass1 && pass2); } // FIXME // If pc values from the leaves map to the same source file info, // coalese these leaves into one. bool CoalesceCallsiteLeaves(CSProfNode* node); bool CoalesceCallsiteLeaves(CSProfile* prof) { CSProfTree* csproftree = prof->GetTree(); if (!csproftree) { return true; } return CoalesceCallsiteLeaves(csproftree->GetRoot()); } // FIXME typedef std::map<String, CSProfCallSiteNode*, StringLt> StringToCallSiteMap; typedef std::map<String, CSProfCallSiteNode*, StringLt>::iterator StringToCallSiteMapIt; typedef std::map<String, CSProfCallSiteNode*, StringLt>::value_type StringToCallSiteMapVal; bool CoalesceCallsiteLeaves(CSProfNode* node) { bool noError = true; if (!node) { return noError; } // FIXME: Use this set to determine if we have a duplicate source line StringToCallSiteMap sourceInfoMap; // For each immediate child of this node... for (CSProfNodeChildIterator it(node); it.Current(); /* */) { CSProfCodeNode* child = dynamic_cast<CSProfCodeNode*>(it.CurNode()); BriefAssertion(child); // always true (FIXME) it++; // advance iterator -- it is pointing at 'child' bool inspect = (child->IsLeaf() && (child->GetType() == CSProfNode::CALLSITE)); if (inspect) { // This child is a leaf. Test for duplicate source line info. CSProfCallSiteNode* c = dynamic_cast<CSProfCallSiteNode*>(child); String myid = String(c->GetFile()) + String(c->GetProc()) + String(c->GetLine()); StringToCallSiteMapIt it = sourceInfoMap.find(myid); if (it != sourceInfoMap.end()) { // found -- we have a duplicate CSProfCallSiteNode* c1 = (*it).second; // add weights of 'c' and 'c1' suint newWeight = c->GetWeight() + c1->GetWeight(); c1->SetWeight(newWeight); // remove 'child' from tree child->Unlink(); delete child; } else { // no entry found -- add sourceInfoMap.insert(StringToCallSiteMapVal(myid, c)); } } else if (!child->IsLeaf()) { // Recur: noError = noError && CoalesceCallsiteLeaves(child); } } return noError; } <|endoftext|>
<commit_before>#include "stdafx.h" #include <tcp_server.h> #include "asio_service_deamon.h" #include "io_dispatcher.h" AsioServiceDeamon::AsioServiceDeamon() { } AsioServiceDeamon::~AsioServiceDeamon() { delete _service; delete _server; //delete _network_service; } void AsioServiceDeamon::start(const std::string& serviceName, const uint32_t& threadNum/* = irene::net_params::smart_thread_nums()*/) { _serviceName = serviceName; //create io service instance _service = new IOService; //create tcp server instance _server = new TcpServer(InetAddress(48360), *_service, 1); //create network service instance //_network_service = new NetworkService(); //register io events IODispatcher io_dispatcher; _server->setNewConnectionCallback( std::bind(&IODispatcher::NewConnectionHandler, &io_dispatcher, std::placeholders::_1, std::placeholders::_2) ); _server->setWriteCompletedCallback( std::bind(&IODispatcher::WriteCompletedHandler, &io_dispatcher, std::placeholders::_1, std::placeholders::_2) ); _server->setReadCompletedCallback( std::bind(&IODispatcher::ReadCompletedHandler, &io_dispatcher, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) ); _server->setConnectionClosedCallback( std::bind(&IODispatcher::ConnectionClosed, &io_dispatcher, std::placeholders::_1) ); _server->start(); } void AsioServiceDeamon::stop() { }<commit_msg>* 修改一个无法从最外部传入线程数的编写失误<commit_after>#include "stdafx.h" #include <tcp_server.h> #include "asio_service_deamon.h" #include "io_dispatcher.h" AsioServiceDeamon::AsioServiceDeamon() { } AsioServiceDeamon::~AsioServiceDeamon() { delete _service; delete _server; //delete _network_service; } void AsioServiceDeamon::start(const std::string& serviceName, const uint32_t& threadNum/* = irene::net_params::smart_thread_nums()*/) { _serviceName = serviceName; //create io service instance _service = new IOService; //create tcp server instance _server = new TcpServer(InetAddress(48360), *_service, threadNum); //create network service instance //_network_service = new NetworkService(); //register io events IODispatcher io_dispatcher; _server->setNewConnectionCallback( std::bind(&IODispatcher::NewConnectionHandler, &io_dispatcher, std::placeholders::_1, std::placeholders::_2) ); _server->setWriteCompletedCallback( std::bind(&IODispatcher::WriteCompletedHandler, &io_dispatcher, std::placeholders::_1, std::placeholders::_2) ); _server->setReadCompletedCallback( std::bind(&IODispatcher::ReadCompletedHandler, &io_dispatcher, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4) ); _server->setConnectionClosedCallback( std::bind(&IODispatcher::ConnectionClosed, &io_dispatcher, std::placeholders::_1) ); _server->start(); } void AsioServiceDeamon::stop() { }<|endoftext|>
<commit_before>#include "pipe.hpp" #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include <stdio.h> Pipe::Pipe() {} bool Pipe::execute(const vector<string> &lhs, const vector<string> &rhs) { int pid1; int status; int pipes[2]; //int out; //pass in commands to args char* leftArgs[512]; unsigned i; for (i = 0; i < lhs.size()-1; i++) { leftArgs[i] = (char*)lhs[i].c_str(); } leftArgs[i] = NULL; char* rightArgs[512]; unsigned j; for (j = 0; j < rhs.size(); j++) { rightArgs[j] = (char*)rhs[j].c_str(); } rightArgs[j] = NULL; //set file descriptors //int in = open(input.c_str(), O_RDONLY); int outback = dup(1); //int inback = dup(0); //set output destination string filename = lhs[lhs.size() - 1]; int in = open(filename.c_str(), O_RDONLY); //create pipe pipe(pipes); dup2(pipes[0], in); dup2(pipes[1], STDOUT_FILENO); pid1 = fork(); if (pid1 == -1) { perror("fork"); exit(1); } if (pid1 == 0) // child process { if (execvp(leftArgs[0], leftArgs) == -1) { perror("exec"); //exit(1); } exit(1); } else // parent process { if (waitpid(pid1, &status, 0) == -1) { perror("wait"); exit(1); } if (WEXITSTATUS(status) != 0) { return false; } } close(pipes[0]); int pid2 = fork(); if (pid2 == -1) { perror("fork"); exit(1); } if (pid2 == 0) { //dup2(pipes[0], 0); //close(pipes[1]); if (execvp(rightArgs[0], rightArgs) == -1) { perror("exec"); exit(1); } } else { //dup2(pipes[1], newOut); //close(pipes[0]); if (execvp(rightArgs[0], rightArgs) == -1) { perror("exec"); exit(1); } dup2(outback, 1); dup2(outback, pipes[1]); close(pipes[1]); } return true; }<commit_msg>pipe trial<commit_after>#include "pipe.hpp" #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include <stdio.h> Pipe::Pipe() {} bool Pipe::execute(const vector<string> &lhs, const vector<string> &rhs) { pid_t pid1; int status; int pipes[2]; //int out; //pass in commands to args char* leftArgs[512]; unsigned i; for (i = 0; i < lhs.size()-1; i++) { leftArgs[i] = (char*)lhs[i].c_str(); } leftArgs[i] = NULL; char* rightArgs[512]; unsigned j; for (j = 0; j < rhs.size(); j++) { rightArgs[j] = (char*)rhs[j].c_str(); } rightArgs[j] = NULL; //set file descriptors //int in = open(input.c_str(), O_RDONLY); int outback = dup(1); //int inback = dup(0); //set output destination string filename = lhs[lhs.size() - 1]; int in = open(filename.c_str(), O_RDONLY); //create pipe pipe(pipes); dup2(pipes[0], in); dup2(pipes[1], STDOUT_FILENO); pid1 = fork(); if (pid1 == -1) { perror("fork"); exit(1); } if (pid1 == 0) // child process { cout << "1ST FORK" << endl; if (execvp(leftArgs[0], leftArgs) == -1) { perror("exec"); //exit(1); } exit(1); } else // parent process { if (waitpid(pid1, &status, 0) == -1) { perror("wait"); exit(1); } if (WEXITSTATUS(status) != 0) { return false; } } close(pipes[0]); pid_t pid2 = fork(); if (pid2 == -1) { perror("fork"); exit(1); } if (pid2 == 0) { cout << "2ND FORK" << endl; //dup2(pipes[0], 0); //close(pipes[1]); if (execvp(rightArgs[0], rightArgs) == -1) { perror("exec"); exit(1); } } else { //dup2(pipes[1], newOut); //close(pipes[0]); if (execvp(rightArgs[0], rightArgs) == -1) { perror("exec"); exit(1); } dup2(outback, 1); dup2(outback, pipes[1]); close(pipes[1]); } return true; }<|endoftext|>
<commit_before>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "DistributedBeadingStrategy.h" namespace cura { DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const { Beading ret; ret.total_thickness = thickness; if (bead_count > 0) { ret.bead_widths.resize(bead_count, thickness / bead_count); for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++) { ret.toolpath_locations.emplace_back(thickness * (bead_idx * 2 + 1) / bead_count / 2); } ret.left_over = 0; } else { ret.left_over = thickness; } return ret; } coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const { return std::max(0LL, (bead_count - 2)) * optimal_width_inner + std::min(2LL, bead_count) * optimal_width_outer; } coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const { // TODO: doesnt take min and max width into account const coord_t optimal_thickness = this->getOptimalThickness(lower_bead_count); return optimal_thickness + (optimal_thickness < 2 ? optimal_width_outer : optimal_width_inner) / 2; } coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { coord_t thickness_left = thickness; coord_t count = 0; count += std::min(2LL, (thickness + optimal_width_outer / 2) / optimal_width_outer); thickness_left -= count * optimal_width_outer; if (thickness_left >= (optimal_width_inner / 2)) { count += (thickness_left + optimal_width_inner / 2) / optimal_width_inner; } return count; } } // namespace cura <commit_msg>Process one more review comment.<commit_after>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "DistributedBeadingStrategy.h" namespace cura { DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const { Beading ret; ret.total_thickness = thickness; if (bead_count > 0) { ret.bead_widths.resize(bead_count, thickness / bead_count); for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++) { ret.toolpath_locations.emplace_back(thickness * (bead_idx * 2 + 1) / bead_count / 2); } ret.left_over = 0; } else { ret.left_over = thickness; } return ret; } coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const { return std::max(0LL, (bead_count - 2)) * optimal_width_inner + std::min(2LL, bead_count) * optimal_width_outer; } coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const { // TODO: doesnt take min and max width into account const coord_t optimal_thickness = this->getOptimalThickness(lower_bead_count); return optimal_thickness + (optimal_thickness < 2 ? optimal_width_outer : optimal_width_inner) / 2; } coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { coord_t thickness_left = thickness; coord_t count = std::min(2LL, (thickness + optimal_width_outer / 2) / optimal_width_outer); thickness_left -= count * optimal_width_outer; if (thickness_left >= (optimal_width_inner / 2)) { count += (thickness_left + optimal_width_inner / 2) / optimal_width_inner; } return count; } } // namespace cura <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // CellMLSupport plugin //============================================================================== #include "cellmlfilemanager.h" #include "cellmlsupportplugin.h" #include "filemanager.h" //============================================================================== #include <QFile> #include <QFileInfo> #include <QIODevice> #include <QXmlStreamReader> //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== PLUGININFO_FUNC CellMLSupportPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to support <a href=\"http://www.cellml.org/\">CellML</a>.")); descriptions.insert("fr", QString::fromUtf8("une extension pour supporter <a href=\"http://www.cellml.org/\">CellML</a>.")); return new PluginInfo(PluginInfo::Support, false, QStringList() << "Core" << "CellMLAPI" << "Compiler" << "CoreSolver", descriptions); } //============================================================================== // Core interface //============================================================================== void CellMLSupportPlugin::initialize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::finalize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // Make a call to the instance of the CellML file manager so that it gets // properly set up before it actually gets used // Note: we do it here rather than in initialize() since we need the Core // plugin to be initialised (so we can get access to our 'global' file // manager)... CellmlFileManager::instance(); } //============================================================================== void CellMLSupportPlugin::loadSettings(QSettings *pSettings) { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::saveSettings(QSettings *pSettings) const { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // File interface //============================================================================== FileTypes CellMLSupportPlugin::fileTypes() const { // Return the CellML file type that the CellMLSupport plugin supports return FileTypes() << FileType(qobject_cast<FileInterface *>(this), CellmlMimeType, CellmlFileExtension); } //============================================================================== QString CellMLSupportPlugin::fileTypeDescription(const QString &pMimeType) const { // Return the description for the requested MIME type, that is as long as it // is for the CellML MIME type if (!pMimeType.compare(CellmlMimeType)) return tr("CellML File"); else // Not a MIME type that we can recognise, so... return QString(); } //============================================================================== // GUI interface //============================================================================== void CellMLSupportPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin specific //============================================================================== bool isCellmlFile(const QString &pFileName) { // Return whether the file is a CellML file if (!QFileInfo(pFileName).completeSuffix().compare(CellmlFileExtension)) // We are dealing with a file which file extension is that of a CellML // file, so... return true; // The file doesn't have the 'correct' file extension, so check whether it's // a new file if (Core::FileManager::instance()->isNew(pFileName)) return true; // The file neither has the 'correct' file extension nor is a new file, so // quickly check its contents QFile file(pFileName); if (!file.open(QIODevice::ReadOnly)) // We can't open the file, so... return false; // Try to read the file as if it was an XML file QXmlStreamReader xml(&file); bool res = false; while (!xml.atEnd() && !xml.hasError()) { xml.readNext(); if (xml.isStartElement()) { // This is our root element, so for the file to be considered a // CellML file it should be a model element in either the CellML 1.0 // or 1.1 namespace if ( !xml.name().toString().compare("model") && ( (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.0#")) || (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.1#")))) { // All the requirements are gathered for the file to be // considered a CellML file, so... res = true; } break; } } file.close(); // We are done, so... return res; } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up.<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // CellMLSupport plugin //============================================================================== #include "cellmlfilemanager.h" #include "cellmlsupportplugin.h" #include "filemanager.h" //============================================================================== #include <QFile> #include <QFileInfo> #include <QIODevice> #include <QXmlStreamReader> //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== PLUGININFO_FUNC CellMLSupportPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to support <a href=\"http://www.cellml.org/\">CellML</a>.")); descriptions.insert("fr", QString::fromUtf8("une extension pour supporter <a href=\"http://www.cellml.org/\">CellML</a>.")); return new PluginInfo(PluginInfo::Support, false, QStringList() << "Core" << "CellMLAPI" << "Compiler" << "CoreSolver", descriptions); } //============================================================================== // Core interface //============================================================================== void CellMLSupportPlugin::initialize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::finalize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // Make a call to the instance of the CellML file manager so that it gets // properly set up before it actually gets used // Note: we do it here rather than in initialize() since we need the Core // plugin to be initialised (so we can get access to our 'global' file // manager)... CellmlFileManager::instance(); } //============================================================================== void CellMLSupportPlugin::loadSettings(QSettings *pSettings) { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::saveSettings(QSettings *pSettings) const { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // File interface //============================================================================== FileTypes CellMLSupportPlugin::fileTypes() const { // Return the CellML file type that the CellMLSupport plugin supports return FileTypes() << FileType(qobject_cast<FileInterface *>(this), CellmlMimeType, CellmlFileExtension); } //============================================================================== QString CellMLSupportPlugin::fileTypeDescription(const QString &pMimeType) const { // Return the description for the requested MIME type, that is as long as it // is for the CellML MIME type if (!pMimeType.compare(CellmlMimeType)) return tr("CellML File"); else // Not a MIME type that we can recognise, so... return QString(); } //============================================================================== // GUI interface //============================================================================== void CellMLSupportPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin specific //============================================================================== bool isCellmlFile(const QString &pFileName) { // Return whether the file is a CellML file if (!QFileInfo(pFileName).completeSuffix().compare(CellmlFileExtension)) // We are dealing with a file which file extension is that of a CellML // file, so... return true; // The file doesn't have the 'correct' file extension, so check whether it's // a new file if (Core::FileManager::instance()->isNew(pFileName)) return true; // The file neither has the 'correct' file extension nor is a new file, so // quickly check its contents QFile file(pFileName); if (!file.open(QIODevice::ReadOnly)) // We can't open the file, so... return false; // Try to read the file as if it was an XML file QXmlStreamReader xml(&file); bool res = false; xml.readNext(); while (!xml.atEnd()) { if (xml.isStartElement()) { // This is our root element, so for the file to be considered a // CellML file it should be a model element in either the CellML 1.0 // or 1.1 namespace if ( !xml.name().toString().compare("model") && ( (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.0#")) || (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.1#")))) { // All the requirements are gathered for the file to be // considered a CellML file, so... res = true; } break; } xml.readNext(); } file.close(); // We are done, so... return res; } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>