text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights * embodied in the content of this file are licensed under the BSD * (revised) open source license. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Shashwat Lal Das * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society. */ #include <shogun/classifier/vw/VwEnvironment.h> using namespace shogun; CVwEnvironment::CVwEnvironment() : CSGObject(), vw_version("5.1"), v_length(4) { init(); } void CVwEnvironment::init() { num_bits = 18; thread_bits = 0; mask = (1 << num_bits) - 1; stride = 1; min_label = 0.; max_label = 1.; eta = 10.; eta_decay_rate = 1.; adaptive = false; l1_regularization = 0.; random_weights = false; initial_weight = 0.; update_sum = 0.; t = 1.; initial_t = 1.; power_t = 0.5; example_number = 0; weighted_examples = 0.; weighted_unlabeled_examples = 0.; weighted_labels = 0.; total_features = 0; sum_loss = 0.; passes_complete = 0; num_passes = 1; ngram = 0; skips = 0; ignore_some = false; index_t length = ((index_t) 1) << num_bits; thread_mask = (stride * (length >> thread_bits)) - 1; } <commit_msg>rename lenght -> len to fix warning about naming collision<commit_after>/* * Copyright (c) 2009 Yahoo! Inc. All rights reserved. The copyrights * embodied in the content of this file are licensed under the BSD * (revised) open source license. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Shashwat Lal Das * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society. */ #include <shogun/classifier/vw/VwEnvironment.h> using namespace shogun; CVwEnvironment::CVwEnvironment() : CSGObject(), vw_version("5.1"), v_length(4) { init(); } void CVwEnvironment::init() { num_bits = 18; thread_bits = 0; mask = (1 << num_bits) - 1; stride = 1; min_label = 0.; max_label = 1.; eta = 10.; eta_decay_rate = 1.; adaptive = false; l1_regularization = 0.; random_weights = false; initial_weight = 0.; update_sum = 0.; t = 1.; initial_t = 1.; power_t = 0.5; example_number = 0; weighted_examples = 0.; weighted_unlabeled_examples = 0.; weighted_labels = 0.; total_features = 0; sum_loss = 0.; passes_complete = 0; num_passes = 1; ngram = 0; skips = 0; ignore_some = false; index_t len= ((index_t) 1) << num_bits; thread_mask = (stride * (len >> thread_bits)) - 1; } <|endoftext|>
<commit_before>#include <jni.h> // To get free disk space #include <sys/vfs.h> #include "../../../../../defines.hpp" #include "../../../../../platform/http_request.hpp" #include "../../../../../base/logging.hpp" #include "../../../../../base/string_utils.hpp" #include "../../../../../coding/zip_reader.hpp" #include "../../../../../coding/url_encode.hpp" #include "../../../../../platform/platform.hpp" #include "../../../../../platform/http_request.hpp" #include "../../../../../std/vector.hpp" #include "../../../../../std/string.hpp" #include "../../../../../std/bind.hpp" #include "../core/jni_helper.hpp" #include "Framework.hpp" // Special error codes to notify GUI about free space //@{ #define ERR_DOWNLOAD_SUCCESS 0 #define ERR_NOT_ENOUGH_MEMORY -1 #define ERR_NOT_ENOUGH_FREE_SPACE -2 #define ERR_STORAGE_DISCONNECTED -3 #define ERR_DOWNLOAD_ERROR -4 #define ERR_NO_MORE_FILES -5 #define ERR_FILE_IN_PROGRESS -6 //@} struct FileToDownload { vector<string> m_urls; string m_fileName; string m_pathOnSdcard; uint64_t m_fileSize; }; static string g_apkPath; static string g_sdcardPath; static vector<FileToDownload> g_filesToDownload; static int g_totalDownloadedBytes; static int g_totalBytesToDownload; extern "C" { int HasSpaceForFiles(size_t fileSize) { struct statfs st; if (statfs(g_sdcardPath.c_str(), &st) != 0) return ERR_STORAGE_DISCONNECTED; if (st.f_bsize * st.f_bavail <= fileSize) return ERR_NOT_ENOUGH_FREE_SPACE; return fileSize; } JNIEXPORT jint JNICALL Java_com_mapswithme_maps_DownloadResourcesActivity_nativeGetBytesToDownload(JNIEnv * env, jobject thiz, jstring apkPath, jstring sdcardPath) { { char const * strApkPath = env->GetStringUTFChars(apkPath, 0); if (!strApkPath) return ERR_NOT_ENOUGH_MEMORY; g_apkPath = strApkPath; env->ReleaseStringUTFChars(apkPath, strApkPath); char const * strSdcardPath = env->GetStringUTFChars(sdcardPath, 0); if (!strSdcardPath) return ERR_NOT_ENOUGH_MEMORY; g_sdcardPath = strSdcardPath; env->ReleaseStringUTFChars(sdcardPath, strSdcardPath); } jint totalBytesToDownload = 0; string buffer; ReaderPtr<Reader>(GetPlatform().GetReader("external_resources.txt")).ReadAsString(buffer); stringstream in(buffer); string name; int size; while (true) { in >> name; if (!in.good()) break; in >> size; if (!in.good()) break; FileToDownload f; f.m_pathOnSdcard = g_sdcardPath + name; f.m_fileName = name; uint64_t sizeOnSdcard = 0; Platform::GetFileSizeByFullPath(f.m_pathOnSdcard, sizeOnSdcard); if (size != sizeOnSdcard) { LOG(LINFO, ("should check : ", name, "sized", size, "bytes")); f.m_fileSize = size; g_filesToDownload.push_back(f); totalBytesToDownload += size; } } g_totalDownloadedBytes = 0; int res = HasSpaceForFiles(totalBytesToDownload); switch (res) { case ERR_STORAGE_DISCONNECTED: LOG(LWARNING, ("External file system is not available")); break; case ERR_NOT_ENOUGH_FREE_SPACE: LOG(LWARNING, ("Not enough space to extract files")); break; }; g_totalBytesToDownload = totalBytesToDownload; return res; } void DownloadFileFinished(shared_ptr<jobject> obj, downloader::HttpRequest & req) { int errorCode = 0; CHECK(req.Status() != downloader::HttpRequest::EInProgress, ("should be either Completed or Failed")); switch (req.Status()) { case downloader::HttpRequest::ECompleted: errorCode = ERR_DOWNLOAD_SUCCESS; break; case downloader::HttpRequest::EFailed: errorCode = ERR_DOWNLOAD_ERROR; break; }; FileToDownload & curFile = g_filesToDownload.back(); LOG(LINFO, ("finished downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes")); /// slight hack, check manually for Maps extension and AddMap accordingly if (curFile.m_fileName.find(".mwm") != string::npos) { LOG(LINFO, ("adding it as a map")); g_framework->AddMap(curFile.m_fileName); } g_totalDownloadedBytes += curFile.m_fileSize; LOG(LINFO, ("totalDownloadedBytes:", g_totalDownloadedBytes)); g_filesToDownload.pop_back(); JNIEnv * env = jni::GetEnv(); jmethodID onFinishMethod = env->GetMethodID(env->GetObjectClass(*obj.get()), "onDownloadFinished", "(I)V"); CHECK(onFinishMethod, ("Not existing method: void onDownloadFinished(int)")); env->CallVoidMethod(*obj.get(), onFinishMethod, errorCode); } void DownloadFileProgress(shared_ptr<jobject> obj, downloader::HttpRequest & req) { LOG(LINFO, (req.Progress().first, "bytes for", g_filesToDownload.back().m_fileName, "was downloaded")); JNIEnv * env = jni::GetEnv(); jmethodID onProgressMethod = env->GetMethodID(env->GetObjectClass(*obj.get()), "onDownloadProgress", "(IIII)V"); CHECK(onProgressMethod, ("Not existing method: void onDownloadProgress(int, int, int, int)")); FileToDownload & curFile = g_filesToDownload.back(); jint curTotal = req.Progress().second; jint curProgress = req.Progress().first; jint glbTotal = g_totalBytesToDownload; jint glbProgress = g_totalDownloadedBytes + req.Progress().first; env->CallVoidMethod(*obj.get(), onProgressMethod, curTotal, curProgress, glbTotal, glbProgress); } void DownloadURLListFinished(downloader::HttpRequest & req, downloader::HttpRequest::CallbackT onFinish, downloader::HttpRequest::CallbackT onProgress) { if (req.Status() == downloader::HttpRequest::EFailed) onFinish(req); else { FileToDownload & curFile = g_filesToDownload.back(); LOG(LINFO, ("finished URL list download for", curFile.m_fileName)); downloader::ParseServerList(req.Data(), curFile.m_urls); for (size_t i = 0; i < curFile.m_urls.size(); ++i) { curFile.m_urls[i] = curFile.m_urls[i] + OMIM_OS_NAME "/" + strings::to_string(g_framework->Storage().GetCurrentVersion()) + "/" + UrlEncode(curFile.m_fileName); LOG(LINFO, (curFile.m_urls[i])); } downloader::HttpRequest::GetFile(curFile.m_urls, curFile.m_pathOnSdcard, curFile.m_fileSize, onFinish, onProgress); } } JNIEXPORT int JNICALL Java_com_mapswithme_maps_DownloadResourcesActivity_nativeDownloadNextFile(JNIEnv * env, jobject thiz, jobject observer) { if (g_filesToDownload.empty()) return ERR_NO_MORE_FILES; FileToDownload & curFile = g_filesToDownload.back(); LOG(LINFO, ("downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes")); downloader::HttpRequest::CallbackT onFinish(bind(&DownloadFileFinished, jni::make_global_ref(observer), _1)); downloader::HttpRequest::CallbackT onProgress(bind(&DownloadFileProgress, jni::make_global_ref(observer), _1)); downloader::HttpRequest::PostJson(GetPlatform().MetaServerUrl(), curFile.m_fileName, bind(&DownloadURLListFinished, _1, onFinish, onProgress)); return ERR_FILE_IN_PROGRESS; } // Move downloaded maps from /sdcard/Android/data/com.mapswithme.maps/files/ // to /sdcard/MapsWithMe JNIEXPORT void JNICALL Java_com_mapswithme_maps_DownloadResourcesActivity_nativeMoveMaps(JNIEnv * env, jobject thiz, jstring fromPath, jstring toPath) { string from, to; { char const * strFrom = env->GetStringUTFChars(fromPath, 0); if (!strFrom) return; from = strFrom; env->ReleaseStringUTFChars(fromPath, strFrom); char const * strTo = env->GetStringUTFChars(toPath, 0); if (!strTo) return; to = strTo; env->ReleaseStringUTFChars(toPath, strTo); } Platform & pl = GetPlatform(); Platform::FilesList files; // Move *.mwm files pl.GetFilesInDir(from, "*" DATA_FILE_EXTENSION, files); for (size_t i = 0; i < files.size(); ++i) { LOG(LINFO, (from + files[i], to + files[i])); rename((from + files[i]).c_str(), (to + files[i]).c_str()); } // Delete not finished *.downloading files files.clear(); pl.GetFilesInDir(from, "*" DOWNLOADING_FILE_EXTENSION, files); pl.GetFilesInDir(from, "*" RESUME_FILE_EXTENSION, files); for (size_t i = 0; i < files.size(); ++i) remove((from + files[i]).c_str()); } } <commit_msg>made downloading chunk smaller for smoothing GUI downloading progress.<commit_after>#include <jni.h> // To get free disk space #include <sys/vfs.h> #include "../../../../../defines.hpp" #include "../../../../../platform/http_request.hpp" #include "../../../../../base/logging.hpp" #include "../../../../../base/string_utils.hpp" #include "../../../../../coding/zip_reader.hpp" #include "../../../../../coding/url_encode.hpp" #include "../../../../../platform/platform.hpp" #include "../../../../../platform/http_request.hpp" #include "../../../../../std/vector.hpp" #include "../../../../../std/string.hpp" #include "../../../../../std/bind.hpp" #include "../core/jni_helper.hpp" #include "Framework.hpp" // Special error codes to notify GUI about free space //@{ #define ERR_DOWNLOAD_SUCCESS 0 #define ERR_NOT_ENOUGH_MEMORY -1 #define ERR_NOT_ENOUGH_FREE_SPACE -2 #define ERR_STORAGE_DISCONNECTED -3 #define ERR_DOWNLOAD_ERROR -4 #define ERR_NO_MORE_FILES -5 #define ERR_FILE_IN_PROGRESS -6 //@} struct FileToDownload { vector<string> m_urls; string m_fileName; string m_pathOnSdcard; uint64_t m_fileSize; }; static string g_apkPath; static string g_sdcardPath; static vector<FileToDownload> g_filesToDownload; static int g_totalDownloadedBytes; static int g_totalBytesToDownload; extern "C" { int HasSpaceForFiles(size_t fileSize) { struct statfs st; if (statfs(g_sdcardPath.c_str(), &st) != 0) return ERR_STORAGE_DISCONNECTED; if (st.f_bsize * st.f_bavail <= fileSize) return ERR_NOT_ENOUGH_FREE_SPACE; return fileSize; } JNIEXPORT jint JNICALL Java_com_mapswithme_maps_DownloadResourcesActivity_nativeGetBytesToDownload(JNIEnv * env, jobject thiz, jstring apkPath, jstring sdcardPath) { { char const * strApkPath = env->GetStringUTFChars(apkPath, 0); if (!strApkPath) return ERR_NOT_ENOUGH_MEMORY; g_apkPath = strApkPath; env->ReleaseStringUTFChars(apkPath, strApkPath); char const * strSdcardPath = env->GetStringUTFChars(sdcardPath, 0); if (!strSdcardPath) return ERR_NOT_ENOUGH_MEMORY; g_sdcardPath = strSdcardPath; env->ReleaseStringUTFChars(sdcardPath, strSdcardPath); } jint totalBytesToDownload = 0; string buffer; ReaderPtr<Reader>(GetPlatform().GetReader("external_resources.txt")).ReadAsString(buffer); stringstream in(buffer); string name; int size; while (true) { in >> name; if (!in.good()) break; in >> size; if (!in.good()) break; FileToDownload f; f.m_pathOnSdcard = g_sdcardPath + name; f.m_fileName = name; uint64_t sizeOnSdcard = 0; Platform::GetFileSizeByFullPath(f.m_pathOnSdcard, sizeOnSdcard); if (size != sizeOnSdcard) { LOG(LINFO, ("should check : ", name, "sized", size, "bytes")); f.m_fileSize = size; g_filesToDownload.push_back(f); totalBytesToDownload += size; } } g_totalDownloadedBytes = 0; int res = HasSpaceForFiles(totalBytesToDownload); switch (res) { case ERR_STORAGE_DISCONNECTED: LOG(LWARNING, ("External file system is not available")); break; case ERR_NOT_ENOUGH_FREE_SPACE: LOG(LWARNING, ("Not enough space to extract files")); break; }; g_totalBytesToDownload = totalBytesToDownload; return res; } void DownloadFileFinished(shared_ptr<jobject> obj, downloader::HttpRequest & req) { int errorCode = 0; CHECK(req.Status() != downloader::HttpRequest::EInProgress, ("should be either Completed or Failed")); switch (req.Status()) { case downloader::HttpRequest::ECompleted: errorCode = ERR_DOWNLOAD_SUCCESS; break; case downloader::HttpRequest::EFailed: errorCode = ERR_DOWNLOAD_ERROR; break; }; FileToDownload & curFile = g_filesToDownload.back(); LOG(LINFO, ("finished downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes")); /// slight hack, check manually for Maps extension and AddMap accordingly if (curFile.m_fileName.find(".mwm") != string::npos) { LOG(LINFO, ("adding it as a map")); g_framework->AddMap(curFile.m_fileName); } g_totalDownloadedBytes += curFile.m_fileSize; LOG(LINFO, ("totalDownloadedBytes:", g_totalDownloadedBytes)); g_filesToDownload.pop_back(); JNIEnv * env = jni::GetEnv(); jmethodID onFinishMethod = env->GetMethodID(env->GetObjectClass(*obj.get()), "onDownloadFinished", "(I)V"); CHECK(onFinishMethod, ("Not existing method: void onDownloadFinished(int)")); env->CallVoidMethod(*obj.get(), onFinishMethod, errorCode); } void DownloadFileProgress(shared_ptr<jobject> obj, downloader::HttpRequest & req) { LOG(LINFO, (req.Progress().first, "bytes for", g_filesToDownload.back().m_fileName, "was downloaded")); JNIEnv * env = jni::GetEnv(); jmethodID onProgressMethod = env->GetMethodID(env->GetObjectClass(*obj.get()), "onDownloadProgress", "(IIII)V"); CHECK(onProgressMethod, ("Not existing method: void onDownloadProgress(int, int, int, int)")); FileToDownload & curFile = g_filesToDownload.back(); jint curTotal = req.Progress().second; jint curProgress = req.Progress().first; jint glbTotal = g_totalBytesToDownload; jint glbProgress = g_totalDownloadedBytes + req.Progress().first; env->CallVoidMethod(*obj.get(), onProgressMethod, curTotal, curProgress, glbTotal, glbProgress); } void DownloadURLListFinished(downloader::HttpRequest & req, downloader::HttpRequest::CallbackT onFinish, downloader::HttpRequest::CallbackT onProgress) { if (req.Status() == downloader::HttpRequest::EFailed) onFinish(req); else { FileToDownload & curFile = g_filesToDownload.back(); LOG(LINFO, ("finished URL list download for", curFile.m_fileName)); downloader::ParseServerList(req.Data(), curFile.m_urls); for (size_t i = 0; i < curFile.m_urls.size(); ++i) { curFile.m_urls[i] = curFile.m_urls[i] + OMIM_OS_NAME "/" + strings::to_string(g_framework->Storage().GetCurrentVersion()) + "/" + UrlEncode(curFile.m_fileName); LOG(LINFO, (curFile.m_urls[i])); } downloader::HttpRequest::GetFile(curFile.m_urls, curFile.m_pathOnSdcard, curFile.m_fileSize, onFinish, onProgress, 64 * 1024); } } JNIEXPORT int JNICALL Java_com_mapswithme_maps_DownloadResourcesActivity_nativeDownloadNextFile(JNIEnv * env, jobject thiz, jobject observer) { if (g_filesToDownload.empty()) return ERR_NO_MORE_FILES; FileToDownload & curFile = g_filesToDownload.back(); LOG(LINFO, ("downloading", curFile.m_fileName, "sized", curFile.m_fileSize, "bytes")); downloader::HttpRequest::CallbackT onFinish(bind(&DownloadFileFinished, jni::make_global_ref(observer), _1)); downloader::HttpRequest::CallbackT onProgress(bind(&DownloadFileProgress, jni::make_global_ref(observer), _1)); downloader::HttpRequest::PostJson(GetPlatform().MetaServerUrl(), curFile.m_fileName, bind(&DownloadURLListFinished, _1, onFinish, onProgress)); return ERR_FILE_IN_PROGRESS; } // Move downloaded maps from /sdcard/Android/data/com.mapswithme.maps/files/ // to /sdcard/MapsWithMe JNIEXPORT void JNICALL Java_com_mapswithme_maps_DownloadResourcesActivity_nativeMoveMaps(JNIEnv * env, jobject thiz, jstring fromPath, jstring toPath) { string from, to; { char const * strFrom = env->GetStringUTFChars(fromPath, 0); if (!strFrom) return; from = strFrom; env->ReleaseStringUTFChars(fromPath, strFrom); char const * strTo = env->GetStringUTFChars(toPath, 0); if (!strTo) return; to = strTo; env->ReleaseStringUTFChars(toPath, strTo); } Platform & pl = GetPlatform(); Platform::FilesList files; // Move *.mwm files pl.GetFilesInDir(from, "*" DATA_FILE_EXTENSION, files); for (size_t i = 0; i < files.size(); ++i) { LOG(LINFO, (from + files[i], to + files[i])); rename((from + files[i]).c_str(), (to + files[i]).c_str()); } // Delete not finished *.downloading files files.clear(); pl.GetFilesInDir(from, "*" DOWNLOADING_FILE_EXTENSION, files); pl.GetFilesInDir(from, "*" RESUME_FILE_EXTENSION, files); for (size_t i = 0; i < files.size(); ++i) remove((from + files[i]).c_str()); } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #ifndef _Stroika_Foundation_Configuration_Enumeration_inl_ #define _Stroika_Foundation_Configuration_Enumeration_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika::Foundation::Configuration { /* ******************************************************************************** ******************************** Configuration::Inc **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM Inc (ENUM e) { return ToEnum<ENUM> (ToInt (e) + 1); } /* ******************************************************************************** ****************************** Configuration::ToInt **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<typename underlying_type<ENUM>::type> (e); } /* ******************************************************************************** ********************* Configuration::GetDistanceSpanned ************************ ******************************************************************************** */ template <typename ENUM> inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> GetDistanceSpanned () { return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ENUM::eCOUNT); } /* ******************************************************************************** ***************************** Configuration::ToEnum **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND); return static_cast<ENUM> (e); } /* ******************************************************************************** ******************** Configuration::OffsetFromStart **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> OffsetFromStart (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ToInt (e) - ToInt (ENUM::eSTART)); } template <typename ENUM> inline constexpr ENUM OffsetFromStart (make_unsigned_t<typename underlying_type<ENUM>::type> offset) { return ToEnum<ENUM> (offset + ENUM::eSTART); } /* ******************************************************************************** ************************** Configuration::EnumNames **************************** ******************************************************************************** */ template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames) : fEnumNames_ () { // @todo find some way to INITIALZIE the static array.... - needed for constexpr function! // @see qCANNOT_FIGURE_OUT_HOW_TO_INIT_STD_ARRAY_FROM_STD_INITIALIZER_ auto oi = fEnumNames_.begin (); for (EnumName<ENUM_TYPE> i : origEnumNames) { Require (oi != fEnumNames_.end ()); *oi = i; ++oi; } RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> inline constexpr EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init) : fEnumNames_ (init) { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> template <size_t N> inline constexpr EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N]) : fEnumNames_ (origEnumNames) { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const { return fEnumNames_; } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const { return fEnumNames_.begin (); } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const { return fEnumNames_.end (); } template <typename ENUM_TYPE> inline constexpr size_t EnumNames<ENUM_TYPE>::size () const { return fEnumNames_.size (); } template <typename ENUM_TYPE> inline constexpr const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const { if (e == ENUM_TYPE::eEND) { return nullptr; } #if qDebug Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ()); auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* { for (auto i : fEnumNames_) { if (i.first == e) { return i.second; } } return nullptr; }; Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second); #endif return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second; } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const { auto tmp = PeekName (e); RequireNotNull (tmp); return tmp; } template <typename ENUM_TYPE> const ENUM_TYPE* EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const { /* * NB: this is only safe returning an internal pointer, because the pointer is internal to * static, immudatable data - the basic_array associated with this EnumNames<> structure. */ RequireNotNull (name); for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) { if (::wcscmp (i->second, name) == 0) { return &i->first; } } return nullptr; } template <typename ENUM_TYPE> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const { const ENUM_TYPE* tmp = PeekValue (name); RequireNotNull (tmp); return *tmp; } template <typename ENUM_TYPE> template <typename NOT_FOUND_EXCEPTION> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const { RequireNotNull (name); const ENUM_TYPE* tmp = PeekValue (name); if (tmp == nullptr) [[UNLIKELY_ATTR]] { //Execution::Throw (notFoundException); throw (notFoundException); } return *tmp; } template <typename ENUM_TYPE> inline constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const { Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ()); using IndexType = make_unsigned_t<typename underlying_type<ENUM_TYPE>::type>; for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) { Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i); } } /* ******************************************************************************** ************************** Configuration::DefaultNames ************************* ******************************************************************************** */ template <typename ENUM_TYPE> inline DefaultNames<ENUM_TYPE>::DefaultNames () : EnumNames<ENUM_TYPE> (k) { } } #endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/ <commit_msg>cosmetic<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #ifndef _Stroika_Foundation_Configuration_Enumeration_inl_ #define _Stroika_Foundation_Configuration_Enumeration_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika::Foundation::Configuration { /* ******************************************************************************** ******************************** Configuration::Inc **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM Inc (ENUM e) { return ToEnum<ENUM> (ToInt (e) + 1); } /* ******************************************************************************** ****************************** Configuration::ToInt **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<typename underlying_type<ENUM>::type> (e); } /* ******************************************************************************** ********************* Configuration::GetDistanceSpanned ************************ ******************************************************************************** */ template <typename ENUM> constexpr make_unsigned_t<typename underlying_type<ENUM>::type> GetDistanceSpanned () { return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ENUM::eCOUNT); } /* ******************************************************************************** ***************************** Configuration::ToEnum **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND); return static_cast<ENUM> (e); } /* ******************************************************************************** ******************** Configuration::OffsetFromStart **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> OffsetFromStart (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ToInt (e) - ToInt (ENUM::eSTART)); } template <typename ENUM> inline constexpr ENUM OffsetFromStart (make_unsigned_t<typename underlying_type<ENUM>::type> offset) { return ToEnum<ENUM> (offset + ENUM::eSTART); } /* ******************************************************************************** ************************** Configuration::EnumNames **************************** ******************************************************************************** */ template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames) : fEnumNames_ () { // @todo find some way to INITIALZIE the static array.... - needed for constexpr function! // @see qCANNOT_FIGURE_OUT_HOW_TO_INIT_STD_ARRAY_FROM_STD_INITIALIZER_ auto oi = fEnumNames_.begin (); for (EnumName<ENUM_TYPE> i : origEnumNames) { Require (oi != fEnumNames_.end ()); *oi = i; ++oi; } RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> inline constexpr EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init) : fEnumNames_ (init) { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> template <size_t N> inline constexpr EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N]) : fEnumNames_ (origEnumNames) { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const { return fEnumNames_; } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const { return fEnumNames_.begin (); } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const { return fEnumNames_.end (); } template <typename ENUM_TYPE> inline constexpr size_t EnumNames<ENUM_TYPE>::size () const { return fEnumNames_.size (); } template <typename ENUM_TYPE> inline constexpr const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const { if (e == ENUM_TYPE::eEND) { return nullptr; } #if qDebug Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ()); auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* { for (auto i : fEnumNames_) { if (i.first == e) { return i.second; } } return nullptr; }; Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second); #endif return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second; } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const { auto tmp = PeekName (e); RequireNotNull (tmp); return tmp; } template <typename ENUM_TYPE> const ENUM_TYPE* EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const { /* * NB: this is only safe returning an internal pointer, because the pointer is internal to * static, immudatable data - the basic_array associated with this EnumNames<> structure. */ RequireNotNull (name); for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) { if (::wcscmp (i->second, name) == 0) { return &i->first; } } return nullptr; } template <typename ENUM_TYPE> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const { const ENUM_TYPE* tmp = PeekValue (name); RequireNotNull (tmp); return *tmp; } template <typename ENUM_TYPE> template <typename NOT_FOUND_EXCEPTION> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const { RequireNotNull (name); const ENUM_TYPE* tmp = PeekValue (name); if (tmp == nullptr) [[UNLIKELY_ATTR]] { //Execution::Throw (notFoundException); throw (notFoundException); } return *tmp; } template <typename ENUM_TYPE> inline constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const { Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ()); using IndexType = make_unsigned_t<typename underlying_type<ENUM_TYPE>::type>; for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) { Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i); } } /* ******************************************************************************** ************************** Configuration::DefaultNames ************************* ******************************************************************************** */ template <typename ENUM_TYPE> inline DefaultNames<ENUM_TYPE>::DefaultNames () : EnumNames<ENUM_TYPE> (k) { } } #endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/ <|endoftext|>
<commit_before>#pragma once #include <functional> #include <stdexcept> #include "blackhole/config.hpp" #include "blackhole/utils/meta.hpp" namespace blackhole { namespace log { typedef std::function<void()> exception_handler_t; class default_exception_handler_t { public: void operator()() const { #ifdef BLACKHOLE_DEBUG throw; #else try { throw; } catch (const std::exception& err) { std::cout << "logging core error occurred: " << err.what() << std::endl; } catch (...) { std::cout << "logging core error occurred: unknown" << std::endl; } #endif } }; namespace aux { template<typename Handler> class launcher { protected: typedef Handler handler_type; typedef void exception_type; handler_type handler; public: launcher(const handler_type& handler) : handler(handler) {} void operator()() { throw; } }; template<typename Exception, typename Base> class intermediate : public Base { protected: typedef typename Base::handler_type handler_type; typedef Exception exception_type; public: intermediate(const handler_type& handler) : Base(handler) { typedef std::is_base_of<typename Base::exception_type, exception_type> correct_hierarchy; static_assert(!correct_hierarchy::value, "can't build correct exception handling hierarchy"); } void operator()() { try { Base::operator()(); } catch (const Exception& err) { this->handler(err); } } }; template<typename TypeList, typename Handler> struct handler_hierarchy { typedef typename boost::mpl::fold< TypeList, aux::launcher<Handler>, boost::mpl::bind<boost::mpl::quote2<aux::intermediate>, boost::mpl::_2, boost::mpl::_1> >::type type; }; } // namespace aux template<typename TypeList, typename Handler> class exception_handler : public aux::handler_hierarchy<TypeList, Handler>::type { typedef typename aux::handler_hierarchy<TypeList, Handler>::type base_type; public: exception_handler(Handler handler) : base_type(handler) {} void operator()() { base_type::operator()(); } }; namespace aux { template<typename Handler, typename... Args> struct handler_maker { typedef exception_handler< typename boost::mpl::reverse< typename meta::vector::from_variadic<Args...>::type >::type, Handler > type; }; } // namespace aux namespace exception { template<typename Handler> struct handler_factory_t { template<typename... Args> static typename aux::handler_maker<Handler, Args...>::type make() { typedef typename aux::handler_maker<Handler, Args...>::type handler_type; return handler_type(Handler()); } }; } // namespace exception } // namespace log } // namespace blackhole <commit_msg>[Bug Fix] Forgotten include added.<commit_after>#pragma once #include <functional> #include <iostream> #include <stdexcept> #include "blackhole/config.hpp" #include "blackhole/utils/meta.hpp" namespace blackhole { namespace log { typedef std::function<void()> exception_handler_t; class default_exception_handler_t { public: void operator()() const { #ifdef BLACKHOLE_DEBUG throw; #else try { throw; } catch (const std::exception& err) { std::cout << "logging core error occurred: " << err.what() << std::endl; } catch (...) { std::cout << "logging core error occurred: unknown" << std::endl; } #endif } }; namespace aux { template<typename Handler> class launcher { protected: typedef Handler handler_type; typedef void exception_type; handler_type handler; public: launcher(const handler_type& handler) : handler(handler) {} void operator()() { throw; } }; template<typename Exception, typename Base> class intermediate : public Base { protected: typedef typename Base::handler_type handler_type; typedef Exception exception_type; public: intermediate(const handler_type& handler) : Base(handler) { typedef std::is_base_of<typename Base::exception_type, exception_type> correct_hierarchy; static_assert(!correct_hierarchy::value, "can't build correct exception handling hierarchy"); } void operator()() { try { Base::operator()(); } catch (const Exception& err) { this->handler(err); } } }; template<typename TypeList, typename Handler> struct handler_hierarchy { typedef typename boost::mpl::fold< TypeList, aux::launcher<Handler>, boost::mpl::bind<boost::mpl::quote2<aux::intermediate>, boost::mpl::_2, boost::mpl::_1> >::type type; }; } // namespace aux template<typename TypeList, typename Handler> class exception_handler : public aux::handler_hierarchy<TypeList, Handler>::type { typedef typename aux::handler_hierarchy<TypeList, Handler>::type base_type; public: exception_handler(Handler handler) : base_type(handler) {} void operator()() { base_type::operator()(); } }; namespace aux { template<typename Handler, typename... Args> struct handler_maker { typedef exception_handler< typename boost::mpl::reverse< typename meta::vector::from_variadic<Args...>::type >::type, Handler > type; }; } // namespace aux namespace exception { template<typename Handler> struct handler_factory_t { template<typename... Args> static typename aux::handler_maker<Handler, Args...>::type make() { typedef typename aux::handler_maker<Handler, Args...>::type handler_type; return handler_type(Handler()); } }; } // namespace exception } // namespace log } // namespace blackhole <|endoftext|>
<commit_before>/* Copyright 2015-2020 Igor Petrovic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "board/Board.h" #include "board/Internal.h" #include "core/src/general/Interrupt.h" #include "board/common/io/Helpers.h" #include "Pins.h" namespace Board { void uniqueID(uniqueID_t& uid) { uint32_t id[3]; id[0] = HAL_GetUIDw0(); id[1] = HAL_GetUIDw1(); id[2] = HAL_GetUIDw2(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF; } } namespace detail { namespace setup { void application() { //Reset of all peripherals, Initializes the Flash interface and the Systick HAL_Init(); detail::setup::clocks(); detail::setup::io(); NVM::init(); detail::setup::adc(); detail::setup::timers(); #ifdef USB_MIDI_SUPPORTED detail::setup::usb(); #endif } void bootloader() { HAL_Init(); detail::setup::clocks(); detail::setup::io(); } void io() { #ifdef NUMBER_OF_IN_SR CORE_IO_CONFIG({ SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #else #ifdef NUMBER_OF_BUTTON_ROWS for (int i = 0; i < NUMBER_OF_BUTTON_ROWS; i++) #else for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++) #endif { core::io::mcuPin_t pin = detail::map::buttonPin(i); #ifndef BUTTONS_EXT_PULLUPS CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::up, core::io::gpioSpeed_t::medium, 0x00 }); #else CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #endif } #endif #ifdef NUMBER_OF_BUTTON_COLUMNS CORE_IO_CONFIG({ DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0); CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1); CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2); #endif #ifdef NUMBER_OF_OUT_SR CORE_IO_CONFIG({ SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #ifdef SR_OUT_OE_PORT CORE_IO_CONFIG({ SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #endif //init all outputs on shift register CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); detail::io::sr595wait(); CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); #ifdef SR_OUT_OE_PORT CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN); #endif #else #ifdef NUMBER_OF_LED_ROWS CORE_IO_CONFIG({ DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0); CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1); CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2); for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) #else for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) #endif { core::io::mcuPin_t pin = detail::map::ledPin(i); CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::outputOD, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #if MAX_ADC_CHANNELS > 0 for (int i = 0; i < MAX_ADC_CHANNELS; i++) { core::io::mcuPin_t pin = detail::map::adcPin(i); CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::analog }); CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #ifdef NUMBER_OF_MUX CORE_IO_CONFIG({ MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #ifdef MUX_PORT_S3 CORE_IO_CONFIG({ MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #endif #endif #ifdef BTLDR_BUTTON_PORT CORE_IO_CONFIG({ BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input }); #endif #ifdef LED_INDICATORS CORE_IO_CONFIG({ LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN); INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN); INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN); INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN); #endif #ifdef LED_BTLDR_PORT CORE_IO_CONFIG({ LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN); #endif } } // namespace setup } // namespace detail } // namespace Board<commit_msg>board: use pull-down on btldr button if button is active high, otherwise use pull-up<commit_after>/* Copyright 2015-2020 Igor Petrovic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "board/Board.h" #include "board/Internal.h" #include "core/src/general/Interrupt.h" #include "board/common/io/Helpers.h" #include "Pins.h" namespace Board { void uniqueID(uniqueID_t& uid) { uint32_t id[3]; id[0] = HAL_GetUIDw0(); id[1] = HAL_GetUIDw1(); id[2] = HAL_GetUIDw2(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF; } } namespace detail { namespace setup { void application() { //Reset of all peripherals, Initializes the Flash interface and the Systick HAL_Init(); detail::setup::clocks(); detail::setup::io(); NVM::init(); detail::setup::adc(); detail::setup::timers(); #ifdef USB_MIDI_SUPPORTED detail::setup::usb(); #endif } void bootloader() { HAL_Init(); detail::setup::clocks(); detail::setup::io(); } void io() { #ifdef NUMBER_OF_IN_SR CORE_IO_CONFIG({ SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #else #ifdef NUMBER_OF_BUTTON_ROWS for (int i = 0; i < NUMBER_OF_BUTTON_ROWS; i++) #else for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++) #endif { core::io::mcuPin_t pin = detail::map::buttonPin(i); #ifndef BUTTONS_EXT_PULLUPS CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::up, core::io::gpioSpeed_t::medium, 0x00 }); #else CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #endif } #endif #ifdef NUMBER_OF_BUTTON_COLUMNS CORE_IO_CONFIG({ DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0); CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1); CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2); #endif #ifdef NUMBER_OF_OUT_SR CORE_IO_CONFIG({ SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #ifdef SR_OUT_OE_PORT CORE_IO_CONFIG({ SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #endif //init all outputs on shift register CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); detail::io::sr595wait(); CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); #ifdef SR_OUT_OE_PORT CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN); #endif #else #ifdef NUMBER_OF_LED_ROWS CORE_IO_CONFIG({ DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0); CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1); CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2); for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) #else for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) #endif { core::io::mcuPin_t pin = detail::map::ledPin(i); CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::outputOD, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #if MAX_ADC_CHANNELS > 0 for (int i = 0; i < MAX_ADC_CHANNELS; i++) { core::io::mcuPin_t pin = detail::map::adcPin(i); CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::analog }); CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #ifdef NUMBER_OF_MUX CORE_IO_CONFIG({ MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #ifdef MUX_PORT_S3 CORE_IO_CONFIG({ MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); #endif #endif #ifdef BTLDR_BUTTON_PORT #ifdef BTLDR_BUTTON_AH CORE_IO_CONFIG({ BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input, core::io::pullMode_t::down, core::io::gpioSpeed_t::medium, 0x00 }); #else CORE_IO_CONFIG({ BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input, core::io::pullMode_t::up, core::io::gpioSpeed_t::medium, 0x00 }); #endif #endif #ifdef LED_INDICATORS CORE_IO_CONFIG({ LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_CONFIG({ LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN); INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN); INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN); INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN); #endif #ifdef LED_BTLDR_PORT CORE_IO_CONFIG({ LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 }); CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN); #endif } } // namespace setup } // namespace detail } // namespace Board<|endoftext|>
<commit_before>/* * Remote control for the Fadecandy firmware, using the ARM debug interface. * * Copyright (c) 2013 Micah Elizabeth Scott * * 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 <Arduino.h> #include "fc_remote.h" #include "testjig.h" #include "firmware_data.h" bool FcRemote::installFirmware() { // Install firmware, blinking both target and local LEDs in unison. bool blink = false; ARMKinetisDebug::FlashProgrammer programmer(target, fw_data, fw_sectorCount); if (!programmer.begin()) return false; while (!programmer.isComplete()) { blink = !blink; if (!programmer.next()) return false; if (!setLED(blink)) return false; digitalWrite(ledPin, blink); } return true; } bool FcRemote::boot() { // Run the new firmware, and let it boot if (!target.reset()) return false; delay(50); return true; } bool FcRemote::setLED(bool on) { const unsigned pin = target.PTC5; return target.pinMode(pin, OUTPUT) && target.digitalWrite(pin, on); } bool FcRemote::setFlags(uint8_t cflag) { // Set control flags return target.memStoreByte(fw_pFlags, cflag); } bool FcRemote::initLUT() { // Install a trivial identity-mapping LUT, writing directly to the firmware's LUT buffer. for (unsigned channel = 0; channel < 3; channel++) { for (unsigned index = 0; index < LUT_CH_SIZE; index++) { if (!setLUT(channel, index, index << 8)) return false; } } return true; } bool FcRemote::setLUT(unsigned channel, unsigned index, int value) { return target.memStoreHalf(fw_pLUT + 2*(index + channel*LUT_CH_SIZE), constrain(value, 0, 0xFFFF)); } bool FcRemote::setPixel(unsigned index, int red, int green, int blue) { // Write one pixel directly into the fbNext framebuffer on the target. uint32_t idPacket = index / PIXELS_PER_PACKET; uint32_t idOffset = fw_usbPacketBufOffset + 1 + (index % PIXELS_PER_PACKET) * 3; uint32_t fb; // Address of the current fcFramebuffer bound to fbNext uint32_t packet; // Pointer to usb_packet in question return target.memLoad(fw_pFbNext, fb) && target.memLoad(fb + idPacket*4, packet) && target.memStoreByte(packet + idOffset + 0, constrain(red, 0, 255)) && target.memStoreByte(packet + idOffset + 1, constrain(green, 0, 255)) && target.memStoreByte(packet + idOffset + 2, constrain(blue, 0, 255)); } float FcRemote::measureFrameRate(float minDuration) { // Use the end-to-end LED data signal to measure the overall system frame rate. // Gaps of >50us indicate frame boundaries pinMode(dataFeedbackPin, INPUT); uint32_t minMicros = minDuration * 1000000; uint32_t startTime = micros(); uint32_t gapStart = 0; bool inGap = false; uint32_t frames = 0; uint32_t duration; while (1) { long now = micros(); duration = now - startTime; if (duration >= minMicros) break; if (digitalRead(dataFeedbackPin)) { // Definitely not in a gap, found some data inGap = false; gapStart = now; } else if (inGap) { // Already in a gap, wait for some data. } else if (uint32_t(now - gapStart) >= 50) { // We just found an inter-frame gap inGap = true; frames++; } } return frames / (duration * 1e-6); } bool FcRemote::testFrameRate() { const float goalFPS = 375; const float maxFPS = 450; target.log(target.LOG_NORMAL, "FPS: Measuring frame rate..."); float fps = measureFrameRate(); target.log(target.LOG_NORMAL, "FPS: Measured %.2f frames/sec", fps); if (fps > maxFPS) { target.log(target.LOG_ERROR, "FPS: ERROR, frame rate of %.2f frames/sec is unrealistically high!", fps); return false; } if (fps < goalFPS) { target.log(target.LOG_ERROR, "FPS: ERROR, frame rate of %.2f frames/sec is below goal of %.2f!", fps, goalFPS); return false; } return true; } <commit_msg>Tweaked frame counting<commit_after>/* * Remote control for the Fadecandy firmware, using the ARM debug interface. * * Copyright (c) 2013 Micah Elizabeth Scott * * 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 <Arduino.h> #include "fc_remote.h" #include "testjig.h" #include "firmware_data.h" bool FcRemote::installFirmware() { // Install firmware, blinking both target and local LEDs in unison. bool blink = false; ARMKinetisDebug::FlashProgrammer programmer(target, fw_data, fw_sectorCount); if (!programmer.begin()) return false; while (!programmer.isComplete()) { blink = !blink; if (!programmer.next()) return false; if (!setLED(blink)) return false; digitalWrite(ledPin, blink); } return true; } bool FcRemote::boot() { // Run the new firmware, and let it boot if (!target.reset()) return false; delay(50); return true; } bool FcRemote::setLED(bool on) { const unsigned pin = target.PTC5; return target.pinMode(pin, OUTPUT) && target.digitalWrite(pin, on); } bool FcRemote::setFlags(uint8_t cflag) { // Set control flags return target.memStoreByte(fw_pFlags, cflag); } bool FcRemote::initLUT() { // Install a trivial identity-mapping LUT, writing directly to the firmware's LUT buffer. for (unsigned channel = 0; channel < 3; channel++) { for (unsigned index = 0; index < LUT_CH_SIZE; index++) { if (!setLUT(channel, index, index << 8)) return false; } } return true; } bool FcRemote::setLUT(unsigned channel, unsigned index, int value) { return target.memStoreHalf(fw_pLUT + 2*(index + channel*LUT_CH_SIZE), constrain(value, 0, 0xFFFF)); } bool FcRemote::setPixel(unsigned index, int red, int green, int blue) { // Write one pixel directly into the fbNext framebuffer on the target. uint32_t idPacket = index / PIXELS_PER_PACKET; uint32_t idOffset = fw_usbPacketBufOffset + 1 + (index % PIXELS_PER_PACKET) * 3; uint32_t fb; // Address of the current fcFramebuffer bound to fbNext uint32_t packet; // Pointer to usb_packet in question return target.memLoad(fw_pFbNext, fb) && target.memLoad(fb + idPacket*4, packet) && target.memStoreByte(packet + idOffset + 0, constrain(red, 0, 255)) && target.memStoreByte(packet + idOffset + 1, constrain(green, 0, 255)) && target.memStoreByte(packet + idOffset + 2, constrain(blue, 0, 255)); } float FcRemote::measureFrameRate(float minDuration) { // Use the end-to-end LED data signal to measure the overall system frame rate. // Gaps of >50us indicate frame boundaries pinMode(dataFeedbackPin, INPUT); uint32_t minMicros = minDuration * 1000000; uint32_t startTime = micros(); uint32_t gapStart = 0; bool inGap = false; uint32_t frames = 0; uint32_t duration; bool anyData = false; while (1) { uint32_t now = micros(); duration = now - startTime; if (duration >= minMicros) break; if (digitalRead(dataFeedbackPin)) { // Definitely not in a gap, found some data // set anyData true indicating we saw data at least once // anyData ensures we don't count frames if dataFeedbackPin // is stuck low inGap = false; gapStart = now; anyData = true; } else if (inGap) { // Already in a gap, wait for some data. } else if (anyData && (uint32_t(now - gapStart) >= 50)) { // We've seen data, and // We just found an inter-frame gap inGap = true; frames++; } } return frames / (duration * 1e-6); } bool FcRemote::testFrameRate() { const float goalFPS = 375; const float maxFPS = 450; target.log(target.LOG_NORMAL, "FPS: Measuring frame rate..."); float fps = measureFrameRate(); target.log(target.LOG_NORMAL, "FPS: Measured %.2f frames/sec", fps); if (fps > maxFPS) { target.log(target.LOG_ERROR, "FPS: ERROR, frame rate of %.2f frames/sec is unrealistically high!", fps); return false; } if (fps < goalFPS) { target.log(target.LOG_ERROR, "FPS: ERROR, frame rate of %.2f frames/sec is below goal of %.2f!", fps, goalFPS); return false; } return true; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** **********************************************************************************************************************/ /* * CallDescriptor.cpp * * Created on: Feb 29, 2012 * Author: Dimitar Asenov */ #include "expression_editor/operators/CallDescriptor.h" #include "OOModel/src/expressions/VariableAccess.h" #include "OOModel/src/expressions/EmptyExpression.h" #include "OOModel/src/expressions/CommaExpression.h" #include "OOModel/src/expressions/MethodCallExpression.h" namespace OOInteraction { CallDescriptor::CallDescriptor(const QString& name, const QString& signature, int num_operands, int precedence, Associativity associativity) : OOOperatorDescriptor(name, signature, num_operands, precedence, associativity) {} OOModel::Expression* CallDescriptor::create(const QList<OOModel::Expression*>& operands) { Q_ASSERT(operands.size() == 2); auto varName = dynamic_cast<OOModel::VariableAccess*>( operands.first()); Q_ASSERT(varName); OOModel::MethodCallExpression* opr = new OOModel::MethodCallExpression(varName->ref()->name()); OOModel::Expression* prefix = varName->ref()->prefix(); varName->replaceChild(prefix, new OOModel::EmptyExpression()); SAFE_DELETE(varName); opr->ref()->setPrefix(prefix); if (auto comma = dynamic_cast<OOModel::CommaExpression*>(operands.last())) { for(auto arg : comma->allSubOperands(true)) opr->arguments()->append(arg); SAFE_DELETE(comma); } else if (!dynamic_cast<OOModel::EmptyExpression*>(operands.last()) ) opr->arguments()->append(operands.last()); return opr; } } /* namespace OOInteraction */ <commit_msg>Fix a bug when creating a method call expression<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** **********************************************************************************************************************/ /* * CallDescriptor.cpp * * Created on: Feb 29, 2012 * Author: Dimitar Asenov */ #include "expression_editor/operators/CallDescriptor.h" #include "OOModel/src/expressions/VariableAccess.h" #include "OOModel/src/expressions/EmptyExpression.h" #include "OOModel/src/expressions/CommaExpression.h" #include "OOModel/src/expressions/MethodCallExpression.h" namespace OOInteraction { CallDescriptor::CallDescriptor(const QString& name, const QString& signature, int num_operands, int precedence, Associativity associativity) : OOOperatorDescriptor(name, signature, num_operands, precedence, associativity) {} OOModel::Expression* CallDescriptor::create(const QList<OOModel::Expression*>& operands) { Q_ASSERT(operands.size() == 2); auto varName = dynamic_cast<OOModel::VariableAccess*>( operands.first()); Q_ASSERT(varName); OOModel::MethodCallExpression* opr = new OOModel::MethodCallExpression(varName->ref()->name()); OOModel::Expression* prefix = varName->ref()->prefix(); varName->ref()->replaceChild(prefix, new OOModel::EmptyExpression()); SAFE_DELETE(varName); opr->ref()->setPrefix(prefix); if (auto comma = dynamic_cast<OOModel::CommaExpression*>(operands.last())) { for(auto arg : comma->allSubOperands(true)) opr->arguments()->append(arg); SAFE_DELETE(comma); } else if (!dynamic_cast<OOModel::EmptyExpression*>(operands.last()) ) opr->arguments()->append(operands.last()); return opr; } } /* namespace OOInteraction */ <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <af/defines.h> #include <af/blas.h> #include <Array.hpp> #include <clBLAS.h> namespace opencl { template<typename T> Array<T> matmul(const Array<T> &lhs, const Array<T> &rhs, af_blas_transpose optLhs, af_blas_transpose optRhs); template<typename T> Array<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_blas_transpose optLhs, af_blas_transpose optRhs); STATIC_ void initBlas() { static std::once_flag clblasSetupFlag; call_once(clblasSetupFlag, clblasSetup); } } <commit_msg>Including missing headers for call_once in blas.hpp<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <af/defines.h> #include <af/blas.h> #include <Array.hpp> #include <clBLAS.h> #include <mutex> namespace opencl { template<typename T> Array<T> matmul(const Array<T> &lhs, const Array<T> &rhs, af_blas_transpose optLhs, af_blas_transpose optRhs); template<typename T> Array<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_blas_transpose optLhs, af_blas_transpose optRhs); STATIC_ void initBlas() { static std::once_flag clblasSetupFlag; call_once(clblasSetupFlag, clblasSetup); } } <|endoftext|>
<commit_before>#include <dbus/dbus-glib.h> #include <webkit2/webkit-web-extension.h> #include <JavaScriptCore/JSContextRef.h> #include <JavaScriptCore/JSStringRef.h> #include <string.h> #include "dbus.h" #include "utils.h" static GDBusConnection* connection; static gboolean web_page_send_request(WebKitWebPage* web_page, WebKitURIRequest* request, WebKitURIResponse* redirected_response, gpointer data) { GError* error = NULL; // ignore redirected requests - it's transparent to the user if (redirected_response != NULL) { return FALSE; } const char* uri = webkit_uri_request_get_uri(request); SoupMessageHeaders* headers = webkit_uri_request_get_http_headers(request); GVariantDict dictIn; GVariant* variantIn = soup_headers_to_gvariant_dict(headers); g_variant_dict_init(&dictIn, variantIn); g_variant_dict_insert(&dictIn, "uri", "s", uri); variantIn = g_variant_dict_end(&dictIn); GVariant* tuple[1]; tuple[0] = variantIn; GVariant* results = g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK, "HandleRequest", g_variant_new_tuple(tuple, 1), G_VARIANT_TYPE_TUPLE, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_variant_dict_clear(&dictIn); if (results == NULL) { g_printerr("ERR g_dbus_connection_call_sync %s\n", error->message); g_error_free(error); return FALSE; } GVariantDict dictOut; g_variant_dict_init(&dictOut, g_variant_get_child_value(results, 0)); bool ret = FALSE; const gchar* newuri = NULL; const gchar* cancel = NULL; if (g_variant_dict_lookup(&dictOut, "cancel", "s", &cancel) && cancel != NULL && !g_strcmp0(cancel, "1")) { ret = TRUE; } else if (g_variant_dict_lookup(&dictOut, "uri", "s", &newuri) && newuri != NULL) { webkit_uri_request_set_uri(request, newuri); } g_variant_dict_remove(&dictOut, "uri"); results = g_variant_dict_end(&dictOut); update_soup_headers_with_dict(headers, results); g_variant_unref(results); return ret; } static void web_page_created_callback(WebKitWebExtension* extension, WebKitWebPage* web_page, gpointer data) { g_signal_connect(web_page, "send-request", G_CALLBACK(web_page_send_request), data); } static gboolean event_listener(WebKitDOMDOMWindow* view, WebKitDOMEvent* event, gpointer data) { // find a better way to exchange data between client and here. XHR ? // use CustomEvent, but how is it possible to get event->detail() ? char* message = webkit_dom_keyboard_event_get_key_identifier((WebKitDOMKeyboardEvent*)event); GError* error = NULL; g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK, "NotifyEvent", g_variant_new("(s)", message), G_VARIANT_TYPE("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (error != NULL) { g_printerr("Failed to finish dbus call: %s\n", error->message); g_error_free(error); } g_free(message); return TRUE; } static void window_object_cleared_callback(WebKitScriptWorld* world, WebKitWebPage* page, WebKitFrame* frame, gchar* eventName) { WebKitDOMDocument* document = webkit_web_page_get_dom_document(page); WebKitDOMDOMWindow* window = webkit_dom_document_get_default_view(document); webkit_dom_event_target_add_event_listener(WEBKIT_DOM_EVENT_TARGET(window), eventName, G_CALLBACK(event_listener), false, NULL); } extern "C" { G_MODULE_EXPORT void webkit_web_extension_initialize_with_user_data(WebKitWebExtension* extension, const GVariant* constData) { gchar* address = NULL; gchar* eventName = NULL; g_variant_get((GVariant*)constData, "(ss)", &address, &eventName); g_signal_connect(webkit_script_world_get_default(), "window-object-cleared", G_CALLBACK(window_object_cleared_callback), eventName); g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), NULL); GError* error = NULL; connection = g_dbus_connection_new_for_address_sync(address, G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, NULL, NULL, &error); if (connection == NULL) { g_printerr("Failed to open connection to bus: %s\n", error->message); g_error_free(error); } } } <commit_msg>Remove comment<commit_after>#include <dbus/dbus-glib.h> #include <webkit2/webkit-web-extension.h> #include <JavaScriptCore/JSContextRef.h> #include <JavaScriptCore/JSStringRef.h> #include <string.h> #include "dbus.h" #include "utils.h" static GDBusConnection* connection; static gboolean web_page_send_request(WebKitWebPage* web_page, WebKitURIRequest* request, WebKitURIResponse* redirected_response, gpointer data) { GError* error = NULL; // ignore redirected requests - it's transparent to the user if (redirected_response != NULL) { return FALSE; } const char* uri = webkit_uri_request_get_uri(request); SoupMessageHeaders* headers = webkit_uri_request_get_http_headers(request); GVariantDict dictIn; GVariant* variantIn = soup_headers_to_gvariant_dict(headers); g_variant_dict_init(&dictIn, variantIn); g_variant_dict_insert(&dictIn, "uri", "s", uri); variantIn = g_variant_dict_end(&dictIn); GVariant* tuple[1]; tuple[0] = variantIn; GVariant* results = g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK, "HandleRequest", g_variant_new_tuple(tuple, 1), G_VARIANT_TYPE_TUPLE, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_variant_dict_clear(&dictIn); if (results == NULL) { g_printerr("ERR g_dbus_connection_call_sync %s\n", error->message); g_error_free(error); return FALSE; } GVariantDict dictOut; g_variant_dict_init(&dictOut, g_variant_get_child_value(results, 0)); bool ret = FALSE; const gchar* newuri = NULL; const gchar* cancel = NULL; if (g_variant_dict_lookup(&dictOut, "cancel", "s", &cancel) && cancel != NULL && !g_strcmp0(cancel, "1")) { ret = TRUE; } else if (g_variant_dict_lookup(&dictOut, "uri", "s", &newuri) && newuri != NULL) { webkit_uri_request_set_uri(request, newuri); } g_variant_dict_remove(&dictOut, "uri"); results = g_variant_dict_end(&dictOut); update_soup_headers_with_dict(headers, results); g_variant_unref(results); return ret; } static void web_page_created_callback(WebKitWebExtension* extension, WebKitWebPage* web_page, gpointer data) { g_signal_connect(web_page, "send-request", G_CALLBACK(web_page_send_request), data); } static gboolean event_listener(WebKitDOMDOMWindow* view, WebKitDOMEvent* event, gpointer data) { char* message = webkit_dom_keyboard_event_get_key_identifier((WebKitDOMKeyboardEvent*)event); GError* error = NULL; g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK, "NotifyEvent", g_variant_new("(s)", message), G_VARIANT_TYPE("(s)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (error != NULL) { g_printerr("Failed to finish dbus call: %s\n", error->message); g_error_free(error); } g_free(message); return TRUE; } static void window_object_cleared_callback(WebKitScriptWorld* world, WebKitWebPage* page, WebKitFrame* frame, gchar* eventName) { WebKitDOMDocument* document = webkit_web_page_get_dom_document(page); WebKitDOMDOMWindow* window = webkit_dom_document_get_default_view(document); webkit_dom_event_target_add_event_listener(WEBKIT_DOM_EVENT_TARGET(window), eventName, G_CALLBACK(event_listener), false, NULL); } extern "C" { G_MODULE_EXPORT void webkit_web_extension_initialize_with_user_data(WebKitWebExtension* extension, const GVariant* constData) { gchar* address = NULL; gchar* eventName = NULL; g_variant_get((GVariant*)constData, "(ss)", &address, &eventName); g_signal_connect(webkit_script_world_get_default(), "window-object-cleared", G_CALLBACK(window_object_cleared_callback), eventName); g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), NULL); GError* error = NULL; connection = g_dbus_connection_new_for_address_sync(address, G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, NULL, NULL, &error); if (connection == NULL) { g_printerr("Failed to open connection to bus: %s\n", error->message); g_error_free(error); } } } <|endoftext|>
<commit_before>AliJetReader *CreateJetReader(Char_t *jr); // Common config AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1); AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius) { // Creates a jet finder task, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJets", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJets", "This task requires an input event handler"); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskJets *jetana; AliJetReader *er = CreateJetReader(jr); // Define jet header and jet finder AliJetFinder *jetFinder = CreateJetFinder(jf,radius); if (jetFinder){ if (er) jetFinder->SetJetReader(er); } char *cRadius = ""; if(radius>0)cRadius = Form("%02d",(int)(radius*10)); jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius)); TString type = mgr->GetInputEventHandler()->GetDataType(); if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf)); AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(), AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius)); // Connect jet finder to task. jetana->SetJetFinder(jetFinder); jetana->SetConfigFile(""); jetana->SetDebugLevel(10); mgr->AddTask(jetana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer()); // AOD output slot will be used in a different way in future mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (jetana, 1, cout_jet); return jetana; } AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){ AliJetFinder *jetFinder = 0; switch (jf) { case "CDF": AliCdfJetHeader *jh = new AliCdfJetHeader(); jh->SetRadius(0.7); jetFinder = new AliCdfJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "DA": AliDAJetHeader *jh=new AliDAJetHeader(); jh->SetComment("DA jet code with default parameters"); jh->SelectJets(kTRUE); jh->SetNclust(10); jetFinder = new AliDAJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "FASTJET": AliFastJetHeaderV1 *jh = new AliFastJetHeaderV1(); jh->SetRparam(0.4); // setup parameters if(radius>0)jh->SetRparam(radius); jh->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh jetFinder = new AliFastJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default parameters"); jh->BackgMode(0); jh->SetRadius(0.4); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1MC": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default MC parameters"); jh->BackgMode(0); jh->SetRadius(1.0); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; default: Printf("\n >>>>>>> AddTaskJets Error Wrong jet finder selected\n"); break; } return jetFinder; } AliJetReader *CreateJetReader(Char_t *jr){ AliJetReader *er = 0; switch (jr) { case "MC": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "MC2": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics spearate config charged only"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetChargedOnly(kTRUE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "ESD": AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader(); jrh->SetComment("Testing"); jrh->SetFirstEvent(0); jrh->SetLastEvent(1000); jrh->SetPtCut(0.); jrh->SetReadSignalOnly(kFALSE); // Define reader and set its header er = new AliJetESDReader(); er->SetReaderHeader(jrh); break; case "AOD": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD Reader"); jrh->SetPtCut(0.); jrh->SetTestFilterMask(1<<0); // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(1);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC2": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(2);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; default: ::Error("AddTaskJets", "Wrong jet reader selected\n"); return 0; } return er; } <commit_msg>set debug level to 0<commit_after>AliJetReader *CreateJetReader(Char_t *jr); // Common config AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1); AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius) { // Creates a jet finder task, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJets", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJets", "This task requires an input event handler"); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskJets *jetana; AliJetReader *er = CreateJetReader(jr); // Define jet header and jet finder AliJetFinder *jetFinder = CreateJetFinder(jf,radius); if (jetFinder){ if (er) jetFinder->SetJetReader(er); } char *cRadius = ""; if(radius>0)cRadius = Form("%02d",(int)(radius*10)); jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius)); TString type = mgr->GetInputEventHandler()->GetDataType(); if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf)); AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",jr,jf,cRadius), TList::Class(), AliAnalysisManager::kOutputContainer, Form("jethist%s_%s%s.root",jr,jf,cRadius)); // Connect jet finder to task. jetana->SetJetFinder(jetFinder); jetana->SetConfigFile(""); jetana->SetDebugLevel(0); mgr->AddTask(jetana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (jetana, 0, mgr->GetCommonInputContainer()); // AOD output slot will be used in a different way in future mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (jetana, 1, cout_jet); return jetana; } AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){ AliJetFinder *jetFinder = 0; switch (jf) { case "CDF": AliCdfJetHeader *jh = new AliCdfJetHeader(); jh->SetRadius(0.7); jetFinder = new AliCdfJetFinder(); jetFinder->SetOutputFile("jets.root"); if (jh) jetFinder->SetJetHeader(jh); break; case "DA": AliDAJetHeader *jh=new AliDAJetHeader(); jh->SetComment("DA jet code with default parameters"); jh->SelectJets(kTRUE); jh->SetNclust(10); jetFinder = new AliDAJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "FASTJET": AliFastJetHeaderV1 *jh = new AliFastJetHeaderV1(); jh->SetRparam(0.4); // setup parameters if(radius>0)jh->SetRparam(radius); jh->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh jetFinder = new AliFastJetFinder(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default parameters"); jh->BackgMode(0); jh->SetRadius(0.4); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; case "UA1MC": AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1(); jh->SetComment("UA1 jet code with default MC parameters"); jh->BackgMode(0); jh->SetRadius(1.0); if(radius>0)jh->SetRadius(radius); jh->SetEtSeed(4.); jh->SetLegoNbinPhi(432); jh->SetLegoNbinEta(274); jh->SetLegoEtaMin(-2); jh->SetLegoEtaMax(+2); jh->SetMinJetEt(10.); jh->SetJetEtaMax(1.5); jh->SetJetEtaMin(-1.5); jetFinder = new AliUA1JetFinderV1(); if (jh) jetFinder->SetJetHeader(jh); break; default: Printf("\n >>>>>>> AddTaskJets Error Wrong jet finder selected\n"); break; } return jetFinder; } AliJetReader *CreateJetReader(Char_t *jr){ AliJetReader *er = 0; switch (jr) { case "MC": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "MC2": AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader(); jrh->SetComment("MC full Kinematics spearate config charged only"); jrh->SetFastSimTPC(kFALSE); jrh->SetFastSimEMCAL(kFALSE); jrh->SetChargedOnly(kTRUE); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9 // Define reader and set its header er = new AliJetKineReader(); er->SetReaderHeader(jrh); break; case "ESD": AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader(); jrh->SetComment("Testing"); jrh->SetFirstEvent(0); jrh->SetLastEvent(1000); jrh->SetPtCut(0.); jrh->SetReadSignalOnly(kFALSE); // Define reader and set its header er = new AliJetESDReader(); er->SetReaderHeader(jrh); break; case "AOD": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD Reader"); jrh->SetPtCut(0.); jrh->SetTestFilterMask(1<<0); // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(1);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; case "AODMC2": AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader(); jrh->SetComment("AOD MC Reader"); jrh->SetPtCut(0.); jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9 jrh->SetReadAODMC(2);// 1 all primary MC , 2 all primary charged // Define reader and set its header er = new AliJetAODReader(); er->SetReaderHeader(jrh); break; default: ::Error("AddTaskJets", "Wrong jet reader selected\n"); return 0; } return er; } <|endoftext|>
<commit_before>/** * \file wpbnf_search.cc * * * * \author Ethan Burns * \date 2008-10-29 */ #include <assert.h> #include <math.h> #include <limits> #include <vector> #include <algorithm> #include "wpbnf_search.h" #include "search.h" #include "state.h" #include "util/timer.h" #include "util/cumulative_ave.h" using namespace std; using namespace WPBNF; #define MIN_M 1 #define MAX_INT std::numeric_limits<int>::max() AtomicInt WPBNFSearch::min_expansions(MIN_M); WPBNFSearch::PBNFThread::PBNFThread(NBlockGraph *graph, WPBNFSearch *search) : graph(graph), search(search), set_hot(false) { next_best = 0.0; } WPBNFSearch::PBNFThread::~PBNFThread(void) {} /** * Run the search thread. */ void WPBNFSearch::PBNFThread::run(void) { vector<State *> *path; NBlock *n = NULL; do { n = graph->next_nblock(n, !set_hot); if (n && search->dynamic_m){ next_best = graph->best_free_val(); } set_hot = false; if (n) { expansions = 0; exp_this_block = 0; path = search_nblock(n); if (path) search->set_path(path); ave_exp_per_nblock.add_val(exp_this_block); } } while (!search->done && n); graph->set_done(); } /** * Get the average number of expansions per-nblock. */ fp_type WPBNFSearch::PBNFThread::get_ave_exp_per_nblock(void) { return ave_exp_per_nblock.read(); } /** * Get the average size of open lists. */ fp_type WPBNFSearch::PBNFThread::get_ave_open_size(void) { return ave_open_size.read(); } /** * Search a single NBlock. */ vector<State *> *WPBNFSearch::PBNFThread::search_nblock(NBlock *n) { vector<State *> *path = NULL; OpenList *open_fp = &n->open_fp; PQOpenList<State::PQOpsF> *open_f = &n->open_f; // ClosedList *closed = &n->closed; while (!search->done && !open_fp->empty() && !should_switch(n)) { State *s = open_fp->take(); open_f->remove(s); ave_open_size.add_val(open_fp->size()); if (search->weight * s->get_f() >= search->bound.read()) continue; if (s->is_goal()) { path = s->get_path(); break; } expansions += 1; exp_this_block += 1; vector<State *> *children = search->expand(s); vector<State *>::iterator iter; for (iter = children->begin(); iter != children->end(); iter++) { if (search->weight * (*iter)->get_f() >= search->bound.read()) { delete *iter; continue; } unsigned int block = search->project->project(*iter); PQOpenList<State::PQOpsFPrime> *next_open_fp = &graph->get_nblock(block)->open_fp; PQOpenList<State::PQOpsF> *next_open_f = &graph->get_nblock(block)->open_f; ClosedList *next_closed = &graph->get_nblock(block)->closed; State *dup = next_closed->lookup(*iter); if (dup) { if (dup->get_g() > (*iter)->get_g()) { dup->update((*iter)->get_parent(), (*iter)->get_g()); if (dup->is_open()) { next_open_fp->see_update(dup); next_open_f->see_update(dup); } else { next_open_fp->add(dup); next_open_f->add(dup); } ave_open_size.add_val(next_open_fp->size()); } delete *iter; } else { next_closed->add(*iter); if ((*iter)->is_goal()) { path = (*iter)->get_path(); delete children; return path; } next_open_fp->add(*iter); next_open_f->add(*iter); ave_open_size.add_val(next_open_fp->size()); } } delete children; } return path; } /** * Test the graph to see if we should switch to a new NBlock. * \param n The current NBlock. * * \note We should make this more complex... we should also check our * successor NBlocks. */ bool WPBNFSearch::PBNFThread::should_switch(NBlock *n) { bool ret; if (next_best == 0.0 || graph->best_free_val() != 0.0){ if (expansions < search->min_expansions.read()) return false; } else{ return n->open_fp.get_best_val() > next_best; } expansions = 0; fp_type free = graph->next_nblock_f_value(); fp_type cur = n->open_fp.get_best_val(); NBlock *best_scope = graph->best_in_scope(n); if (best_scope) { fp_type scope = best_scope->open_fp.get_best_val(); ret = free < cur || scope < cur; if (!ret) graph->wont_release(n); else if (scope < free) { graph->set_hot(best_scope); set_hot = true; } } else { ret = free < cur; } return ret; } /************************************************************/ /************************************************************/ /************************************************************/ WPBNFSearch::WPBNFSearch(unsigned int n_threads, unsigned int min_e) : n_threads(n_threads), project(NULL), path(NULL), bound(fp_infinity), graph(NULL) { pthread_mutex_init(&path_mutex, NULL); if (min_e == 0){ dynamic_m = true; WPBNFSearch::min_expansions = AtomicInt(MIN_M); } else{ dynamic_m = false; WPBNFSearch::min_expansions = AtomicInt(min_e); } } WPBNFSearch::~WPBNFSearch(void) { if (graph) delete graph; } vector<State *> *WPBNFSearch::search(State *initial) { project = initial->get_domain()->get_projection(); vector<PBNFThread *> threads; vector<PBNFThread *>::iterator iter; fp_type sum = 0.0; unsigned int num = 0; fp_type osum = 0.0; unsigned int onum = 0; Timer t; t.start(); graph = new NBlockGraph(project, initial); t.stop(); weight = initial->get_domain()->get_heuristic()->get_weight(); for (unsigned int i = 0; i < n_threads; i += 1) { PBNFThread *t = new PBNFThread(graph, this); threads.push_back(t); t->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->join(); fp_type ave = (*iter)->get_ave_exp_per_nblock(); if (ave != 0) { sum += ave; num += 1; } fp_type oave = (*iter)->get_ave_open_size(); if (oave != 0) { osum += oave; onum += 1; } delete *iter; } if (num == 0) cout << "expansions-per-nblock: -1" << endl; else cout << "expansions-per-nblock: " << sum / num << endl; if (onum == 0) cout << "avg-open-list-size: -1" << endl; else cout << "avg-open-list-size: " << osum / onum << endl; cout << "nblock-graph-creation-time: " << t.get_wall_time() << endl; cout << "total-nblocks: " << project->get_num_nblocks() << endl; cout << "created-nblocks: " << graph->get_ncreated_nblocks() << endl; return path; } /** * Set an incumbant solution. */ void WPBNFSearch::set_path(vector<State *> *p) { pthread_mutex_lock(&path_mutex); assert(p->at(0)->get_g() == p->at(0)->get_f()); if (p && bound.read() > p->at(0)->get_g()) { this->path = p; bound.set(p->at(0)->get_g()); if ((weight * graph->get_f_min()) > p->at(0)->get_g()) done = true; } pthread_mutex_unlock(&path_mutex); } <commit_msg>Better termination and pruning tests in wPBNF.<commit_after>/** * \file wpbnf_search.cc * * * * \author Ethan Burns * \date 2008-10-29 */ #include <assert.h> #include <math.h> #include <limits> #include <vector> #include <algorithm> #include "wpbnf_search.h" #include "search.h" #include "state.h" #include "util/timer.h" #include "util/cumulative_ave.h" using namespace std; using namespace WPBNF; #define MIN_M 1 #define MAX_INT std::numeric_limits<int>::max() AtomicInt WPBNFSearch::min_expansions(MIN_M); WPBNFSearch::PBNFThread::PBNFThread(NBlockGraph *graph, WPBNFSearch *search) : graph(graph), search(search), set_hot(false) { next_best = 0.0; } WPBNFSearch::PBNFThread::~PBNFThread(void) {} /** * Run the search thread. */ void WPBNFSearch::PBNFThread::run(void) { vector<State *> *path; NBlock *n = NULL; do { n = graph->next_nblock(n, !set_hot); if ((search->weight * graph->get_f_min()) > search->bound.read()) break; if (n && search->dynamic_m) next_best = graph->best_free_val(); set_hot = false; if (n) { expansions = 0; exp_this_block = 0; path = search_nblock(n); if (path) search->set_path(path); ave_exp_per_nblock.add_val(exp_this_block); } } while (!search->done && n); search->done = true; graph->set_done(); } /** * Get the average number of expansions per-nblock. */ fp_type WPBNFSearch::PBNFThread::get_ave_exp_per_nblock(void) { return ave_exp_per_nblock.read(); } /** * Get the average size of open lists. */ fp_type WPBNFSearch::PBNFThread::get_ave_open_size(void) { return ave_open_size.read(); } /** * Search a single NBlock. */ vector<State *> *WPBNFSearch::PBNFThread::search_nblock(NBlock *n) { vector<State *> *path = NULL; OpenList *open_fp = &n->open_fp; PQOpenList<State::PQOpsF> *open_f = &n->open_f; // ClosedList *closed = &n->closed; while (!search->done && !open_fp->empty() && !should_switch(n)) { State *s = open_fp->take(); open_f->remove(s); ave_open_size.add_val(open_fp->size()); // If the best f value in this nblock is bad, prune everything. if (search->weight * open_f->get_best_val() >= search->bound.read()) { open_f->prune(); open_fp->prune(); break; } // If the individual f value is bad, prune the single node. if (search->weight * s->get_f() >= search->bound.read()) continue; if (s->is_goal()) { path = s->get_path(); break; } expansions += 1; exp_this_block += 1; vector<State *> *children = search->expand(s); vector<State *>::iterator iter; for (iter = children->begin(); iter != children->end(); iter++) { if (search->weight * (*iter)->get_f() >= search->bound.read()) { delete *iter; continue; } unsigned int block = search->project->project(*iter); PQOpenList<State::PQOpsFPrime> *next_open_fp = &graph->get_nblock(block)->open_fp; PQOpenList<State::PQOpsF> *next_open_f = &graph->get_nblock(block)->open_f; ClosedList *next_closed = &graph->get_nblock(block)->closed; State *dup = next_closed->lookup(*iter); if (dup) { if (dup->get_g() > (*iter)->get_g()) { dup->update((*iter)->get_parent(), (*iter)->get_g()); if (dup->is_open()) { next_open_fp->see_update(dup); next_open_f->see_update(dup); } else { next_open_fp->add(dup); next_open_f->add(dup); } ave_open_size.add_val(next_open_fp->size()); } delete *iter; } else { next_closed->add(*iter); if ((*iter)->is_goal()) { path = (*iter)->get_path(); delete children; return path; } next_open_fp->add(*iter); next_open_f->add(*iter); ave_open_size.add_val(next_open_fp->size()); } } delete children; } return path; } /** * Test the graph to see if we should switch to a new NBlock. * \param n The current NBlock. * * \note We should make this more complex... we should also check our * successor NBlocks. */ bool WPBNFSearch::PBNFThread::should_switch(NBlock *n) { bool ret; if (next_best == 0.0 || graph->best_free_val() != 0.0){ if (expansions < search->min_expansions.read()) return false; } else{ return n->open_fp.get_best_val() > next_best; } expansions = 0; fp_type free = graph->next_nblock_f_value(); fp_type cur = n->open_fp.get_best_val(); NBlock *best_scope = graph->best_in_scope(n); if (best_scope) { fp_type scope = best_scope->open_fp.get_best_val(); ret = free < cur || scope < cur; if (!ret) graph->wont_release(n); else if (scope < free) { graph->set_hot(best_scope); set_hot = true; } } else { ret = free < cur; } return ret; } /************************************************************/ /************************************************************/ /************************************************************/ WPBNFSearch::WPBNFSearch(unsigned int n_threads, unsigned int min_e) : n_threads(n_threads), project(NULL), path(NULL), bound(fp_infinity), graph(NULL) { pthread_mutex_init(&path_mutex, NULL); if (min_e == 0){ dynamic_m = true; WPBNFSearch::min_expansions = AtomicInt(MIN_M); } else{ dynamic_m = false; WPBNFSearch::min_expansions = AtomicInt(min_e); } } WPBNFSearch::~WPBNFSearch(void) { if (graph) delete graph; } vector<State *> *WPBNFSearch::search(State *initial) { project = initial->get_domain()->get_projection(); vector<PBNFThread *> threads; vector<PBNFThread *>::iterator iter; fp_type sum = 0.0; unsigned int num = 0; fp_type osum = 0.0; unsigned int onum = 0; Timer t; t.start(); graph = new NBlockGraph(project, initial); t.stop(); weight = initial->get_domain()->get_heuristic()->get_weight(); for (unsigned int i = 0; i < n_threads; i += 1) { PBNFThread *t = new PBNFThread(graph, this); threads.push_back(t); t->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->join(); fp_type ave = (*iter)->get_ave_exp_per_nblock(); if (ave != 0) { sum += ave; num += 1; } fp_type oave = (*iter)->get_ave_open_size(); if (oave != 0) { osum += oave; onum += 1; } delete *iter; } if (num == 0) cout << "expansions-per-nblock: -1" << endl; else cout << "expansions-per-nblock: " << sum / num << endl; if (onum == 0) cout << "avg-open-list-size: -1" << endl; else cout << "avg-open-list-size: " << osum / onum << endl; cout << "nblock-graph-creation-time: " << t.get_wall_time() << endl; cout << "total-nblocks: " << project->get_num_nblocks() << endl; cout << "created-nblocks: " << graph->get_ncreated_nblocks() << endl; return path; } /** * Set an incumbant solution. */ void WPBNFSearch::set_path(vector<State *> *p) { pthread_mutex_lock(&path_mutex); assert(p->at(0)->get_g() == p->at(0)->get_f()); if (p && bound.read() > p->at(0)->get_g()) { this->path = p; bound.set(p->at(0)->get_g()); if ((weight * graph->get_f_min()) > p->at(0)->get_g()) done = true; } pthread_mutex_unlock(&path_mutex); } <|endoftext|>
<commit_before>//===-- PowerPCTargetMachine.cpp - Define TargetMachine for PowerPC -------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "PowerPCTargetMachine.h" #include "PowerPC.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/IntrinsicLowering.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetMachineImpls.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; // allocatePowerPCTargetMachine - Allocate and return a subclass of // TargetMachine that implements the PowerPC backend. // TargetMachine *llvm::allocatePowerPCTargetMachine(const Module &M, IntrinsicLowering *IL) { return new PowerPCTargetMachine(M, IL); } /// PowerPCTargetMachine ctor - Create an ILP32 architecture model /// /// FIXME: Should double alignment be 8 bytes? Then we get a PtrAl != DoubleAl /// abort PowerPCTargetMachine::PowerPCTargetMachine(const Module &M, IntrinsicLowering *IL) : TargetMachine("PowerPC", IL, false, 4, 4, 4, 4, 4, 4, 4, 4), FrameInfo(TargetFrameInfo::StackGrowsDown, 16, -4), JITInfo(*this) { } /// addPassesToEmitAssembly - Add passes to the specified pass manager /// to implement a static compiler for this target. /// bool PowerPCTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) { // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); PM.add(createPPCSimpleInstructionSelector(*this)); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createRegisterAllocator()); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createPrologEpilogCodeInserter()); PM.add(createPPCCodePrinterPass(Out, *this)); PM.add(createMachineCodeDeleter()); return false; } /// addPassesToJITCompile - Add passes to the specified pass manager to /// implement a fast dynamic compiler for this target. /// void PowerPCJITInfo::addPassesToJITCompile(FunctionPassManager &PM) { // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); PM.add(createPPCSimpleInstructionSelector(TM)); PM.add(createRegisterAllocator()); PM.add(createPrologEpilogCodeInserter()); } <commit_msg>Fix all of those problems that the PPC backend has running 176.gcc :)<commit_after>//===-- PowerPCTargetMachine.cpp - Define TargetMachine for PowerPC -------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "PowerPCTargetMachine.h" #include "PowerPC.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/IntrinsicLowering.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetMachineImpls.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; // allocatePowerPCTargetMachine - Allocate and return a subclass of // TargetMachine that implements the PowerPC backend. // TargetMachine *llvm::allocatePowerPCTargetMachine(const Module &M, IntrinsicLowering *IL) { return new PowerPCTargetMachine(M, IL); } /// PowerPCTargetMachine ctor - Create an ILP32 architecture model /// /// FIXME: Should double alignment be 8 bytes? Then we get a PtrAl != DoubleAl /// abort PowerPCTargetMachine::PowerPCTargetMachine(const Module &M, IntrinsicLowering *IL) : TargetMachine("PowerPC", IL, false, 4, 4, 4, 4, 4, 4, 4, 4), FrameInfo(TargetFrameInfo::StackGrowsDown, 16, -4), JITInfo(*this) { } /// addPassesToEmitAssembly - Add passes to the specified pass manager /// to implement a static compiler for this target. /// bool PowerPCTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) { // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); PM.add(createPPCSimpleInstructionSelector(*this)); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createRegisterAllocator()); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createPrologEpilogCodeInserter()); PM.add(createPPCCodePrinterPass(Out, *this)); PM.add(createMachineCodeDeleter()); return false; } /// addPassesToJITCompile - Add passes to the specified pass manager to /// implement a fast dynamic compiler for this target. /// void PowerPCJITInfo::addPassesToJITCompile(FunctionPassManager &PM) { // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); PM.add(createPPCSimpleInstructionSelector(TM)); PM.add(createRegisterAllocator()); PM.add(createPrologEpilogCodeInserter()); } <|endoftext|>
<commit_before>//===-- PowerPCTargetMachine.cpp - Define TargetMachine for PowerPC -------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "PowerPC.h" #include "PowerPCTargetMachine.h" #include "PowerPCFrameInfo.h" #include "PPC32TargetMachine.h" #include "PPC64TargetMachine.h" #include "PPC32JITInfo.h" #include "PPC64JITInfo.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/IntrinsicLowering.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Support/CommandLine.h" #include <iostream> using namespace llvm; namespace llvm { cl::opt<bool> AIX("aix", cl::desc("Generate AIX/xcoff instead of Darwin/MachO"), cl::Hidden); } namespace { const std::string PPC32ID = "PowerPC/32bit"; const std::string PPC64ID = "PowerPC/64bit"; // Register the targets RegisterTarget<PPC32TargetMachine> X("ppc32", " PowerPC 32-bit"); #if 0 RegisterTarget<PPC64TargetMachine> Y("ppc64", " PowerPC 64-bit (unimplemented)"); #endif } PowerPCTargetMachine::PowerPCTargetMachine(const std::string &name, IntrinsicLowering *IL, const TargetData &TD, const PowerPCFrameInfo &TFI) : TargetMachine(name, IL, TD), FrameInfo(TFI) {} unsigned PPC32TargetMachine::getJITMatchQuality() { return 0; #if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER) return 10; #else return 0; #endif } /// addPassesToEmitAssembly - Add passes to the specified pass manager /// to implement a static compiler for this target. /// bool PowerPCTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) { bool LP64 = (0 != dynamic_cast<PPC64TargetMachine *>(this)); // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); if (LP64) PM.add(createPPC64ISelSimple(*this)); else PM.add(createPPC32ISelSimple(*this)); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createRegisterAllocator()); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createPrologEpilogCodeInserter()); // Must run branch selection immediately preceding the asm printer PM.add(createPPCBranchSelectionPass()); if (AIX) PM.add(createAIXAsmPrinter(Out, *this)); else PM.add(createDarwinAsmPrinter(Out, *this)); PM.add(createMachineCodeDeleter()); return false; } void PowerPCJITInfo::addPassesToJITCompile(FunctionPassManager &PM) { return; // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); PM.add(createPPC32ISelSimple(TM)); PM.add(createRegisterAllocator()); PM.add(createPrologEpilogCodeInserter()); // Must run branch selection immediately preceding the asm printer PM.add(createPPCBranchSelectionPass()); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); } void PowerPCJITInfo::replaceMachineCodeForFunction(void *Old, void *New) { assert(0 && "Cannot execute PowerPCJITInfo::replaceMachineCodeForFunction()"); } /// PowerPCTargetMachine ctor - Create an ILP32 architecture model /// PPC32TargetMachine::PPC32TargetMachine(const Module &M, IntrinsicLowering *IL) : PowerPCTargetMachine(PPC32ID, IL, TargetData(PPC32ID,false,4,4,4,4,4,4,2,1,4), PowerPCFrameInfo(*this, false)), JITInfo(*this) {} /// PPC64TargetMachine ctor - Create a LP64 architecture model /// PPC64TargetMachine::PPC64TargetMachine(const Module &M, IntrinsicLowering *IL) : PowerPCTargetMachine(PPC64ID, IL, TargetData(PPC64ID,false,8,4,4,4,4,4,2,1,4), PowerPCFrameInfo(*this, true)) {} unsigned PPC32TargetMachine::getModuleMatchQuality(const Module &M) { if (M.getEndianness() == Module::BigEndian && M.getPointerSize() == Module::Pointer32) return 10; // Direct match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } unsigned PPC64TargetMachine::getModuleMatchQuality(const Module &M) { if (M.getEndianness() == Module::BigEndian && M.getPointerSize() == Module::Pointer64) return 10; // Direct match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } <commit_msg>Remove this method.<commit_after>//===-- PowerPCTargetMachine.cpp - Define TargetMachine for PowerPC -------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "PowerPC.h" #include "PowerPCTargetMachine.h" #include "PowerPCFrameInfo.h" #include "PPC32TargetMachine.h" #include "PPC64TargetMachine.h" #include "PPC32JITInfo.h" #include "PPC64JITInfo.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/IntrinsicLowering.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Support/CommandLine.h" #include <iostream> using namespace llvm; namespace llvm { cl::opt<bool> AIX("aix", cl::desc("Generate AIX/xcoff instead of Darwin/MachO"), cl::Hidden); } namespace { const std::string PPC32ID = "PowerPC/32bit"; const std::string PPC64ID = "PowerPC/64bit"; // Register the targets RegisterTarget<PPC32TargetMachine> X("ppc32", " PowerPC 32-bit"); #if 0 RegisterTarget<PPC64TargetMachine> Y("ppc64", " PowerPC 64-bit (unimplemented)"); #endif } PowerPCTargetMachine::PowerPCTargetMachine(const std::string &name, IntrinsicLowering *IL, const TargetData &TD, const PowerPCFrameInfo &TFI) : TargetMachine(name, IL, TD), FrameInfo(TFI) {} unsigned PPC32TargetMachine::getJITMatchQuality() { return 0; #if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER) return 10; #else return 0; #endif } /// addPassesToEmitAssembly - Add passes to the specified pass manager /// to implement a static compiler for this target. /// bool PowerPCTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) { bool LP64 = (0 != dynamic_cast<PPC64TargetMachine *>(this)); // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); if (LP64) PM.add(createPPC64ISelSimple(*this)); else PM.add(createPPC32ISelSimple(*this)); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createRegisterAllocator()); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); PM.add(createPrologEpilogCodeInserter()); // Must run branch selection immediately preceding the asm printer PM.add(createPPCBranchSelectionPass()); if (AIX) PM.add(createAIXAsmPrinter(Out, *this)); else PM.add(createDarwinAsmPrinter(Out, *this)); PM.add(createMachineCodeDeleter()); return false; } void PowerPCJITInfo::addPassesToJITCompile(FunctionPassManager &PM) { // FIXME: Implement efficient support for garbage collection intrinsics. PM.add(createLowerGCPass()); // FIXME: Implement the invoke/unwind instructions! PM.add(createLowerInvokePass()); // FIXME: Implement the switch instruction in the instruction selector! PM.add(createLowerSwitchPass()); PM.add(createLowerConstantExpressionsPass()); // Make sure that no unreachable blocks are instruction selected. PM.add(createUnreachableBlockEliminationPass()); PM.add(createPPC32ISelSimple(TM)); PM.add(createRegisterAllocator()); PM.add(createPrologEpilogCodeInserter()); // Must run branch selection immediately preceding the asm printer PM.add(createPPCBranchSelectionPass()); if (PrintMachineCode) PM.add(createMachineFunctionPrinterPass(&std::cerr)); } /// PowerPCTargetMachine ctor - Create an ILP32 architecture model /// PPC32TargetMachine::PPC32TargetMachine(const Module &M, IntrinsicLowering *IL) : PowerPCTargetMachine(PPC32ID, IL, TargetData(PPC32ID,false,4,4,4,4,4,4,2,1,4), PowerPCFrameInfo(*this, false)), JITInfo(*this) {} /// PPC64TargetMachine ctor - Create a LP64 architecture model /// PPC64TargetMachine::PPC64TargetMachine(const Module &M, IntrinsicLowering *IL) : PowerPCTargetMachine(PPC64ID, IL, TargetData(PPC64ID,false,8,4,4,4,4,4,2,1,4), PowerPCFrameInfo(*this, true)) {} unsigned PPC32TargetMachine::getModuleMatchQuality(const Module &M) { if (M.getEndianness() == Module::BigEndian && M.getPointerSize() == Module::Pointer32) return 10; // Direct match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } unsigned PPC64TargetMachine::getModuleMatchQuality(const Module &M) { if (M.getEndianness() == Module::BigEndian && M.getPointerSize() == Module::Pointer64) return 10; // Direct match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } <|endoftext|>
<commit_before>/** * @file Internal.cpp * @author Mislav Novakovic <[email protected]> * @brief Implementation of header internal helper classes. * * Copyright (c) 2017 Deutsche Telekom AG. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #include <iostream> #include "Internal.hpp" #include "Libyang.hpp" #include "Tree_Data.hpp" extern "C" { #include "libyang.h" #include "tree_data.h" #include "tree_schema.h" } void check_libyang_error() { const char *errmsg = ly_errmsg(); if (errmsg) { throw std::runtime_error(errmsg); } }; Deleter::Deleter(ly_ctx *ctx, S_Deleter parent): t(Free_Type::CONTEXT), parent(parent), context(nullptr) { v.ctx = ctx; }; Deleter::Deleter(struct lyd_node *data, S_Deleter parent): t(Free_Type::DATA_NODE), parent(parent), context(nullptr) { v.data = data; }; Deleter::Deleter(struct lys_node *schema, S_Deleter parent): t(Free_Type::SCHEMA_NODE), parent(parent), context(nullptr) { v.schema = schema; }; Deleter::Deleter(struct lys_module *module, S_Deleter parent): t(Free_Type::MODULE), parent(parent), context(nullptr) { v.module = module; }; Deleter::Deleter(struct lys_submodule *submodule, S_Deleter parent): t(Free_Type::SUBMODULE), parent(parent), context(nullptr) { v.submodule = submodule; }; Deleter::Deleter(S_Context context, struct lyxml_elem *elem, S_Deleter parent): t(Free_Type::XML), parent(parent), context(context) { v.elem = elem; }; Deleter::Deleter(struct ly_set *set, S_Deleter parent): t(Free_Type::SET), parent(parent), context(nullptr) { v.set = set; } Deleter::Deleter(struct lyd_difflist *diff, S_Deleter parent): t(Free_Type::DIFFLIST), parent(parent), context(nullptr) { v.diff = diff; } Deleter::~Deleter() { switch(t) { case Free_Type::CONTEXT: if (v.ctx) ly_ctx_destroy(v.ctx, nullptr); v.ctx = nullptr; break; case Free_Type::DATA_NODE: if (v.data) lyd_free(v.data); v.data = nullptr; break; case Free_Type::SCHEMA_NODE: break; case Free_Type::MODULE: break; case Free_Type::SUBMODULE: break; case Free_Type::XML: if (v.elem) lyxml_free(context->ctx, v.elem); v.elem = nullptr; break; case Free_Type::SET: if (v.set) ly_set_free(v.set); v.set = nullptr; break; case Free_Type::DIFFLIST: if (v.diff) lyd_free_diff(v.diff); v.diff = nullptr; break; } }; <commit_msg>C++: fix constructor warnings<commit_after>/** * @file Internal.cpp * @author Mislav Novakovic <[email protected]> * @brief Implementation of header internal helper classes. * * Copyright (c) 2017 Deutsche Telekom AG. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #include <iostream> #include "Internal.hpp" #include "Libyang.hpp" #include "Tree_Data.hpp" extern "C" { #include "libyang.h" #include "tree_data.h" #include "tree_schema.h" } void check_libyang_error() { const char *errmsg = ly_errmsg(); if (errmsg) { throw std::runtime_error(errmsg); } }; Deleter::Deleter(ly_ctx *ctx, S_Deleter parent): t(Free_Type::CONTEXT), parent(parent) { context = NULL; v.ctx = ctx; }; Deleter::Deleter(struct lyd_node *data, S_Deleter parent): t(Free_Type::DATA_NODE), parent(parent) { context = NULL; v.data = data; }; Deleter::Deleter(struct lys_node *schema, S_Deleter parent): t(Free_Type::SCHEMA_NODE), parent(parent) { context = NULL; v.schema = schema; }; Deleter::Deleter(struct lys_module *module, S_Deleter parent): t(Free_Type::MODULE), parent(parent) { context = NULL; v.module = module; }; Deleter::Deleter(struct lys_submodule *submodule, S_Deleter parent): t(Free_Type::SUBMODULE), parent(parent) { context = NULL; v.submodule = submodule; }; Deleter::Deleter(S_Context context, struct lyxml_elem *elem, S_Deleter parent): t(Free_Type::XML), parent(parent) { context = NULL; v.elem = elem; }; Deleter::Deleter(struct ly_set *set, S_Deleter parent): t(Free_Type::SET), parent(parent) { context = NULL; v.set = set; } Deleter::Deleter(struct lyd_difflist *diff, S_Deleter parent): t(Free_Type::DIFFLIST), parent(parent) { context = NULL; v.diff = diff; } Deleter::~Deleter() { switch(t) { case Free_Type::CONTEXT: if (v.ctx) ly_ctx_destroy(v.ctx, nullptr); v.ctx = nullptr; break; case Free_Type::DATA_NODE: if (v.data) lyd_free(v.data); v.data = nullptr; break; case Free_Type::SCHEMA_NODE: break; case Free_Type::MODULE: break; case Free_Type::SUBMODULE: break; case Free_Type::XML: if (v.elem) lyxml_free(context->ctx, v.elem); v.elem = nullptr; break; case Free_Type::SET: if (v.set) ly_set_free(v.set); v.set = nullptr; break; case Free_Type::DIFFLIST: if (v.diff) lyd_free_diff(v.diff); v.diff = nullptr; break; } }; <|endoftext|>
<commit_before><commit_msg>fix templates for forwarding do not work with inline mails Thanks to vondom for providing the patch, and thanks to everyone who tested.<commit_after><|endoftext|>
<commit_before><commit_msg>added tooltips, which do not work yet, due to missing feature in KAction<commit_after><|endoftext|>
<commit_before> #include "arguments.h" #include "common.h" #include <iostream> #include <string> int Arguments::ParseArguments(Arguments::Parameters *params, const char **args, int argsCnt) { std::string tmp; std::string tmpArg; for (int i = 0; i < argsCnt; i++) { std::string value(args[i]); A3URLCommon::StrUnqoute(&value); if (value.compare("#url") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 10; params->Url = tmp; tmp.clear(); } else { return 11; } } else if (value.compare("#method") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 12; params->Method = tmp; tmp.clear(); } else { return 13; } } else if (value.compare("#postData") == 0) { while (i < argsCnt) { if (i+1 >= argsCnt) break; if (strncmp(args[i+1], "\"#", 2) == 0) break; tmp.append(args[i+1]); A3URLCommon::StrUnqoute(&tmp); params->PostData.append(tmp); std::cout << params->c_str() << std::endl; tmp.clear(); i++; } } else if (value.compare("#headers") == 0) { while (i < argsCnt) { if (i+2 >= argsCnt) break; if (strncmp(args[i+1], "\"#", 2) == 0 || strncmp(args[i+2], "\"#", 2) == 0) break; tmpArg.append(args[i+1]); A3URLCommon::StrUnqoute(&tmpArg); tmp.append(tmpArg); tmpArg.clear(); tmp.append(": "); tmpArg.append(args[i+2]); A3URLCommon::StrUnqoute(&tmpArg); tmp.append(tmpArg); tmpArg.clear(); params->Headers.push_back(tmp); tmp.clear(); i += 2; } } else if (value.compare("#jsonToArray") == 0) { params->JsonToArray = true; } else if (value.compare("#clientid") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 14; params->ClientID = A3URLCommon::StrToInt(tmp); tmp.clear(); } else { return 15; } } else if (value.compare("#redirect") == 0) { params->Redirect = true; if (i+1 < argsCnt) { if (strcmp(args[i+1], "#") != 0) continue; i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.empty()) return 16; params->MaxRedirects = A3URLCommon::StrToInt(tmp); tmp.clear(); } } else if (value.compare("#timeout") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 17; params->MaxTimeout = (long int)(A3URLCommon::StrToInt(tmp)); tmp.clear(); } else { return 18; } } tmpArg.clear(); tmp.clear(); } return 0; }; <commit_msg>fixed arguments<commit_after> #include "arguments.h" #include "common.h" #include <iostream> #include <string> int Arguments::ParseArguments(Arguments::Parameters *params, const char **args, int argsCnt) { std::string tmp; std::string tmpArg; for (int i = 0; i < argsCnt; i++) { std::string value(args[i]); A3URLCommon::StrUnqoute(&value); if (value.compare("#url") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 10; params->Url = tmp; tmp.clear(); } else { return 11; } } else if (value.compare("#method") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 12; params->Method = tmp; tmp.clear(); } else { return 13; } } else if (value.compare("#postData") == 0) { while (i < argsCnt) { if (i+1 >= argsCnt) break; if (strncmp(args[i+1], "\"#", 2) == 0) break; tmp.append(args[i+1]); A3URLCommon::StrUnqoute(&tmp); params->PostData.append(tmp); std::cout << params->PostData.c_str() << std::endl; tmp.clear(); i++; } } else if (value.compare("#headers") == 0) { while (i < argsCnt) { if (i+2 >= argsCnt) break; if (strncmp(args[i+1], "\"#", 2) == 0 || strncmp(args[i+2], "\"#", 2) == 0) break; tmpArg.append(args[i+1]); A3URLCommon::StrUnqoute(&tmpArg); tmp.append(tmpArg); tmpArg.clear(); tmp.append(": "); tmpArg.append(args[i+2]); A3URLCommon::StrUnqoute(&tmpArg); tmp.append(tmpArg); tmpArg.clear(); params->Headers.push_back(tmp); tmp.clear(); i += 2; } } else if (value.compare("#jsonToArray") == 0) { params->JsonToArray = true; } else if (value.compare("#clientid") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 14; params->ClientID = A3URLCommon::StrToInt(tmp); tmp.clear(); } else { return 15; } } else if (value.compare("#redirect") == 0) { params->Redirect = true; if (i+1 < argsCnt) { if (strcmp(args[i+1], "#") != 0) continue; i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.empty()) return 16; params->MaxRedirects = A3URLCommon::StrToInt(tmp); tmp.clear(); } } else if (value.compare("#timeout") == 0) { if (i+1 < argsCnt) { i++; tmp.append(args[i]); A3URLCommon::StrUnqoute(&tmp); if (tmp.at(0) == '#' || tmp.empty()) return 17; params->MaxTimeout = (long int)(A3URLCommon::StrToInt(tmp)); tmp.clear(); } else { return 18; } } tmpArg.clear(); tmp.clear(); } return 0; }; <|endoftext|>
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * 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 <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include "DmaConfigProxy.h" #include "GeneratedTypes.h" #include "NandSimIndicationWrapper.h" #include "NandSimRequestProxy.h" #include "StrstrIndicationWrapper.h" #include "StrstrRequestProxy.h" static int trace_memory = 1; extern "C" { #include "sys/ioctl.h" #include "portalmem.h" #include "sock_utils.h" #include "dmaManager.h" #include "dmaSendFd.h" } size_t numBytes = 1 << 12; #ifndef BOARD_bluesim size_t nandBytes = 1 << 24; #else size_t nandBytes = 1 << 14; #endif class NandSimIndication : public NandSimIndicationWrapper { public: unsigned int rDataCnt; virtual void readDone(uint32_t v){ fprintf(stderr, "NandSim::readDone v=%x\n", v); sem_post(&sem); } virtual void writeDone(uint32_t v){ fprintf(stderr, "NandSim::writeDone v=%x\n", v); sem_post(&sem); } virtual void eraseDone(uint32_t v){ fprintf(stderr, "NandSim::eraseDone v=%x\n", v); sem_post(&sem); } virtual void configureNandDone(){ fprintf(stderr, "NandSim::configureNandDone\n"); sem_post(&sem); } NandSimIndication(int id) : NandSimIndicationWrapper(id) { sem_init(&sem, 0, 0); } void wait() { fprintf(stderr, "NandSim::wait for semaphore\n"); sem_wait(&sem); } private: sem_t sem; }; class StrstrIndication : public StrstrIndicationWrapper { public: StrstrIndication(unsigned int id) : StrstrIndicationWrapper(id){ sem_init(&sem, 0, 0); match_cnt = 0; }; virtual void setupComplete() { sem_post(&sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); if (v == -1) sem_post(&sem); else match_cnt++; } void wait() { fprintf(stderr, "Strstr::wait for semaphore\n"); sem_wait(&sem); } private: sem_t sem; int match_cnt; }; int main(int argc, const char **argv) { unsigned int srcGen = 0; NandSimRequestProxy *nandsimRequest = 0; DmaConfigProxy *dmaConfig = 0; NandSimIndication *nandsimIndication = 0; DmaIndication *dmaIndication = 0; StrstrRequestProxy *strstrRequest = 0; DmaConfigProxy *nandsimDmaConfig = 0; StrstrIndication *strstrIndication = 0; DmaIndication *nandsimDmaIndication = 0; fprintf(stderr, "Main::%s %s\n", __DATE__, __TIME__); nandsimRequest = new NandSimRequestProxy(IfcNames_NandSimRequest); dmaConfig = new DmaConfigProxy(IfcNames_DmaConfig); DmaManager *dma = new DmaManager(dmaConfig); nandsimIndication = new NandSimIndication(IfcNames_NandSimIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); strstrRequest = new StrstrRequestProxy(IfcNames_StrstrRequest); nandsimDmaConfig = new DmaConfigProxy(IfcNames_NandsimDmaConfig); strstrIndication = new StrstrIndication(IfcNames_StrstrIndication); DmaManager *nandsimDma = new DmaManager(nandsimDmaConfig); nandsimDmaIndication = new DmaIndication(nandsimDma,IfcNames_NandsimDmaIndication); portalExec_start(); fprintf(stderr, "Main::allocating memory...\n"); // allocate memory for strstr data int haystackAlloc = portalAlloc(numBytes); int needleAlloc = portalAlloc(numBytes); int mpNextAlloc = portalAlloc(numBytes); int ref_haystackAlloc = dma->reference(haystackAlloc); int ref_needleAlloc = dma->reference(needleAlloc); int ref_mpNextAlloc = dma->reference(mpNextAlloc); char *needle = (char *)portalMmap(needleAlloc, numBytes); char *haystack = (char *)portalMmap(haystackAlloc, numBytes); int *mpNext = (int *)portalMmap(mpNextAlloc, numBytes); // allocate memory buffer for nandsim to use as backing store int nandBacking = portalAlloc(nandBytes); int ref_nandBacking = dma->reference(nandBacking); // give the nandsim a pointer to its backing store nandsimRequest->configureNand(ref_nandBacking, nandBytes); nandsimIndication->wait(); // write a pattern into the scratch memory and flush const char *needle_text = "ababab"; const char *haystack_text = "acabcabacababacababababababcacabcabacababacabababc"; int needle_len = strlen(needle_text); int haystack_len = strlen(haystack_text); strncpy(needle, needle_text, needle_len); strncpy(haystack, haystack_text, haystack_len); compute_MP_next(needle, mpNext, needle_len); portalDCacheFlushInval(needleAlloc, numBytes, needle); portalDCacheFlushInval(mpNextAlloc, numBytes, mpNext); portalDCacheFlushInval(haystackAlloc, numBytes, haystack); fprintf(stderr, "Main::flush and invalidate complete\n"); // write the contents of haystack into "flash" memory nandsimRequest->startWrite(ref_haystackAlloc, 0, 0, numBytes, 16); nandsimIndication->wait(); // this is a temporary hack. We are inlining the pertinant lines from DmaManager_reference // for this to work, NANDSIMHACK must be defined. What this does is send an SGList of the size // haystackAlloc to strstrDMA starting at offset 0 in the nandsim backing store. int id = nandsimDma->priv.handle++; int ref_haystackInNandMemory = send_fd_to_portal(nandsimDma->priv.device, haystackAlloc, id, global_pa_fd); sem_wait(&(nandsimDma->priv.confSem)); fprintf(stderr, "about to setup device %d %d\n", ref_needleAlloc, ref_mpNextAlloc); strstrRequest->setup(ref_needleAlloc, ref_mpNextAlloc, needle_len); strstrIndication->wait(); fprintf(stderr, "about to invoke search %d\n", ref_haystackInNandMemory); strstrRequest->search(ref_haystackInNandMemory, haystack_len, 1); strstrIndication->wait(); } <commit_msg>first try at userspace sglist<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * 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 <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include "DmaConfigProxy.h" #include "GeneratedTypes.h" #include "NandSimIndicationWrapper.h" #include "NandSimRequestProxy.h" #include "StrstrIndicationWrapper.h" #include "StrstrRequestProxy.h" static int trace_memory = 1; extern "C" { #include "sys/ioctl.h" #include "portalmem.h" #include "sock_utils.h" #include "dmaManager.h" #include "userReference.h" } size_t numBytes = 1 << 12; #ifndef BOARD_bluesim size_t nandBytes = 1 << 24; #else size_t nandBytes = 1 << 14; #endif class NandSimIndication : public NandSimIndicationWrapper { public: unsigned int rDataCnt; virtual void readDone(uint32_t v){ fprintf(stderr, "NandSim::readDone v=%x\n", v); sem_post(&sem); } virtual void writeDone(uint32_t v){ fprintf(stderr, "NandSim::writeDone v=%x\n", v); sem_post(&sem); } virtual void eraseDone(uint32_t v){ fprintf(stderr, "NandSim::eraseDone v=%x\n", v); sem_post(&sem); } virtual void configureNandDone(){ fprintf(stderr, "NandSim::configureNandDone\n"); sem_post(&sem); } NandSimIndication(int id) : NandSimIndicationWrapper(id) { sem_init(&sem, 0, 0); } void wait() { fprintf(stderr, "NandSim::wait for semaphore\n"); sem_wait(&sem); } private: sem_t sem; }; class StrstrIndication : public StrstrIndicationWrapper { public: StrstrIndication(unsigned int id) : StrstrIndicationWrapper(id){ sem_init(&sem, 0, 0); match_cnt = 0; }; virtual void setupComplete() { sem_post(&sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); if (v == -1) sem_post(&sem); else match_cnt++; } void wait() { fprintf(stderr, "Strstr::wait for semaphore\n"); sem_wait(&sem); } private: sem_t sem; int match_cnt; }; int main(int argc, const char **argv) { unsigned int srcGen = 0; NandSimRequestProxy *nandsimRequest = 0; DmaConfigProxy *dmaConfig = 0; NandSimIndication *nandsimIndication = 0; DmaIndication *dmaIndication = 0; StrstrRequestProxy *strstrRequest = 0; DmaConfigProxy *nandsimDmaConfig = 0; StrstrIndication *strstrIndication = 0; DmaIndication *nandsimDmaIndication = 0; fprintf(stderr, "Main::%s %s\n", __DATE__, __TIME__); nandsimRequest = new NandSimRequestProxy(IfcNames_NandSimRequest); dmaConfig = new DmaConfigProxy(IfcNames_DmaConfig); DmaManager *dma = new DmaManager(dmaConfig); nandsimIndication = new NandSimIndication(IfcNames_NandSimIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); strstrRequest = new StrstrRequestProxy(IfcNames_StrstrRequest); nandsimDmaConfig = new DmaConfigProxy(IfcNames_NandsimDmaConfig); strstrIndication = new StrstrIndication(IfcNames_StrstrIndication); DmaManager *nandsimDma = new DmaManager(nandsimDmaConfig); nandsimDmaIndication = new DmaIndication(nandsimDma,IfcNames_NandsimDmaIndication); portalExec_start(); fprintf(stderr, "Main::allocating memory...\n"); // allocate memory for strstr data int haystackAlloc = portalAlloc(numBytes); int needleAlloc = portalAlloc(numBytes); int mpNextAlloc = portalAlloc(numBytes); printf("[%s:%d]\n", __FUNCTION__, __LINE__); int ref_haystackAlloc = dma->reference(haystackAlloc); printf("[%s:%d]\n", __FUNCTION__, __LINE__); int ref_needleAlloc = dma->reference(needleAlloc); int ref_mpNextAlloc = dma->reference(mpNextAlloc); char *needle = (char *)portalMmap(needleAlloc, numBytes); char *haystack = (char *)portalMmap(haystackAlloc, numBytes); int *mpNext = (int *)portalMmap(mpNextAlloc, numBytes); // allocate memory buffer for nandsim to use as backing store int nandBacking = portalAlloc(nandBytes); int ref_nandBacking = dma->reference(nandBacking); // give the nandsim a pointer to its backing store nandsimRequest->configureNand(ref_nandBacking, nandBytes); nandsimIndication->wait(); // write a pattern into the scratch memory and flush const char *needle_text = "ababab"; const char *haystack_text = "acabcabacababacababababababcacabcabacababacabababc"; int needle_len = strlen(needle_text); int haystack_len = strlen(haystack_text); strncpy(needle, needle_text, needle_len); strncpy(haystack, haystack_text, haystack_len); compute_MP_next(needle, mpNext, needle_len); portalDCacheFlushInval(needleAlloc, numBytes, needle); portalDCacheFlushInval(mpNextAlloc, numBytes, mpNext); portalDCacheFlushInval(haystackAlloc, numBytes, haystack); fprintf(stderr, "Main::flush and invalidate complete\n"); // write the contents of haystack into "flash" memory nandsimRequest->startWrite(ref_haystackAlloc, 0, 0, numBytes, 16); nandsimIndication->wait(); // this is a temporary hack. We are inlining the pertinant lines from DmaManager_reference // for this to work, NANDSIMHACK must be defined. What this does is send an SGList of the size // haystackAlloc to strstrDMA starting at offset 0 in the nandsim backing store. int id = nandsimDma->priv.handle++; RegionRef region[] = {{0, 0x100000}, {0x100000, 0x100000}}; printf("[%s:%d]\n", __FUNCTION__, __LINE__); int ref_haystackInNandMemory = send_reference_to_portal(nandsimDma->priv.device, sizeof(region)/sizeof(region[0]), region, id); sem_wait(&(nandsimDma->priv.confSem)); fprintf(stderr, "about to setup device %d %d\n", ref_needleAlloc, ref_mpNextAlloc); strstrRequest->setup(ref_needleAlloc, ref_mpNextAlloc, needle_len); strstrIndication->wait(); fprintf(stderr, "about to invoke search %d\n", ref_haystackInNandMemory); strstrRequest->search(ref_haystackInNandMemory, haystack_len, 1); strstrIndication->wait(); } <|endoftext|>
<commit_before>#include "TH1F.h" #include "TH2F.h" #include "TGraphAsymmErrors.h" #include "TFile.h" #include "TStyle.h" #include "TLegend.h" #include "TLatex.h" #include "TProfile.h" #include "TPaveText.h" #include "THStack.h" #include "TCanvas.h" #include <string> #include <iostream> #include <sstream> #include "TColor.h" #include "../plotStyles/AtlasStyle.C" #include "../plotStyles/AtlasUtils.h" #include "../plotStyles/AtlasUtils.C" #include "../plotStyles/TriggerPerfPaperConsts.h" #include "../plotStyles/tdrstyle.C" //#include "../FakeRate/EstimateBackground.C" using namespace std; int stack_upgrade_WH() { //gROOT->ProcessLine(".L ./tdrstyle.C"); //setTDRStyle(); gStyle->SetPadColor(0); gStyle->SetCanvasColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(0); gStyle->SetPadBorderMode(0); gStyle->SetStatColor(0); gStyle->SetOptStat(0000000); gStyle->SetOptFit(0111); gStyle->SetOptTitle(0); gStyle->SetTitleStyle(0); gStyle->SetTitleFillColor(0); gStyle->SetPalette(1); const int nFiles = 4; //Int_t r = 4; //DoubleEle + WZ //TString fileNames[nFiles] = {"DoubleEle","TT_42X_TruePU","WZ_42X_TruePU","ZZ_42X_TruePU","DY_42X_TruePU","Htt120_42X_TruePU","Hww120_42X_TruePU"}; //DoubleEle + WZjets TString fileNames[nFiles] = {"2012", "WZ", "WZJets", "ZZTo4L" }; TString inputDir = "/home/jpavel/analysis/CMS/histograms/WH/20131014/Summary/"; TString outputDir = "/home/jpavel/analysis/CMS/Plots/Stack/WH/20131014/WZJets"; gROOT->ProcessLine(".!mkdir -p "+outputDir+"/png"); gROOT->ProcessLine(".!mkdir -p "+outputDir+"/pdf"); TFile * f[nFiles]; std::stringstream indexes; for(int iFile = 0; iFile < nFiles; iFile++) { indexes.str(""); indexes << inputDir << fileNames[iFile]; std::string input_file=indexes.str()+".root"; f[iFile] = TFile::Open(input_file.c_str()); if(!f[iFile]) { std::cerr << "Error: file " << input_file << " could not be opened." << std::endl; return 1; } else std::cout << "File " << input_file << " succesfully opened!" << std::endl; } const int nHist1 = 3; //const int nHist1 = 44; TString histNames1[nHist1] = {"h_HvisMass_after130LT", "h_HvisMass_below130LT","h_cut_flow"};// ,"h_H_svMass_type_1","h_H_svMass_type_2","h_H_svMass_type_3","h_H_svMass_type_4","h_H_svMass_type_5","h_H_svMass_type_6","h_H_svMass_type_7","h_H_svMass_type_8"}; //TString histBGNames1[nHist1] = {"h_FR_svMass","h_H_FR_svMass_type_1","h_H_FR_svMass_type_2","h_H_FR_svMass_type_3","h_H_FR_svMass_type_4","h_H_FR_svMass_type_5","h_H_FR_svMass_type_6","h_H_FR_svMass_type_7","h_H_FR_svMass_type_8"}; TString histTitles[nHist1] = {"M^{vis}_{#tau_{#mu}#tau}[GeV]", "M^{vis}_{#tau_{#mu}#tau}[GeV]", "Cut name" };//,"M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]"}; TString PaveText[nHist1] = {"CMS preliminary 2012 LT > 130 GeV", "CMS preliminary 2012 LT < 130 GeV", "CMS preliminary" };//,"MMMT","MMME","MMET","EETT","EEMT","EEME","EEET","EETT"}; TH1F * h_1d[nHist1][nFiles]; TH1F * h_1BG[nHist1]; // TH1F * signal[nHist1]; Double_t weights[nFiles]; Double_t xsection[nFiles]={1.0, 1.057, 1.057, 0.130};//, 0.208, 0.01203, 0.0048}; // pb Double_t events[nFiles]={1.0, 2979624, 2017979, 4989540};//, 210160, 400973, 548760}; // pb Color_t colors[nFiles]={kBlack,kRed,kRed,kBlue}; const double total_lumi = 19711.2250; //// pb-1 for(int iFile = 0; iFile < nFiles; iFile++) { double lumi = events[iFile]/xsection[iFile]; if(iFile > 0) weights[iFile]=total_lumi/lumi; else weights[iFile] = 1.0; std::cout << weights[iFile] << std::endl; } for(int iFile = 0; iFile < nFiles; iFile++) { for(int iHist = 0; iHist < nHist1; iHist++) { h_1d[iHist][iFile] = (TH1F*)f[iFile]->Get(histNames1[iHist]); h_1d[iHist][iFile]->Scale(weights[iFile]); if(iHist < 2) h_1d[iHist][iFile]->Rebin(10); } } // std::vector<double>* BGcounts = EstimateBackground(); //getting histograms for the background //~ for(int iBG=0; iBG < BGcounts->size(); iBG++) //~ { //~ std::cout << BGcounts->at(iBG) << std::endl; //~ //~ } //~ //~ for(int iHist=0; iHist < nHist1; iHist++) //~ { //~ h_1BG[iHist]=(TH1F*)f[0]->Get(histBGNames1[iHist]); //~ if(iHist>0) h_1BG[iHist]->Scale(BGcounts->at(iHist-1)/h_1BG[iHist]->Integral()); //~ h_1BG[iHist]->Rebin(20); //~ if(iHist==1) h_1BG[0]=(TH1F*)h_1BG[iHist]->Clone(); //~ if(iHist>1) h_1BG[0]->Add(h_1BG[iHist]); //~ //~ } h_1d[0][0]->Draw(); //~ //~ int ZZ_Color = TColor::GetColor("#99ff99"); //~ int WZ_Color = TColor::GetColor("#660099"); //~ int TTbar_Color = TColor::GetColor("#cc66cc"); //~ int Zjet_Color = TColor::GetColor("#32c3ff"); //~ TCanvas *c1 = new TCanvas("c1","",5,30,650,600); //gPad->SetLogy(); c1->SetGrid(0,0); c1->SetFillStyle(4000); c1->SetFillColor(10); c1->SetTicky(); c1->SetObjectStat(0); c1->SetLogy(0); //~ for(int iHist = 0; iHist < nHist1; iHist++){ //~ signal[iHist] = (TH1F*)h_1d[iHist][5]->Clone();} for(int iHist = 0; iHist < nHist1; iHist++) { THStack *hs = new THStack("hs","Stacked MC histograms"); for(int iFile=1; iFile < nFiles; iFile++) { h_1d[iHist][iFile]->SetLineWidth(0); //h_1d[iHist][iFile]->SetFillStyle(3244); h_1d[iHist][iFile]->SetFillColor(colors[iFile]); //~ if(iFile == 1){ } //~ else if(iFile == 2){ h_1d[iHist][iFile]->SetFillColor(WZ_Color); } //~ else if(iFile == 3){ h_1d[iHist][iFile]->SetFillColor(TTbar_Color); } //~ else if(iFile == 4){ h_1d[iHist][iFile]->SetFillColor(Zjet_Color); } //~ else if(iFile == 5){ //~ signal[iHist]->Add(h_1d[iHist][iFile+1]); //~ signal[iHist]->SetLineColor(kRed); //~ signal[iHist]->SetLineWidth(2.0); //~ //~ } //if(iFile < 5) if(iFile!=1) hs->Add(h_1d[iHist][iFile],"hist"); } // hs->Add(h_1BG[iHist],"hist"); //~ //~ //hs->Add(signal[iHist],"hist"); //~ h_1d[iHist][0]->SetMarkerStyle(21); h_1d[iHist][0]->SetMarkerSize(0.7); //~ TLegend* leg = new TLegend(0.65,0.60,0.88,0.88,NULL,"brNDC"); leg->SetFillColor(0); leg->SetTextSize(0.035); leg->SetBorderSize(0); //~ leg->AddEntry(h_1d[iHist][0],"data 2012","p"); leg->AddEntry(h_1d[iHist][1],"WZ","f"); // leg->AddEntry(h_1d[iHist][2],"WZ","f"); leg->AddEntry(h_1d[iHist][3],"ZZTo4L","f"); //~ leg->AddEntry(h_1d[iHist][4],"t#bar{t}Z","f"); //~ leg->AddEntry(h_1d[iHist][5],"ggZZ2L2L","f"); //~ leg->AddEntry(h_1d[iHist][6],"ggZZ4L","f"); //~ leg->AddEntry(h_1BG[iHist],"reducible","f"); //~ //~ leg->AddEntry(h_1d[iHist][4],"Z+jets","f"); //~ leg->AddEntry(signal[iHist],"ZH(125)","f"); //~ TString lumist="19.7 fb^{-1}"; TPaveText *ll = new TPaveText(0.15, 0.95, 0.95, 0.99, "NDC"); ll->SetTextSize(0.03); ll->SetTextFont(62); ll->SetFillColor(0); ll->SetBorderSize(0); ll->SetMargin(0.01); ll->SetTextAlign(12); // align left TString text = PaveText[iHist]; ll->AddText(0.01,0.6,text); text = "#sqrt{s} = 8 TeV L = "; text = text + lumist; // ll->SetTextAlign(32); // align right ll->AddText(0.6, 0.5, text); //~ /*double max_dy = h_1d[iHist][4]->GetMaximum(); //~ double max_data = h_1d[iHist][0]->GetMaximum(); //~ double max = 0; //~ //~ if (max_dy > max_data){ //~ max = max_dy;} //~ else { //~ max = max_data;} //~ if (max != 0) hs->SetMaximum(max); //~ //~ cout << "max data: " << max_data << endl; //~ cout << "max dy: " << max_dy << endl; //~ */ //~ h_1d[iHist][0]->Draw("PE01"); //~ double max = h_1d[iHist][0]->GetMaximum(); //~ h_1d[iHist][0]->GetYaxis()->SetRangeUser(1e-2,200*max); //~ // if(iHist > 0 && iHist < 4) h_1d[iHist][0]->GetXaxis()->SetRangeUser(0,150); //~ h_1d[iHist][0]->GetXaxis()->SetTitle(histTitles[iHist]); hs->Draw("same"); //~ // signal[iHist]->Scale(10.); //~ signal[iHist]->Draw("histsame"); h_1d[iHist][0]->Draw("samePE01"); //~ //~ leg->Draw("same"); ll->Draw("same"); if(iHist==2) { c1->SetLogy(); h_1d[iHist][0]->GetYaxis()->SetRangeUser(5,5e8); } gPad->RedrawAxis(); //~ //~ c1->SetLogy(); c1->Print(outputDir+"/png/"+histNames1[iHist]+".png"); c1->Print(outputDir+"/pdf/"+histNames1[iHist]+".pdf"); c1->SetLogy(0); //~ c1->Print("Moriond/Mu_"+histNames1[iHist]+"_all.eps"); //~ c1->SetLogy(0); //~ h_1d[iHist][0]->GetYaxis()->SetRangeUser(0,1.5*max); //~ //~ c1->Print("Moriond/Mu_"+histNames1[iHist]+"_all_normal.png"); //~ c1->Print("Moriond/Mu_"+histNames1[iHist]+"_all_normal.eps"); //~ //~ //~ //~ leg->Clear(); //~ hs->Clear(); } return 0; } <commit_msg>cut flow updated<commit_after>#include "TH1F.h" #include "TH2F.h" #include "TGraphAsymmErrors.h" #include "TFile.h" #include "TStyle.h" #include "TLegend.h" #include "TLatex.h" #include "TProfile.h" #include "TPaveText.h" #include "THStack.h" #include "TCanvas.h" #include <string> #include <iostream> #include <sstream> #include "TColor.h" #include "../plotStyles/AtlasStyle.C" #include "../plotStyles/AtlasUtils.h" #include "../plotStyles/AtlasUtils.C" #include "../plotStyles/TriggerPerfPaperConsts.h" #include "../plotStyles/tdrstyle.C" //#include "../FakeRate/EstimateBackground.C" using namespace std; int stack_upgrade_WH() { //gROOT->ProcessLine(".L ./tdrstyle.C"); //setTDRStyle(); gStyle->SetPadColor(0); gStyle->SetCanvasColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(0); gStyle->SetPadBorderMode(0); gStyle->SetStatColor(0); gStyle->SetOptStat(0000000); gStyle->SetOptFit(0111); gStyle->SetOptTitle(0); gStyle->SetTitleStyle(0); gStyle->SetTitleFillColor(0); gStyle->SetPalette(1); const int nFiles = 4; //Int_t r = 4; //DoubleEle + WZ //TString fileNames[nFiles] = {"DoubleEle","TT_42X_TruePU","WZ_42X_TruePU","ZZ_42X_TruePU","DY_42X_TruePU","Htt120_42X_TruePU","Hww120_42X_TruePU"}; //DoubleEle + WZjets TString fileNames[nFiles] = {"2012", "WZ", "WZJets", "ZZTo4L" }; TString inputDir = "/home/jpavel/analysis/CMS/histograms/WH/20131014/Summary/"; TString outputDir = "/home/jpavel/analysis/CMS/Plots/Stack/WH/20131014/WZJets"; gROOT->ProcessLine(".!mkdir -p "+outputDir+"/png"); gROOT->ProcessLine(".!mkdir -p "+outputDir+"/pdf"); TFile * f[nFiles]; std::stringstream indexes; for(int iFile = 0; iFile < nFiles; iFile++) { indexes.str(""); indexes << inputDir << fileNames[iFile]; std::string input_file=indexes.str()+".root"; f[iFile] = TFile::Open(input_file.c_str()); if(!f[iFile]) { std::cerr << "Error: file " << input_file << " could not be opened." << std::endl; return 1; } else std::cout << "File " << input_file << " succesfully opened!" << std::endl; } const int nHist1 = 3; //const int nHist1 = 44; TString histNames1[nHist1] = {"h_HvisMass_above130LT", "h_HvisMass_below130LT","h_cut_flow"};// ,"h_H_svMass_type_1","h_H_svMass_type_2","h_H_svMass_type_3","h_H_svMass_type_4","h_H_svMass_type_5","h_H_svMass_type_6","h_H_svMass_type_7","h_H_svMass_type_8"}; //TString histBGNames1[nHist1] = {"h_FR_svMass","h_H_FR_svMass_type_1","h_H_FR_svMass_type_2","h_H_FR_svMass_type_3","h_H_FR_svMass_type_4","h_H_FR_svMass_type_5","h_H_FR_svMass_type_6","h_H_FR_svMass_type_7","h_H_FR_svMass_type_8"}; TString histTitles[nHist1] = {"M^{vis}_{#tau_{#mu}#tau}[GeV]", "M^{vis}_{#tau_{#mu}#tau}[GeV]", "Cut name" };//,"M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]","M_{#tau#tau}[GeV]"}; TString PaveText[nHist1] = {"CMS preliminary 2012 LT > 130 GeV", "CMS preliminary 2012 LT < 130 GeV", "CMS preliminary" };//,"MMMT","MMME","MMET","EETT","EEMT","EEME","EEET","EETT"}; TH1F * h_1d[nHist1][nFiles]; TH1F * h_1BG[nHist1]; // TH1F * signal[nHist1]; Double_t weights[nFiles]; Double_t xsection[nFiles]={1.0, 1.057, 1.057, 0.130};//, 0.208, 0.01203, 0.0048}; // pb Double_t events[nFiles]={1.0, 2979624, 2017979, 4989540};//, 210160, 400973, 548760}; // pb Color_t colors[nFiles]={kBlack,kRed,kRed,kBlue}; const double total_lumi = 19711.2250; //// pb-1 for(int iFile = 0; iFile < nFiles; iFile++) { double lumi = events[iFile]/xsection[iFile]; if(iFile > 0) weights[iFile]=total_lumi/lumi; else weights[iFile] = 1.0; std::cout << weights[iFile] << std::endl; } for(int iFile = 0; iFile < nFiles; iFile++) { for(int iHist = 0; iHist < nHist1; iHist++) { h_1d[iHist][iFile] = (TH1F*)f[iFile]->Get(histNames1[iHist]); h_1d[iHist][iFile]->Scale(weights[iFile]); if(iHist < 2) h_1d[iHist][iFile]->Rebin(10); } } // std::vector<double>* BGcounts = EstimateBackground(); //getting histograms for the background //~ for(int iBG=0; iBG < BGcounts->size(); iBG++) //~ { //~ std::cout << BGcounts->at(iBG) << std::endl; //~ //~ } //~ //~ for(int iHist=0; iHist < nHist1; iHist++) //~ { //~ h_1BG[iHist]=(TH1F*)f[0]->Get(histBGNames1[iHist]); //~ if(iHist>0) h_1BG[iHist]->Scale(BGcounts->at(iHist-1)/h_1BG[iHist]->Integral()); //~ h_1BG[iHist]->Rebin(20); //~ if(iHist==1) h_1BG[0]=(TH1F*)h_1BG[iHist]->Clone(); //~ if(iHist>1) h_1BG[0]->Add(h_1BG[iHist]); //~ //~ } h_1d[0][0]->Draw(); //~ //~ int ZZ_Color = TColor::GetColor("#99ff99"); //~ int WZ_Color = TColor::GetColor("#660099"); //~ int TTbar_Color = TColor::GetColor("#cc66cc"); //~ int Zjet_Color = TColor::GetColor("#32c3ff"); //~ TCanvas *c1 = new TCanvas("c1","",5,30,650,600); //gPad->SetLogy(); c1->SetGrid(0,0); c1->SetFillStyle(4000); c1->SetFillColor(10); c1->SetTicky(); c1->SetObjectStat(0); c1->SetLogy(0); //~ for(int iHist = 0; iHist < nHist1; iHist++){ //~ signal[iHist] = (TH1F*)h_1d[iHist][5]->Clone();} for(int iHist = 0; iHist < nHist1; iHist++) { THStack *hs = new THStack("hs","Stacked MC histograms"); for(int iFile=1; iFile < nFiles; iFile++) { h_1d[iHist][iFile]->SetLineWidth(0); //h_1d[iHist][iFile]->SetFillStyle(3244); h_1d[iHist][iFile]->SetFillColor(colors[iFile]); //~ if(iFile == 1){ } //~ else if(iFile == 2){ h_1d[iHist][iFile]->SetFillColor(WZ_Color); } //~ else if(iFile == 3){ h_1d[iHist][iFile]->SetFillColor(TTbar_Color); } //~ else if(iFile == 4){ h_1d[iHist][iFile]->SetFillColor(Zjet_Color); } //~ else if(iFile == 5){ //~ signal[iHist]->Add(h_1d[iHist][iFile+1]); //~ signal[iHist]->SetLineColor(kRed); //~ signal[iHist]->SetLineWidth(2.0); //~ //~ } //if(iFile < 5) if(iFile!=1) hs->Add(h_1d[iHist][iFile],"hist"); } // hs->Add(h_1BG[iHist],"hist"); //~ //~ //hs->Add(signal[iHist],"hist"); //~ h_1d[iHist][0]->SetMarkerStyle(21); h_1d[iHist][0]->SetMarkerSize(0.7); //~ TLegend* leg = new TLegend(0.65,0.60,0.88,0.88,NULL,"brNDC"); leg->SetFillColor(0); leg->SetTextSize(0.035); leg->SetBorderSize(0); //~ leg->AddEntry(h_1d[iHist][0],"data 2012","p"); leg->AddEntry(h_1d[iHist][1],"WZ","f"); // leg->AddEntry(h_1d[iHist][2],"WZ","f"); leg->AddEntry(h_1d[iHist][3],"ZZTo4L","f"); //~ leg->AddEntry(h_1d[iHist][4],"t#bar{t}Z","f"); //~ leg->AddEntry(h_1d[iHist][5],"ggZZ2L2L","f"); //~ leg->AddEntry(h_1d[iHist][6],"ggZZ4L","f"); //~ leg->AddEntry(h_1BG[iHist],"reducible","f"); //~ //~ leg->AddEntry(h_1d[iHist][4],"Z+jets","f"); //~ leg->AddEntry(signal[iHist],"ZH(125)","f"); //~ TString lumist="19.7 fb^{-1}"; TPaveText *ll = new TPaveText(0.15, 0.95, 0.95, 0.99, "NDC"); ll->SetTextSize(0.03); ll->SetTextFont(62); ll->SetFillColor(0); ll->SetBorderSize(0); ll->SetMargin(0.01); ll->SetTextAlign(12); // align left TString text = PaveText[iHist]; ll->AddText(0.01,0.6,text); text = "#sqrt{s} = 8 TeV L = "; text = text + lumist; // ll->SetTextAlign(32); // align right ll->AddText(0.6, 0.5, text); //~ /*double max_dy = h_1d[iHist][4]->GetMaximum(); //~ double max_data = h_1d[iHist][0]->GetMaximum(); //~ double max = 0; //~ //~ if (max_dy > max_data){ //~ max = max_dy;} //~ else { //~ max = max_data;} //~ if (max != 0) hs->SetMaximum(max); //~ //~ cout << "max data: " << max_data << endl; //~ cout << "max dy: " << max_dy << endl; //~ */ //~ h_1d[iHist][0]->Draw("PE01"); //~ double max = h_1d[iHist][0]->GetMaximum(); //~ h_1d[iHist][0]->GetYaxis()->SetRangeUser(1e-2,200*max); //~ // if(iHist > 0 && iHist < 4) h_1d[iHist][0]->GetXaxis()->SetRangeUser(0,150); //~ h_1d[iHist][0]->GetXaxis()->SetTitle(histTitles[iHist]); hs->Draw("same"); //~ // signal[iHist]->Scale(10.); //~ signal[iHist]->Draw("histsame"); h_1d[iHist][0]->Draw("samePE01"); //~ //~ leg->Draw("same"); ll->Draw("same"); if(iHist==2) { c1->SetLogy(); h_1d[iHist][0]->GetYaxis()->SetRangeUser(5,5e8); } gPad->RedrawAxis(); //~ //~ c1->SetLogy(); c1->Print(outputDir+"/png/"+histNames1[iHist]+".png"); c1->Print(outputDir+"/pdf/"+histNames1[iHist]+".pdf"); c1->SetLogy(0); //~ c1->Print("Moriond/Mu_"+histNames1[iHist]+"_all.eps"); //~ c1->SetLogy(0); //~ h_1d[iHist][0]->GetYaxis()->SetRangeUser(0,1.5*max); //~ //~ c1->Print("Moriond/Mu_"+histNames1[iHist]+"_all_normal.png"); //~ c1->Print("Moriond/Mu_"+histNames1[iHist]+"_all_normal.eps"); //~ //~ //~ //~ leg->Clear(); //~ hs->Clear(); } return 0; } <|endoftext|>
<commit_before>#include <brickred/base_logger.h> #include <cstdio> namespace brickred { BRICKRED_PRECREATED_SINGLETON_IMPL(BaseLogger) static void defaultLogFunc(int level, const char *format, va_list args) { if (level < BaseLogger::LogLevel::MIN || level >= BaseLogger::LogLevel::MAX) { return; } static const char *log_level_string[] = { "DEBUG", "INFO", "WARNING", "ERROR", }; ::fprintf(stderr, "[%s] ", log_level_string[level]); ::vfprintf(stderr, format, args); ::fprintf(stderr, "\n"); } BaseLogger::BaseLogger() : log_func_(defaultLogFunc) { } BaseLogger::~BaseLogger() { } void BaseLogger::setLogFunc(LogFunc log_func) { log_func_ = log_func; } void BaseLogger::log(int level, const char *format, ...) { #ifdef BRICKRED_BUILD_ENABLE_BASE_LOG va_list args; va_start(args, format); log_func_(level, format, args); va_end(args); #endif } } // namespace brickred <commit_msg>work sync<commit_after>#include <brickred/base_logger.h> #include <cstdio> namespace brickred { BRICKRED_PRECREATED_SINGLETON_IMPL(BaseLogger) static void defaultLogFunc(int level, const char *format, va_list args) { if (level < BaseLogger::LogLevel::MIN || level >= BaseLogger::LogLevel::MAX) { return; } static const char *log_level_string[] = { "DEBUG", "WARNING", "ERROR", }; ::fprintf(stderr, "[%s] ", log_level_string[level]); ::vfprintf(stderr, format, args); ::fprintf(stderr, "\n"); } BaseLogger::BaseLogger() : log_func_(defaultLogFunc) { } BaseLogger::~BaseLogger() { } void BaseLogger::setLogFunc(LogFunc log_func) { log_func_ = log_func; } void BaseLogger::log(int level, const char *format, ...) { #ifdef BRICKRED_BUILD_ENABLE_BASE_LOG va_list args; va_start(args, format); log_func_(level, format, args); va_end(args); #endif } } // namespace brickred <|endoftext|>
<commit_before>//===--- Tools.cpp - Tools Implementations --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "Tools.h" #include "ToolChains.h" #include "swift/Basic/Dwarf.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/Range.h" #include "swift/Driver/Driver.h" #include "swift/Driver/Job.h" #include "swift/Driver/Options.h" #include "swift/Frontend/Frontend.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/Path.h" using namespace swift; using namespace swift::driver; using namespace swift::driver::tools; using namespace llvm::opt; StringRef swift::getPlatformNameForTriple(const llvm::Triple &triple) { if (triple.isiOS()) { llvm::Triple::ArchType arch = triple.getArch(); if (arch == llvm::Triple::ArchType::x86 || arch == llvm::Triple::ArchType::x86_64) return "iphonesimulator"; return "iphoneos"; } if (triple.isMacOSX()) return "macosx"; return ""; } /// Swift Tool namespace { static void addInputsOfType(ArgStringList &Arguments, const Job *J, types::ID InputType) { if (const Command *Cmd = dyn_cast<Command>(J)) { auto &output = Cmd->getOutput().getAnyOutputForType(InputType); if (!output.empty()) Arguments.push_back(output.c_str()); } else if (const JobList *JL = dyn_cast<JobList>(J)) { for (const Job *J : *JL) addInputsOfType(Arguments, J, InputType); } else { llvm_unreachable("Unable to add input arguments for unknown Job class"); } } static void addPrimaryInputsOfType(ArgStringList &Arguments, const Job *J, types::ID InputType) { if (const Command *Cmd = dyn_cast<Command>(J)) { auto &outputInfo = Cmd->getOutput(); if (outputInfo.getPrimaryOutputType() == InputType) Arguments.push_back(outputInfo.getPrimaryOutputFilename().c_str()); } else if (const JobList *JL = dyn_cast<JobList>(J)) { for (const Job *J : *JL) addPrimaryInputsOfType(Arguments, J, InputType); } else { llvm_unreachable("Unable to add input arguments for unknown Job class"); } } } Job *Swift::constructJob(const JobAction &JA, std::unique_ptr<JobList> Inputs, std::unique_ptr<CommandOutput> Output, const ActionList &InputActions, const ArgList &Args, const OutputInfo &OI) const { ArgStringList Arguments; const char *Exec = getToolChain().getDriver().getSwiftProgramPath().c_str(); // Invoke ourselves in -frontend mode. Arguments.push_back("-frontend"); Arguments.push_back("-target"); std::string TripleStr = getToolChain().getTripleString(); Arguments.push_back(Args.MakeArgString(TripleStr)); // Determine the frontend mode option. const char *FrontendModeOption = nullptr; switch (OI.CompilerMode) { case OutputInfo::Mode::StandardCompile: case OutputInfo::Mode::SingleCompile: { switch (Output->getPrimaryOutputType()) { case types::TY_Object: FrontendModeOption = "-c"; break; case types::TY_RawSIL: FrontendModeOption = "-emit-silgen"; break; case types::TY_SIL: FrontendModeOption = "-emit-sil"; break; case types::TY_LLVM_IR: FrontendModeOption = "-emit-ir"; break; case types::TY_LLVM_BC: FrontendModeOption = "-emit-bc"; break; case types::TY_SwiftModuleFile: // Since this is our primary output, we need to specify the option here. FrontendModeOption = "-emit-module"; break; case types::TY_Nothing: // We were told to output nothing, so get the last mode option and use that. if (const Arg *A = Args.getLastArg(options::OPT_modes_Group)) FrontendModeOption = A->getSpelling().data(); else llvm_unreachable("We were told to perform a standard compile, " "but no mode option was passed to the driver."); break; default: llvm_unreachable("Invalid output type"); } break; } case OutputInfo::Mode::Immediate: FrontendModeOption = "-i"; break; case OutputInfo::Mode::REPL: FrontendModeOption = "-repl"; break; } assert(FrontendModeOption != nullptr && "No frontend mode option specified!"); Arguments.push_back(FrontendModeOption); assert(Inputs->empty() && "The Swift frontend does not expect to be fed any input Jobs!"); // Add input arguments. switch (OI.CompilerMode) { case OutputInfo::Mode::StandardCompile: { assert(InputActions.size() == 1 && "The Swift frontend expects exactly one input (the primary file)!"); const InputAction *IA = dyn_cast<InputAction>(InputActions[0]); assert(IA && "Only InputActions can be passed as inputs!"); const Arg &PrimaryInputArg = IA->getInputArg(); bool FoundPrimaryInput = false; for (const Arg *A : make_range(Args.filtered_begin(options::OPT_INPUT), Args.filtered_end())) { Option Opt = A->getOption(); if (A->getOption().matches(options::OPT_INPUT)) { // See if this input should be passed with -primary-file. if (!FoundPrimaryInput && PrimaryInputArg.getIndex() == A->getIndex()) { Arguments.push_back("-primary-file"); FoundPrimaryInput = true; } Arguments.push_back(A->getValue()); } } break; } case OutputInfo::Mode::SingleCompile: case OutputInfo::Mode::Immediate: { for (const Action *A : InputActions) { const InputAction *IA = dyn_cast<InputAction>(A); assert(IA && "Only InputActions can be passed as inputs!"); IA->getInputArg().render(Args, Arguments); } break; } case OutputInfo::Mode::REPL: { assert(InputActions.empty() && "REPL mode accepts no inputs!"); break; } } Arguments.push_back("-module-name"); Arguments.push_back(Args.MakeArgString(OI.ModuleName)); Args.AddLastArg(Arguments, options::OPT_g); // Pass the optimization level down to the frontend. Args.AddLastArg(Arguments, options::OPT_O_Group); // Set the SDK for the frontend. if (!OI.SDKPath.empty()) { Arguments.push_back("-sdk"); Arguments.push_back(Args.MakeArgString(OI.SDKPath)); } // Pass through the values passed to -Xfrontend. Args.AddAllArgValues(Arguments, options::OPT_Xfrontend); Args.AddLastArg(Arguments, options::OPT_parse_as_library); Args.AddLastArg(Arguments, options::OPT_parse_sil); Args.AddLastArg(Arguments, options::OPT_parse_stdlib); const std::string &ModuleOutputPath = Output->getAdditionalOutputForType(types::ID::TY_SwiftModuleFile); if (!ModuleOutputPath.empty()) { Arguments.push_back("-emit-module"); Arguments.push_back("-emit-module-path"); Arguments.push_back(ModuleOutputPath.c_str()); } const std::string &SerializedDiagnosticsPath = Output->getAdditionalOutputForType(types::TY_SerializedDiagnostics); if (!SerializedDiagnosticsPath.empty()) { Arguments.push_back("-serialize-diagnostics"); Arguments.push_back("-serialize-diagnostics-path"); Arguments.push_back(SerializedDiagnosticsPath.c_str()); } // Add the output file argument if necessary. if (Output->getPrimaryOutputType() != types::TY_Nothing) { Arguments.push_back("-o"); Arguments.push_back(Output->getPrimaryOutputFilename().c_str()); } if (OI.CompilerMode == OutputInfo::Mode::Immediate) Args.AddLastArg(Arguments, options::OPT__DASH_DASH); return new Command(JA, *this, std::move(Inputs), std::move(Output), Exec, Arguments); } Job *MergeModule::constructJob(const JobAction &JA, std::unique_ptr<JobList> Inputs, std::unique_ptr<CommandOutput> Output, const ActionList &InputActions, const ArgList &Args, const OutputInfo &OI) const { ArgStringList Arguments; const char *Exec = getToolChain().getDriver().getSwiftProgramPath().c_str(); // Invoke ourself in -frontend mode. Arguments.push_back("-frontend"); // Tell all files to parse as library, which is necessary to load them as // serialized ASTs. Arguments.push_back("-parse-as-library"); Arguments.push_back("-module-name"); Arguments.push_back(Args.MakeArgString(OI.ModuleName)); // We just want to emit a module, so pass -emit-module without any other // mode options. Arguments.push_back("-emit-module"); assert(Output->getPrimaryOutputType() == types::TY_SwiftModuleFile && "The MergeModule tool only produces swiftmodule files!"); Arguments.push_back("-o"); Arguments.push_back(Args.MakeArgString(Output->getPrimaryOutputFilename())); size_t origLen = Arguments.size(); (void)origLen; addInputsOfType(Arguments, Inputs.get(), types::TY_SwiftModuleFile); assert(Arguments.size() - origLen == Inputs->size() && "every input to MergeModule must generate a swiftmodule"); return new Command(JA, *this, std::move(Inputs), std::move(Output), Exec, Arguments); } /// Darwin Tools llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Arch) { return llvm::StringSwitch<llvm::Triple::ArchType>(Arch) .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86) .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4", llvm::Triple::x86) .Case("x86_64", llvm::Triple::x86_64) .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm) .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm) .Cases("armv7s", "xscale", llvm::Triple::arm) .Default(llvm::Triple::UnknownArch); } void darwin::DarwinTool::anchor() {} void darwin::DarwinTool::AddDarwinArch(const ArgList &Args, ArgStringList &CmdArgs) const { StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args); CmdArgs.push_back("-arch"); CmdArgs.push_back(Args.MakeArgString(ArchName)); } Job *darwin::Linker::constructJob(const JobAction &JA, std::unique_ptr<JobList> Inputs, std::unique_ptr<CommandOutput> Output, const ActionList &InputActions, const ArgList &Args, const OutputInfo &OI) const { assert(Output->getPrimaryOutputType() == types::TY_Image && "Invalid linker output type."); ArgStringList Arguments; addPrimaryInputsOfType(Arguments, Inputs.get(), types::TY_Object); if (Args.hasArg(options::OPT_g)) { Arguments.push_back("-sectalign"); Arguments.push_back(MachOASTSegmentName); Arguments.push_back(MachOASTSectionName); Arguments.push_back("4"); Arguments.push_back("-sectcreate"); Arguments.push_back(MachOASTSegmentName); Arguments.push_back(MachOASTSectionName); size_t argCount = Arguments.size(); if (OI.CompilerMode == OutputInfo::Mode::SingleCompile) addInputsOfType(Arguments, Inputs.get(), types::TY_SwiftModuleFile); else addPrimaryInputsOfType(Arguments, Inputs.get(), types::TY_SwiftModuleFile); assert(argCount + 1 == Arguments.size() && "no swiftmodule found for -g"); (void)argCount; } Args.AddAllArgValues(Arguments, options::OPT_Xlinker); Args.AddAllArgs(Arguments, options::OPT_linker_option_Group); Args.AddAllArgs(Arguments, options::OPT_F); if (!OI.SDKPath.empty()) { Arguments.push_back("-syslibroot"); Arguments.push_back(Args.MakeArgString(OI.SDKPath)); } Arguments.push_back("-lSystem"); AddDarwinArch(Args, Arguments); const toolchains::Darwin &TC = getDarwinToolChain(); const Driver &D = TC.getDriver(); // Add the runtime library link path, which is platform-specific and found // relative to the compiler. // FIXME: Duplicated from CompilerInvocation, but in theory the runtime // library link path and the standard library module import path don't // need to be the same. llvm::SmallString<128> RuntimeLibPath(D.getSwiftProgramPath()); llvm::sys::path::remove_filename(RuntimeLibPath); // remove /swift llvm::sys::path::remove_filename(RuntimeLibPath); // remove /bin llvm::sys::path::append(RuntimeLibPath, "lib", "swift"); llvm::sys::path::append(RuntimeLibPath, getPlatformNameForTriple(TC.getTriple())); Arguments.push_back("-L"); Arguments.push_back(Args.MakeArgString(RuntimeLibPath)); // FIXME: We probably shouldn't be adding an rpath here unless we know ahead // of time the standard library won't be copied. Arguments.push_back("-rpath"); Arguments.push_back(Args.MakeArgString(RuntimeLibPath)); // FIXME: Properly handle deployment targets. assert(TC.getTriple().isiOS() || TC.getTriple().isMacOSX()); if (TC.getTriple().isiOS()) { Arguments.push_back("-iphoneos_version_min"); Arguments.push_back("7.0.0"); } else { Arguments.push_back("-macosx_version_min"); Arguments.push_back("10.8.0"); } // This should be the last option, for convenience in checking output. Arguments.push_back("-o"); Arguments.push_back(Output->getPrimaryOutputFilename().c_str()); std::string Exec = D.getProgramPath("ld", getToolChain()); return new Command(JA, *this, std::move(Inputs), std::move(Output), Args.MakeArgString(Exec), Arguments); } <commit_msg>[driver] Added support for passing a few additional arguments through to the frontend.<commit_after>//===--- Tools.cpp - Tools Implementations --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "Tools.h" #include "ToolChains.h" #include "swift/Basic/Dwarf.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/Range.h" #include "swift/Driver/Driver.h" #include "swift/Driver/Job.h" #include "swift/Driver/Options.h" #include "swift/Frontend/Frontend.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/Path.h" using namespace swift; using namespace swift::driver; using namespace swift::driver::tools; using namespace llvm::opt; StringRef swift::getPlatformNameForTriple(const llvm::Triple &triple) { if (triple.isiOS()) { llvm::Triple::ArchType arch = triple.getArch(); if (arch == llvm::Triple::ArchType::x86 || arch == llvm::Triple::ArchType::x86_64) return "iphonesimulator"; return "iphoneos"; } if (triple.isMacOSX()) return "macosx"; return ""; } /// Swift Tool namespace { static void addInputsOfType(ArgStringList &Arguments, const Job *J, types::ID InputType) { if (const Command *Cmd = dyn_cast<Command>(J)) { auto &output = Cmd->getOutput().getAnyOutputForType(InputType); if (!output.empty()) Arguments.push_back(output.c_str()); } else if (const JobList *JL = dyn_cast<JobList>(J)) { for (const Job *J : *JL) addInputsOfType(Arguments, J, InputType); } else { llvm_unreachable("Unable to add input arguments for unknown Job class"); } } static void addPrimaryInputsOfType(ArgStringList &Arguments, const Job *J, types::ID InputType) { if (const Command *Cmd = dyn_cast<Command>(J)) { auto &outputInfo = Cmd->getOutput(); if (outputInfo.getPrimaryOutputType() == InputType) Arguments.push_back(outputInfo.getPrimaryOutputFilename().c_str()); } else if (const JobList *JL = dyn_cast<JobList>(J)) { for (const Job *J : *JL) addPrimaryInputsOfType(Arguments, J, InputType); } else { llvm_unreachable("Unable to add input arguments for unknown Job class"); } } } Job *Swift::constructJob(const JobAction &JA, std::unique_ptr<JobList> Inputs, std::unique_ptr<CommandOutput> Output, const ActionList &InputActions, const ArgList &Args, const OutputInfo &OI) const { ArgStringList Arguments; const char *Exec = getToolChain().getDriver().getSwiftProgramPath().c_str(); // Invoke ourselves in -frontend mode. Arguments.push_back("-frontend"); Arguments.push_back("-target"); std::string TripleStr = getToolChain().getTripleString(); Arguments.push_back(Args.MakeArgString(TripleStr)); // Determine the frontend mode option. const char *FrontendModeOption = nullptr; switch (OI.CompilerMode) { case OutputInfo::Mode::StandardCompile: case OutputInfo::Mode::SingleCompile: { switch (Output->getPrimaryOutputType()) { case types::TY_Object: FrontendModeOption = "-c"; break; case types::TY_RawSIL: FrontendModeOption = "-emit-silgen"; break; case types::TY_SIL: FrontendModeOption = "-emit-sil"; break; case types::TY_LLVM_IR: FrontendModeOption = "-emit-ir"; break; case types::TY_LLVM_BC: FrontendModeOption = "-emit-bc"; break; case types::TY_SwiftModuleFile: // Since this is our primary output, we need to specify the option here. FrontendModeOption = "-emit-module"; break; case types::TY_Nothing: // We were told to output nothing, so get the last mode option and use that. if (const Arg *A = Args.getLastArg(options::OPT_modes_Group)) FrontendModeOption = A->getSpelling().data(); else llvm_unreachable("We were told to perform a standard compile, " "but no mode option was passed to the driver."); break; default: llvm_unreachable("Invalid output type"); } break; } case OutputInfo::Mode::Immediate: FrontendModeOption = "-i"; break; case OutputInfo::Mode::REPL: FrontendModeOption = "-repl"; break; } assert(FrontendModeOption != nullptr && "No frontend mode option specified!"); Arguments.push_back(FrontendModeOption); assert(Inputs->empty() && "The Swift frontend does not expect to be fed any input Jobs!"); // Add input arguments. switch (OI.CompilerMode) { case OutputInfo::Mode::StandardCompile: { assert(InputActions.size() == 1 && "The Swift frontend expects exactly one input (the primary file)!"); const InputAction *IA = dyn_cast<InputAction>(InputActions[0]); assert(IA && "Only InputActions can be passed as inputs!"); const Arg &PrimaryInputArg = IA->getInputArg(); bool FoundPrimaryInput = false; for (const Arg *A : make_range(Args.filtered_begin(options::OPT_INPUT), Args.filtered_end())) { Option Opt = A->getOption(); if (A->getOption().matches(options::OPT_INPUT)) { // See if this input should be passed with -primary-file. if (!FoundPrimaryInput && PrimaryInputArg.getIndex() == A->getIndex()) { Arguments.push_back("-primary-file"); FoundPrimaryInput = true; } Arguments.push_back(A->getValue()); } } break; } case OutputInfo::Mode::SingleCompile: case OutputInfo::Mode::Immediate: { for (const Action *A : InputActions) { const InputAction *IA = dyn_cast<InputAction>(A); assert(IA && "Only InputActions can be passed as inputs!"); IA->getInputArg().render(Args, Arguments); } break; } case OutputInfo::Mode::REPL: { assert(InputActions.empty() && "REPL mode accepts no inputs!"); break; } } Arguments.push_back("-module-name"); Arguments.push_back(Args.MakeArgString(OI.ModuleName)); Args.AddLastArg(Arguments, options::OPT_module_link_name); Args.AddLastArg(Arguments, options::OPT_g); // Pass the optimization level down to the frontend. Args.AddLastArg(Arguments, options::OPT_O_Group); // Set the SDK for the frontend. if (!OI.SDKPath.empty()) { Arguments.push_back("-sdk"); Arguments.push_back(Args.MakeArgString(OI.SDKPath)); } // Pass through the values passed to -Xfrontend. Args.AddAllArgValues(Arguments, options::OPT_Xfrontend); Args.AddLastArg(Arguments, options::OPT_parse_as_library); Args.AddLastArg(Arguments, options::OPT_parse_sil); Args.AddLastArg(Arguments, options::OPT_parse_stdlib); Args.AddAllArgs(Arguments, options::OPT_I); Args.AddAllArgs(Arguments, options::OPT_l, options::OPT_framework); const std::string &ModuleOutputPath = Output->getAdditionalOutputForType(types::ID::TY_SwiftModuleFile); if (!ModuleOutputPath.empty()) { Arguments.push_back("-emit-module"); Arguments.push_back("-emit-module-path"); Arguments.push_back(ModuleOutputPath.c_str()); } const std::string &SerializedDiagnosticsPath = Output->getAdditionalOutputForType(types::TY_SerializedDiagnostics); if (!SerializedDiagnosticsPath.empty()) { Arguments.push_back("-serialize-diagnostics"); Arguments.push_back("-serialize-diagnostics-path"); Arguments.push_back(SerializedDiagnosticsPath.c_str()); } // Add the output file argument if necessary. if (Output->getPrimaryOutputType() != types::TY_Nothing) { Arguments.push_back("-o"); Arguments.push_back(Output->getPrimaryOutputFilename().c_str()); } if (OI.CompilerMode == OutputInfo::Mode::Immediate) Args.AddLastArg(Arguments, options::OPT__DASH_DASH); return new Command(JA, *this, std::move(Inputs), std::move(Output), Exec, Arguments); } Job *MergeModule::constructJob(const JobAction &JA, std::unique_ptr<JobList> Inputs, std::unique_ptr<CommandOutput> Output, const ActionList &InputActions, const ArgList &Args, const OutputInfo &OI) const { ArgStringList Arguments; const char *Exec = getToolChain().getDriver().getSwiftProgramPath().c_str(); // Invoke ourself in -frontend mode. Arguments.push_back("-frontend"); // Tell all files to parse as library, which is necessary to load them as // serialized ASTs. Arguments.push_back("-parse-as-library"); Arguments.push_back("-module-name"); Arguments.push_back(Args.MakeArgString(OI.ModuleName)); // We just want to emit a module, so pass -emit-module without any other // mode options. Arguments.push_back("-emit-module"); assert(Output->getPrimaryOutputType() == types::TY_SwiftModuleFile && "The MergeModule tool only produces swiftmodule files!"); Arguments.push_back("-o"); Arguments.push_back(Args.MakeArgString(Output->getPrimaryOutputFilename())); size_t origLen = Arguments.size(); (void)origLen; addInputsOfType(Arguments, Inputs.get(), types::TY_SwiftModuleFile); assert(Arguments.size() - origLen == Inputs->size() && "every input to MergeModule must generate a swiftmodule"); return new Command(JA, *this, std::move(Inputs), std::move(Output), Exec, Arguments); } /// Darwin Tools llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Arch) { return llvm::StringSwitch<llvm::Triple::ArchType>(Arch) .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86) .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4", llvm::Triple::x86) .Case("x86_64", llvm::Triple::x86_64) .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm) .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm) .Cases("armv7s", "xscale", llvm::Triple::arm) .Default(llvm::Triple::UnknownArch); } void darwin::DarwinTool::anchor() {} void darwin::DarwinTool::AddDarwinArch(const ArgList &Args, ArgStringList &CmdArgs) const { StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args); CmdArgs.push_back("-arch"); CmdArgs.push_back(Args.MakeArgString(ArchName)); } Job *darwin::Linker::constructJob(const JobAction &JA, std::unique_ptr<JobList> Inputs, std::unique_ptr<CommandOutput> Output, const ActionList &InputActions, const ArgList &Args, const OutputInfo &OI) const { assert(Output->getPrimaryOutputType() == types::TY_Image && "Invalid linker output type."); ArgStringList Arguments; addPrimaryInputsOfType(Arguments, Inputs.get(), types::TY_Object); if (Args.hasArg(options::OPT_g)) { Arguments.push_back("-sectalign"); Arguments.push_back(MachOASTSegmentName); Arguments.push_back(MachOASTSectionName); Arguments.push_back("4"); Arguments.push_back("-sectcreate"); Arguments.push_back(MachOASTSegmentName); Arguments.push_back(MachOASTSectionName); size_t argCount = Arguments.size(); if (OI.CompilerMode == OutputInfo::Mode::SingleCompile) addInputsOfType(Arguments, Inputs.get(), types::TY_SwiftModuleFile); else addPrimaryInputsOfType(Arguments, Inputs.get(), types::TY_SwiftModuleFile); assert(argCount + 1 == Arguments.size() && "no swiftmodule found for -g"); (void)argCount; } Args.AddAllArgValues(Arguments, options::OPT_Xlinker); Args.AddAllArgs(Arguments, options::OPT_linker_option_Group); Args.AddAllArgs(Arguments, options::OPT_F); if (!OI.SDKPath.empty()) { Arguments.push_back("-syslibroot"); Arguments.push_back(Args.MakeArgString(OI.SDKPath)); } Arguments.push_back("-lSystem"); AddDarwinArch(Args, Arguments); const toolchains::Darwin &TC = getDarwinToolChain(); const Driver &D = TC.getDriver(); // Add the runtime library link path, which is platform-specific and found // relative to the compiler. // FIXME: Duplicated from CompilerInvocation, but in theory the runtime // library link path and the standard library module import path don't // need to be the same. llvm::SmallString<128> RuntimeLibPath(D.getSwiftProgramPath()); llvm::sys::path::remove_filename(RuntimeLibPath); // remove /swift llvm::sys::path::remove_filename(RuntimeLibPath); // remove /bin llvm::sys::path::append(RuntimeLibPath, "lib", "swift"); llvm::sys::path::append(RuntimeLibPath, getPlatformNameForTriple(TC.getTriple())); Arguments.push_back("-L"); Arguments.push_back(Args.MakeArgString(RuntimeLibPath)); // FIXME: We probably shouldn't be adding an rpath here unless we know ahead // of time the standard library won't be copied. Arguments.push_back("-rpath"); Arguments.push_back(Args.MakeArgString(RuntimeLibPath)); // FIXME: Properly handle deployment targets. assert(TC.getTriple().isiOS() || TC.getTriple().isMacOSX()); if (TC.getTriple().isiOS()) { Arguments.push_back("-iphoneos_version_min"); Arguments.push_back("7.0.0"); } else { Arguments.push_back("-macosx_version_min"); Arguments.push_back("10.8.0"); } // This should be the last option, for convenience in checking output. Arguments.push_back("-o"); Arguments.push_back(Output->getPrimaryOutputFilename().c_str()); std::string Exec = D.getProgramPath("ld", getToolChain()); return new Command(JA, *this, std::move(Inputs), std::move(Output), Args.MakeArgString(Exec), Arguments); } <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; Var x("x"), y("y"), c("c"); int main(int argc, char **argv) { // First define the function that gives the initial state. { Param<float> cx, cy; Func initial("initial"); // The initial state is a quantity of three chemicals present // at each pixel near the boundaries Expr dx = (x - cx), dy = (y - cy); Expr r = dx * dx + dy * dy; Expr mask = r < 200 * 200; initial(x, y, c) = random_float();// * select(mask, 1.0f, 0.001f); initial.reorder(c, x, y).bound(c, 0, 3).vectorize(c).gpu_tile(x, y, 4, 4); initial.output_buffer().set_bounds(2, 0, 3); initial.output_buffer().set_stride(0, 3); initial.output_buffer().set_stride(2, 1); initial.compile_to_file("reaction_diffusion_2_init", {cx, cy}, "reaction_diffusion_2_init"); } // Then the function that updates the state. Also depends on user input. { ImageParam state(Float(32), 3, "state"); Param<int> mouse_x, mouse_y; Param<float> cx, cy; Param<int> frame; Func clamped = BoundaryConditions::repeat_edge(state); state.set_bounds(2, 0, 3); Func blur_x("blur_x"), blur_y("blur_y"), blur("blur"); blur_x(x, y, c) = (clamped(x-3, y, c) + clamped(x-1, y, c) + clamped(x, y, c) + clamped(x+1, y, c) + clamped(x+3, y, c)); blur_y(x, y, c) = (clamped(x, y-3, c) + clamped(x, y-1, c) + clamped(x, y, c) + clamped(x, y+1, c) + clamped(x, y+3, c)); blur(x, y, c) = (blur_x(x, y, c) + blur_y(x, y, c))/10; Expr R = blur(x, y, 0); Expr G = blur(x, y, 1); Expr B = blur(x, y, 2); // Push the colors outwards with a sigmoid Expr s = 0.5f; R *= (1 - s) + s * R * (3 - 2 * R); G *= (1 - s) + s * G * (3 - 2 * G); B *= (1 - s) + s * B * (3 - 2 * B); // Reaction Expr dR = B * (1 - R - G); Expr dG = (1 - B) * (R - G); Expr dB = 1 - B + 2 * G * R - R - G; Expr bump = (frame % 1024) / 1024.0f; bump *= 1 - bump; Expr alpha = lerp(0.3f, 0.7f, bump); dR = select(dR > 0, dR*alpha, dR); Expr t = 0.1f; R += t * dR; G += t * dG; B += t * dB; R = clamp(R, 0.0f, 1.0f); G = clamp(G, 0.0f, 1.0f); B = clamp(B, 0.0f, 1.0f); Func new_state("new_state"); new_state(x, y, c) = select(c == 0, R, select(c == 1, G, B)); // Noise at the edges new_state(x, state.top(), c) = random_float(frame)*0.2f; new_state(x, state.bottom(), c) = random_float(frame)*0.2f; new_state(state.left(), y, c) = random_float(frame)*0.2f; new_state(state.right(), y, c) = random_float(frame)*0.2f; // Add some white where the mouse is Expr min_x = clamp(mouse_x - 20, 0, state.width()-1); Expr max_x = clamp(mouse_x + 20, 0, state.width()-1); Expr min_y = clamp(mouse_y - 20, 0, state.height()-1); Expr max_y = clamp(mouse_y + 20, 0, state.height()-1); RDom clobber(min_x, max_x - min_x + 1, min_y, max_y - min_y + 1); Expr dx = clobber.x - mouse_x; Expr dy = clobber.y - mouse_y; Expr radius = dx * dx + dy * dy; new_state(clobber.x, clobber.y, c) = select(radius < 400.0f, 1.0f, new_state(clobber.x, clobber.y, c)); new_state.reorder(c, x, y).bound(c, 0, 3).unroll(c); blur.reorder(c, x, y).vectorize(c); blur.compute_at(new_state, Var::gpu_threads()); new_state.gpu_tile(x, y, 8, 2); new_state.update(0).reorder(c, x).unroll(c); new_state.update(1).reorder(c, x).unroll(c); new_state.update(2).reorder(c, y).unroll(c); new_state.update(3).reorder(c, y).unroll(c); new_state.update(4).reorder(c, clobber.x).unroll(c); new_state.update(0).gpu_tile(x, 8); new_state.update(1).gpu_tile(x, 8); new_state.update(2).gpu_tile(y, 8); new_state.update(3).gpu_tile(y, 8); new_state.update(4).gpu_tile(clobber.x, clobber.y, 1, 1); std::vector<Argument> args(6); args[0] = state; args[1] = mouse_x; args[2] = mouse_y; args[3] = cx; args[4] = cy; args[5] = frame; state.set_stride(0, 3); state.set_stride(2, 1); state.set_extent(2, 3); new_state.output_buffer().set_extent(2, 3); new_state.output_buffer().set_stride(0, 3); new_state.output_buffer().set_stride(2, 1); new_state.compile_to_file("reaction_diffusion_2_update", args, "reaction_diffusion_2_update"); } // Now the function that converts the state into an bgra8 image. { ImageParam state(Float(32), 3, "state"); Func contour; contour(x, y, c) = pow(state(x, y, c) * (1 - state(x, y, c)) * 4, 8); Expr c0 = contour(x, y, 0), c1 = contour(x, y, 1), c2 = contour(x, y, 2); Expr R = min(c0, max(c1, c2)); Expr G = (c0 + c1 + c2)/3; Expr B = max(c0, max(c1, c2)); Expr alpha = 255 << 24; Expr red = cast<int32_t>(R * 255) * (1 << 16); Expr green = cast<int32_t>(G * 255) * (1 << 8); Expr blue = cast<int32_t>(B * 255) * (1 << 0); Func render("render"); render(x, y) = alpha + red + green + blue; state.set_bounds(2, 0, 3); state.set_stride(2, 1); state.set_stride(0, 3); render.gpu_tile(x, y, 32, 4); render.compile_to_file("reaction_diffusion_2_render", {state}, "reaction_diffusion_2_render"); } return 0; } <commit_msg>Update to new dim(n) syntax for setting bounds and strides on Funcs and buffers.<commit_after>#include "Halide.h" using namespace Halide; Var x("x"), y("y"), c("c"); int main(int argc, char **argv) { // First define the function that gives the initial state. { Param<float> cx, cy; Func initial("initial"); // The initial state is a quantity of three chemicals present // at each pixel near the boundaries Expr dx = (x - cx), dy = (y - cy); Expr r = dx * dx + dy * dy; Expr mask = r < 200 * 200; initial(x, y, c) = random_float();// * select(mask, 1.0f, 0.001f); initial.reorder(c, x, y).bound(c, 0, 3).vectorize(c).gpu_tile(x, y, 4, 4); initial.output_buffer().dim(2).set_bounds(0, 3); initial.output_buffer().dim(0).set_stride(3); initial.output_buffer().dim(2).set_stride(1); initial.compile_to_file("reaction_diffusion_2_init", {cx, cy}, "reaction_diffusion_2_init"); } // Then the function that updates the state. Also depends on user input. { ImageParam state(Float(32), 3, "state"); Param<int> mouse_x, mouse_y; Param<float> cx, cy; Param<int> frame; Func clamped = BoundaryConditions::repeat_edge(state); state.dim(2).set_bounds(0, 3); Func blur_x("blur_x"), blur_y("blur_y"), blur("blur"); blur_x(x, y, c) = (clamped(x-3, y, c) + clamped(x-1, y, c) + clamped(x, y, c) + clamped(x+1, y, c) + clamped(x+3, y, c)); blur_y(x, y, c) = (clamped(x, y-3, c) + clamped(x, y-1, c) + clamped(x, y, c) + clamped(x, y+1, c) + clamped(x, y+3, c)); blur(x, y, c) = (blur_x(x, y, c) + blur_y(x, y, c))/10; Expr R = blur(x, y, 0); Expr G = blur(x, y, 1); Expr B = blur(x, y, 2); // Push the colors outwards with a sigmoid Expr s = 0.5f; R *= (1 - s) + s * R * (3 - 2 * R); G *= (1 - s) + s * G * (3 - 2 * G); B *= (1 - s) + s * B * (3 - 2 * B); // Reaction Expr dR = B * (1 - R - G); Expr dG = (1 - B) * (R - G); Expr dB = 1 - B + 2 * G * R - R - G; Expr bump = (frame % 1024) / 1024.0f; bump *= 1 - bump; Expr alpha = lerp(0.3f, 0.7f, bump); dR = select(dR > 0, dR*alpha, dR); Expr t = 0.1f; R += t * dR; G += t * dG; B += t * dB; R = clamp(R, 0.0f, 1.0f); G = clamp(G, 0.0f, 1.0f); B = clamp(B, 0.0f, 1.0f); Func new_state("new_state"); new_state(x, y, c) = select(c == 0, R, select(c == 1, G, B)); // Noise at the edges new_state(x, state.top(), c) = random_float(frame)*0.2f; new_state(x, state.bottom(), c) = random_float(frame)*0.2f; new_state(state.left(), y, c) = random_float(frame)*0.2f; new_state(state.right(), y, c) = random_float(frame)*0.2f; // Add some white where the mouse is Expr min_x = clamp(mouse_x - 20, 0, state.width()-1); Expr max_x = clamp(mouse_x + 20, 0, state.width()-1); Expr min_y = clamp(mouse_y - 20, 0, state.height()-1); Expr max_y = clamp(mouse_y + 20, 0, state.height()-1); RDom clobber(min_x, max_x - min_x + 1, min_y, max_y - min_y + 1); Expr dx = clobber.x - mouse_x; Expr dy = clobber.y - mouse_y; Expr radius = dx * dx + dy * dy; new_state(clobber.x, clobber.y, c) = select(radius < 400.0f, 1.0f, new_state(clobber.x, clobber.y, c)); new_state.reorder(c, x, y).bound(c, 0, 3).unroll(c); blur.reorder(c, x, y).vectorize(c); blur.compute_at(new_state, Var::gpu_threads()); new_state.gpu_tile(x, y, 8, 2); new_state.update(0).reorder(c, x).unroll(c); new_state.update(1).reorder(c, x).unroll(c); new_state.update(2).reorder(c, y).unroll(c); new_state.update(3).reorder(c, y).unroll(c); new_state.update(4).reorder(c, clobber.x).unroll(c); new_state.update(0).gpu_tile(x, 8); new_state.update(1).gpu_tile(x, 8); new_state.update(2).gpu_tile(y, 8); new_state.update(3).gpu_tile(y, 8); new_state.update(4).gpu_tile(clobber.x, clobber.y, 1, 1); std::vector<Argument> args(6); args[0] = state; args[1] = mouse_x; args[2] = mouse_y; args[3] = cx; args[4] = cy; args[5] = frame; state.dim(0).set_stride(3); state.dim(2).set_stride(1); state.dim(2).set_extent(3); new_state.output_buffer().dim(2).set_extent(3); new_state.output_buffer().dim(0).set_stride(3); new_state.output_buffer().dim(2).set_stride(1); new_state.compile_to_file("reaction_diffusion_2_update", args, "reaction_diffusion_2_update"); } // Now the function that converts the state into an bgra8 image. { ImageParam state(Float(32), 3, "state"); Func contour; contour(x, y, c) = pow(state(x, y, c) * (1 - state(x, y, c)) * 4, 8); Expr c0 = contour(x, y, 0), c1 = contour(x, y, 1), c2 = contour(x, y, 2); Expr R = min(c0, max(c1, c2)); Expr G = (c0 + c1 + c2)/3; Expr B = max(c0, max(c1, c2)); Expr alpha = 255 << 24; Expr red = cast<int32_t>(R * 255) * (1 << 16); Expr green = cast<int32_t>(G * 255) * (1 << 8); Expr blue = cast<int32_t>(B * 255) * (1 << 0); Func render("render"); render(x, y) = alpha + red + green + blue; state.dim(2).set_bounds(0, 3); state.dim(2).set_stride(1); state.dim(0).set_stride(3); render.gpu_tile(x, y, 32, 4); render.compile_to_file("reaction_diffusion_2_render", {state}, "reaction_diffusion_2_render"); } return 0; } <|endoftext|>
<commit_before>/* cclive * Copyright (C) 2010-2013 Toni Gundogdu <[email protected]> * * This file is part of cclive <http://cclive.sourceforge.net/>. * * 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/>. */ #include <ccinternal> #include <stdexcept> #include <iostream> #include <clocale> #include <ccapplication> #include <ccquvi> using namespace cc; int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); application::exit_status es = application::ok; application app; try { es = app.exec(argc, argv); } // Thrown by quvi::query constructor (e.g. quvi_init failure). catch (const quvi::error& e) { std::clog << "libquvi: error: " << e.what() << std::endl; es = application::error; } // Thrown by boost (e.g. cc::go_background failure). catch (const std::runtime_error& e) { std::clog << "error: " << e.what() << std::endl; es = application::error; } // Thrown by boost::program_options (cc::options). catch(const std::exception& e) { std::clog << "error: " << e.what() << std::endl; es = application::error; } return es; } // vim: set ts=2 sw=2 tw=72 expandtab: <commit_msg>main: catch boost::exception<commit_after>/* cclive * Copyright (C) 2010-2013 Toni Gundogdu <[email protected]> * * This file is part of cclive <http://cclive.sourceforge.net/>. * * 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/>. */ #include <ccinternal> #include <boost/exception/diagnostic_information.hpp> #include <boost/exception/errinfo_file_name.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/exception/errinfo_errno.hpp> #include <stdexcept> #include <iostream> #include <clocale> #include <ccapplication> #include <ccquvi> #include <ccutil> using namespace cc; static application::exit_status print(const boost::exception& x) { std::clog << "error: "; if (std::string const *s = boost::get_error_info<boost::errinfo_file_name>(x)) { std::clog << *s << ": "; } bool have_strerror = false; if (int const *n = boost::get_error_info<boost::errinfo_errno>(x)) { std::clog << cc::perror() << " (" << *n << ")"; have_strerror = true; } try { throw; } catch (const std::exception& x) { if (!have_strerror) std::clog << x.what(); } catch (...) { std::clog << boost::diagnostic_information(x); } std::clog << std::endl; return application::error; } int main(int argc, char *argv[]) { setlocale(LC_ALL, ""); application::exit_status es = application::ok; application app; try { es = app.exec(argc, argv); } // Thrown by quvi::query constructor (e.g. quvi_init, quvi_new). catch (const quvi::error& e) { std::clog << "libquvi: error: " << e.what() << std::endl; es = application::error; } // Thrown by boost (e.g. cc::go_background failure). catch (const std::runtime_error& e) { std::clog << "error: " << e.what() << std::endl; es = application::error; } // Thrown by boost::program_options (cc::options). catch (const boost::exception& x) { es = print(x); } return es; } // vim: set ts=2 sw=2 tw=72 expandtab: <|endoftext|>
<commit_before>/* * author: Max Kellermann <[email protected]> */ #ifndef CERT_DATABASE_HXX #define CERT_DATABASE_HXX #include "pg/Connection.hxx" #include <string> #include <vector> struct CertDatabaseConfig; class CertDatabase { PgConnection conn; const std::string schema; public: explicit CertDatabase(const CertDatabaseConfig &_config); ConnStatusType GetStatus() const { return conn.GetStatus(); } gcc_pure const char *GetErrorMessage() const { return conn.GetErrorMessage(); } bool CheckConnected(); void EnsureConnected(); gcc_pure int GetSocket() const { return conn.GetSocket(); } void ConsumeInput() { conn.ConsumeInput(); } PgNotify GetNextNotify() { return conn.GetNextNotify(); } PgResult ListenModified(); PgResult NotifyModified(); gcc_pure std::string GetCurrentTimestamp() { const auto result = conn.Execute("SELECT CURRENT_TIMESTAMP"); return result.GetOnlyStringChecked(); } gcc_pure std::string GetLastModified() { const auto result = conn.Execute("SELECT MAX(modified) FROM server_certificates"); return result.GetOnlyStringChecked(); } PgResult InsertServerCertificate(const char *common_name, const char *not_before, const char *not_after, PgBinaryValue cert, PgBinaryValue key) { return conn.ExecuteBinary("INSERT INTO server_certificates(" "common_name, not_before, not_after, " "certificate_der, key_der) " "VALUES($1, $2, $3, $4, $5)", common_name, not_before, not_after, cert, key); } PgResult UpdateServerCertificate(const char *common_name, const char *not_before, const char *not_after, PgBinaryValue cert, PgBinaryValue key) { return conn.ExecuteBinary("UPDATE server_certificates SET " "not_before=$2, not_after=$3, " "certificate_der=$4, key_der=$5, " "modified=CURRENT_TIMESTAMP, deleted=FALSE " "WHERE common_name=$1", common_name, not_before, not_after, cert, key); } PgResult DeleteServerCertificateByCommonName(const char *common_name) { return conn.ExecuteParams(true, "DELETE FROM server_certificates " "WHERE common_name=$1 AND NOT deleted", common_name); } PgResult FindServerCertificateByCommonName(const char *common_name) { return conn.ExecuteParams(true, "SELECT certificate_der " "FROM server_certificates " "WHERE common_name=$1 AND NOT deleted", common_name); } PgResult FindServerCertificateKeyByCommonName(const char *common_name) { return conn.ExecuteParams(true, "SELECT certificate_der, key_der " "FROM server_certificates " "WHERE common_name=$1 AND NOT deleted", common_name); } PgResult GetModifiedServerCertificatesMeta(const char *since) { return conn.ExecuteParams("SELECT deleted, modified, common_name " "FROM server_certificates " "WHERE modified>$1", since); } PgResult TailModifiedServerCertificatesMeta() { return conn.ExecuteParams("SELECT deleted, modified, common_name " "FROM server_certificates " "ORDER BY modified LIMIT 20"); } }; #endif <commit_msg>certdb/CertDatabase: use UPDATE/deleted=TRUE instead of DELETE<commit_after>/* * author: Max Kellermann <[email protected]> */ #ifndef CERT_DATABASE_HXX #define CERT_DATABASE_HXX #include "pg/Connection.hxx" #include <string> #include <vector> struct CertDatabaseConfig; class CertDatabase { PgConnection conn; const std::string schema; public: explicit CertDatabase(const CertDatabaseConfig &_config); ConnStatusType GetStatus() const { return conn.GetStatus(); } gcc_pure const char *GetErrorMessage() const { return conn.GetErrorMessage(); } bool CheckConnected(); void EnsureConnected(); gcc_pure int GetSocket() const { return conn.GetSocket(); } void ConsumeInput() { conn.ConsumeInput(); } PgNotify GetNextNotify() { return conn.GetNextNotify(); } PgResult ListenModified(); PgResult NotifyModified(); gcc_pure std::string GetCurrentTimestamp() { const auto result = conn.Execute("SELECT CURRENT_TIMESTAMP"); return result.GetOnlyStringChecked(); } gcc_pure std::string GetLastModified() { const auto result = conn.Execute("SELECT MAX(modified) FROM server_certificates"); return result.GetOnlyStringChecked(); } PgResult InsertServerCertificate(const char *common_name, const char *not_before, const char *not_after, PgBinaryValue cert, PgBinaryValue key) { return conn.ExecuteBinary("INSERT INTO server_certificates(" "common_name, not_before, not_after, " "certificate_der, key_der) " "VALUES($1, $2, $3, $4, $5)", common_name, not_before, not_after, cert, key); } PgResult UpdateServerCertificate(const char *common_name, const char *not_before, const char *not_after, PgBinaryValue cert, PgBinaryValue key) { return conn.ExecuteBinary("UPDATE server_certificates SET " "not_before=$2, not_after=$3, " "certificate_der=$4, key_der=$5, " "modified=CURRENT_TIMESTAMP, deleted=FALSE " "WHERE common_name=$1", common_name, not_before, not_after, cert, key); } PgResult DeleteServerCertificateByCommonName(const char *common_name) { return conn.ExecuteParams(true, "UPDATE server_certificates SET " "modified=CURRENT_TIMESTAMP, deleted=TRUE " "WHERE common_name=$1 AND NOT deleted", common_name); } PgResult FindServerCertificateByCommonName(const char *common_name) { return conn.ExecuteParams(true, "SELECT certificate_der " "FROM server_certificates " "WHERE common_name=$1 AND NOT deleted", common_name); } PgResult FindServerCertificateKeyByCommonName(const char *common_name) { return conn.ExecuteParams(true, "SELECT certificate_der, key_der " "FROM server_certificates " "WHERE common_name=$1 AND NOT deleted", common_name); } PgResult GetModifiedServerCertificatesMeta(const char *since) { return conn.ExecuteParams("SELECT deleted, modified, common_name " "FROM server_certificates " "WHERE modified>$1", since); } PgResult TailModifiedServerCertificatesMeta() { return conn.ExecuteParams("SELECT deleted, modified, common_name " "FROM server_certificates " "ORDER BY modified LIMIT 20"); } }; #endif <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/speed_decider/speed_decider.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/log.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using common::math::Vec2d; SpeedDecider::SpeedDecider() : Task("SpeedDecider") {} bool SpeedDecider::Init(const PlanningConfig& config) { dp_st_speed_config_ = config.em_planner_config().dp_st_speed_config(); st_boundary_config_ = dp_st_speed_config_.st_boundary_config(); return true; } apollo::common::Status SpeedDecider::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); init_point_ = frame_->PlanningStartPoint(); adc_sl_boundary_ = reference_line_info_->AdcSlBoundary(); reference_line_ = &reference_line_info_->reference_line(); if (!MakeObjectDecision(reference_line_info->speed_data(), reference_line_info->path_decision()) .ok()) { const std::string msg = "Get object decision by speed profile failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } SpeedDecider::StPosition SpeedDecider::GetStPosition( const SpeedData& speed_profile, const StBoundary& st_boundary) const { StPosition st_position = BELOW; const double start_t = st_boundary.min_t(); const double end_t = st_boundary.max_t(); for (const auto& speed_point : speed_profile.speed_vector()) { if (speed_point.t() < start_t) { continue; } if (speed_point.t() > end_t) { break; } STPoint st_point(speed_point.s(), speed_point.t()); if (st_boundary.IsPointInBoundary(st_point)) { const std::string msg = "dp_st_graph failed: speed profile cross st_boundaries."; AERROR << msg; st_position = CROSS; return st_position; } double s_upper = reference_line_info_->reference_line().Length() - reference_line_info_->AdcSlBoundary().end_s(); double s_lower = 0.0; if (st_boundary.GetBoundarySRange(speed_point.t(), &s_upper, &s_lower)) { if (s_lower > speed_point.s()) { st_position = BELOW; } else if (s_upper < speed_point.s()) { st_position = ABOVE; } } } return st_position; } bool SpeedDecider::IsFollowTooClose(const PathObstacle& path_obstacle) const { if (!path_obstacle.IsBlockingObstacle()) { return false; } if (path_obstacle.st_boundary().min_t() > 0.0) { return false; } const double obs_speed = path_obstacle.obstacle()->Speed(); const double ego_speed = init_point_.v(); if (obs_speed > ego_speed) { return false; } const double distance = path_obstacle.st_boundary().min_s() - FLAGS_min_stop_distance_obstacle; constexpr double decel = 1.0; return distance < std::pow((ego_speed - obs_speed), 2) * 0.5 / decel; } Status SpeedDecider::MakeObjectDecision( const SpeedData& speed_profile, PathDecision* const path_decision) const { if (speed_profile.speed_vector().size() < 2) { const std::string msg = "dp_st_graph failed to get speed profile."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } for (const auto* obstacle : path_decision->path_obstacles().Items()) { auto* path_obstacle = path_decision->Find(obstacle->Id()); const auto& boundary = path_obstacle->st_boundary(); if (boundary.IsEmpty() || boundary.max_s() < 0.0 || boundary.max_t() < 0.0) { AppendIgnoreDecision(path_obstacle); continue; } if (path_obstacle->HasLongitudinalDecision()) { AppendIgnoreDecision(path_obstacle); continue; } auto position = GetStPosition(speed_profile, boundary); switch (position) { case BELOW: if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) { ObjectDecisionType stop_decision; if (CreateStopDecision(*path_obstacle, &stop_decision, -FLAGS_stop_distance_traffic_light)) { path_obstacle->AddLongitudinalDecision("dp_st_graph/keep_clear", stop_decision); } } else if (CheckIsFollowByT(boundary) && (boundary.max_t() - boundary.min_t() > FLAGS_follow_min_time_sec)) { // stop for low_speed decelerating if (IsFollowTooClose(*path_obstacle)) { ObjectDecisionType stop_decision; if (CreateStopDecision(*path_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { path_obstacle->AddLongitudinalDecision("dp_st_graph/too_close", stop_decision); } } else { // high speed or low speed accelerating // FOLLOW decision ObjectDecisionType follow_decision; if (CreateFollowDecision(*path_obstacle, &follow_decision)) { path_obstacle->AddLongitudinalDecision("dp_st_graph", follow_decision); } } } else { // YIELD decision ObjectDecisionType yield_decision; if (CreateYieldDecision(boundary, &yield_decision)) { path_obstacle->AddLongitudinalDecision("dp_st_graph", yield_decision); } } break; case ABOVE: if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) { ObjectDecisionType ignore; ignore.mutable_ignore(); path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore); } else { // OVERTAKE decision ObjectDecisionType overtake_decision; if (CreateOvertakeDecision(*path_obstacle, &overtake_decision)) { path_obstacle->AddLongitudinalDecision("dp_st_graph", overtake_decision); } } break; case CROSS: { ObjectDecisionType stop_decision; if (CreateStopDecision(*path_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { path_obstacle->AddLongitudinalDecision("dp_st_graph", stop_decision); } } break; default: AERROR << "Unknown position:" << position; } AppendIgnoreDecision(path_obstacle); } return Status::OK(); } void SpeedDecider::AppendIgnoreDecision(PathObstacle* path_obstacle) const { ObjectDecisionType ignore_decision; ignore_decision.mutable_ignore(); if (!path_obstacle->HasLongitudinalDecision()) { path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore_decision); } if (!path_obstacle->HasLateralDecision()) { path_obstacle->AddLateralDecision("dp_st_graph", ignore_decision); } } bool SpeedDecider::CreateStopDecision(const PathObstacle& path_obstacle, ObjectDecisionType* const stop_decision, double stop_distance) const { const auto& boundary = path_obstacle.st_boundary(); auto* stop = stop_decision->mutable_stop(); stop->set_distance_s(stop_distance); const double fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + stop_distance; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < fence_s) { ADEBUG << "Stop fence is further away, ignore."; return false; } const auto fence_point = reference_line_->GetReferencePoint(fence_s); auto* stop_point = stop->mutable_stop_point(); stop_point->set_x(fence_point.x()); stop_point->set_y(fence_point.y()); stop_point->set_z(0.0); stop->set_stop_heading(fence_point.heading()); return true; } bool SpeedDecider::CreateFollowDecision( const PathObstacle& path_obstacle, ObjectDecisionType* const follow_decision) const { DCHECK_NOTNULL(follow_decision); const auto& boundary = path_obstacle.st_boundary(); auto* follow = follow_decision->mutable_follow(); const double follow_speed = init_point_.v(); const double follow_distance_s = -std::fmax( follow_speed * FLAGS_follow_time_buffer, FLAGS_follow_min_distance); follow->set_distance_s(follow_distance_s); const double reference_s = adc_sl_boundary_.end_s() + boundary.min_s() + follow_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_s) { ADEBUG << "Follow reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_s); auto* fence_point = follow->mutable_fence_point(); fence_point->set_x(ref_point.x()); fence_point->set_y(ref_point.y()); fence_point->set_z(0.0); follow->set_fence_heading(ref_point.heading()); return true; } bool SpeedDecider::CreateYieldDecision( const StBoundary& boundary, ObjectDecisionType* const yield_decision) const { auto* yield = yield_decision->mutable_yield(); // in meters const double kMinYieldDistance = FLAGS_yield_min_distance; const double yield_distance_s = std::max(-boundary.min_s(), -1.0 * kMinYieldDistance); yield->set_distance_s(yield_distance_s); const double reference_line_fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + yield_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_line_fence_s) { ADEBUG << "Yield reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s); yield->mutable_fence_point()->set_x(ref_point.x()); yield->mutable_fence_point()->set_y(ref_point.y()); yield->mutable_fence_point()->set_z(0.0); yield->set_fence_heading(ref_point.heading()); return true; } bool SpeedDecider::CreateOvertakeDecision( const PathObstacle& path_obstacle, ObjectDecisionType* const overtake_decision) const { DCHECK_NOTNULL(overtake_decision); const auto& boundary = path_obstacle.st_boundary(); auto* overtake = overtake_decision->mutable_overtake(); // in seconds constexpr double kOvertakeTimeBuffer = 3.0; // in meters constexpr double kMinOvertakeDistance = 10.0; const auto& velocity = path_obstacle.obstacle()->Perception().velocity(); const double obstacle_speed = common::math::Vec2d::CreateUnitVec2d(init_point_.path_point().theta()) .InnerProd(Vec2d(velocity.x(), velocity.y())); const double overtake_distance_s = std::fmax( std::fmax(init_point_.v(), obstacle_speed) * kOvertakeTimeBuffer, kMinOvertakeDistance); overtake->set_distance_s(overtake_distance_s); const double reference_line_fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + overtake_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_line_fence_s) { ADEBUG << "Overtake reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s); overtake->mutable_fence_point()->set_x(ref_point.x()); overtake->mutable_fence_point()->set_y(ref_point.y()); overtake->mutable_fence_point()->set_z(0.0); overtake->set_fence_heading(ref_point.heading()); return true; } bool SpeedDecider::CheckIsFollowByT(const StBoundary& boundary) const { if (boundary.BottomLeftPoint().s() > boundary.BottomRightPoint().s()) { return false; } constexpr double kFollowTimeEpsilon = 1e-3; constexpr double kFollowCutOffTime = 0.5; if (boundary.min_t() > kFollowCutOffTime || boundary.max_t() < kFollowTimeEpsilon) { return false; } return true; } } // namespace planning } // namespace apollo <commit_msg>planning: fix cross case for non-blocking obstacle<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/speed_decider/speed_decider.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/log.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using common::math::Vec2d; SpeedDecider::SpeedDecider() : Task("SpeedDecider") {} bool SpeedDecider::Init(const PlanningConfig& config) { dp_st_speed_config_ = config.em_planner_config().dp_st_speed_config(); st_boundary_config_ = dp_st_speed_config_.st_boundary_config(); return true; } apollo::common::Status SpeedDecider::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); init_point_ = frame_->PlanningStartPoint(); adc_sl_boundary_ = reference_line_info_->AdcSlBoundary(); reference_line_ = &reference_line_info_->reference_line(); if (!MakeObjectDecision(reference_line_info->speed_data(), reference_line_info->path_decision()) .ok()) { const std::string msg = "Get object decision by speed profile failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } SpeedDecider::StPosition SpeedDecider::GetStPosition( const SpeedData& speed_profile, const StBoundary& st_boundary) const { StPosition st_position = BELOW; const double start_t = st_boundary.min_t(); const double end_t = st_boundary.max_t(); for (const auto& speed_point : speed_profile.speed_vector()) { if (speed_point.t() < start_t) { continue; } if (speed_point.t() > end_t) { break; } STPoint st_point(speed_point.s(), speed_point.t()); if (st_boundary.IsPointInBoundary(st_point)) { const std::string msg = "dp_st_graph failed: speed profile cross st_boundaries."; AERROR << msg; st_position = CROSS; return st_position; } double s_upper = reference_line_info_->reference_line().Length() - reference_line_info_->AdcSlBoundary().end_s(); double s_lower = 0.0; if (st_boundary.GetBoundarySRange(speed_point.t(), &s_upper, &s_lower)) { if (s_lower > speed_point.s()) { st_position = BELOW; } else if (s_upper < speed_point.s()) { st_position = ABOVE; } } } return st_position; } bool SpeedDecider::IsFollowTooClose(const PathObstacle& path_obstacle) const { if (!path_obstacle.IsBlockingObstacle()) { return false; } if (path_obstacle.st_boundary().min_t() > 0.0) { return false; } const double obs_speed = path_obstacle.obstacle()->Speed(); const double ego_speed = init_point_.v(); if (obs_speed > ego_speed) { return false; } const double distance = path_obstacle.st_boundary().min_s() - FLAGS_min_stop_distance_obstacle; constexpr double decel = 1.0; return distance < std::pow((ego_speed - obs_speed), 2) * 0.5 / decel; } Status SpeedDecider::MakeObjectDecision( const SpeedData& speed_profile, PathDecision* const path_decision) const { if (speed_profile.speed_vector().size() < 2) { const std::string msg = "dp_st_graph failed to get speed profile."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } for (const auto* obstacle : path_decision->path_obstacles().Items()) { auto* path_obstacle = path_decision->Find(obstacle->Id()); const auto& boundary = path_obstacle->st_boundary(); if (boundary.IsEmpty() || boundary.max_s() < 0.0 || boundary.max_t() < 0.0) { AppendIgnoreDecision(path_obstacle); continue; } if (path_obstacle->HasLongitudinalDecision()) { AppendIgnoreDecision(path_obstacle); continue; } auto position = GetStPosition(speed_profile, boundary); switch (position) { case BELOW: if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) { ObjectDecisionType stop_decision; if (CreateStopDecision(*path_obstacle, &stop_decision, -FLAGS_stop_distance_traffic_light)) { path_obstacle->AddLongitudinalDecision("dp_st_graph/keep_clear", stop_decision); } } else if (CheckIsFollowByT(boundary) && (boundary.max_t() - boundary.min_t() > FLAGS_follow_min_time_sec)) { // stop for low_speed decelerating if (IsFollowTooClose(*path_obstacle)) { ObjectDecisionType stop_decision; if (CreateStopDecision(*path_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { path_obstacle->AddLongitudinalDecision("dp_st_graph/too_close", stop_decision); } } else { // high speed or low speed accelerating // FOLLOW decision ObjectDecisionType follow_decision; if (CreateFollowDecision(*path_obstacle, &follow_decision)) { path_obstacle->AddLongitudinalDecision("dp_st_graph", follow_decision); } } } else { // YIELD decision ObjectDecisionType yield_decision; if (CreateYieldDecision(boundary, &yield_decision)) { path_obstacle->AddLongitudinalDecision("dp_st_graph", yield_decision); } } break; case ABOVE: if (boundary.boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) { ObjectDecisionType ignore; ignore.mutable_ignore(); path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore); } else { // OVERTAKE decision ObjectDecisionType overtake_decision; if (CreateOvertakeDecision(*path_obstacle, &overtake_decision)) { path_obstacle->AddLongitudinalDecision("dp_st_graph/overtake", overtake_decision); } } break; case CROSS: { if (obstacle->IsBlockingObstacle()) { ObjectDecisionType stop_decision; if (CreateStopDecision(*path_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { path_obstacle->AddLongitudinalDecision("dp_st_graph/cross", stop_decision); } } break; } default: AERROR << "Unknown position:" << position; } AppendIgnoreDecision(path_obstacle); } return Status::OK(); } void SpeedDecider::AppendIgnoreDecision(PathObstacle* path_obstacle) const { ObjectDecisionType ignore_decision; ignore_decision.mutable_ignore(); if (!path_obstacle->HasLongitudinalDecision()) { path_obstacle->AddLongitudinalDecision("dp_st_graph", ignore_decision); } if (!path_obstacle->HasLateralDecision()) { path_obstacle->AddLateralDecision("dp_st_graph", ignore_decision); } } bool SpeedDecider::CreateStopDecision(const PathObstacle& path_obstacle, ObjectDecisionType* const stop_decision, double stop_distance) const { const auto& boundary = path_obstacle.st_boundary(); auto* stop = stop_decision->mutable_stop(); stop->set_distance_s(stop_distance); const double fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + stop_distance; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < fence_s) { ADEBUG << "Stop fence is further away, ignore."; return false; } const auto fence_point = reference_line_->GetReferencePoint(fence_s); auto* stop_point = stop->mutable_stop_point(); stop_point->set_x(fence_point.x()); stop_point->set_y(fence_point.y()); stop_point->set_z(0.0); stop->set_stop_heading(fence_point.heading()); return true; } bool SpeedDecider::CreateFollowDecision( const PathObstacle& path_obstacle, ObjectDecisionType* const follow_decision) const { DCHECK_NOTNULL(follow_decision); const auto& boundary = path_obstacle.st_boundary(); auto* follow = follow_decision->mutable_follow(); const double follow_speed = init_point_.v(); const double follow_distance_s = -std::fmax( follow_speed * FLAGS_follow_time_buffer, FLAGS_follow_min_distance); follow->set_distance_s(follow_distance_s); const double reference_s = adc_sl_boundary_.end_s() + boundary.min_s() + follow_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_s) { ADEBUG << "Follow reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_s); auto* fence_point = follow->mutable_fence_point(); fence_point->set_x(ref_point.x()); fence_point->set_y(ref_point.y()); fence_point->set_z(0.0); follow->set_fence_heading(ref_point.heading()); return true; } bool SpeedDecider::CreateYieldDecision( const StBoundary& boundary, ObjectDecisionType* const yield_decision) const { auto* yield = yield_decision->mutable_yield(); // in meters const double kMinYieldDistance = FLAGS_yield_min_distance; const double yield_distance_s = std::max(-boundary.min_s(), -1.0 * kMinYieldDistance); yield->set_distance_s(yield_distance_s); const double reference_line_fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + yield_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_line_fence_s) { ADEBUG << "Yield reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s); yield->mutable_fence_point()->set_x(ref_point.x()); yield->mutable_fence_point()->set_y(ref_point.y()); yield->mutable_fence_point()->set_z(0.0); yield->set_fence_heading(ref_point.heading()); return true; } bool SpeedDecider::CreateOvertakeDecision( const PathObstacle& path_obstacle, ObjectDecisionType* const overtake_decision) const { DCHECK_NOTNULL(overtake_decision); const auto& boundary = path_obstacle.st_boundary(); auto* overtake = overtake_decision->mutable_overtake(); // in seconds constexpr double kOvertakeTimeBuffer = 3.0; // in meters constexpr double kMinOvertakeDistance = 10.0; const auto& velocity = path_obstacle.obstacle()->Perception().velocity(); const double obstacle_speed = common::math::Vec2d::CreateUnitVec2d(init_point_.path_point().theta()) .InnerProd(Vec2d(velocity.x(), velocity.y())); const double overtake_distance_s = std::fmax( std::fmax(init_point_.v(), obstacle_speed) * kOvertakeTimeBuffer, kMinOvertakeDistance); overtake->set_distance_s(overtake_distance_s); const double reference_line_fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + overtake_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_line_fence_s) { ADEBUG << "Overtake reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s); overtake->mutable_fence_point()->set_x(ref_point.x()); overtake->mutable_fence_point()->set_y(ref_point.y()); overtake->mutable_fence_point()->set_z(0.0); overtake->set_fence_heading(ref_point.heading()); return true; } bool SpeedDecider::CheckIsFollowByT(const StBoundary& boundary) const { if (boundary.BottomLeftPoint().s() > boundary.BottomRightPoint().s()) { return false; } constexpr double kFollowTimeEpsilon = 1e-3; constexpr double kFollowCutOffTime = 0.5; if (boundary.min_t() > kFollowCutOffTime || boundary.max_t() < kFollowTimeEpsilon) { return false; } return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. /* * InsertCompartmentRowsCommand.cpp * * Created on: 15 Sep 2014 * Author: dada */ #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "model/CCompartment.h" #include "model/CModel.h" #include <utilities/CCopasiException.h> #include "CQCompartmentDM.h" #include "UndoCompartmentData.h" #include "InsertCompartmentRowsCommand.h" InsertCompartmentRowsCommand::InsertCompartmentRowsCommand( int position, int rows, CQCompartmentDM *pCompartmentDM) : CCopasiUndoCommand("Compartment", COMPARTMENT_INSERT) , mpCompartmentDM(pCompartmentDM) , mRows(rows) , mPosition(position) , mIndex() , mpCompartmentData(NULL) , mValue() { setText(QObject::tr(": Inserted new compartment")); } InsertCompartmentRowsCommand::InsertCompartmentRowsCommand( int position, int rows, CQCompartmentDM *pCompartmentDM, const QModelIndex &index, const QVariant &value) : CCopasiUndoCommand("Compartment", COMPARTMENT_INSERT) , mpCompartmentDM(pCompartmentDM) , mRows(rows) , mPosition(position) , mIndex(index) , mpCompartmentData(NULL) , mValue(value) { setText(QObject::tr(": Inserted new compartment")); } void InsertCompartmentRowsCommand::redo() { if (mpCompartmentData == NULL) { assert(mpCompartmentDM->getDataModel() != NULL); CModel * pModel = mpCompartmentDM->getDataModel()->getModel(); assert(pModel != NULL); mpCompartmentDM->insertNewCompartmentRow(mPosition, mRows, mIndex, mValue); int Index = mIndex.isValid() ? mIndex.row() : mPosition; CCompartment *pCompartment = &pModel->getCompartments()[Index]; mpCompartmentData = new UndoCompartmentData(pCompartment); } else { mpCompartmentDM->addCompartmentRow(mpCompartmentData); } setUndoState(true); setAction("Add to list"); setName(mpCompartmentData->getName()); } void InsertCompartmentRowsCommand::undo() { try { mpCompartmentDM->deleteCompartmentRow(mpCompartmentData); setUndoState(false); setAction("Remove from list"); } catch (CCopasiException&) { // handle the case that the compartment does not // exist that is to be removed } } InsertCompartmentRowsCommand::~InsertCompartmentRowsCommand() { pdelete(mpCompartmentData); } <commit_msg>- fix possible crash when creating new compartment if index points to a higher row than #compartments available<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. /* * InsertCompartmentRowsCommand.cpp * * Created on: 15 Sep 2014 * Author: dada */ #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "model/CCompartment.h" #include "model/CModel.h" #include <utilities/CCopasiException.h> #include "CQCompartmentDM.h" #include "UndoCompartmentData.h" #include "InsertCompartmentRowsCommand.h" InsertCompartmentRowsCommand::InsertCompartmentRowsCommand( int position, int rows, CQCompartmentDM *pCompartmentDM) : CCopasiUndoCommand("Compartment", COMPARTMENT_INSERT) , mpCompartmentDM(pCompartmentDM) , mRows(rows) , mPosition(position) , mIndex() , mpCompartmentData(NULL) , mValue() { setText(QObject::tr(": Inserted new compartment")); } InsertCompartmentRowsCommand::InsertCompartmentRowsCommand( int position, int rows, CQCompartmentDM *pCompartmentDM, const QModelIndex &index, const QVariant &value) : CCopasiUndoCommand("Compartment", COMPARTMENT_INSERT) , mpCompartmentDM(pCompartmentDM) , mRows(rows) , mPosition(position) , mIndex(index) , mpCompartmentData(NULL) , mValue(value) { setText(QObject::tr(": Inserted new compartment")); } void InsertCompartmentRowsCommand::redo() { if (mpCompartmentData == NULL) { assert(mpCompartmentDM->getDataModel() != NULL); CModel * pModel = mpCompartmentDM->getDataModel()->getModel(); assert(pModel != NULL); mpCompartmentDM->insertNewCompartmentRow(mPosition, mRows, mIndex, mValue); // the new compartment has to be the last compartment ... as create compartment // adds it at the end CCompartment *pCompartment = &pModel->getCompartments()[pModel->getCompartments().size() - 1]; mpCompartmentData = new UndoCompartmentData(pCompartment); } else { mpCompartmentDM->addCompartmentRow(mpCompartmentData); } setUndoState(true); setAction("Add to list"); setName(mpCompartmentData->getName()); } void InsertCompartmentRowsCommand::undo() { try { mpCompartmentDM->deleteCompartmentRow(mpCompartmentData); setUndoState(false); setAction("Remove from list"); } catch (CCopasiException&) { // handle the case that the compartment does not // exist that is to be removed } } InsertCompartmentRowsCommand::~InsertCompartmentRowsCommand() { pdelete(mpCompartmentData); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.2 2001/11/07 14:50:31 hristov Minor correction of the Log part Revision 1.1 2001/11/02 15:37:26 hristov Digitizer class created. Code cleaning and bug fixes (J.Chudoba) */ #include <iostream> #include <TTree.h> #include <TObjArray.h> #include <TFile.h> #include <TDirectory.h> #include <TParticle.h> #include "AliRICHDigitizer.h" #include "AliRICHChamber.h" #include "AliHitMap.h" #include "AliRICHHitMapA1.h" #include "AliRICH.h" #include "AliRICHHit.h" #include "AliRICHSDigit.h" #include "AliRICHDigit.h" #include "AliRICHTransientDigit.h" #include "AliRun.h" #include "AliPDG.h" #include "AliRunDigitizer.h" ClassImp(AliRICHDigitizer) //___________________________________________ AliRICHDigitizer::AliRICHDigitizer() { // Default constructor - don't use it fHits = 0; fSDigits = 0; fHitMap = 0; fTDList = 0; } //////////////////////////////////////////////////////////////////////// AliRICHDigitizer::AliRICHDigitizer(AliRunDigitizer* manager) :AliDigitizer(manager) { // ctor which should be used fHits = 0; fSDigits = 0; fHitMap = 0; fTDList = 0; fDebug = 0; if (GetDebug()>2) cerr<<"AliRICHDigitizer::AliRICHDigitizer" <<"(AliRunDigitizer* manager) was processed"<<endl; } //////////////////////////////////////////////////////////////////////// AliRICHDigitizer::~AliRICHDigitizer() { // Destructor if (fHits) { fHits->Delete(); delete fHits; } if (fSDigits) { fSDigits->Delete(); delete fSDigits; } for (Int_t i=0; i++; i<kNCH ) delete fHitMap[i]; delete [] fHitMap; if (fTDList) { fTDList->Delete(); delete fTDList; } } //------------------------------------------------------------------------ Bool_t AliRICHDigitizer::Exists(const AliRICHSDigit *padhit) { return (fHitMap[fNch]->TestHit(padhit->PadX(),padhit->PadY())); } //------------------------------------------------------------------------ void AliRICHDigitizer::Update(AliRICHSDigit *padhit) { AliRICHTransientDigit *pdigit = static_cast<AliRICHTransientDigit*>( fHitMap[fNch]->GetHit(padhit->PadX(),padhit->PadY())); // update charge // Int_t iqpad = Int_t(padhit->QPad()); // charge per pad pdigit->AddSignal(iqpad); pdigit->AddPhysicsSignal(iqpad); // update list of tracks // Int_t track, charge; track = fTrack+fMask; if (fSignal) { charge = iqpad; } else { charge = kBgTag; } pdigit->UpdateTrackList(track,charge); } //------------------------------------------------------------------------ void AliRICHDigitizer::CreateNew(AliRICHSDigit *padhit) { fTDList->AddAtAndExpand( new AliRICHTransientDigit(fNch,fDigits),fCounter); fHitMap[fNch]->SetHit(padhit->PadX(),padhit->PadY(),fCounter); AliRICHTransientDigit* pdigit = static_cast<AliRICHTransientDigit*>(fTDList->Last()); // list of tracks Int_t track, charge; if (fSignal) { track = fTrack; charge = padhit->QPad(); } else { track = kBgTag; charge = kBgTag; } pdigit->AddToTrackList(track,charge); fCounter++; } //////////////////////////////////////////////////////////////////////// Bool_t AliRICHDigitizer::Init() { // Initialisation fHits = new TClonesArray("AliRICHHit",1000); fSDigits = new TClonesArray("AliRICHSDigit",1000); return kTRUE; } //////////////////////////////////////////////////////////////////////// //void AliRICHDigitizer::Digitise(Int_t nev, Int_t flag) void AliRICHDigitizer::Exec(Option_t* option) { TString optionString = option; if (optionString.Data() == "deb") { cout<<"AliMUONDigitizer::Exec: called with option deb "<<endl; fDebug = 3; } AliRICHChamber* iChamber; AliSegmentation* segmentation; fTDList = new TObjArray; AliRICH *pRICH = (AliRICH *) gAlice->GetDetector("RICH"); pRICH->MakeBranchInTreeD(fManager->GetTreeD()); fHitMap= new AliHitMap* [kNCH]; for (Int_t i =0; i<kNCH; i++) { iChamber= &(pRICH->Chamber(i)); segmentation=iChamber->GetSegmentationModel(1); fHitMap[i] = new AliRICHHitMapA1(segmentation, fTDList); } // Loop over files to digitize fSignal = kTRUE; fCounter = 0; for (Int_t inputFile=0; inputFile<fManager->GetNinputs(); inputFile++) { // Connect RICH branches if (inputFile > 0 ) fSignal = kFALSE; TBranch *branchHits = 0; TBranch *branchSDigits = 0; TTree *treeH = fManager->GetInputTreeH(inputFile); if (GetDebug()>2) { cerr<<" inputFile "<<inputFile<<endl; cerr<<" treeH, fHits "<<treeH<<" "<<fHits<<endl; } if (treeH && fHits) { branchHits = treeH->GetBranch("RICH"); if (branchHits) { fHits->Clear(); branchHits->SetAddress(&fHits); } else Error("Exec","branch RICH was not found"); } if (GetDebug()>2) cerr<<" branchHits = "<<branchHits<<endl; if (treeH && fSDigits) { branchSDigits = treeH->GetBranch("RICHSDigits"); if (branchSDigits) branchSDigits->SetAddress(&fSDigits); else Error("exec","branch RICHSDigits was not found"); } if (GetDebug()>2) cerr<<" branchSDigits = "<<branchSDigits<<endl; // // Loop over tracks // Int_t ntracks =(Int_t) treeH->GetEntries(); for (fTrack=0; fTrack<ntracks; fTrack++) { fHits->Clear(); fSDigits->Clear(); branchHits->GetEntry(fTrack); branchSDigits->GetEntry(fTrack); // // Loop over hits for(Int_t i = 0; i < fHits->GetEntriesFast(); ++i) { AliRICHHit* mHit = static_cast<AliRICHHit*>(fHits->At(i)); fNch = mHit->Chamber()-1; // chamber number if (fNch >= kNCH) { cerr<<"AliRICHDigitizer: chamber nr. fNch out of range: "<<fNch<<endl; cerr<<" track: "<<fTrack<<endl; continue; } iChamber = &(pRICH->Chamber(fNch)); // // Loop over pad hits for (AliRICHSDigit* mPad= (AliRICHSDigit*)pRICH->FirstPad(mHit,fSDigits); mPad; mPad=(AliRICHSDigit*)pRICH->NextPad(fSDigits)) { Int_t iqpad = mPad->QPad(); // charge per pad fDigits[0]=mPad->PadX(); fDigits[1]=mPad->PadY(); fDigits[2]=iqpad; fDigits[3]=iqpad; fDigits[4]=mPad->HitNumber(); // build the list of fired pads and update the info if (Exists(mPad)) { Update(mPad); } else { CreateNew(mPad); } } //end loop over clusters } // hit loop } // track loop } // end file loop if (GetDebug()>2) cerr<<"END OF FILE LOOP"<<endl; Int_t tracks[kMAXTRACKSPERRICHDIGIT]; Int_t charges[kMAXTRACKSPERRICHDIGIT]; Int_t nentries=fTDList->GetEntriesFast(); for (Int_t nent=0;nent<nentries;nent++) { AliRICHTransientDigit *transDigit=(AliRICHTransientDigit*)fTDList->At(nent); if (transDigit==0) continue; Int_t ich=transDigit->GetChamber(); Int_t q=transDigit->Signal(); iChamber=&(pRICH->Chamber(ich)); AliRICHResponse * response=iChamber->GetResponseModel(); Int_t adcmax= (Int_t) response->MaxAdc(); // add white noise and do zero-suppression and signal truncation (new electronics,old electronics gaus 1.2,0.2) //printf("Treshold: %d\n",iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY())); // tmp change // Int_t pedestal = iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY()); Int_t pedestal = 0; //printf("Pedestal:%d\n",pedestal); //Int_t pedestal=0; Float_t treshold = (pedestal + 4*2.2); Float_t meanNoise = gRandom->Gaus(2.2, 0.3); Float_t noise = gRandom->Gaus(0, meanNoise); q+=(Int_t)(noise + pedestal); //q+=(Int_t)(noise); // magic number to be parametrised !!! if ( q <= treshold) { q = q - pedestal; continue; } q = q - pedestal; if ( q >= adcmax) q=adcmax; fDigits[0]=transDigit->PadX(); fDigits[1]=transDigit->PadY(); fDigits[2]=q; fDigits[3]=transDigit->Physics(); fDigits[4]=transDigit->Hit(); Int_t nptracks = transDigit->GetNTracks(); // this was changed to accomodate the real number of tracks if (nptracks > kMAXTRACKSPERRICHDIGIT) { printf("Attention - tracks > 10 %d\n",nptracks); nptracks=kMAXTRACKSPERRICHDIGIT; } if (nptracks > 2) { printf("Attention - tracks > 2 %d \n",nptracks); } for (Int_t tr=0;tr<nptracks;tr++) { tracks[tr]=transDigit->GetTrack(tr); charges[tr]=transDigit->GetCharge(tr); } //end loop over list of tracks for one pad if (nptracks < kMAXTRACKSPERRICHDIGIT ) { for (Int_t t=nptracks; t<kMAXTRACKSPERRICHDIGIT; t++) { tracks[t]=0; charges[t]=0; } } //write file //if (ich==2) //fprintf(points,"%4d, %4d, %4d\n",digits[0],digits[1],digits[2]); // fill digits pRICH->AddDigits(ich,tracks,charges,fDigits); } fManager->GetTreeD()->Fill(); pRICH->ResetDigits(); fTDList->Delete(); // or fTDList->Clear(); ??? for(Int_t ii=0;ii<kNCH;++ii) { if (fHitMap[ii]) { delete fHitMap[ii]; fHitMap[ii]=0; } } TClonesArray *richDigits; for (Int_t k=0;k<kNCH;k++) { richDigits = pRICH->DigitsAddress(k); Int_t ndigit=richDigits->GetEntriesFast(); printf ("Chamber %d digits %d \n",k,ndigit); } pRICH->ResetDigits(); /// ??? should it be here??? fManager->GetTreeD()->Write(0,TObject::kOverwrite); delete [] fHitMap; delete fTDList; if (fHits) fHits->Delete(); if (fSDigits) fSDigits->Delete(); } <commit_msg>Wrong order of arguments in for-statement corrected.<commit_after>/************************************************************************** * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.3 2001/12/05 14:53:34 hristov Destructor corrected Revision 1.2 2001/11/07 14:50:31 hristov Minor correction of the Log part Revision 1.1 2001/11/02 15:37:26 hristov Digitizer class created. Code cleaning and bug fixes (J.Chudoba) */ #include <iostream> #include <TTree.h> #include <TObjArray.h> #include <TFile.h> #include <TDirectory.h> #include <TParticle.h> #include "AliRICHDigitizer.h" #include "AliRICHChamber.h" #include "AliHitMap.h" #include "AliRICHHitMapA1.h" #include "AliRICH.h" #include "AliRICHHit.h" #include "AliRICHSDigit.h" #include "AliRICHDigit.h" #include "AliRICHTransientDigit.h" #include "AliRun.h" #include "AliPDG.h" #include "AliRunDigitizer.h" ClassImp(AliRICHDigitizer) //___________________________________________ AliRICHDigitizer::AliRICHDigitizer() { // Default constructor - don't use it fHits = 0; fSDigits = 0; fHitMap = 0; fTDList = 0; } //////////////////////////////////////////////////////////////////////// AliRICHDigitizer::AliRICHDigitizer(AliRunDigitizer* manager) :AliDigitizer(manager) { // ctor which should be used fHits = 0; fSDigits = 0; fHitMap = 0; fTDList = 0; fDebug = 0; if (GetDebug()>2) cerr<<"AliRICHDigitizer::AliRICHDigitizer" <<"(AliRunDigitizer* manager) was processed"<<endl; } //////////////////////////////////////////////////////////////////////// AliRICHDigitizer::~AliRICHDigitizer() { // Destructor if (fHits) { fHits->Delete(); delete fHits; } if (fSDigits) { fSDigits->Delete(); delete fSDigits; } for (Int_t i=0; i<kNCH; i++ ) delete fHitMap[i]; delete [] fHitMap; if (fTDList) { fTDList->Delete(); delete fTDList; } } //------------------------------------------------------------------------ Bool_t AliRICHDigitizer::Exists(const AliRICHSDigit *padhit) { return (fHitMap[fNch]->TestHit(padhit->PadX(),padhit->PadY())); } //------------------------------------------------------------------------ void AliRICHDigitizer::Update(AliRICHSDigit *padhit) { AliRICHTransientDigit *pdigit = static_cast<AliRICHTransientDigit*>( fHitMap[fNch]->GetHit(padhit->PadX(),padhit->PadY())); // update charge // Int_t iqpad = Int_t(padhit->QPad()); // charge per pad pdigit->AddSignal(iqpad); pdigit->AddPhysicsSignal(iqpad); // update list of tracks // Int_t track, charge; track = fTrack+fMask; if (fSignal) { charge = iqpad; } else { charge = kBgTag; } pdigit->UpdateTrackList(track,charge); } //------------------------------------------------------------------------ void AliRICHDigitizer::CreateNew(AliRICHSDigit *padhit) { fTDList->AddAtAndExpand( new AliRICHTransientDigit(fNch,fDigits),fCounter); fHitMap[fNch]->SetHit(padhit->PadX(),padhit->PadY(),fCounter); AliRICHTransientDigit* pdigit = static_cast<AliRICHTransientDigit*>(fTDList->Last()); // list of tracks Int_t track, charge; if (fSignal) { track = fTrack; charge = padhit->QPad(); } else { track = kBgTag; charge = kBgTag; } pdigit->AddToTrackList(track,charge); fCounter++; } //////////////////////////////////////////////////////////////////////// Bool_t AliRICHDigitizer::Init() { // Initialisation fHits = new TClonesArray("AliRICHHit",1000); fSDigits = new TClonesArray("AliRICHSDigit",1000); return kTRUE; } //////////////////////////////////////////////////////////////////////// //void AliRICHDigitizer::Digitise(Int_t nev, Int_t flag) void AliRICHDigitizer::Exec(Option_t* option) { TString optionString = option; if (optionString.Data() == "deb") { cout<<"AliMUONDigitizer::Exec: called with option deb "<<endl; fDebug = 3; } AliRICHChamber* iChamber; AliSegmentation* segmentation; fTDList = new TObjArray; AliRICH *pRICH = (AliRICH *) gAlice->GetDetector("RICH"); pRICH->MakeBranchInTreeD(fManager->GetTreeD()); fHitMap= new AliHitMap* [kNCH]; for (Int_t i =0; i<kNCH; i++) { iChamber= &(pRICH->Chamber(i)); segmentation=iChamber->GetSegmentationModel(1); fHitMap[i] = new AliRICHHitMapA1(segmentation, fTDList); } // Loop over files to digitize fSignal = kTRUE; fCounter = 0; for (Int_t inputFile=0; inputFile<fManager->GetNinputs(); inputFile++) { // Connect RICH branches if (inputFile > 0 ) fSignal = kFALSE; TBranch *branchHits = 0; TBranch *branchSDigits = 0; TTree *treeH = fManager->GetInputTreeH(inputFile); if (GetDebug()>2) { cerr<<" inputFile "<<inputFile<<endl; cerr<<" treeH, fHits "<<treeH<<" "<<fHits<<endl; } if (treeH && fHits) { branchHits = treeH->GetBranch("RICH"); if (branchHits) { fHits->Clear(); branchHits->SetAddress(&fHits); } else Error("Exec","branch RICH was not found"); } if (GetDebug()>2) cerr<<" branchHits = "<<branchHits<<endl; if (treeH && fSDigits) { branchSDigits = treeH->GetBranch("RICHSDigits"); if (branchSDigits) branchSDigits->SetAddress(&fSDigits); else Error("exec","branch RICHSDigits was not found"); } if (GetDebug()>2) cerr<<" branchSDigits = "<<branchSDigits<<endl; // // Loop over tracks // Int_t ntracks =(Int_t) treeH->GetEntries(); for (fTrack=0; fTrack<ntracks; fTrack++) { fHits->Clear(); fSDigits->Clear(); branchHits->GetEntry(fTrack); branchSDigits->GetEntry(fTrack); // // Loop over hits for(Int_t i = 0; i < fHits->GetEntriesFast(); ++i) { AliRICHHit* mHit = static_cast<AliRICHHit*>(fHits->At(i)); fNch = mHit->Chamber()-1; // chamber number if (fNch >= kNCH) { cerr<<"AliRICHDigitizer: chamber nr. fNch out of range: "<<fNch<<endl; cerr<<" track: "<<fTrack<<endl; continue; } iChamber = &(pRICH->Chamber(fNch)); // // Loop over pad hits for (AliRICHSDigit* mPad= (AliRICHSDigit*)pRICH->FirstPad(mHit,fSDigits); mPad; mPad=(AliRICHSDigit*)pRICH->NextPad(fSDigits)) { Int_t iqpad = mPad->QPad(); // charge per pad fDigits[0]=mPad->PadX(); fDigits[1]=mPad->PadY(); fDigits[2]=iqpad; fDigits[3]=iqpad; fDigits[4]=mPad->HitNumber(); // build the list of fired pads and update the info if (Exists(mPad)) { Update(mPad); } else { CreateNew(mPad); } } //end loop over clusters } // hit loop } // track loop } // end file loop if (GetDebug()>2) cerr<<"END OF FILE LOOP"<<endl; Int_t tracks[kMAXTRACKSPERRICHDIGIT]; Int_t charges[kMAXTRACKSPERRICHDIGIT]; Int_t nentries=fTDList->GetEntriesFast(); for (Int_t nent=0;nent<nentries;nent++) { AliRICHTransientDigit *transDigit=(AliRICHTransientDigit*)fTDList->At(nent); if (transDigit==0) continue; Int_t ich=transDigit->GetChamber(); Int_t q=transDigit->Signal(); iChamber=&(pRICH->Chamber(ich)); AliRICHResponse * response=iChamber->GetResponseModel(); Int_t adcmax= (Int_t) response->MaxAdc(); // add white noise and do zero-suppression and signal truncation (new electronics,old electronics gaus 1.2,0.2) //printf("Treshold: %d\n",iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY())); // tmp change // Int_t pedestal = iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY()); Int_t pedestal = 0; //printf("Pedestal:%d\n",pedestal); //Int_t pedestal=0; Float_t treshold = (pedestal + 4*2.2); Float_t meanNoise = gRandom->Gaus(2.2, 0.3); Float_t noise = gRandom->Gaus(0, meanNoise); q+=(Int_t)(noise + pedestal); //q+=(Int_t)(noise); // magic number to be parametrised !!! if ( q <= treshold) { q = q - pedestal; continue; } q = q - pedestal; if ( q >= adcmax) q=adcmax; fDigits[0]=transDigit->PadX(); fDigits[1]=transDigit->PadY(); fDigits[2]=q; fDigits[3]=transDigit->Physics(); fDigits[4]=transDigit->Hit(); Int_t nptracks = transDigit->GetNTracks(); // this was changed to accomodate the real number of tracks if (nptracks > kMAXTRACKSPERRICHDIGIT) { printf("Attention - tracks > 10 %d\n",nptracks); nptracks=kMAXTRACKSPERRICHDIGIT; } if (nptracks > 2) { printf("Attention - tracks > 2 %d \n",nptracks); } for (Int_t tr=0;tr<nptracks;tr++) { tracks[tr]=transDigit->GetTrack(tr); charges[tr]=transDigit->GetCharge(tr); } //end loop over list of tracks for one pad if (nptracks < kMAXTRACKSPERRICHDIGIT ) { for (Int_t t=nptracks; t<kMAXTRACKSPERRICHDIGIT; t++) { tracks[t]=0; charges[t]=0; } } //write file //if (ich==2) //fprintf(points,"%4d, %4d, %4d\n",digits[0],digits[1],digits[2]); // fill digits pRICH->AddDigits(ich,tracks,charges,fDigits); } fManager->GetTreeD()->Fill(); pRICH->ResetDigits(); fTDList->Delete(); // or fTDList->Clear(); ??? for(Int_t ii=0;ii<kNCH;++ii) { if (fHitMap[ii]) { delete fHitMap[ii]; fHitMap[ii]=0; } } TClonesArray *richDigits; for (Int_t k=0;k<kNCH;k++) { richDigits = pRICH->DigitsAddress(k); Int_t ndigit=richDigits->GetEntriesFast(); printf ("Chamber %d digits %d \n",k,ndigit); } pRICH->ResetDigits(); /// ??? should it be here??? fManager->GetTreeD()->Write(0,TObject::kOverwrite); delete [] fHitMap; delete fTDList; if (fHits) fHits->Delete(); if (fSDigits) fSDigits->Delete(); } <|endoftext|>
<commit_before>//---------------------------- dof_constraints_03.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2004 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- dof_constraints_03.cc --------------------------- // simply check what happens when condensing matrices. This test was // written when I changed a few things in the algorithm #include "../tests.h" #include <lac/sparsity_pattern.h> #include <lac/sparse_matrix.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <grid/grid_tools.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <dofs/dof_accessor.h> #include <dofs/dof_tools.h> #include <dofs/dof_constraints.h> #include <fe/fe_q.h> #include <fstream> #include <iostream> template <int dim> void test () { deallog << dim << "D" << std::endl; Triangulation<dim> triangulation; GridGenerator::hyper_cube (triangulation); // refine once, then refine first cell to // create hanging nodes triangulation.refine_global (1); triangulation.begin_active()->set_refine_flag (); triangulation.execute_coarsening_and_refinement (); deallog << "Number of cells: " << triangulation.n_active_cells() << std::endl; // set up a DoFHandler and compute hanging // node constraints for a Q2 element FE_Q<dim> fe(2); DoFHandler<dim> dof_handler (triangulation); dof_handler.distribute_dofs (fe); deallog << "Number of dofs: " << dof_handler.n_dofs() << std::endl; ConstraintMatrix constraints; DoFTools::make_hanging_node_constraints (dof_handler, constraints); constraints.close (); deallog << "Number of constraints: " << constraints.n_constraints() << std::endl; // then set up a sparsity pattern and a // matrix on top of it SparsityPattern sparsity (dof_handler.n_dofs(), dof_handler.n_dofs(), dof_handler.max_couplings_between_dofs()); DoFTools::make_sparsity_pattern (dof_handler, sparsity); constraints.condense (sparsity); SparseMatrix<double> A(sparsity); // then fill the matrix by setting up // bogus matrix entries std::vector<unsigned int> local_dofs (fe.dofs_per_cell); FullMatrix<double> local_matrix (fe.dofs_per_cell, fe.dofs_per_cell); for (typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); cell != dof_handler.end(); ++cell) { cell->get_dof_indices (local_dofs); local_matrix.clear (); for (unsigned int i=0; i<fe.dofs_per_cell; ++i) for (unsigned int j=0; j<fe.dofs_per_cell; ++j) local_matrix(i,j) = (i+1.)*(j+1.)*(local_dofs[i]+1.)*(local_dofs[j]+1.); // copy local to global for (unsigned int i=0; i<fe.dofs_per_cell; ++i) for (unsigned int j=0; j<fe.dofs_per_cell; ++j) A.add (local_dofs[i], local_dofs[j], local_matrix(i,j)); } // now condense away constraints from A constraints.condense (A); // and output what we have for (SparseMatrix<double>::const_iterator i=A.begin(); i!=A.end(); ++i) deallog << i->row() << ' ' << i->column() << ' ' << i->value() << std::endl; } int main () { std::ofstream logfile("dof_constraints_03.output"); deallog.attach(logfile); deallog.depth_console(0); try { test<1> (); test<2> (); test<3> (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; }; } <commit_msg>Doc update.<commit_after>//---------------------------- dof_constraints_03.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2004 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- dof_constraints_03.cc --------------------------- // simply check what happens when condensing matrices. This test was written // when I changed a few things in the algorithm. By simply looping over all // entries of the sparse matrix, we also check that things went right during // compression of the sparsity pattern. #include "../tests.h" #include <lac/sparsity_pattern.h> #include <lac/sparse_matrix.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <grid/grid_tools.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <dofs/dof_accessor.h> #include <dofs/dof_tools.h> #include <dofs/dof_constraints.h> #include <fe/fe_q.h> #include <fstream> #include <iostream> template <int dim> void test () { deallog << dim << "D" << std::endl; Triangulation<dim> triangulation; GridGenerator::hyper_cube (triangulation); // refine once, then refine first cell to // create hanging nodes triangulation.refine_global (1); triangulation.begin_active()->set_refine_flag (); triangulation.execute_coarsening_and_refinement (); deallog << "Number of cells: " << triangulation.n_active_cells() << std::endl; // set up a DoFHandler and compute hanging // node constraints for a Q2 element FE_Q<dim> fe(2); DoFHandler<dim> dof_handler (triangulation); dof_handler.distribute_dofs (fe); deallog << "Number of dofs: " << dof_handler.n_dofs() << std::endl; ConstraintMatrix constraints; DoFTools::make_hanging_node_constraints (dof_handler, constraints); constraints.close (); deallog << "Number of constraints: " << constraints.n_constraints() << std::endl; // then set up a sparsity pattern and a // matrix on top of it SparsityPattern sparsity (dof_handler.n_dofs(), dof_handler.n_dofs(), dof_handler.max_couplings_between_dofs()); DoFTools::make_sparsity_pattern (dof_handler, sparsity); constraints.condense (sparsity); SparseMatrix<double> A(sparsity); // then fill the matrix by setting up // bogus matrix entries std::vector<unsigned int> local_dofs (fe.dofs_per_cell); FullMatrix<double> local_matrix (fe.dofs_per_cell, fe.dofs_per_cell); for (typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); cell != dof_handler.end(); ++cell) { cell->get_dof_indices (local_dofs); local_matrix.clear (); for (unsigned int i=0; i<fe.dofs_per_cell; ++i) for (unsigned int j=0; j<fe.dofs_per_cell; ++j) local_matrix(i,j) = (i+1.)*(j+1.)*(local_dofs[i]+1.)*(local_dofs[j]+1.); // copy local to global for (unsigned int i=0; i<fe.dofs_per_cell; ++i) for (unsigned int j=0; j<fe.dofs_per_cell; ++j) A.add (local_dofs[i], local_dofs[j], local_matrix(i,j)); } // now condense away constraints from A constraints.condense (A); // and output what we have for (SparseMatrix<double>::const_iterator i=A.begin(); i!=A.end(); ++i) deallog << i->row() << ' ' << i->column() << ' ' << i->value() << std::endl; } int main () { std::ofstream logfile("dof_constraints_03.output"); deallog.attach(logfile); deallog.depth_console(0); try { test<1> (); test<2> (); test<3> (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; }; } <|endoftext|>
<commit_before>#pragma once // `krbn::local_datagram::client` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" BEGIN_BOOST_INCLUDE #include <boost/asio.hpp> #include <boost/signals2.hpp> END_BOOST_INCLUDE #include "dispatcher.hpp" #include "logger.hpp" #include "thread_utility.hpp" namespace krbn { namespace local_datagram { class client final : public pqrs::dispatcher::extra::dispatcher_client { public: // Signals boost::signals2::signal<void(void)> connected; boost::signals2::signal<void(const boost::system::error_code&)> connect_failed; boost::signals2::signal<void(void)> closed; // Methods client(const client&) = delete; client(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher) : dispatcher_client(weak_dispatcher), io_service_(), work_(std::make_unique<boost::asio::io_service::work>(io_service_)), socket_(io_service_), connected_(false) { io_service_thread_ = std::thread([this] { (this->io_service_).run(); }); } virtual ~client(void) { async_close(); if (io_service_thread_.joinable()) { work_ = nullptr; io_service_thread_.join(); } detach_from_dispatcher([] { }); } void async_connect(const std::string& path, boost::optional<std::chrono::milliseconds> server_check_interval) { async_close(); io_service_.post([this, path, server_check_interval] { connected_ = false; // Open { boost::system::error_code error_code; socket_.open(boost::asio::local::datagram_protocol::socket::protocol_type(), error_code); if (error_code) { enqueue_to_dispatcher([this, error_code] { connect_failed(error_code); }); return; } } // Connect socket_.async_connect(boost::asio::local::datagram_protocol::endpoint(path), [this, server_check_interval](auto&& error_code) { if (error_code) { enqueue_to_dispatcher([this, error_code] { connect_failed(error_code); }); } else { connected_ = true; stop_server_check(); start_server_check(server_check_interval); enqueue_to_dispatcher([this] { connected(); }); } }); }); } void async_close(void) { io_service_.post([this] { stop_server_check(); // Close socket boost::system::error_code error_code; socket_.cancel(error_code); socket_.close(error_code); // Signal if (connected_) { connected_ = false; enqueue_to_dispatcher([this] { closed(); }); } }); } void async_send(const std::vector<uint8_t>& v) { auto ptr = std::make_shared<buffer>(v); io_service_.post([this, ptr] { do_async_send(ptr); }); } void async_send(const uint8_t* _Nonnull p, size_t length) { auto ptr = std::make_shared<buffer>(p, length); io_service_.post([this, ptr] { do_async_send(ptr); }); } private: class buffer final { public: buffer(const std::vector<uint8_t> v) { v_ = v; } buffer(const uint8_t* _Nonnull p, size_t length) { v_.resize(length); memcpy(&(v_[0]), p, length); } const std::vector<uint8_t>& get_vector(void) const { return v_; } private: std::vector<uint8_t> v_; }; void do_async_send(std::shared_ptr<buffer> ptr) { socket_.async_send(boost::asio::buffer(ptr->get_vector()), [this, ptr](auto&& error_code, auto&& bytes_transferred) { if (error_code) { async_close(); } }); } // This method is executed in `io_service_thread_`. void start_server_check(boost::optional<std::chrono::milliseconds> server_check_interval) { if (server_check_interval) { server_check_enabled_ = true; check_server(*server_check_interval); } } // This method is executed in `io_service_thread_`. void stop_server_check(void) { server_check_enabled_ = false; } // This method is executed in `io_service_thread_`. void check_server(std::chrono::milliseconds server_check_interval) { if (!server_check_enabled_) { return; } std::vector<uint8_t> data; async_send(data); // Enqueue next check enqueue_to_dispatcher( [this, server_check_interval] { io_service_.post([this, server_check_interval] { check_server(server_check_interval); }); }, when_now() + server_check_interval); } boost::asio::io_service io_service_; std::unique_ptr<boost::asio::io_service::work> work_; boost::asio::local::datagram_protocol::socket socket_; std::thread io_service_thread_; bool connected_; bool server_check_enabled_; }; } // namespace local_datagram } // namespace krbn <commit_msg>use dispatcher::extra::timer @ client<commit_after>#pragma once // `krbn::local_datagram::client` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" BEGIN_BOOST_INCLUDE #include <boost/asio.hpp> #include <boost/signals2.hpp> END_BOOST_INCLUDE #include "dispatcher.hpp" #include "logger.hpp" #include "thread_utility.hpp" namespace krbn { namespace local_datagram { class client final : public pqrs::dispatcher::extra::dispatcher_client { public: // Signals boost::signals2::signal<void(void)> connected; boost::signals2::signal<void(const boost::system::error_code&)> connect_failed; boost::signals2::signal<void(void)> closed; // Methods client(const client&) = delete; client(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher) : dispatcher_client(weak_dispatcher), io_service_(), work_(std::make_unique<boost::asio::io_service::work>(io_service_)), socket_(io_service_), connected_(false), server_check_timer_(*this) { io_service_thread_ = std::thread([this] { (this->io_service_).run(); }); } virtual ~client(void) { async_close(); if (io_service_thread_.joinable()) { work_ = nullptr; io_service_thread_.join(); } detach_from_dispatcher([] { }); } void async_connect(const std::string& path, boost::optional<std::chrono::milliseconds> server_check_interval) { async_close(); io_service_.post([this, path, server_check_interval] { connected_ = false; // Open { boost::system::error_code error_code; socket_.open(boost::asio::local::datagram_protocol::socket::protocol_type(), error_code); if (error_code) { enqueue_to_dispatcher([this, error_code] { connect_failed(error_code); }); return; } } // Connect socket_.async_connect(boost::asio::local::datagram_protocol::endpoint(path), [this, server_check_interval](auto&& error_code) { if (error_code) { enqueue_to_dispatcher([this, error_code] { connect_failed(error_code); }); } else { connected_ = true; stop_server_check(); start_server_check(server_check_interval); enqueue_to_dispatcher([this] { connected(); }); } }); }); } void async_close(void) { io_service_.post([this] { stop_server_check(); // Close socket boost::system::error_code error_code; socket_.cancel(error_code); socket_.close(error_code); // Signal if (connected_) { connected_ = false; enqueue_to_dispatcher([this] { closed(); }); } }); } void async_send(const std::vector<uint8_t>& v) { auto ptr = std::make_shared<buffer>(v); io_service_.post([this, ptr] { do_async_send(ptr); }); } void async_send(const uint8_t* _Nonnull p, size_t length) { auto ptr = std::make_shared<buffer>(p, length); io_service_.post([this, ptr] { do_async_send(ptr); }); } private: class buffer final { public: buffer(const std::vector<uint8_t> v) { v_ = v; } buffer(const uint8_t* _Nonnull p, size_t length) { v_.resize(length); memcpy(&(v_[0]), p, length); } const std::vector<uint8_t>& get_vector(void) const { return v_; } private: std::vector<uint8_t> v_; }; void do_async_send(std::shared_ptr<buffer> ptr) { socket_.async_send(boost::asio::buffer(ptr->get_vector()), [this, ptr](auto&& error_code, auto&& bytes_transferred) { if (error_code) { async_close(); } }); } // This method is executed in `io_service_thread_`. void start_server_check(boost::optional<std::chrono::milliseconds> server_check_interval) { if (server_check_interval) { server_check_timer_.start( [this] { io_service_.post([this] { check_server(); }); }, *server_check_interval); } } // This method is executed in `io_service_thread_`. void stop_server_check(void) { server_check_timer_.stop(); } // This method is executed in `io_service_thread_`. void check_server(void) { std::vector<uint8_t> data; async_send(data); } boost::asio::io_service io_service_; std::unique_ptr<boost::asio::io_service::work> work_; boost::asio::local::datagram_protocol::socket socket_; std::thread io_service_thread_; bool connected_; pqrs::dispatcher::extra::timer server_check_timer_; }; } // namespace local_datagram } // namespace krbn <|endoftext|>
<commit_before>// Copyright (c) 2008 The Native Client Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // NaCl-NPAPI Interface // This directory is shared because it contains browser plugin side and // untrusted NaCl module side components. #include <stdio.h> #include <stdlib.h> #include "native_client/src/include/nacl_string.h" #include "native_client/src/shared/npruntime/nacl_npapi.h" #ifdef __native_client__ #include "native_client/src/shared/npruntime/npnavigator.h" #endif // __native_client__ namespace { enum DebugState { DEBUG_STATE_NOT_CHECKED = 0, DEBUG_STATE_NOT_ENABLED, DEBUG_STATE_ENABLED }; DebugState debug_output_enabled = DEBUG_STATE_NOT_CHECKED; bool DebugOutputEnabled() { if (DEBUG_STATE_NOT_CHECKED == debug_output_enabled) { if (getenv("NACL_NPAPI_DEBUG")) { debug_output_enabled = DEBUG_STATE_ENABLED; } else { debug_output_enabled = DEBUG_STATE_NOT_ENABLED; } } return DEBUG_STATE_ENABLED == debug_output_enabled; } nacl::string FormatNPVariantInternal(const NPVariant* variant) { nacl::stringstream ss; if (NULL == variant) { ss << "NULL"; } else if (NPVARIANT_IS_VOID(*variant)) { ss << "NPVariant(VOID)"; } else if (NPVARIANT_IS_NULL(*variant)) { ss << "NPVariant(NULL)"; } else if (NPVARIANT_IS_BOOLEAN(*variant)) { ss << "NPVariant(bool, " << (NPVARIANT_TO_BOOLEAN(*variant) ? "true" : "false") << ")"; } else if (NPVARIANT_IS_INT32(*variant)) { ss << "NPVariant(int32_t, " << NPVARIANT_TO_INT32(*variant) << ")"; } else if (NPVARIANT_IS_DOUBLE(*variant)) { ss << "NPVariant(double, " << NPVARIANT_TO_DOUBLE(*variant) << ")"; } else if (NPVARIANT_IS_STRING(*variant)) { ss << "NPVariant(string, \""; NPString str = NPVARIANT_TO_STRING(*variant); if (0 != str.UTF8Length && NULL != str.UTF8Characters) { nacl::string s(str.UTF8Characters); ss << s.substr(0, str.UTF8Length); } ss << "\")"; } else if (NPVARIANT_IS_OBJECT(*variant)) { ss << "NPVariant(object, " << NPVARIANT_TO_OBJECT(*variant) << ")"; } else { ss << "NPVariant(BAD TYPE)"; } return ss.str(); } } // namespace namespace nacl { static const size_t kFormatBufSize = 1024; const char* FormatNPIdentifier(NPIdentifier ident) { static char buf[kFormatBufSize]; buf[0] = 0; if (!DebugOutputEnabled()) { return buf; } nacl::string s("NPIdentifier("); if (NPN_IdentifierIsString(ident)) { const NPUTF8* name = NPN_UTF8FromIdentifier(ident); s += name; NPN_MemFree(const_cast<NPUTF8*>(name)); } else { s += static_cast<int>(NPN_IntFromIdentifier(ident)); } s += ")"; strncpy(buf, s.c_str(), kFormatBufSize); buf[kFormatBufSize - 1] = 0; return buf; } const char* FormatNPVariant(const NPVariant* variant) { static char buf[kFormatBufSize]; buf[0] = 0; if (!DebugOutputEnabled()) { return buf; } strncpy(buf, FormatNPVariantInternal(variant).c_str(), kFormatBufSize); buf[kFormatBufSize - 1] = 0; return buf; } const char* FormatNPVariantVector(const NPVariant* vect, uint32_t count) { static char buf[kFormatBufSize]; buf[0] = 0; if (!DebugOutputEnabled()) { return buf; } nacl::stringstream ss; ss << "["; for (uint32_t i = 0; i < count; ++i) { ss << FormatNPVariantInternal(vect + i); if (i < count - 1) { ss << ", "; } } ss << "]"; strncpy(buf, ss.str().c_str(), kFormatBufSize); buf[kFormatBufSize - 1] = 0; return buf; } void DebugPrintf(const char *fmt, ...) { if (!DebugOutputEnabled()) { return; } va_list argptr; #ifdef __native_client__ fprintf(stderr, "@@@ NACL "); #else fprintf(stderr, "@@@ HOST "); #endif // __native_client__ va_start(argptr, fmt); vfprintf(stderr, fmt, argptr); va_end(argptr); fflush(stderr); } } // namespace nacl <commit_msg>Add #include <string.h> in naclnp_util.cc per stuartmorgan's feedback on npapi work<commit_after>// Copyright (c) 2008 The Native Client Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // NaCl-NPAPI Interface // This directory is shared because it contains browser plugin side and // untrusted NaCl module side components. #include <stdio.h> #include <stdlib.h> #include <string.h> #include "native_client/src/include/nacl_string.h" #include "native_client/src/shared/npruntime/nacl_npapi.h" #ifdef __native_client__ #include "native_client/src/shared/npruntime/npnavigator.h" #endif // __native_client__ namespace { enum DebugState { DEBUG_STATE_NOT_CHECKED = 0, DEBUG_STATE_NOT_ENABLED, DEBUG_STATE_ENABLED }; DebugState debug_output_enabled = DEBUG_STATE_NOT_CHECKED; bool DebugOutputEnabled() { if (DEBUG_STATE_NOT_CHECKED == debug_output_enabled) { if (getenv("NACL_NPAPI_DEBUG")) { debug_output_enabled = DEBUG_STATE_ENABLED; } else { debug_output_enabled = DEBUG_STATE_NOT_ENABLED; } } return DEBUG_STATE_ENABLED == debug_output_enabled; } nacl::string FormatNPVariantInternal(const NPVariant* variant) { nacl::stringstream ss; if (NULL == variant) { ss << "NULL"; } else if (NPVARIANT_IS_VOID(*variant)) { ss << "NPVariant(VOID)"; } else if (NPVARIANT_IS_NULL(*variant)) { ss << "NPVariant(NULL)"; } else if (NPVARIANT_IS_BOOLEAN(*variant)) { ss << "NPVariant(bool, " << (NPVARIANT_TO_BOOLEAN(*variant) ? "true" : "false") << ")"; } else if (NPVARIANT_IS_INT32(*variant)) { ss << "NPVariant(int32_t, " << NPVARIANT_TO_INT32(*variant) << ")"; } else if (NPVARIANT_IS_DOUBLE(*variant)) { ss << "NPVariant(double, " << NPVARIANT_TO_DOUBLE(*variant) << ")"; } else if (NPVARIANT_IS_STRING(*variant)) { ss << "NPVariant(string, \""; NPString str = NPVARIANT_TO_STRING(*variant); if (0 != str.UTF8Length && NULL != str.UTF8Characters) { nacl::string s(str.UTF8Characters); ss << s.substr(0, str.UTF8Length); } ss << "\")"; } else if (NPVARIANT_IS_OBJECT(*variant)) { ss << "NPVariant(object, " << NPVARIANT_TO_OBJECT(*variant) << ")"; } else { ss << "NPVariant(BAD TYPE)"; } return ss.str(); } } // namespace namespace nacl { static const size_t kFormatBufSize = 1024; const char* FormatNPIdentifier(NPIdentifier ident) { static char buf[kFormatBufSize]; buf[0] = 0; if (!DebugOutputEnabled()) { return buf; } nacl::string s("NPIdentifier("); if (NPN_IdentifierIsString(ident)) { const NPUTF8* name = NPN_UTF8FromIdentifier(ident); s += name; NPN_MemFree(const_cast<NPUTF8*>(name)); } else { s += static_cast<int>(NPN_IntFromIdentifier(ident)); } s += ")"; strncpy(buf, s.c_str(), kFormatBufSize); buf[kFormatBufSize - 1] = 0; return buf; } const char* FormatNPVariant(const NPVariant* variant) { static char buf[kFormatBufSize]; buf[0] = 0; if (!DebugOutputEnabled()) { return buf; } strncpy(buf, FormatNPVariantInternal(variant).c_str(), kFormatBufSize); buf[kFormatBufSize - 1] = 0; return buf; } const char* FormatNPVariantVector(const NPVariant* vect, uint32_t count) { static char buf[kFormatBufSize]; buf[0] = 0; if (!DebugOutputEnabled()) { return buf; } nacl::stringstream ss; ss << "["; for (uint32_t i = 0; i < count; ++i) { ss << FormatNPVariantInternal(vect + i); if (i < count - 1) { ss << ", "; } } ss << "]"; strncpy(buf, ss.str().c_str(), kFormatBufSize); buf[kFormatBufSize - 1] = 0; return buf; } void DebugPrintf(const char *fmt, ...) { if (!DebugOutputEnabled()) { return; } va_list argptr; #ifdef __native_client__ fprintf(stderr, "@@@ NACL "); #else fprintf(stderr, "@@@ HOST "); #endif // __native_client__ va_start(argptr, fmt); vfprintf(stderr, fmt, argptr); va_end(argptr); fflush(stderr); } } // namespace nacl <|endoftext|>
<commit_before>/* Copyright (c) 2016 Bastien Durix 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. */ /** * \brief Images acquisition software * \author Bastien Durix */ #include <boost/program_options.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <camera/Camera.h> #include <tracking/Tracker.h> #include <display3d/DisplayClass.h> #include <display3d/DisplayFrame.h> #include <fileio/CameraFile.h> int main(int argc, char** argv) { std::string camfile; unsigned int camID; boost::program_options::options_description desc("OPTIONS"); desc.add_options() ("help", "Help message") ("camfile", boost::program_options::value<std::string>(&camfile)->default_value("cam.xml"), "Camera file") ("camID", boost::program_options::value<unsigned int>(&camID)->default_value(1), "Camera number") ; boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } camera::Camera::Ptr cam = fileio::ReadCamera(camfile); tracking::Tracker tracker(4); tracker.init(cam); cv::VideoCapture capture; capture.open( camID ); capture.set(CV_CAP_PROP_FRAME_WIDTH, cam->getIntrinsics()->getWidth()); capture.set(CV_CAP_PROP_FRAME_HEIGHT, cam->getIntrinsics()->getHeight()); capture.set(CV_CAP_PROP_FPS, 20); const std::string WINDOW_NAME = "Images acquisition"; bool fini = false; while(!fini) { cv::Mat view; cv::Mat aff; // get the new frame from capture and copy it to view capture >> aff; aff.copyTo(view); // if no more images to process exit the loop if(view.empty()) { std::cerr << "No view taken" << std::endl; break; } // detect the markers tracker.detect(aff); imshow(WINDOW_NAME , aff); char key; if( (key=cv::waitKey( 10 )) >= 0) { if(key == 'a' || key == 'A') { if(tracker.addCurrDetection()) std::cout << "View taken !" << std::endl; else std::cout << "Some markers are not seen in the image" << std::endl; } if(key=='q' || key=='Q') { std::cout << "Computing markers relative position..." << std::endl; fini = tracker.computeMulti(); if(!fini) std::cout << "Not enough images" << std::endl; } } } std::cout << "Success !! " << std::endl; display3d::DisplayClass disclass("Acquisitions",cam->getIntrinsics()->getWidth(),cam->getIntrinsics()->getHeight()); display3d::DisplayFrame(disclass,mathtools::affine::Frame<3>::CanonicFrame()); disclass.setIntrinsics(cam->getIntrinsics()); fini = false; while(!fini) { cv::Mat view; cv::Mat aff; // get the new frame from capture and copy it to view capture >> aff; aff.copyTo(view); // if no more images to process exit the loop if(view.empty()) { std::cerr << "No acquired view" << std::endl; break; } // detect the markers tracker.detect(aff); Eigen::Matrix<double,3,4> matTr = tracker.getCurrTr(); disclass.setExtrinsics(matTr); imshow(WINDOW_NAME , aff); disclass.setBackground(view); disclass.display(); char key; if( (key=cv::waitKey( 10 )) >= 0) { if(key == 'a' || key == 'A') { std::cout << matTr << std::endl; mathtools::affine::Frame<3>::Ptr frame_cur; frame_cur = mathtools::affine::Frame<3>::CreateFrame(matTr.col(3),matTr.col(0),matTr.col(1),matTr.col(2)); camera::Extrinsics::Ptr extr(new camera::Extrinsics(frame_cur)); camera::Camera::Ptr camimg(new camera::Camera(cam->getIntrinsics(),extr)); } if(key=='q' || key=='Q') { fini = true; } } } cv::destroyWindow(WINDOW_NAME); capture.release(); return 0; } <commit_msg>Method call correction<commit_after>/* Copyright (c) 2016 Bastien Durix 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. */ /** * \brief Images acquisition software * \author Bastien Durix */ #include <boost/program_options.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <camera/Camera.h> #include <tracking/Tracker.h> #include <display3d/DisplayClass.h> #include <display3d/DisplayFrame.h> #include <fileio/CameraFile.h> int main(int argc, char** argv) { std::string camfile; unsigned int camID; boost::program_options::options_description desc("OPTIONS"); desc.add_options() ("help", "Help message") ("camfile", boost::program_options::value<std::string>(&camfile)->default_value("cam.xml"), "Camera file") ("camID", boost::program_options::value<unsigned int>(&camID)->default_value(1), "Camera number") ; boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } camera::Camera::Ptr cam = fileio::ReadCamera(camfile); tracking::Tracker tracker(4); tracker.init(cam); cv::VideoCapture capture; capture.open( camID ); capture.set(CV_CAP_PROP_FRAME_WIDTH, cam->getIntrinsics()->getWidth()); capture.set(CV_CAP_PROP_FRAME_HEIGHT, cam->getIntrinsics()->getHeight()); capture.set(CV_CAP_PROP_FPS, 20); const std::string WINDOW_NAME = "Images acquisition"; bool fini = false; while(!fini) { cv::Mat view; cv::Mat aff; // get the new frame from capture and copy it to view capture >> aff; aff.copyTo(view); // if no more images to process exit the loop if(view.empty()) { std::cerr << "No view taken" << std::endl; break; } // detect the markers tracker.detect(aff); imshow(WINDOW_NAME , aff); char key; if( (key=cv::waitKey( 10 )) >= 0) { if(key == 'a' || key == 'A') { if(tracker.addCurrDetection()) std::cout << "View taken !" << std::endl; else std::cout << "Some markers are not seen in the image" << std::endl; } if(key=='q' || key=='Q') { std::cout << "Computing markers relative position..." << std::endl; fini = tracker.computeMulti(); if(!fini) std::cout << "Not enough images" << std::endl; } } } std::cout << "Success !! " << std::endl; display3d::DisplayClass disclass("Acquisitions",cam->getIntrinsics()->getWidth(),cam->getIntrinsics()->getHeight()); display3d::DisplayFrame(disclass,mathtools::affine::Frame<3>::CanonicFrame()); disclass.setIntrinsics(cam->getIntrinsics()); fini = false; while(!fini) { cv::Mat view; cv::Mat aff; // get the new frame from capture and copy it to view capture >> aff; aff.copyTo(view); // if no more images to process exit the loop if(view.empty()) { std::cerr << "No acquired view" << std::endl; break; } // detect the markers tracker.detect(aff); Eigen::Matrix<double,3,4> matTr; tracker.getCurrTr(matTr); disclass.setExtrinsics(matTr); imshow(WINDOW_NAME , aff); //disclass.setBackground(view); disclass.display(); char key; if( (key=cv::waitKey( 10 )) >= 0) { if(key == 'a' || key == 'A') { std::cout << matTr << std::endl; mathtools::affine::Frame<3>::Ptr frame_cur; frame_cur = mathtools::affine::Frame<3>::CreateFrame(matTr.col(3),matTr.col(0),matTr.col(1),matTr.col(2)); camera::Extrinsics::Ptr extr(new camera::Extrinsics(frame_cur)); camera::Camera::Ptr camimg(new camera::Camera(cam->getIntrinsics(),extr)); } if(key=='q' || key=='Q') { fini = true; } } } cv::destroyWindow(WINDOW_NAME); capture.release(); return 0; } <|endoftext|>
<commit_before>#include <boost/program_options.hpp> #include "opencl_fft/clFFT.h" #include <CL/cl.h> int main(int argc, char **argv) { // Get platform and device information cl_platform_id platform_id = NULL; cl_device_id device_id = NULL; cl_uint ret_num_devices; cl_uint ret_num_platforms; cl_int ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms); ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices); // Create an OpenCL context cl_context context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret); // Create a command queue cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &ret); // clFFT_Direction dir = clFFT_Forward; clFFT_Dim3 n = { 1024, 1, 1 }; clFFT_DataFormat dataFormat = clFFT_SplitComplexFormat; clFFT_Dimension dim = clFFT_1D; cl_int *error_code = (cl_int *)malloc(sizeof(cl_int)); clFFT_Plan fftPlan = clFFT_CreatePlan(context, n, dim, dataFormat, error_code); // Clean up ret = clFlush(command_queue); ret = clFinish(command_queue); ret = clReleaseCommandQueue(command_queue); ret = clReleaseContext(context); exit(0); } // #define __NO_STD_VECTOR // Use cl::vector instead of STL version // #include "cl.hpp" // // #include <iostream> // //using namespace std; // //void displayPlatformInfo(cl::vector<cl::Platform>platformList, // int deviceType) //{ // // print out some device specific information // cout << "Platform number is: " << platformList.size() << endl; // // string platformVendor; // platformList[0].getInfo((cl_platform_info)CL_PLATFORM_VENDOR, // &platformVendor); // // cout << "device Type " // << ((deviceType == CL_DEVICE_TYPE_GPU) ? "GPU" : "CPU") << endl; // cout << "Platform is by: " << platformVendor << "\n"; //} // //int main(int argc, char **argv) //{ // int deviceType = CL_DEVICE_TYPE_GPU; // CL_DEVICE_TYPE_CPU; // // cl::vector<cl::Platform> platformList; // cl::Platform::get(&platformList); // // displayPlatformInfo(platformList, deviceType); // // cl_context_properties cprops[3] = // { CL_CONTEXT_PLATFORM, // (cl_context_properties)(platformList[0])(), 0 }; // // cl::Context context(deviceType, cprops); // // cl::vector<cl::Device> devices = // context.getInfo<CL_CONTEXT_DEVICES>(); // // #ifdef PROFILING // cl::CommandQueue queue(context, devices[0], // CL_QUEUE_PROFILING_ENABLE); // #else // ifdef PROFILING // cl::CommandQueue queue(context, devices[0], 0); // #endif // ifdef PROFILING //} <commit_msg>remove main.cpp (code has been moved to unit test)<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // 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. #include <iostream> #include "object.h" #include "concurrency_copy.h" namespace gc { ConcurrencyCopy::ConcurrencyCopy(void) : copy_mutex_() , copy_cond_(copy_mutex_) , collect_mutex_() , collect_cond_(collect_mutex_) , thread_([this]{ concurrency_closure(); }) { heaptr_ = new byte_t[kSemispaceSize * 2]; CHAOS_CHECK(heaptr_ != nullptr, "create semispace failed"); fromspace_ = heaptr_ + kSemispaceSize; tospace_ = heaptr_; allocptr_ = tospace_; thread_.start(); } ConcurrencyCopy::~ConcurrencyCopy(void) { running_ = false; copy_cond_.notify_one(); thread_.join(); delete [] heaptr_; } void* ConcurrencyCopy::alloc(std::size_t n) { if (allocptr_ + n > tospace_ + kSemispaceSize) collect(); Chaos::ScopedLock<Chaos::Mutex> g(mutex_); auto* p = allocptr_; allocptr_ += n; return p; } void ConcurrencyCopy::concurrency_closure(void) { while (running_) { { Chaos::ScopedLock<Chaos::Mutex> g(copy_mutex_); while (running_ && !copying_) copy_cond_.wait(); if (!running_) break; } collecting(); copying_ = false; } } BaseObject* ConcurrencyCopy::forward(BaseObject* from_ref) { auto* to_ref = from_ref->forward(); if (to_ref == nullptr) { to_ref = copy(from_ref); ++object_counter_; } return Chaos::down_cast<BaseObject*>(to_ref); } BaseObject* ConcurrencyCopy::copy(BaseObject* from_ref) { auto* p = allocptr_; allocptr_ += from_ref->get_size(); CHAOS_CHECK(allocptr_ <= tospace_ + kSemispaceSize, "out of memory"); BaseObject* to_ref{}; if (from_ref->is_int()) to_ref = new (p) Int(std::move(*Chaos::down_cast<Int*>(from_ref))); else if (from_ref->is_pair()) to_ref = new (p) Pair(std::move(*Chaos::down_cast<Pair*>(from_ref))); CHAOS_CHECK(to_ref != nullptr, "copy object failed"); from_ref->set_forward(to_ref); worklist_.push_back(to_ref); return to_ref; } void ConcurrencyCopy::collecting(void) { std::size_t old_count = object_counter_; object_counter_ = 0; { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); // semispace flip std::swap(fromspace_, tospace_); allocptr_ = tospace_; for (auto& obj : roots_) obj = forward(obj); } collecting_ = true; collect_cond_.notify_one(); while (true) { if (worklist_.empty()) break; auto* obj = worklist_.back(); worklist_.pop_back(); if (obj->is_pair()) { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); auto* pair = Chaos::down_cast<Pair*>(obj); auto* first = pair->first(); if (first != nullptr) pair->set_first(forward(first)); auto* second = pair->second(); if (second != nullptr) pair->set_second(forward(second)); } } std::cout << "[" << old_count << "] objects alive before collecting, " << "[" << object_counter_ << "] objects alive after collecting." << std::endl; } ConcurrencyCopy& ConcurrencyCopy::get_instance(void) { static ConcurrencyCopy ins; return ins; } void ConcurrencyCopy::collect(void) { copying_ = true; collecting_ = false; copy_cond_.notify_one(); { Chaos::ScopedLock<Chaos::Mutex> g(collect_mutex_); while (!collecting_) collect_cond_.wait(); } } BaseObject* ConcurrencyCopy::put_in(int value) { auto* obj = new (alloc(sizeof(Int))) Int(); obj->set_value(value); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* ConcurrencyCopy::put_in(BaseObject* first, BaseObject* second) { auto* obj = new (alloc(sizeof(Pair))) Pair(); if (first != nullptr) obj->set_first(first); if (second != nullptr) obj->set_second(second); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* ConcurrencyCopy::fetch_out(void) { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); auto* obj = roots_.back(); roots_.pop_back(); return obj; } } <commit_msg>:bug: fix(ConcurrencyCopy): fixed concurrency copying gc<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // 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. #include <iostream> #include "object.h" #include "concurrency_copy.h" namespace gc { ConcurrencyCopy::ConcurrencyCopy(void) : copy_mutex_() , copy_cond_(copy_mutex_) , collect_mutex_() , collect_cond_(collect_mutex_) , thread_([this]{ concurrency_closure(); }) { heaptr_ = new byte_t[kSemispaceSize * 2]; CHAOS_CHECK(heaptr_ != nullptr, "create semispace failed"); fromspace_ = heaptr_ + kSemispaceSize; tospace_ = heaptr_; allocptr_ = tospace_; thread_.start(); } ConcurrencyCopy::~ConcurrencyCopy(void) { running_ = false; copy_cond_.notify_one(); thread_.join(); delete [] heaptr_; } void* ConcurrencyCopy::alloc(std::size_t n) { if (allocptr_ + n > tospace_ + kSemispaceSize) collect(); Chaos::ScopedLock<Chaos::Mutex> g(mutex_); auto* p = allocptr_; allocptr_ += n; return p; } void ConcurrencyCopy::concurrency_closure(void) { while (running_) { { Chaos::ScopedLock<Chaos::Mutex> g(copy_mutex_); while (running_ && !copying_) copy_cond_.wait(); if (!running_) break; } collecting(); copying_ = false; } } BaseObject* ConcurrencyCopy::forward(BaseObject* from_ref) { auto* to_ref = from_ref->forward(); if (to_ref == nullptr) { to_ref = copy(from_ref); ++object_counter_; } return Chaos::down_cast<BaseObject*>(to_ref); } BaseObject* ConcurrencyCopy::copy(BaseObject* from_ref) { auto* p = allocptr_; allocptr_ += from_ref->get_size(); CHAOS_CHECK(allocptr_ <= tospace_ + kSemispaceSize, "out of memory"); BaseObject* to_ref{}; if (from_ref->is_int()) to_ref = new (p) Int(std::move(*Chaos::down_cast<Int*>(from_ref))); else if (from_ref->is_pair()) to_ref = new (p) Pair(std::move(*Chaos::down_cast<Pair*>(from_ref))); CHAOS_CHECK(to_ref != nullptr, "copy object failed"); from_ref->set_forward(to_ref); worklist_.push_back(to_ref); return to_ref; } void ConcurrencyCopy::collecting(void) { std::size_t old_count = object_counter_; object_counter_ = 0; { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); // semispace flip std::swap(fromspace_, tospace_); allocptr_ = tospace_; for (auto& obj : roots_) obj = forward(obj); } collecting_ = true; collect_cond_.notify_one(); while (true) { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); if (worklist_.empty()) break; auto* obj = worklist_.back(); worklist_.pop_back(); if (obj->is_pair()) { auto* pair = Chaos::down_cast<Pair*>(obj); auto* first = pair->first(); if (first != nullptr) pair->set_first(forward(first)); auto* second = pair->second(); if (second != nullptr) pair->set_second(forward(second)); } } std::cout << "[" << old_count << "] objects alive before collecting, " << "[" << object_counter_ << "] objects alive after collecting." << std::endl; } ConcurrencyCopy& ConcurrencyCopy::get_instance(void) { static ConcurrencyCopy ins; return ins; } void ConcurrencyCopy::collect(void) { copying_ = true; collecting_ = false; copy_cond_.notify_one(); { Chaos::ScopedLock<Chaos::Mutex> g(collect_mutex_); while (!collecting_) collect_cond_.wait(); } } BaseObject* ConcurrencyCopy::put_in(int value) { auto* obj = new (alloc(sizeof(Int))) Int(); obj->set_value(value); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* ConcurrencyCopy::put_in(BaseObject* first, BaseObject* second) { auto* obj = new (alloc(sizeof(Pair))) Pair(); if (first != nullptr) obj->set_first(first); if (second != nullptr) obj->set_second(second); roots_.push_back(obj); ++object_counter_; return obj; } BaseObject* ConcurrencyCopy::fetch_out(void) { Chaos::ScopedLock<Chaos::Mutex> g(mutex_); auto* obj = roots_.back(); roots_.pop_back(); return obj; } } <|endoftext|>
<commit_before>#pragma once #include <QStandardItemModel> #include <QTimer> #include <boost/noncopyable.hpp> #include <pajlada/signals/signal.hpp> #include <vector> #include "debug/AssertInGuiThread.hpp" namespace chatterino { template <typename TVectorItem> struct SignalVectorItemArgs { const TVectorItem &item; int index; void *caller; }; template <typename TVectorItem> class ReadOnlySignalVector : boost::noncopyable { public: ReadOnlySignalVector() { QObject::connect(&this->itemsChangedTimer, &QTimer::timeout, [this] { this->delayedItemsChanged.invoke(); }); this->itemsChangedTimer.setInterval(100); this->itemsChangedTimer.setSingleShot(true); } virtual ~ReadOnlySignalVector() = default; pajlada::Signals::Signal<SignalVectorItemArgs<TVectorItem>> itemInserted; pajlada::Signals::Signal<SignalVectorItemArgs<TVectorItem>> itemRemoved; pajlada::Signals::NoArgSignal delayedItemsChanged; const std::vector<TVectorItem> &getVector() const { assertInGuiThread(); return this->vector; } void invokeDelayedItemsChanged() { assertInGuiThread(); if (!this->itemsChangedTimer.isActive()) { itemsChangedTimer.start(); } } protected: std::vector<TVectorItem> vector; QTimer itemsChangedTimer; }; template <typename TVectorItem> class BaseSignalVector : public ReadOnlySignalVector<TVectorItem> { public: // returns the actual index of the inserted item virtual int insertItem(const TVectorItem &item, int proposedIndex = -1, void *caller = 0) = 0; void removeItem(int index, void *caller = 0) { assertInGuiThread(); assert(index >= 0 && index < this->vector.size()); TVectorItem item = this->vector[index]; this->vector.erase(this->vector.begin() + index); SignalVectorItemArgs<TVectorItem> args{item, index, caller}; this->itemRemoved.invoke(args); this->invokeDelayedItemsChanged(); } int appendItem(const TVectorItem &item, void *caller = 0) { return this->insertItem(item, -1, caller); } }; template <typename TVectorItem> class UnsortedSignalVector : public BaseSignalVector<TVectorItem> { public: virtual int insertItem(const TVectorItem &item, int index = -1, void *caller = 0) override { assertInGuiThread(); if (index == -1) { index = this->vector.size(); } else { assert(index >= 0 && index <= this->vector.size()); } this->vector.insert(this->vector.begin() + index, item); SignalVectorItemArgs<TVectorItem> args{item, index, caller}; this->itemInserted.invoke(args); this->invokeDelayedItemsChanged(); return index; } }; template <typename TVectorItem, typename Compare> class SortedSignalVector : public BaseSignalVector<TVectorItem> { public: virtual int insertItem(const TVectorItem &item, int = -1, void *caller = nullptr) override { assertInGuiThread(); auto it = std::lower_bound(this->vector.begin(), this->vector.end(), item, Compare{}); int index = it - this->vector.begin(); this->vector.insert(it, item); SignalVectorItemArgs<TVectorItem> args{item, index, caller}; this->itemInserted.invoke(args); this->invokeDelayedItemsChanged(); return index; } }; } // namespace chatterino <commit_msg>added isSorted method to signalvector<commit_after>#pragma once #include <QStandardItemModel> #include <QTimer> #include <boost/noncopyable.hpp> #include <pajlada/signals/signal.hpp> #include <vector> #include "debug/AssertInGuiThread.hpp" namespace chatterino { template <typename TVectorItem> struct SignalVectorItemArgs { const TVectorItem &item; int index; void *caller; }; template <typename TVectorItem> class ReadOnlySignalVector : boost::noncopyable { public: ReadOnlySignalVector() { QObject::connect(&this->itemsChangedTimer, &QTimer::timeout, [this] { this->delayedItemsChanged.invoke(); }); this->itemsChangedTimer.setInterval(100); this->itemsChangedTimer.setSingleShot(true); } virtual ~ReadOnlySignalVector() = default; pajlada::Signals::Signal<SignalVectorItemArgs<TVectorItem>> itemInserted; pajlada::Signals::Signal<SignalVectorItemArgs<TVectorItem>> itemRemoved; pajlada::Signals::NoArgSignal delayedItemsChanged; const std::vector<TVectorItem> &getVector() const { assertInGuiThread(); return this->vector; } void invokeDelayedItemsChanged() { assertInGuiThread(); if (!this->itemsChangedTimer.isActive()) { itemsChangedTimer.start(); } } virtual bool isSorted() const = 0; protected: std::vector<TVectorItem> vector; QTimer itemsChangedTimer; }; template <typename TVectorItem> class BaseSignalVector : public ReadOnlySignalVector<TVectorItem> { public: // returns the actual index of the inserted item virtual int insertItem(const TVectorItem &item, int proposedIndex = -1, void *caller = 0) = 0; void removeItem(int index, void *caller = 0) { assertInGuiThread(); assert(index >= 0 && index < this->vector.size()); TVectorItem item = this->vector[index]; this->vector.erase(this->vector.begin() + index); SignalVectorItemArgs<TVectorItem> args{item, index, caller}; this->itemRemoved.invoke(args); this->invokeDelayedItemsChanged(); } int appendItem(const TVectorItem &item, void *caller = 0) { return this->insertItem(item, -1, caller); } }; template <typename TVectorItem> class UnsortedSignalVector : public BaseSignalVector<TVectorItem> { public: virtual int insertItem(const TVectorItem &item, int index = -1, void *caller = 0) override { assertInGuiThread(); if (index == -1) { index = this->vector.size(); } else { assert(index >= 0 && index <= this->vector.size()); } this->vector.insert(this->vector.begin() + index, item); SignalVectorItemArgs<TVectorItem> args{item, index, caller}; this->itemInserted.invoke(args); this->invokeDelayedItemsChanged(); return index; } virtual bool isSorted() const override { return false; } }; template <typename TVectorItem, typename Compare> class SortedSignalVector : public BaseSignalVector<TVectorItem> { public: virtual int insertItem(const TVectorItem &item, int = -1, void *caller = nullptr) override { assertInGuiThread(); auto it = std::lower_bound(this->vector.begin(), this->vector.end(), item, Compare{}); int index = it - this->vector.begin(); this->vector.insert(it, item); SignalVectorItemArgs<TVectorItem> args{item, index, caller}; this->itemInserted.invoke(args); this->invokeDelayedItemsChanged(); return index; } virtual bool isSorted() const override { return true; } }; } // namespace chatterino <|endoftext|>
<commit_before>// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <random.h> #include <bls/bls_worker.h> #include <utiltime.h> #include <iostream> CBLSWorker blsWorker; void InitBLSTests() { blsWorker.Start(); } void CleanupBLSTests() { blsWorker.Stop(); } static void BuildTestVectors(size_t count, size_t invalidCount, BLSPublicKeyVector& pubKeys, BLSSecretKeyVector& secKeys, BLSSignatureVector& sigs, std::vector<uint256>& msgHashes, std::vector<bool>& invalid) { secKeys.resize(count); pubKeys.resize(count); sigs.resize(count); msgHashes.resize(count); invalid.resize(count); for (size_t i = 0; i < invalidCount; i++) { invalid[i] = true; } Shuffle(invalid.begin(), invalid.end(), FastRandomContext()); for (size_t i = 0; i < count; i++) { secKeys[i].MakeNewKey(); pubKeys[i] = secKeys[i].GetPublicKey(); msgHashes[i] = GetRandHash(); sigs[i] = secKeys[i].Sign(msgHashes[i]); if (invalid[i]) { CBLSSecretKey s; s.MakeNewKey(); sigs[i] = s.Sign(msgHashes[i]); } } } static void BLS_PubKeyAggregate_Normal(benchmark::State& state) { CBLSSecretKey secKey1, secKey2; secKey1.MakeNewKey(); secKey2.MakeNewKey(); CBLSPublicKey pubKey1 = secKey1.GetPublicKey(); CBLSPublicKey pubKey2 = secKey2.GetPublicKey(); // Benchmark. while (state.KeepRunning()) { CBLSPublicKey k(pubKey1); k.AggregateInsecure(pubKey2); } } static void BLS_SecKeyAggregate_Normal(benchmark::State& state) { CBLSSecretKey secKey1, secKey2; secKey1.MakeNewKey(); secKey2.MakeNewKey(); CBLSPublicKey pubKey1 = secKey1.GetPublicKey(); CBLSPublicKey pubKey2 = secKey2.GetPublicKey(); // Benchmark. while (state.KeepRunning()) { CBLSSecretKey k(secKey1); k.AggregateInsecure(secKey2); } } static void BLS_Sign_Normal(benchmark::State& state) { CBLSSecretKey secKey; secKey.MakeNewKey(); CBLSPublicKey pubKey = secKey.GetPublicKey(); // Benchmark. while (state.KeepRunning()) { uint256 hash = GetRandHash(); secKey.Sign(hash); } } static void BLS_Verify_Normal(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 10, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. size_t i = 0; while (state.KeepRunning()) { bool valid = sigs[i].VerifyInsecure(pubKeys[i], msgHashes[i]); if (valid && invalid[i]) { std::cout << "expected invalid but it is valid" << std::endl; assert(false); } else if (!valid && !invalid[i]) { std::cout << "expected valid but it is invalid" << std::endl; assert(false); } i = (i + 1) % pubKeys.size(); } } static void BLS_Verify_LargeBlock(size_t txCount, benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(txCount, 0, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. while (state.KeepRunning()) { for (size_t i = 0; i < pubKeys.size(); i++) { sigs[i].VerifyInsecure(pubKeys[i], msgHashes[i]); } } } static void BLS_Verify_LargeBlock1000(benchmark::State& state) { BLS_Verify_LargeBlock(1000, state); } static void BLS_Verify_LargeBlock10000(benchmark::State& state) { BLS_Verify_LargeBlock(10000, state); } static void BLS_Verify_LargeBlockSelfAggregated(size_t txCount, benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(txCount, 0, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. while (state.KeepRunning()) { CBLSSignature aggSig = CBLSSignature::AggregateInsecure(sigs); aggSig.VerifyInsecureAggregated(pubKeys, msgHashes); } } static void BLS_Verify_LargeBlockSelfAggregated1000(benchmark::State& state) { BLS_Verify_LargeBlockSelfAggregated(1000, state); } static void BLS_Verify_LargeBlockSelfAggregated10000(benchmark::State& state) { BLS_Verify_LargeBlockSelfAggregated(10000, state); } static void BLS_Verify_LargeAggregatedBlock(size_t txCount, benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(txCount, 0, pubKeys, secKeys, sigs, msgHashes, invalid); CBLSSignature aggSig = CBLSSignature::AggregateInsecure(sigs); // Benchmark. while (state.KeepRunning()) { aggSig.VerifyInsecureAggregated(pubKeys, msgHashes); } } static void BLS_Verify_LargeAggregatedBlock1000(benchmark::State& state) { BLS_Verify_LargeAggregatedBlock(1000, state); } static void BLS_Verify_LargeAggregatedBlock10000(benchmark::State& state) { BLS_Verify_LargeAggregatedBlock(10000, state); } static void BLS_Verify_LargeAggregatedBlock1000PreVerified(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 0, pubKeys, secKeys, sigs, msgHashes, invalid); CBLSSignature aggSig = CBLSSignature::AggregateInsecure(sigs); std::set<size_t> prevalidated; while (prevalidated.size() < 900) { int idx = GetRandInt((int)pubKeys.size()); if (prevalidated.count((size_t)idx)) { continue; } prevalidated.emplace((size_t)idx); } // Benchmark. while (state.KeepRunning()) { BLSPublicKeyVector nonvalidatedPubKeys; std::vector<uint256> nonvalidatedHashes; nonvalidatedPubKeys.reserve(pubKeys.size()); nonvalidatedHashes.reserve(msgHashes.size()); for (size_t i = 0; i < sigs.size(); i++) { if (prevalidated.count(i)) { continue; } nonvalidatedPubKeys.emplace_back(pubKeys[i]); nonvalidatedHashes.emplace_back(msgHashes[i]); } CBLSSignature aggSigCopy = aggSig; for (auto idx : prevalidated) { aggSigCopy.SubInsecure(sigs[idx]); } bool valid = aggSigCopy.VerifyInsecureAggregated(nonvalidatedPubKeys, nonvalidatedHashes); assert(valid); } } static void BLS_Verify_Batched(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 10, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. size_t i = 0; size_t j = 0; size_t batchSize = 16; while (state.KeepRunning()) { j++; if ((j % batchSize) != 0) { continue; } BLSPublicKeyVector testPubKeys; BLSSignatureVector testSigs; std::vector<uint256> testMsgHashes; testPubKeys.reserve(batchSize); testSigs.reserve(batchSize); testMsgHashes.reserve(batchSize); size_t startI = i; for (size_t k = 0; k < batchSize; k++) { testPubKeys.emplace_back(pubKeys[i]); testSigs.emplace_back(sigs[i]); testMsgHashes.emplace_back(msgHashes[i]); i = (i + 1) % pubKeys.size(); } CBLSSignature batchSig = CBLSSignature::AggregateInsecure(testSigs); bool batchValid = batchSig.VerifyInsecureAggregated(testPubKeys, testMsgHashes); std::vector<bool> valid; if (batchValid) { valid.assign(batchSize, true); } else { for (size_t k = 0; k < batchSize; k++) { bool valid1 = testSigs[k].VerifyInsecure(testPubKeys[k], testMsgHashes[k]); valid.emplace_back(valid1); } } for (size_t k = 0; k < batchSize; k++) { if (valid[k] && invalid[(startI + k) % pubKeys.size()]) { std::cout << "expected invalid but it is valid" << std::endl; assert(false); } else if (!valid[k] && !invalid[(startI + k) % pubKeys.size()]) { std::cout << "expected valid but it is invalid" << std::endl; assert(false); } } } } static void BLS_Verify_BatchedParallel(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 10, pubKeys, secKeys, sigs, msgHashes, invalid); std::list<std::pair<size_t, std::future<bool>>> futures; volatile bool cancel = false; auto cancelCond = [&]() { return cancel; }; // Benchmark. size_t i = 0; while (state.KeepRunning()) { if (futures.size() < 100) { while (futures.size() < 10000) { auto f = blsWorker.AsyncVerifySig(sigs[i], pubKeys[i], msgHashes[i], cancelCond); futures.emplace_back(std::make_pair(i, std::move(f))); i = (i + 1) % pubKeys.size(); } } auto fp = std::move(futures.front()); futures.pop_front(); size_t j = fp.first; bool valid = fp.second.get(); if (valid && invalid[j]) { std::cout << "expected invalid but it is valid" << std::endl; assert(false); } else if (!valid && !invalid[j]) { std::cout << "expected valid but it is invalid" << std::endl; assert(false); } } cancel = true; while (blsWorker.IsAsyncVerifyInProgress()) { MilliSleep(100); } } BENCHMARK(BLS_PubKeyAggregate_Normal, 300 * 1000) BENCHMARK(BLS_SecKeyAggregate_Normal, 700 * 1000) BENCHMARK(BLS_Sign_Normal, 600) BENCHMARK(BLS_Verify_Normal, 350) BENCHMARK(BLS_Verify_LargeBlock1000, 1) BENCHMARK(BLS_Verify_LargeBlockSelfAggregated1000, 1) BENCHMARK(BLS_Verify_LargeBlockSelfAggregated10000, 1) BENCHMARK(BLS_Verify_LargeAggregatedBlock1000, 1) BENCHMARK(BLS_Verify_LargeAggregatedBlock10000, 1) BENCHMARK(BLS_Verify_LargeAggregatedBlock1000PreVerified, 5) BENCHMARK(BLS_Verify_Batched, 500) BENCHMARK(BLS_Verify_BatchedParallel, 1000) <commit_msg>bench: Tweak BLS benchmarks (#4012)<commit_after>// Copyright (c) 2018-2019 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <random.h> #include <bls/bls_worker.h> #include <utiltime.h> #include <iostream> CBLSWorker blsWorker; void InitBLSTests() { blsWorker.Start(); } void CleanupBLSTests() { blsWorker.Stop(); } static void BuildTestVectors(size_t count, size_t invalidCount, BLSPublicKeyVector& pubKeys, BLSSecretKeyVector& secKeys, BLSSignatureVector& sigs, std::vector<uint256>& msgHashes, std::vector<bool>& invalid) { secKeys.resize(count); pubKeys.resize(count); sigs.resize(count); msgHashes.resize(count); invalid.resize(count); for (size_t i = 0; i < invalidCount; i++) { invalid[i] = true; } Shuffle(invalid.begin(), invalid.end(), FastRandomContext()); for (size_t i = 0; i < count; i++) { secKeys[i].MakeNewKey(); pubKeys[i] = secKeys[i].GetPublicKey(); msgHashes[i] = GetRandHash(); sigs[i] = secKeys[i].Sign(msgHashes[i]); if (invalid[i]) { CBLSSecretKey s; s.MakeNewKey(); sigs[i] = s.Sign(msgHashes[i]); } } } static void BLS_PubKeyAggregate_Normal(benchmark::State& state) { CBLSSecretKey secKey1, secKey2; secKey1.MakeNewKey(); secKey2.MakeNewKey(); CBLSPublicKey pubKey1 = secKey1.GetPublicKey(); CBLSPublicKey pubKey2 = secKey2.GetPublicKey(); // Benchmark. while (state.KeepRunning()) { pubKey1.AggregateInsecure(pubKey2); } } static void BLS_SecKeyAggregate_Normal(benchmark::State& state) { CBLSSecretKey secKey1, secKey2; secKey1.MakeNewKey(); secKey2.MakeNewKey(); // Benchmark. while (state.KeepRunning()) { secKey1.AggregateInsecure(secKey2); } } static void BLS_SignatureAggregate_Normal(benchmark::State& state) { uint256 hash = GetRandHash(); CBLSSecretKey secKey1, secKey2; secKey1.MakeNewKey(); secKey2.MakeNewKey(); CBLSSignature sig1 = secKey1.Sign(hash); CBLSSignature sig2 = secKey2.Sign(hash); // Benchmark. while (state.KeepRunning()) { sig1.AggregateInsecure(sig2); } } static void BLS_Sign_Normal(benchmark::State& state) { CBLSSecretKey secKey; secKey.MakeNewKey(); CBLSPublicKey pubKey = secKey.GetPublicKey(); // Benchmark. while (state.KeepRunning()) { uint256 hash = GetRandHash(); secKey.Sign(hash); } } static void BLS_Verify_Normal(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 10, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. size_t i = 0; while (state.KeepRunning()) { bool valid = sigs[i].VerifyInsecure(pubKeys[i], msgHashes[i]); if (valid && invalid[i]) { std::cout << "expected invalid but it is valid" << std::endl; assert(false); } else if (!valid && !invalid[i]) { std::cout << "expected valid but it is invalid" << std::endl; assert(false); } i = (i + 1) % pubKeys.size(); } } static void BLS_Verify_LargeBlock(size_t txCount, benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(txCount, 0, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. while (state.KeepRunning()) { for (size_t i = 0; i < pubKeys.size(); i++) { sigs[i].VerifyInsecure(pubKeys[i], msgHashes[i]); } } } static void BLS_Verify_LargeBlock100(benchmark::State& state) { BLS_Verify_LargeBlock(100, state); } static void BLS_Verify_LargeBlock1000(benchmark::State& state) { BLS_Verify_LargeBlock(1000, state); } static void BLS_Verify_LargeBlockSelfAggregated(size_t txCount, benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(txCount, 0, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. while (state.KeepRunning()) { CBLSSignature aggSig = CBLSSignature::AggregateInsecure(sigs); aggSig.VerifyInsecureAggregated(pubKeys, msgHashes); } } static void BLS_Verify_LargeBlockSelfAggregated100(benchmark::State& state) { BLS_Verify_LargeBlockSelfAggregated(100, state); } static void BLS_Verify_LargeBlockSelfAggregated1000(benchmark::State& state) { BLS_Verify_LargeBlockSelfAggregated(1000, state); } static void BLS_Verify_LargeAggregatedBlock(size_t txCount, benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(txCount, 0, pubKeys, secKeys, sigs, msgHashes, invalid); CBLSSignature aggSig = CBLSSignature::AggregateInsecure(sigs); // Benchmark. while (state.KeepRunning()) { aggSig.VerifyInsecureAggregated(pubKeys, msgHashes); } } static void BLS_Verify_LargeAggregatedBlock100(benchmark::State& state) { BLS_Verify_LargeAggregatedBlock(100, state); } static void BLS_Verify_LargeAggregatedBlock1000(benchmark::State& state) { BLS_Verify_LargeAggregatedBlock(1000, state); } static void BLS_Verify_LargeAggregatedBlock1000PreVerified(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 0, pubKeys, secKeys, sigs, msgHashes, invalid); CBLSSignature aggSig = CBLSSignature::AggregateInsecure(sigs); std::set<size_t> prevalidated; while (prevalidated.size() < 900) { int idx = GetRandInt((int)pubKeys.size()); if (prevalidated.count((size_t)idx)) { continue; } prevalidated.emplace((size_t)idx); } // Benchmark. while (state.KeepRunning()) { BLSPublicKeyVector nonvalidatedPubKeys; std::vector<uint256> nonvalidatedHashes; nonvalidatedPubKeys.reserve(pubKeys.size()); nonvalidatedHashes.reserve(msgHashes.size()); for (size_t i = 0; i < sigs.size(); i++) { if (prevalidated.count(i)) { continue; } nonvalidatedPubKeys.emplace_back(pubKeys[i]); nonvalidatedHashes.emplace_back(msgHashes[i]); } CBLSSignature aggSigCopy = aggSig; for (auto idx : prevalidated) { aggSigCopy.SubInsecure(sigs[idx]); } bool valid = aggSigCopy.VerifyInsecureAggregated(nonvalidatedPubKeys, nonvalidatedHashes); assert(valid); } } static void BLS_Verify_Batched(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 10, pubKeys, secKeys, sigs, msgHashes, invalid); // Benchmark. size_t i = 0; size_t j = 0; size_t batchSize = 16; while (state.KeepRunning()) { j++; if ((j % batchSize) != 0) { continue; } BLSPublicKeyVector testPubKeys; BLSSignatureVector testSigs; std::vector<uint256> testMsgHashes; testPubKeys.reserve(batchSize); testSigs.reserve(batchSize); testMsgHashes.reserve(batchSize); size_t startI = i; for (size_t k = 0; k < batchSize; k++) { testPubKeys.emplace_back(pubKeys[i]); testSigs.emplace_back(sigs[i]); testMsgHashes.emplace_back(msgHashes[i]); i = (i + 1) % pubKeys.size(); } CBLSSignature batchSig = CBLSSignature::AggregateInsecure(testSigs); bool batchValid = batchSig.VerifyInsecureAggregated(testPubKeys, testMsgHashes); std::vector<bool> valid; if (batchValid) { valid.assign(batchSize, true); } else { for (size_t k = 0; k < batchSize; k++) { bool valid1 = testSigs[k].VerifyInsecure(testPubKeys[k], testMsgHashes[k]); valid.emplace_back(valid1); } } for (size_t k = 0; k < batchSize; k++) { if (valid[k] && invalid[(startI + k) % pubKeys.size()]) { std::cout << "expected invalid but it is valid" << std::endl; assert(false); } else if (!valid[k] && !invalid[(startI + k) % pubKeys.size()]) { std::cout << "expected valid but it is invalid" << std::endl; assert(false); } } } } static void BLS_Verify_BatchedParallel(benchmark::State& state) { BLSPublicKeyVector pubKeys; BLSSecretKeyVector secKeys; BLSSignatureVector sigs; std::vector<uint256> msgHashes; std::vector<bool> invalid; BuildTestVectors(1000, 10, pubKeys, secKeys, sigs, msgHashes, invalid); std::list<std::pair<size_t, std::future<bool>>> futures; volatile bool cancel = false; auto cancelCond = [&]() { return cancel; }; // Benchmark. size_t i = 0; while (state.KeepRunning()) { if (futures.size() < 100) { while (futures.size() < 10000) { auto f = blsWorker.AsyncVerifySig(sigs[i], pubKeys[i], msgHashes[i], cancelCond); futures.emplace_back(std::make_pair(i, std::move(f))); i = (i + 1) % pubKeys.size(); } } auto fp = std::move(futures.front()); futures.pop_front(); size_t j = fp.first; bool valid = fp.second.get(); if (valid && invalid[j]) { std::cout << "expected invalid but it is valid" << std::endl; assert(false); } else if (!valid && !invalid[j]) { std::cout << "expected valid but it is invalid" << std::endl; assert(false); } } cancel = true; while (blsWorker.IsAsyncVerifyInProgress()) { MilliSleep(100); } } BENCHMARK(BLS_PubKeyAggregate_Normal, 140 * 1000) BENCHMARK(BLS_SecKeyAggregate_Normal, 800 * 1000) BENCHMARK(BLS_SignatureAggregate_Normal, 100 * 1000) BENCHMARK(BLS_Sign_Normal, 600) BENCHMARK(BLS_Verify_Normal, 350) BENCHMARK(BLS_Verify_LargeBlock100, 3) BENCHMARK(BLS_Verify_LargeBlock1000, 1) BENCHMARK(BLS_Verify_LargeBlockSelfAggregated100, 7) BENCHMARK(BLS_Verify_LargeBlockSelfAggregated1000, 1) BENCHMARK(BLS_Verify_LargeAggregatedBlock100, 7) BENCHMARK(BLS_Verify_LargeAggregatedBlock1000, 1) BENCHMARK(BLS_Verify_LargeAggregatedBlock1000PreVerified, 5) BENCHMARK(BLS_Verify_Batched, 500) BENCHMARK(BLS_Verify_BatchedParallel, 1000) <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // HIMG, by Marcus Geelnard, 2015 // // This is free and unencumbered software released into the public domain. // // See LICENSE for details. //----------------------------------------------------------------------------- #include <chrono> #include <cstdint> #include <fstream> #include <iostream> #include <FreeImage.h> #include "decoder.h" #include "encoder.h" namespace { const int kNumIterations = 30; enum BenchmarkMode { Decode, Encode }; class TimeMeasure { public: void Start() { m_start = std::chrono::system_clock::now(); } double Duration() const { std::chrono::system_clock::time_point t = std::chrono::system_clock::now(); return static_cast<double>( std::chrono::duration_cast<std::chrono::milliseconds>(t - m_start) .count()); } private: std::chrono::system_clock::time_point m_start; }; void ShowUsage(const char *arg0) { std::cout << "Usage: " << arg0 << " [-d][-e] image" << std::endl; std::cout << " -d Decode (default)" << std::endl; std::cout << " -e Encode" << std::endl; } bool LoadFile(const std::string &file_name, std::vector<uint8_t> *buffer) { // Open file. std::ifstream f(file_name.c_str(), std::ifstream::in | std::ofstream::binary); if (!f.good()) { std::cout << "Unable to read file " << file_name << std::endl; return false; } // Get file size. f.seekg(0, std::ifstream::end); int file_size = static_cast<int>(f.tellg()); f.seekg(0, std::ifstream::beg); std::cout << "File size: " << file_size << std::endl; // Read the file data into our buffer. buffer->resize(file_size); f.read(reinterpret_cast<char *>(buffer->data()), file_size); return true; } } // namespace int main(int argc, const char **argv) { // Parse arguments. BenchmarkMode benchmark_mode = Decode; std::string file_name; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] == '-' && arg[1] != 0 && arg[2] == 0) { if (arg[1] == 'd') benchmark_mode = Decode; else if (arg[1] == 'e') benchmark_mode = Encode; } else if (file_name.empty()) { file_name = std::string(arg); } else { ShowUsage(argv[0]); return 0; } } if (file_name.empty()) { ShowUsage(argv[0]); return 0; } // Load the data from a file into memory. std::vector<uint8_t> buffer; LoadFile(file_name, &buffer); FreeImage_Initialise(); TimeMeasure total_measure; total_measure.Start(); double min_dt = -1.0; for (int iteration = 0; iteration < kNumIterations; ++iteration) { TimeMeasure one_measure; one_measure.Start(); if (benchmark_mode == Decode) { // Decode the image. // TODO(m): Add support for other file format decoding (FreeImage, // libjpeg-turbo etc). himg::Decoder decoder; if (!decoder.Decode(buffer.data(), buffer.size())) { std::cout << "Unable to decode image." << std::endl; return -1; } } else { // TODO(m): Implement me! } double dt = one_measure.Duration(); if (min_dt < 0.0 || dt < min_dt) { min_dt = dt; } } double average = total_measure.Duration() / static_cast<double>(kNumIterations); std::cout << " Min: " << min_dt << " ms\n"; std::cout << "Average: " << average << " ms\n"; FreeImage_DeInitialise(); return 0; } <commit_msg>Added FreeImage decoding to the benchmark<commit_after>//----------------------------------------------------------------------------- // HIMG, by Marcus Geelnard, 2015 // // This is free and unencumbered software released into the public domain. // // See LICENSE for details. //----------------------------------------------------------------------------- #include <chrono> #include <cstdint> #include <fstream> #include <iostream> #include <FreeImage.h> #include "decoder.h" #include "encoder.h" namespace { const int kNumIterations = 30; enum BenchmarkMode { Decode, Encode }; class TimeMeasure { public: void Start() { m_start = std::chrono::system_clock::now(); } double Duration() const { std::chrono::system_clock::time_point t = std::chrono::system_clock::now(); return static_cast<double>( std::chrono::duration_cast<std::chrono::milliseconds>(t - m_start) .count()); } private: std::chrono::system_clock::time_point m_start; }; bool IsHimg(const std::vector<uint8_t> &buffer) { return buffer.size() >= 12 && buffer[0] == 'R' && buffer[1] == 'I' && buffer[2] == 'F' && buffer[3] == 'F' && buffer[8] == 'H' && buffer[9] == 'I' && buffer[10] == 'M' && buffer[11] == 'G'; } void ShowUsage(const char *arg0) { std::cout << "Usage: " << arg0 << " [-d][-e] image" << std::endl; std::cout << " -d Decode (default)" << std::endl; std::cout << " -e Encode" << std::endl; } bool LoadFile(const std::string &file_name, std::vector<uint8_t> *buffer) { // Open file. std::ifstream f(file_name.c_str(), std::ifstream::in | std::ofstream::binary); if (!f.good()) { std::cout << "Unable to read file " << file_name << std::endl; return false; } // Get file size. f.seekg(0, std::ifstream::end); int file_size = static_cast<int>(f.tellg()); f.seekg(0, std::ifstream::beg); std::cout << "File size: " << file_size << std::endl; // Read the file data into our buffer. buffer->resize(file_size); f.read(reinterpret_cast<char *>(buffer->data()), file_size); return true; } } // namespace int main(int argc, const char **argv) { // Parse arguments. BenchmarkMode benchmark_mode = Decode; std::string file_name; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] == '-' && arg[1] != 0 && arg[2] == 0) { if (arg[1] == 'd') benchmark_mode = Decode; else if (arg[1] == 'e') benchmark_mode = Encode; } else if (file_name.empty()) { file_name = std::string(arg); } else { ShowUsage(argv[0]); return 0; } } if (file_name.empty()) { ShowUsage(argv[0]); return 0; } // Load the data from a file into memory. std::vector<uint8_t> buffer; LoadFile(file_name, &buffer); FreeImage_Initialise(); TimeMeasure total_measure; total_measure.Start(); double min_dt = -1.0; for (int iteration = 0; iteration < kNumIterations; ++iteration) { TimeMeasure one_measure; one_measure.Start(); if (benchmark_mode == Decode) { // Decode the image. if (IsHimg(buffer)) { // Use the HIMG decoder. himg::Decoder decoder; if (!decoder.Decode(buffer.data(), buffer.size())) { std::cout << "Unable to decode image." << std::endl; return -1; } } else { // Use FreeImage to decode. // TODO(m): Add support for other decoders (libjpeg-turbo!). FIMEMORY* mem = FreeImage_OpenMemory(static_cast<BYTE *>(buffer.data()), buffer.size()); FREE_IMAGE_FORMAT format = FreeImage_GetFIFFromFilename(file_name.c_str()); FIBITMAP *bitmap = FreeImage_LoadFromMemory(format, mem); FreeImage_Unload(bitmap); FreeImage_CloseMemory(mem); } } else { // TODO(m): Implement me! } double dt = one_measure.Duration(); if (min_dt < 0.0 || dt < min_dt) { min_dt = dt; } } double average = total_measure.Duration() / static_cast<double>(kNumIterations); std::cout << " Min: " << min_dt << " ms\n"; std::cout << "Average: " << average << " ms\n"; FreeImage_DeInitialise(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2016 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Rafal Krypa <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ /** * @file smack-labels.cpp * @author Jan Cybulski <[email protected]> * @author Rafal Krypa <[email protected]> * @version 1.0 * @brief Implementation of functions managing smack labels * */ #include <crypt.h> #include <sys/stat.h> #include <sys/smack.h> #include <sys/xattr.h> #include <linux/xattr.h> #include <memory> #include <fts.h> #include <cstring> #include <cstdlib> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <dpl/log/log.h> #include <dpl/errno_string.h> #include "security-manager.h" #include "smack-labels.h" #include "utils.h" namespace SecurityManager { namespace SmackLabels { //! Smack label used for SECURITY_MANAGER_PATH_PUBLIC_RO paths (RO for all apps) const char *const LABEL_FOR_APP_PUBLIC_RO_PATH = "User::Home"; typedef std::function<bool(const FTSENT*)> LabelDecisionFn; static bool labelAll(const FTSENT *ftsent __attribute__((unused))) { return true; } static bool labelDirs(const FTSENT *ftsent) { // label only directories return (S_ISDIR(ftsent->fts_statp->st_mode)); } static bool labelExecs(const FTSENT *ftsent) { // LogDebug("Mode = " << ftsent->fts_statp->st_mode); // this could be helpfull in debugging // label only regular executable files return (S_ISREG(ftsent->fts_statp->st_mode) && (ftsent->fts_statp->st_mode & S_IXUSR)); } static inline void pathSetSmack(const char *path, const std::string &label, const char *xattr_name) { if (smack_set_label_for_path(path, xattr_name, 0, label.c_str())) { LogError("smack_set_label_for_path failed. Path: " << path << " Label:" << label); ThrowMsg(SmackException::FileError, "smack_set_label_for_path failed failed. Path: " << path << " Label: " << label); } } static void dirSetSmack(const std::string &path, const std::string &label, const char *xattr_name, LabelDecisionFn fn) { char *const path_argv[] = {const_cast<char *>(path.c_str()), NULL}; FTSENT *ftsent; auto fts = makeUnique(fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL), fts_close); if (!fts) { LogError("fts_open failed."); ThrowMsg(SmackException::FileError, "fts_open failed."); } while ((ftsent = fts_read(fts.get())) != NULL) { /* Check for error (FTS_ERR) or failed stat(2) (FTS_NS) */ if (ftsent->fts_info == FTS_ERR || ftsent->fts_info == FTS_NS) { LogError("FTS_ERR error or failed stat(2) (FTS_NS)"); ThrowMsg(SmackException::FileError, "FTS_ERR error or failed stat(2) (FTS_NS)"); } /* avoid to tag directories two times */ if (ftsent->fts_info == FTS_D) continue; if (fn(ftsent)) pathSetSmack(ftsent->fts_path, label, xattr_name); } /* If last call to fts_read() set errno, we need to return error. */ if ((errno != 0) && (ftsent == NULL)) { LogError("Last errno from fts_read: " << GetErrnoString(errno)); ThrowMsg(SmackException::FileError, "Last errno from fts_read: " << GetErrnoString(errno)); } } static void labelDir(const std::string &path, const std::string &label, bool set_transmutable, bool set_executables) { // setting access label on everything in given directory and below dirSetSmack(path, label, XATTR_NAME_SMACK, labelAll); // setting transmute on dirs if (set_transmutable) dirSetSmack(path, "TRUE", XATTR_NAME_SMACKTRANSMUTE, labelDirs); // setting SMACK64EXEC labels if (set_executables) dirSetSmack(path, label, XATTR_NAME_SMACKEXEC, &labelExecs); } void setupPath( const std::string &pkgName, const std::string &path, app_install_path_type pathType, const int authorId) { std::string label; bool label_executables, label_transmute; switch (pathType) { case SECURITY_MANAGER_PATH_RW: label = generatePathRWLabel(pkgName); label_executables = false; label_transmute = true; break; case SECURITY_MANAGER_PATH_RO: label = generatePathROLabel(pkgName); label_executables = false; label_transmute = false; break; case SECURITY_MANAGER_PATH_PUBLIC_RO: label.assign(LABEL_FOR_APP_PUBLIC_RO_PATH); label_executables = false; label_transmute = true; break; case SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO: label = generatePathSharedROLabel(pkgName); label_executables = false; label_transmute = true; break; case SECURITY_MANAGER_PATH_TRUSTED_RW: if (authorId < 0) ThrowMsg(SmackException::InvalidParam, "You must define author to use PATH_TRUSED_RW"); label = generatePathTrustedLabel(authorId); label_executables = false; label_transmute = true; break; default: LogError("Path type not known."); Throw(SmackException::InvalidPathType); } return labelDir(path, label, label_transmute, label_executables); } void setupPkgBasePath(const std::string &basePath) { pathSetSmack(basePath.c_str(), LABEL_FOR_APP_PUBLIC_RO_PATH, XATTR_NAME_SMACK); } void setupSharedPrivatePath(const std::string &pkgName, const std::string &path) { pathSetSmack(path.c_str(), generateSharedPrivateLabel(pkgName, path), XATTR_NAME_SMACK); } void generateAppPkgNameFromLabel(const std::string &label, std::string &appName, std::string &pkgName) { static const char pkgPrefix[] = "User::Pkg::"; static const char appPrefix[] = "::App::"; if (label.compare(0, sizeof(pkgPrefix) - 1, pkgPrefix)) ThrowMsg(SmackException::InvalidLabel, "Invalid application process label " << label); size_t pkgStartPos = sizeof(pkgPrefix) - 1; size_t pkgEndPos = label.find(appPrefix, pkgStartPos); if (pkgEndPos != std::string::npos) { LogDebug("Hybrid application process label"); size_t appStartPos = pkgEndPos + sizeof(appPrefix) - 1; appName = label.substr(appStartPos, std::string::npos); pkgName = label.substr(pkgStartPos, pkgEndPos - pkgStartPos); } else { pkgName = label.substr(pkgStartPos, std::string::npos); } if (pkgName.empty()) ThrowMsg(SmackException::InvalidLabel, "No pkgName in Smack label " << label); } std::string generateProcessLabel(const std::string &appName, const std::string &pkgName, bool isHybrid) { std::string label = "User::Pkg::" + pkgName; if (isHybrid) label += "::App::" + appName; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from appName " << appName); return label; } std::string generatePathSharedROLabel(const std::string &pkgName) { std::string label = "User::Pkg::" + pkgName + "::SharedRO"; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName); return label; } std::string generatePathRWLabel(const std::string &pkgName) { std::string label = "User::Pkg::" + pkgName; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName); return label; } std::string generatePathROLabel(const std::string &pkgName) { std::string label = "User::Pkg::" + pkgName + "::RO"; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName); return label; } std::string generateSharedPrivateLabel(const std::string &pkgName, const std::string &path) { // Prefix $1$ causes crypt() to use MD5 function std::string label = "User::Pkg::"; std::string salt = "$1$" + pkgName; const char * cryptLabel = crypt(path.c_str(), salt.c_str()); if (!cryptLabel) { ThrowMsg(SmackException::Base, "crypt error"); } label += cryptLabel; std::replace(label.begin(), label.end(), '/', '%'); if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from path " << path); return label; } template<typename FuncType, typename... ArgsType> static std::string getSmackLabel(FuncType func, ArgsType... args) { char *label; ssize_t labelLen = func(args..., &label); if (labelLen <= 0) ThrowMsg(SmackException::Base, "Error while getting Smack label"); auto labelPtr = makeUnique(label, free); return std::string(labelPtr.get(), labelLen); } std::string getSmackLabelFromSocket(int socketFd) { return getSmackLabel(&smack_new_label_from_socket, socketFd); } std::string getSmackLabelFromPath(const std::string &path) { return getSmackLabel(&smack_new_label_from_path, path.c_str(), XATTR_NAME_SMACK, true); } std::string getSmackLabelFromFd(int fd) { return getSmackLabel(&smack_new_label_from_file, fd, XATTR_NAME_SMACK); } std::string getSmackLabelFromSelf(void) { return getSmackLabel(&smack_new_label_from_self); } std::string getSmackLabelFromPid(pid_t pid) { return getSmackLabel(&smack_new_label_from_process, pid); } std::string generatePathTrustedLabel(const int authorId) { if (authorId < 0) { LogError("Author was not set. It's not possible to generate label for unknown author."); ThrowMsg(SmackException::InvalidLabel, "Could not generate valid label without authorId"); } return "User::Author::" + std::to_string(authorId); } void setSmackLabelForFd(int fd, const std::string &label) { if (smack_set_label_for_file(fd, XATTR_NAME_SMACK, label.c_str())) { LogError("smack_set_label_for_file failed."); ThrowMsg(SmackException::FileError, "smack_set_label_for_file failed."); } } } // namespace SmackLabels } // namespace SecurityManager <commit_msg>Fix in generateAppPkgNameFromLabel implementation<commit_after>/* * Copyright (c) 2014-2016 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Rafal Krypa <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ /** * @file smack-labels.cpp * @author Jan Cybulski <[email protected]> * @author Rafal Krypa <[email protected]> * @version 1.0 * @brief Implementation of functions managing smack labels * */ #include <crypt.h> #include <sys/stat.h> #include <sys/smack.h> #include <sys/xattr.h> #include <linux/xattr.h> #include <memory> #include <fts.h> #include <cstring> #include <cstdlib> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <dpl/log/log.h> #include <dpl/errno_string.h> #include "security-manager.h" #include "smack-labels.h" #include "utils.h" namespace SecurityManager { namespace SmackLabels { //! Smack label used for SECURITY_MANAGER_PATH_PUBLIC_RO paths (RO for all apps) const char *const LABEL_FOR_APP_PUBLIC_RO_PATH = "User::Home"; typedef std::function<bool(const FTSENT*)> LabelDecisionFn; static bool labelAll(const FTSENT *ftsent __attribute__((unused))) { return true; } static bool labelDirs(const FTSENT *ftsent) { // label only directories return (S_ISDIR(ftsent->fts_statp->st_mode)); } static bool labelExecs(const FTSENT *ftsent) { // LogDebug("Mode = " << ftsent->fts_statp->st_mode); // this could be helpfull in debugging // label only regular executable files return (S_ISREG(ftsent->fts_statp->st_mode) && (ftsent->fts_statp->st_mode & S_IXUSR)); } static inline void pathSetSmack(const char *path, const std::string &label, const char *xattr_name) { if (smack_set_label_for_path(path, xattr_name, 0, label.c_str())) { LogError("smack_set_label_for_path failed. Path: " << path << " Label:" << label); ThrowMsg(SmackException::FileError, "smack_set_label_for_path failed failed. Path: " << path << " Label: " << label); } } static void dirSetSmack(const std::string &path, const std::string &label, const char *xattr_name, LabelDecisionFn fn) { char *const path_argv[] = {const_cast<char *>(path.c_str()), NULL}; FTSENT *ftsent; auto fts = makeUnique(fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL), fts_close); if (!fts) { LogError("fts_open failed."); ThrowMsg(SmackException::FileError, "fts_open failed."); } while ((ftsent = fts_read(fts.get())) != NULL) { /* Check for error (FTS_ERR) or failed stat(2) (FTS_NS) */ if (ftsent->fts_info == FTS_ERR || ftsent->fts_info == FTS_NS) { LogError("FTS_ERR error or failed stat(2) (FTS_NS)"); ThrowMsg(SmackException::FileError, "FTS_ERR error or failed stat(2) (FTS_NS)"); } /* avoid to tag directories two times */ if (ftsent->fts_info == FTS_D) continue; if (fn(ftsent)) pathSetSmack(ftsent->fts_path, label, xattr_name); } /* If last call to fts_read() set errno, we need to return error. */ if ((errno != 0) && (ftsent == NULL)) { LogError("Last errno from fts_read: " << GetErrnoString(errno)); ThrowMsg(SmackException::FileError, "Last errno from fts_read: " << GetErrnoString(errno)); } } static void labelDir(const std::string &path, const std::string &label, bool set_transmutable, bool set_executables) { // setting access label on everything in given directory and below dirSetSmack(path, label, XATTR_NAME_SMACK, labelAll); // setting transmute on dirs if (set_transmutable) dirSetSmack(path, "TRUE", XATTR_NAME_SMACKTRANSMUTE, labelDirs); // setting SMACK64EXEC labels if (set_executables) dirSetSmack(path, label, XATTR_NAME_SMACKEXEC, &labelExecs); } void setupPath( const std::string &pkgName, const std::string &path, app_install_path_type pathType, const int authorId) { std::string label; bool label_executables, label_transmute; switch (pathType) { case SECURITY_MANAGER_PATH_RW: label = generatePathRWLabel(pkgName); label_executables = false; label_transmute = true; break; case SECURITY_MANAGER_PATH_RO: label = generatePathROLabel(pkgName); label_executables = false; label_transmute = false; break; case SECURITY_MANAGER_PATH_PUBLIC_RO: label.assign(LABEL_FOR_APP_PUBLIC_RO_PATH); label_executables = false; label_transmute = true; break; case SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO: label = generatePathSharedROLabel(pkgName); label_executables = false; label_transmute = true; break; case SECURITY_MANAGER_PATH_TRUSTED_RW: if (authorId < 0) ThrowMsg(SmackException::InvalidParam, "You must define author to use PATH_TRUSED_RW"); label = generatePathTrustedLabel(authorId); label_executables = false; label_transmute = true; break; default: LogError("Path type not known."); Throw(SmackException::InvalidPathType); } return labelDir(path, label, label_transmute, label_executables); } void setupPkgBasePath(const std::string &basePath) { pathSetSmack(basePath.c_str(), LABEL_FOR_APP_PUBLIC_RO_PATH, XATTR_NAME_SMACK); } void setupSharedPrivatePath(const std::string &pkgName, const std::string &path) { pathSetSmack(path.c_str(), generateSharedPrivateLabel(pkgName, path), XATTR_NAME_SMACK); } void generateAppPkgNameFromLabel(const std::string &label, std::string &appName, std::string &pkgName) { static const char pkgPrefix[] = "User::Pkg::"; static const char appPrefix[] = "::App::"; if (label.compare(0, sizeof(pkgPrefix) - 1, pkgPrefix)) ThrowMsg(SmackException::InvalidLabel, "Invalid application process label " << label); size_t pkgStartPos = sizeof(pkgPrefix) - 1; size_t pkgEndPos = label.find(appPrefix, pkgStartPos); if (pkgEndPos != std::string::npos) { LogDebug("Hybrid application process label"); size_t appStartPos = pkgEndPos + sizeof(appPrefix) - 1; appName = label.substr(appStartPos, std::string::npos); pkgName = label.substr(pkgStartPos, pkgEndPos - pkgStartPos); } else { appName = std::string(); pkgName = label.substr(pkgStartPos, std::string::npos); } if (pkgName.empty()) ThrowMsg(SmackException::InvalidLabel, "No pkgName in Smack label " << label); } std::string generateProcessLabel(const std::string &appName, const std::string &pkgName, bool isHybrid) { std::string label = "User::Pkg::" + pkgName; if (isHybrid) label += "::App::" + appName; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from appName " << appName); return label; } std::string generatePathSharedROLabel(const std::string &pkgName) { std::string label = "User::Pkg::" + pkgName + "::SharedRO"; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName); return label; } std::string generatePathRWLabel(const std::string &pkgName) { std::string label = "User::Pkg::" + pkgName; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName); return label; } std::string generatePathROLabel(const std::string &pkgName) { std::string label = "User::Pkg::" + pkgName + "::RO"; if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName); return label; } std::string generateSharedPrivateLabel(const std::string &pkgName, const std::string &path) { // Prefix $1$ causes crypt() to use MD5 function std::string label = "User::Pkg::"; std::string salt = "$1$" + pkgName; const char * cryptLabel = crypt(path.c_str(), salt.c_str()); if (!cryptLabel) { ThrowMsg(SmackException::Base, "crypt error"); } label += cryptLabel; std::replace(label.begin(), label.end(), '/', '%'); if (smack_label_length(label.c_str()) <= 0) ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from path " << path); return label; } template<typename FuncType, typename... ArgsType> static std::string getSmackLabel(FuncType func, ArgsType... args) { char *label; ssize_t labelLen = func(args..., &label); if (labelLen <= 0) ThrowMsg(SmackException::Base, "Error while getting Smack label"); auto labelPtr = makeUnique(label, free); return std::string(labelPtr.get(), labelLen); } std::string getSmackLabelFromSocket(int socketFd) { return getSmackLabel(&smack_new_label_from_socket, socketFd); } std::string getSmackLabelFromPath(const std::string &path) { return getSmackLabel(&smack_new_label_from_path, path.c_str(), XATTR_NAME_SMACK, true); } std::string getSmackLabelFromFd(int fd) { return getSmackLabel(&smack_new_label_from_file, fd, XATTR_NAME_SMACK); } std::string getSmackLabelFromSelf(void) { return getSmackLabel(&smack_new_label_from_self); } std::string getSmackLabelFromPid(pid_t pid) { return getSmackLabel(&smack_new_label_from_process, pid); } std::string generatePathTrustedLabel(const int authorId) { if (authorId < 0) { LogError("Author was not set. It's not possible to generate label for unknown author."); ThrowMsg(SmackException::InvalidLabel, "Could not generate valid label without authorId"); } return "User::Author::" + std::to_string(authorId); } void setSmackLabelForFd(int fd, const std::string &label) { if (smack_set_label_for_file(fd, XATTR_NAME_SMACK, label.c_str())) { LogError("smack_set_label_for_file failed."); ThrowMsg(SmackException::FileError, "smack_set_label_for_file failed."); } } } // namespace SmackLabels } // namespace SecurityManager <|endoftext|>
<commit_before>#ifndef _SDD_UTIL_HASH_HH_ #define _SDD_UTIL_HASH_HH_ #include <algorithm> // for_each #include <iterator> namespace sdd { namespace util { /*------------------------------------------------------------------------------------------------*/ /// @brief Combine the hash value of x with seed. /// /// Taken from <boost/functional/hash.hpp>. Sligthy modified to use std::hash<T> instead of /// boost::hash_value(). template <typename T> inline void hash_combine(std::size_t& seed, const T& x) noexcept(noexcept(std::hash<T>()(x))) { seed ^= std::hash<T>()(x) + 0x9e3779b9 + (seed<<6) + (seed>>2); } /*------------------------------------------------------------------------------------------------*/ /// @brief Hash a range. template <typename InputIterator> inline void hash_combine(std::size_t& seed, InputIterator cit, InputIterator cend) { using value_type = typename std::iterator_traits<InputIterator>::value_type; std::for_each(cit, cend, [&](const value_type& v){hash_combine(seed, v);}); } /*------------------------------------------------------------------------------------------------*/ /// @brief Call std::hash<> template <typename T> inline std::size_t hash(const T& x) noexcept(noexcept(std::hash<T>()(x))) { return std::hash<T>()(x); } /*------------------------------------------------------------------------------------------------*/ /// @brief Call std::hash<> template <typename InputIterator> inline std::size_t hash(InputIterator cit, InputIterator cend) noexcept(noexcept(std::hash<typename std::decay<decltype(*cit)>::type>()(*cit))) { assert(cit != cend && "Empty range to hash."); std::size_t seed = hash(*cit); hash_combine(seed, cit + 1, cend); return seed; } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::util #endif // _SDD_UTIL_HASH_HH_ <commit_msg>Add missing #include.<commit_after>#ifndef _SDD_UTIL_HASH_HH_ #define _SDD_UTIL_HASH_HH_ #include <algorithm> // for_each #include <assert.h> #include <iterator> namespace sdd { namespace util { /*------------------------------------------------------------------------------------------------*/ /// @brief Combine the hash value of x with seed. /// /// Taken from <boost/functional/hash.hpp>. Sligthy modified to use std::hash<T> instead of /// boost::hash_value(). template <typename T> inline void hash_combine(std::size_t& seed, const T& x) noexcept(noexcept(std::hash<T>()(x))) { seed ^= std::hash<T>()(x) + 0x9e3779b9 + (seed<<6) + (seed>>2); } /*------------------------------------------------------------------------------------------------*/ /// @brief Hash a range. template <typename InputIterator> inline void hash_combine(std::size_t& seed, InputIterator cit, InputIterator cend) { using value_type = typename std::iterator_traits<InputIterator>::value_type; std::for_each(cit, cend, [&](const value_type& v){hash_combine(seed, v);}); } /*------------------------------------------------------------------------------------------------*/ /// @brief Call std::hash<> template <typename T> inline std::size_t hash(const T& x) noexcept(noexcept(std::hash<T>()(x))) { return std::hash<T>()(x); } /*------------------------------------------------------------------------------------------------*/ /// @brief Call std::hash<> template <typename InputIterator> inline std::size_t hash(InputIterator cit, InputIterator cend) noexcept(noexcept(std::hash<typename std::decay<decltype(*cit)>::type>()(*cit))) { assert(cit != cend && "Empty range to hash."); std::size_t seed = hash(*cit); hash_combine(seed, cit + 1, cend); return seed; } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::util #endif // _SDD_UTIL_HASH_HH_ <|endoftext|>
<commit_before>/** @file median_of_3_solution1.cpp @author Altantur Bayarsaikhan (altantur) @purpose Find median number 3 integers @version 1.0 25/10/17 */ #include <iostream> #include <fstream> using namespace std; int main(){ ifstream test_file; int a = 0, b = 0, c = 0, median = 0; int temp = 0; // Read from test files test_file.open ("../test/test1.txt"); test_file >> a; test_file >> b; test_file >> c; test_file.close(); // Find comparing two cout << "Median number is : " << median << endl; return 0; } <commit_msg>solution added by find the median number of 3 integers<commit_after>/** @file median_of_3_solution1.cpp @author Altantur Bayarsaikhan (altantur) @purpose Find median number 3 integers @version 1.0 25/10/17 */ #include <iostream> #include <fstream> using namespace std; int main(){ ifstream test_file; int a = 0, b = 0, c = 0, median = 0; int temp = 0; // Read from test files test_file.open ("../test/test1.txt"); test_file >> a; test_file >> b; test_file >> c; test_file.close(); // Find comparing two if (a > b){ if (b > c){ median = b; } else if (c > a){ median = a; } else{ median = c; } } else{ if (b < c){ median = b; } else if (c < a){ median = a; } else{ median = c; } } cout << "Median number is : " << median << endl; return 0; } <|endoftext|>
<commit_before>/** * Copyright 2008 Matthew Graham * 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 "snapl/command.h" #include "snapl/message.h" #include "snapl/response.h" #include <sstream> using namespace snapl; void command_c::get_input( message_c &msg ) const { msg.set_args( m_input ); } void command_c::set_input( const message_c &msg ) { m_input = msg.args(); } void command_c::get_output( message_c &msg ) const { msg.set_args( m_output ); } void command_c::set_output( const message_c &msg ) { m_output = msg.args(); } void command_c::ok( const std::string &msg ) { m_response_code = "ok"; m_response_msg = msg; } void command_c::err( const std::string &msg ) { m_response_code = "err"; m_response_msg = msg; } void command_c::err( const std::string &file, int line ) { m_response_code = "err"; std::ostringstream format; format << file << ':' << line; m_response_msg = format.str(); } <commit_msg>fixed command.ok to match what's in the header<commit_after>/** * Copyright 2008 Matthew Graham * 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 "snapl/command.h" #include "snapl/message.h" #include "snapl/response.h" #include <sstream> using namespace snapl; void command_c::get_input( message_c &msg ) const { msg.set_args( m_input ); } void command_c::set_input( const message_c &msg ) { m_input = msg.args(); } void command_c::get_output( message_c &msg ) const { msg.set_args( m_output ); } void command_c::set_output( const message_c &msg ) { m_output = msg.args(); } void command_c::ok() { m_response_code = "ok"; m_response_msg = std::string(); } void command_c::err( const std::string &msg ) { m_response_code = "err"; m_response_msg = msg; } void command_c::err( const std::string &file, int line ) { m_response_code = "err"; std::ostringstream format; format << file << ':' << line; m_response_msg = format.str(); } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <iomanip> #include <utility> #include "components/command_line.hpp" /* Create the instance */ cliparser::make_type cliparser::make(string &&progname, const options &&opts) { return std::make_unique<cliparser>( "Usage: " + progname + " OPTION...", std::forward<decltype(opts)>(opts) ); } /* Construct the parser. */ cliparser::parser(string &&synopsis, const options &&opts) : synopsis_(std::forward<decltype(synopsis)>(synopsis)), opts_(std::forward<decltype(opts)>(opts)) { } /* Print program usage message. */ void cliparser::usage() const { std::cout << synopsis_ << '\n' << std::endl; size_t maxlen = 0; /* * Get the length of the longest string in the flag column * which is used to align the description fields. */ for (const auto &opt : opts_) { size_t len = opt.flag_long.length() + opt.flag.length() + 4; maxlen = std::max(len, maxlen); } /* * Print each option, its description and token and possible * values for said token (if any). */ for (auto &opt : opts_) { /* Padding between flags and description. */ size_t pad = maxlen - opt.flag_long.length() - opt.token.length(); std::cout << " " << opt.flag << ", " << opt.flag_long; if (!opt.token.empty()) { std::cout << '=' << opt.token; pad--; } /* * Output the list with accepted values. * This line is printed below the description. */ if (!opt.values.empty()) { std::cout << std::setw(pad + opt.desc.length()) << opt.desc << std::endl; pad = pad + opt.flag_long.length() + opt.token.length() + 7; std::cout << string(pad, ' ') << opt.token << " is one of: "; for (auto &v : opt.values) std::cout << v << (v != opt.values.back() ? ", " : ""); } else { std::cout << std::setw(pad + opt.desc.length()) << opt.desc; } std::cout << std::endl; } } /* Check if the passed option was provided. */ bool cliparser::has(const string &option) const { return optvalues_.find(option) != optvalues_.end(); } /* Gets the value for a given option. */ string cliparser::get(string opt) const { if (has(std::forward<string>(opt))) return optvalues_.find(opt)->second; return ""; } /* Compare option value with given string. */ bool cliparser::compare(string opt, const string_view &val) const { return get(std::move(opt)) == val; } /* Compare option with its short version. */ auto cliparser::is_short(const string_view &option, const string_view &opt_short) const { return option.compare(0, opt_short.length(), opt_short) == 0; } /* Compare option with its long version */ auto cliparser::is_long(const string_view &option, const string_view &opt_long) const { return option.compare(0, opt_long.length(), opt_long) == 0; } /* Compare with both versions. */ auto cliparser::is(const string_view &option, string opt_short, string opt_long) const { return is_short(option, std::move(opt_short)) || is_long(option, std::move(opt_long)); } /* * Process argument vector. * TODO: make this cleaner. */ void cliparser::process_input(const vector<string> &values) { for (size_t i = 0; i < values.size(); i++) { const string_view &arg = values[i]; const string_view &next_arg = values.size() > i + 1 ? values[i + 1] : ""; parse(arg, next_arg); } } /* Parse option value. */ auto cliparser::parse_value(string input, const string_view &input_next, choices values) const { string opt = std::move(input); size_t pos; string_view value; if (input_next.empty() && opt.compare(0, 2, "--") != 0) throw value_error("Missing value for " + string(opt.data())); else if ((pos = opt.find('=')) == string_view::npos && opt.compare(0, 2, "--") == 0) throw value_error("Missing value for " + string(opt.data())); else if (pos == string::npos && !input_next.empty()) value = input_next; else { value = opt.substr(pos + 1); opt = opt.substr(0, pos); } if (!values.empty() && std::find(values.begin(), values.end(), value) == values.end()) throw value_error( "Invalid value '" + string(value.data()) + "' for argument " + string(opt.data()) ); return value; } /* Parse and validate passed arguments and flags. */ void cliparser::parse(const string_view &input, const string_view &input_next) { if (skipnext_) { skipnext_ = false; if (!input_next.empty()) return; } for (auto &&opt : opts_) { if (is(input, opt.flag, opt.flag_long)) { if (opt.token.empty()) { optvalues_.insert(std::make_pair(opt.flag_long.substr(2), "")); } else { auto value = parse_value(input.data(), input_next, opt.values); skipnext_ = (value == input_next); optvalues_.insert(make_pair(opt.flag_long.substr(2), value)); } return; } } if (input.compare(0, 1, "-") == 0) throw argument_error("Unrecognized option " + string(input.data())); } <commit_msg>command_line: use '\n' instead of std::endl<commit_after>#include <iostream> #include <algorithm> #include <iomanip> #include <utility> #include "components/command_line.hpp" /* Create the instance */ cliparser::make_type cliparser::make(string &&progname, const options &&opts) { return std::make_unique<cliparser>( "Usage: " + progname + " OPTION...", std::forward<decltype(opts)>(opts) ); } /* Construct the parser. */ cliparser::parser(string &&synopsis, const options &&opts) : synopsis_(std::forward<decltype(synopsis)>(synopsis)), opts_(std::forward<decltype(opts)>(opts)) { } /* Print program usage message. */ void cliparser::usage() const { std::cout << synopsis_ << "\n\n"; size_t maxlen = 0; /* * Get the length of the longest string in the flag column * which is used to align the description fields. */ for (const auto &opt : opts_) { size_t len = opt.flag_long.length() + opt.flag.length() + 4; maxlen = std::max(len, maxlen); } /* * Print each option, its description and token and possible * values for said token (if any). */ for (auto &opt : opts_) { /* Padding between flags and description. */ size_t pad = maxlen - opt.flag_long.length() - opt.token.length(); std::cout << " " << opt.flag << ", " << opt.flag_long; if (!opt.token.empty()) { std::cout << '=' << opt.token; pad--; } /* * Output the list with accepted values. * This line is printed below the description. */ if (!opt.values.empty()) { std::cout << std::setw(pad + opt.desc.length()) << opt.desc << '\n'; pad = pad + opt.flag_long.length() + opt.token.length() + 7; std::cout << string(pad, ' ') << opt.token << " is one of: "; for (auto &v : opt.values) std::cout << v << (v != opt.values.back() ? ", " : ""); } else { std::cout << std::setw(pad + opt.desc.length()) << opt.desc; } std::cout << std::endl; } } /* Check if the passed option was provided. */ bool cliparser::has(const string &option) const { return optvalues_.find(option) != optvalues_.end(); } /* Gets the value for a given option. */ string cliparser::get(string opt) const { if (has(std::forward<string>(opt))) return optvalues_.find(opt)->second; return ""; } /* Compare option value with given string. */ bool cliparser::compare(string opt, const string_view &val) const { return get(std::move(opt)) == val; } /* Compare option with its short version. */ auto cliparser::is_short(const string_view &option, const string_view &opt_short) const { return option.compare(0, opt_short.length(), opt_short) == 0; } /* Compare option with its long version */ auto cliparser::is_long(const string_view &option, const string_view &opt_long) const { return option.compare(0, opt_long.length(), opt_long) == 0; } /* Compare with both versions. */ auto cliparser::is(const string_view &option, string opt_short, string opt_long) const { return is_short(option, std::move(opt_short)) || is_long(option, std::move(opt_long)); } /* * Process argument vector. * TODO: make this cleaner. */ void cliparser::process_input(const vector<string> &values) { for (size_t i = 0; i < values.size(); i++) { const string_view &arg = values[i]; const string_view &next_arg = values.size() > i + 1 ? values[i + 1] : ""; parse(arg, next_arg); } } /* Parse option value. */ auto cliparser::parse_value(string input, const string_view &input_next, choices values) const { string opt = std::move(input); size_t pos; string_view value; if (input_next.empty() && opt.compare(0, 2, "--") != 0) throw value_error("Missing value for " + string(opt.data())); else if ((pos = opt.find('=')) == string_view::npos && opt.compare(0, 2, "--") == 0) throw value_error("Missing value for " + string(opt.data())); else if (pos == string::npos && !input_next.empty()) value = input_next; else { value = opt.substr(pos + 1); opt = opt.substr(0, pos); } if (!values.empty() && std::find(values.begin(), values.end(), value) == values.end()) throw value_error( "Invalid value '" + string(value.data()) + "' for argument " + string(opt.data()) ); return value; } /* Parse and validate passed arguments and flags. */ void cliparser::parse(const string_view &input, const string_view &input_next) { if (skipnext_) { skipnext_ = false; if (!input_next.empty()) return; } for (auto &&opt : opts_) { if (is(input, opt.flag, opt.flag_long)) { if (opt.token.empty()) { optvalues_.insert(std::make_pair(opt.flag_long.substr(2), "")); } else { auto value = parse_value(input.data(), input_next, opt.values); skipnext_ = (value == input_next); optvalues_.insert(make_pair(opt.flag_long.substr(2), value)); } return; } } if (input.compare(0, 1, "-") == 0) throw argument_error("Unrecognized option " + string(input.data())); } <|endoftext|>
<commit_before>// test cases for rule CWE-611 (createLSParser) #include "tests.h" // --- class DOMConfiguration { public: void setParameter(const XMLCh *parameter, bool value); }; class DOMLSParser { public: DOMConfiguration *getDomConfig(); void parse(const InputSource &data); }; class DOMImplementationLS { public: DOMLSParser *createLSParser(); }; // --- void test5_1(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED] } void test5_2(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); p->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); p->parse(data); // GOOD } DOMImplementationLS *g_impl; DOMLSParser *g_p1, *g_p2; InputSource *g_data; void test5_3_init() { g_p1 = g_impl->createLSParser(); g_p1->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); g_p2 = g_impl->createLSParser(); } void test5_3() { test5_3_init(); g_p1->parse(*g_data); // GOOD g_p2->parse(*g_data); // BAD (parser not correctly configured) [NOT DETECTED] } <commit_msg>C++: More test cases.<commit_after>// test cases for rule CWE-611 (createLSParser) #include "tests.h" // --- class DOMConfiguration { public: void setParameter(const XMLCh *parameter, bool value); }; class DOMLSParser { public: DOMConfiguration *getDomConfig(); void parse(const InputSource &data); }; class DOMImplementationLS { public: DOMLSParser *createLSParser(); }; // --- void test5_1(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED] } void test5_2(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); p->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); p->parse(data); // GOOD } void test5_3(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); p->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, false); p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED] } void test5_4(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); DOMConfiguration *cfg = p->getDomConfig(); cfg->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); p->parse(data); // GOOD } void test5_5(DOMImplementationLS *impl, InputSource &data) { DOMLSParser *p = impl->createLSParser(); DOMConfiguration *cfg = p->getDomConfig(); cfg->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, false); p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED] } DOMImplementationLS *g_impl; DOMLSParser *g_p1, *g_p2; InputSource *g_data; void test5_6_init() { g_p1 = g_impl->createLSParser(); g_p1->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true); g_p2 = g_impl->createLSParser(); } void test5_6() { test5_6_init(); g_p1->parse(*g_data); // GOOD g_p2->parse(*g_data); // BAD (parser not correctly configured) [NOT DETECTED] } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/desktop_background/desktop_background_controller.h" #include <cmath> #include <cstdlib> #include "ash/ash_switches.h" #include "ash/desktop_background/desktop_background_widget_controller.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/test/ash_test_base.h" #include "ash/test/display_manager_test_api.h" #include "ash/test/test_user_wallpaper_delegate.h" #include "base/message_loop/message_loop.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread.h" #include "content/public/test/test_utils.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/test/layer_animator_test_controller.h" using aura::RootWindow; using aura::Window; namespace ash { namespace { // Containers IDs used for tests. const int kDesktopBackgroundId = ash::kShellWindowId_DesktopBackgroundContainer; const int kLockScreenBackgroundId = ash::kShellWindowId_LockScreenBackgroundContainer; // Returns number of child windows in a shell window container. int ChildCountForContainer(int container_id) { Window* root = ash::Shell::GetPrimaryRootWindow(); Window* container = root->GetChildById(container_id); return static_cast<int>(container->children().size()); } // Steps a widget's layer animation until it is completed. Animations must be // enabled. void RunAnimationForWidget(views::Widget* widget) { // Animations must be enabled for stepping to work. ASSERT_NE(ui::ScopedAnimationDurationScaleMode::duration_scale_mode(), ui::ScopedAnimationDurationScaleMode::ZERO_DURATION); ui::Layer* layer = widget->GetNativeView()->layer(); ui::LayerAnimatorTestController controller(layer->GetAnimator()); gfx::AnimationContainerElement* element = layer->GetAnimator(); // Multiple steps are required to complete complex animations. // TODO(vollick): This should not be necessary. crbug.com/154017 while (controller.animator()->is_animating()) { controller.StartThreadedAnimationsIfNeeded(); base::TimeTicks step_time = controller.animator()->last_step_time(); element->Step(step_time + base::TimeDelta::FromMilliseconds(1000)); } } } // namespace class DesktopBackgroundControllerTest : public test::AshTestBase { public: DesktopBackgroundControllerTest() : controller_(NULL) { } virtual ~DesktopBackgroundControllerTest() {} virtual void SetUp() OVERRIDE { test::AshTestBase::SetUp(); // Ash shell initialization creates wallpaper. Reset it so we can manually // control wallpaper creation and animation in our tests. RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); root_window_controller->SetWallpaperController(NULL); root_window_controller->SetAnimatingWallpaperController(NULL); controller_ = Shell::GetInstance()->desktop_background_controller(); wallpaper_delegate_ = static_cast<test::TestUserWallpaperDelegate*>( Shell::GetInstance()->user_wallpaper_delegate()); controller_->set_wallpaper_reload_delay_for_test(0); } protected: // A color that can be passed to CreateImage(). Specifically chosen to not // conflict with any of the default wallpaper colors. static const SkColor kCustomWallpaperColor = SK_ColorMAGENTA; // Creates an image of size |size|. gfx::ImageSkia CreateImage(int width, int height, SkColor color) { SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height); bitmap.allocPixels(); bitmap.eraseColor(color); gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); return image; } // Runs kAnimatingDesktopController's animation to completion. // TODO(bshe): Don't require tests to run animations; it's slow. void RunDesktopControllerAnimation() { DesktopBackgroundWidgetController* controller = Shell::GetPrimaryRootWindowController() ->animating_wallpaper_controller() ->GetController(false); ASSERT_NO_FATAL_FAILURE(RunAnimationForWidget(controller->widget())); } DesktopBackgroundController* controller_; // Not owned. test::TestUserWallpaperDelegate* wallpaper_delegate_; private: DISALLOW_COPY_AND_ASSIGN(DesktopBackgroundControllerTest); }; TEST_F(DesktopBackgroundControllerTest, BasicReparenting) { DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // Wallpaper view/window exists in the desktop background container and // nothing is in the lock screen background container. EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); // Moving background to lock container should succeed the first time but // subsequent calls should do nothing. EXPECT_TRUE(controller->MoveDesktopToLockedContainer()); EXPECT_FALSE(controller->MoveDesktopToLockedContainer()); // One window is moved from desktop to lock container. EXPECT_EQ(0, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(1, ChildCountForContainer(kLockScreenBackgroundId)); // Moving background to desktop container should succeed the first time. EXPECT_TRUE(controller->MoveDesktopToUnlockedContainer()); EXPECT_FALSE(controller->MoveDesktopToUnlockedContainer()); // One window is moved from lock to desktop container. EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); } TEST_F(DesktopBackgroundControllerTest, ControllerOwnership) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode normal_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Create wallpaper and background view. DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // The new wallpaper is ready to start animating. kAnimatingDesktopController // holds the widget controller instance. kDesktopController will get it later. RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); EXPECT_TRUE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); // kDesktopController will receive the widget controller when the animation // is done. EXPECT_FALSE(root_window_controller->wallpaper_controller()); // Force the widget's layer animation to play to completion. RunDesktopControllerAnimation(); // Ownership has moved from kAnimatingDesktopController to kDesktopController. EXPECT_FALSE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); EXPECT_TRUE(root_window_controller->wallpaper_controller()); } // Test for crbug.com/149043 "Unlock screen, no launcher appears". Ensure we // move all desktop views if there are more than one. TEST_F(DesktopBackgroundControllerTest, BackgroundMovementDuringUnlock) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode normal_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Reset wallpaper state, see ControllerOwnership above. DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // Run wallpaper show animation to completion. RunDesktopControllerAnimation(); // User locks the screen, which moves the background forward. controller->MoveDesktopToLockedContainer(); // Suspend/resume cycle causes wallpaper to refresh, loading a new desktop // background that will animate in on top of the old one. controller->CreateEmptyWallpaper(); // In this state we have two desktop background views stored in different // properties. Both are in the lock screen background container. RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); EXPECT_TRUE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); EXPECT_TRUE(root_window_controller->wallpaper_controller()); EXPECT_EQ(0, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(2, ChildCountForContainer(kLockScreenBackgroundId)); // Before the wallpaper's animation completes, user unlocks the screen, which // moves the desktop to the back. controller->MoveDesktopToUnlockedContainer(); // Ensure both desktop backgrounds have moved. EXPECT_EQ(2, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); // Finish the new desktop background animation. RunDesktopControllerAnimation(); // Now there is one desktop background, in the back. EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); } // Test for crbug.com/156542. Animating wallpaper should immediately finish // animation and replace current wallpaper before next animation starts. TEST_F(DesktopBackgroundControllerTest, ChangeWallpaperQuick) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode normal_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Reset wallpaper state, see ControllerOwnership above. DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // Run wallpaper show animation to completion. RunDesktopControllerAnimation(); // Change to a new wallpaper. controller->CreateEmptyWallpaper(); RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); DesktopBackgroundWidgetController* animating_controller = root_window_controller->animating_wallpaper_controller()->GetController( false); EXPECT_TRUE(animating_controller); EXPECT_TRUE(root_window_controller->wallpaper_controller()); // Change to another wallpaper before animation finished. controller->CreateEmptyWallpaper(); // The animating controller should immediately move to desktop controller. EXPECT_EQ(animating_controller, root_window_controller->wallpaper_controller()); // Cache the new animating controller. animating_controller = root_window_controller-> animating_wallpaper_controller()->GetController(false); // Run wallpaper show animation to completion. ASSERT_NO_FATAL_FAILURE( RunAnimationForWidget( root_window_controller->animating_wallpaper_controller()-> GetController(false)->widget())); EXPECT_TRUE(root_window_controller->wallpaper_controller()); EXPECT_FALSE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); // The desktop controller should be the last created animating controller. EXPECT_EQ(animating_controller, root_window_controller->wallpaper_controller()); } TEST_F(DesktopBackgroundControllerTest, ResizeCustomWallpaper) { if (!SupportsMultipleDisplays()) return; test::DisplayManagerTestApi display_manager_test_api( Shell::GetInstance()->display_manager()); display_manager_test_api.UpdateDisplay("320x200"); gfx::ImageSkia image = CreateImage(640, 480, kCustomWallpaperColor); // Set the image as custom wallpaper, wait for the resize to finish, and check // that the resized image is the expected size. controller_->SetWallpaperImage(image, WALLPAPER_LAYOUT_STRETCH); EXPECT_TRUE(image.BackedBySameObjectAs(controller_->GetWallpaper())); content::BrowserThread::GetBlockingPool()->FlushForTesting(); content::RunAllPendingInMessageLoop(); gfx::ImageSkia resized_image = controller_->GetWallpaper(); EXPECT_FALSE(image.BackedBySameObjectAs(resized_image)); EXPECT_EQ(gfx::Size(320, 200).ToString(), resized_image.size().ToString()); // Load the original wallpaper again and check that we're still using the // previously-resized image instead of doing another resize // (http://crbug.com/321402). controller_->SetWallpaperImage(image, WALLPAPER_LAYOUT_STRETCH); content::BrowserThread::GetBlockingPool()->FlushForTesting(); content::RunAllPendingInMessageLoop(); EXPECT_TRUE(resized_image.BackedBySameObjectAs(controller_->GetWallpaper())); } TEST_F(DesktopBackgroundControllerTest, GetMaxDisplaySize) { // Device scale factor shouldn't affect the native size. UpdateDisplay("1000x300*2"); EXPECT_EQ( "1000x300", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // Rotated display should return the rotated size. UpdateDisplay("1000x300*2/r"); EXPECT_EQ( "300x1000", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // UI Scaling shouldn't affect the native size. UpdateDisplay("1000x300*[email protected]"); EXPECT_EQ( "1000x300", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); if (!SupportsMultipleDisplays()) return; // First display has maximum size. UpdateDisplay("400x300,100x100"); EXPECT_EQ( "400x300", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // Second display has maximum size. UpdateDisplay("400x300,500x600"); EXPECT_EQ( "500x600", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // Maximum width and height belongs to different displays. UpdateDisplay("400x300,100x500"); EXPECT_EQ( "400x500", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); } } // namespace ash <commit_msg>Disable DesktopBackgroundControllerTest.BackgroundMovementDuringUnlock<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/desktop_background/desktop_background_controller.h" #include <cmath> #include <cstdlib> #include "ash/ash_switches.h" #include "ash/desktop_background/desktop_background_widget_controller.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/test/ash_test_base.h" #include "ash/test/display_manager_test_api.h" #include "ash/test/test_user_wallpaper_delegate.h" #include "base/message_loop/message_loop.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread.h" #include "content/public/test/test_utils.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/test/layer_animator_test_controller.h" using aura::RootWindow; using aura::Window; namespace ash { namespace { // Containers IDs used for tests. const int kDesktopBackgroundId = ash::kShellWindowId_DesktopBackgroundContainer; const int kLockScreenBackgroundId = ash::kShellWindowId_LockScreenBackgroundContainer; // Returns number of child windows in a shell window container. int ChildCountForContainer(int container_id) { Window* root = ash::Shell::GetPrimaryRootWindow(); Window* container = root->GetChildById(container_id); return static_cast<int>(container->children().size()); } // Steps a widget's layer animation until it is completed. Animations must be // enabled. void RunAnimationForWidget(views::Widget* widget) { // Animations must be enabled for stepping to work. ASSERT_NE(ui::ScopedAnimationDurationScaleMode::duration_scale_mode(), ui::ScopedAnimationDurationScaleMode::ZERO_DURATION); ui::Layer* layer = widget->GetNativeView()->layer(); ui::LayerAnimatorTestController controller(layer->GetAnimator()); gfx::AnimationContainerElement* element = layer->GetAnimator(); // Multiple steps are required to complete complex animations. // TODO(vollick): This should not be necessary. crbug.com/154017 while (controller.animator()->is_animating()) { controller.StartThreadedAnimationsIfNeeded(); base::TimeTicks step_time = controller.animator()->last_step_time(); element->Step(step_time + base::TimeDelta::FromMilliseconds(1000)); } } } // namespace class DesktopBackgroundControllerTest : public test::AshTestBase { public: DesktopBackgroundControllerTest() : controller_(NULL) { } virtual ~DesktopBackgroundControllerTest() {} virtual void SetUp() OVERRIDE { test::AshTestBase::SetUp(); // Ash shell initialization creates wallpaper. Reset it so we can manually // control wallpaper creation and animation in our tests. RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); root_window_controller->SetWallpaperController(NULL); root_window_controller->SetAnimatingWallpaperController(NULL); controller_ = Shell::GetInstance()->desktop_background_controller(); wallpaper_delegate_ = static_cast<test::TestUserWallpaperDelegate*>( Shell::GetInstance()->user_wallpaper_delegate()); controller_->set_wallpaper_reload_delay_for_test(0); } protected: // A color that can be passed to CreateImage(). Specifically chosen to not // conflict with any of the default wallpaper colors. static const SkColor kCustomWallpaperColor = SK_ColorMAGENTA; // Creates an image of size |size|. gfx::ImageSkia CreateImage(int width, int height, SkColor color) { SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height); bitmap.allocPixels(); bitmap.eraseColor(color); gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); return image; } // Runs kAnimatingDesktopController's animation to completion. // TODO(bshe): Don't require tests to run animations; it's slow. void RunDesktopControllerAnimation() { DesktopBackgroundWidgetController* controller = Shell::GetPrimaryRootWindowController() ->animating_wallpaper_controller() ->GetController(false); ASSERT_NO_FATAL_FAILURE(RunAnimationForWidget(controller->widget())); } DesktopBackgroundController* controller_; // Not owned. test::TestUserWallpaperDelegate* wallpaper_delegate_; private: DISALLOW_COPY_AND_ASSIGN(DesktopBackgroundControllerTest); }; TEST_F(DesktopBackgroundControllerTest, BasicReparenting) { DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // Wallpaper view/window exists in the desktop background container and // nothing is in the lock screen background container. EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); // Moving background to lock container should succeed the first time but // subsequent calls should do nothing. EXPECT_TRUE(controller->MoveDesktopToLockedContainer()); EXPECT_FALSE(controller->MoveDesktopToLockedContainer()); // One window is moved from desktop to lock container. EXPECT_EQ(0, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(1, ChildCountForContainer(kLockScreenBackgroundId)); // Moving background to desktop container should succeed the first time. EXPECT_TRUE(controller->MoveDesktopToUnlockedContainer()); EXPECT_FALSE(controller->MoveDesktopToUnlockedContainer()); // One window is moved from lock to desktop container. EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); } TEST_F(DesktopBackgroundControllerTest, ControllerOwnership) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode normal_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Create wallpaper and background view. DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // The new wallpaper is ready to start animating. kAnimatingDesktopController // holds the widget controller instance. kDesktopController will get it later. RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); EXPECT_TRUE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); // kDesktopController will receive the widget controller when the animation // is done. EXPECT_FALSE(root_window_controller->wallpaper_controller()); // Force the widget's layer animation to play to completion. RunDesktopControllerAnimation(); // Ownership has moved from kAnimatingDesktopController to kDesktopController. EXPECT_FALSE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); EXPECT_TRUE(root_window_controller->wallpaper_controller()); } // Test for crbug.com/149043 "Unlock screen, no launcher appears". Ensure we // move all desktop views if there are more than one. // Disabled for crbug.com/366993 TEST_F(DesktopBackgroundControllerTest, DISABLED_BackgroundMovementDuringUnlock) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode normal_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Reset wallpaper state, see ControllerOwnership above. DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // Run wallpaper show animation to completion. RunDesktopControllerAnimation(); // User locks the screen, which moves the background forward. controller->MoveDesktopToLockedContainer(); // Suspend/resume cycle causes wallpaper to refresh, loading a new desktop // background that will animate in on top of the old one. controller->CreateEmptyWallpaper(); // In this state we have two desktop background views stored in different // properties. Both are in the lock screen background container. RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); EXPECT_TRUE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); EXPECT_TRUE(root_window_controller->wallpaper_controller()); EXPECT_EQ(0, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(2, ChildCountForContainer(kLockScreenBackgroundId)); // Before the wallpaper's animation completes, user unlocks the screen, which // moves the desktop to the back. controller->MoveDesktopToUnlockedContainer(); // Ensure both desktop backgrounds have moved. EXPECT_EQ(2, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); // Finish the new desktop background animation. RunDesktopControllerAnimation(); // Now there is one desktop background, in the back. EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId)); } // Test for crbug.com/156542. Animating wallpaper should immediately finish // animation and replace current wallpaper before next animation starts. TEST_F(DesktopBackgroundControllerTest, ChangeWallpaperQuick) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode normal_duration_mode( ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION); // Reset wallpaper state, see ControllerOwnership above. DesktopBackgroundController* controller = Shell::GetInstance()->desktop_background_controller(); controller->CreateEmptyWallpaper(); // Run wallpaper show animation to completion. RunDesktopControllerAnimation(); // Change to a new wallpaper. controller->CreateEmptyWallpaper(); RootWindowController* root_window_controller = Shell::GetPrimaryRootWindowController(); DesktopBackgroundWidgetController* animating_controller = root_window_controller->animating_wallpaper_controller()->GetController( false); EXPECT_TRUE(animating_controller); EXPECT_TRUE(root_window_controller->wallpaper_controller()); // Change to another wallpaper before animation finished. controller->CreateEmptyWallpaper(); // The animating controller should immediately move to desktop controller. EXPECT_EQ(animating_controller, root_window_controller->wallpaper_controller()); // Cache the new animating controller. animating_controller = root_window_controller-> animating_wallpaper_controller()->GetController(false); // Run wallpaper show animation to completion. ASSERT_NO_FATAL_FAILURE( RunAnimationForWidget( root_window_controller->animating_wallpaper_controller()-> GetController(false)->widget())); EXPECT_TRUE(root_window_controller->wallpaper_controller()); EXPECT_FALSE(root_window_controller->animating_wallpaper_controller()-> GetController(false)); // The desktop controller should be the last created animating controller. EXPECT_EQ(animating_controller, root_window_controller->wallpaper_controller()); } TEST_F(DesktopBackgroundControllerTest, ResizeCustomWallpaper) { if (!SupportsMultipleDisplays()) return; test::DisplayManagerTestApi display_manager_test_api( Shell::GetInstance()->display_manager()); display_manager_test_api.UpdateDisplay("320x200"); gfx::ImageSkia image = CreateImage(640, 480, kCustomWallpaperColor); // Set the image as custom wallpaper, wait for the resize to finish, and check // that the resized image is the expected size. controller_->SetWallpaperImage(image, WALLPAPER_LAYOUT_STRETCH); EXPECT_TRUE(image.BackedBySameObjectAs(controller_->GetWallpaper())); content::BrowserThread::GetBlockingPool()->FlushForTesting(); content::RunAllPendingInMessageLoop(); gfx::ImageSkia resized_image = controller_->GetWallpaper(); EXPECT_FALSE(image.BackedBySameObjectAs(resized_image)); EXPECT_EQ(gfx::Size(320, 200).ToString(), resized_image.size().ToString()); // Load the original wallpaper again and check that we're still using the // previously-resized image instead of doing another resize // (http://crbug.com/321402). controller_->SetWallpaperImage(image, WALLPAPER_LAYOUT_STRETCH); content::BrowserThread::GetBlockingPool()->FlushForTesting(); content::RunAllPendingInMessageLoop(); EXPECT_TRUE(resized_image.BackedBySameObjectAs(controller_->GetWallpaper())); } TEST_F(DesktopBackgroundControllerTest, GetMaxDisplaySize) { // Device scale factor shouldn't affect the native size. UpdateDisplay("1000x300*2"); EXPECT_EQ( "1000x300", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // Rotated display should return the rotated size. UpdateDisplay("1000x300*2/r"); EXPECT_EQ( "300x1000", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // UI Scaling shouldn't affect the native size. UpdateDisplay("1000x300*[email protected]"); EXPECT_EQ( "1000x300", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); if (!SupportsMultipleDisplays()) return; // First display has maximum size. UpdateDisplay("400x300,100x100"); EXPECT_EQ( "400x300", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // Second display has maximum size. UpdateDisplay("400x300,500x600"); EXPECT_EQ( "500x600", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); // Maximum width and height belongs to different displays. UpdateDisplay("400x300,100x500"); EXPECT_EQ( "400x500", DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString()); } } // namespace ash <|endoftext|>
<commit_before>// Copyright 2016 AUV-IITK #include <ros.h> #include <Arduino.h> #include <std_msgs/Int32.h> #include <std_msgs/Float64.h> #include <math.h> #define pwmPinWest 4 #define pwmPinEast 5 #define directionPinWest1 26 #define directionPinWest2 27 #define directionPinEast1 35 #define directionPinEast2 29 #define pwmPinNorthSway 2 #define pwmPinSouthSway 3 #define directionPinNorthSway1 31 #define directionPinNorthSway2 30 #define directionPinSouthSway1 33 #define directionPinSouthSway2 32 #define pwmPinNorthUp 6 #define pwmPinSouthUp 7 #define directionPinNorthUp1 24 #define directionPinNorthUp2 25 #define directionPinSouthUp1 22 #define directionPinSouthUp2 23 #define analogPinPressureSensor A0 const float c092 = 506.22; const float s092 = -2.65; const float c093 = 448.62; const float s093 = -2.92; const float c099 = 397.65; // reference as their graph is at lowest const float s099 = -2.71; // reference as their graph is at lowest const float c113 = 539.85; const float s113 = -3.38; const float c117 = 441.32; const float s117 = -3.03; const float c122 = 547.39; const float s122 = -2.93; bool isMovingForward = true; float v; std_msgs::Float64 voltage; ros::NodeHandle nh; int btd092(int pwm) { pwm = (c099 + s099 * pwm - c092) / (s092); if (pwm < 147) return 0; return pwm; } int btd093(int pwm) { pwm = (c099 + s099 * pwm - c093) / (s093); if (pwm < 147) return 0; return pwm; } int btd099(int pwm) { if (pwm < 147) return 0; return pwm; } int btd113(int pwm) { pwm = (c099 + s099 * pwm - c113) / (s113); if (pwm < 147) return 0; return pwm; } int btd117(int pwm) { pwm = (c099 + s099 * pwm - c117) / (s117); if (pwm < 147) return 0; return pwm; } int btd122(int pwm) { pwm = (c099 + s099 * pwm - c122) / (s122); if (pwm < 147) return 0; return pwm; } void thrusterNorthUp(int pwm, int isUpward) { pwm = abs(pwm); pwm = btd122(pwm); analogWrite(pwmPinNorthUp, 255 - pwm); if (isUpward) { digitalWrite(directionPinNorthUp1, HIGH); digitalWrite(directionPinNorthUp2, LOW); } else { digitalWrite(directionPinNorthUp1, LOW); digitalWrite(directionPinNorthUp2, HIGH); } } void thrusterSouthUp(int pwm, int isUpward) { pwm = abs(pwm); pwm = btd117(pwm); analogWrite(pwmPinSouthUp, 255 - pwm); if (isUpward) { digitalWrite(directionPinSouthUp1, HIGH); digitalWrite(directionPinSouthUp2, LOW); } else { digitalWrite(directionPinSouthUp1, LOW); digitalWrite(directionPinSouthUp2, HIGH); } } void thrusterNorthSway(int pwm, int isRight) { pwm = abs(pwm); pwm = btd113(pwm); analogWrite(pwmPinNorthSway, 255 - pwm); if (isRight) { digitalWrite(directionPinNorthSway1, HIGH); digitalWrite(directionPinNorthSway2, LOW); } else { digitalWrite(directionPinNorthSway1, LOW); digitalWrite(directionPinNorthSway2, HIGH); } } void thrusterSouthSway(int pwm, int isRight) { pwm = abs(pwm); pwm = btd099(pwm); analogWrite(pwmPinSouthSway, 255 - pwm); if (isRight) { digitalWrite(directionPinSouthSway1, HIGH); digitalWrite(directionPinSouthSway2, LOW); } else { digitalWrite(directionPinSouthSway1, LOW); digitalWrite(directionPinSouthSway2, HIGH); } } void thrusterEast(int pwm, int isForward) { pwm = abs(pwm); pwm = btd093(pwm); analogWrite(pwmPinEast, 255 - pwm); if (isForward) { digitalWrite(directionPinEast1, HIGH); digitalWrite(directionPinEast2, LOW); } else { digitalWrite(directionPinEast1, LOW); digitalWrite(directionPinEast2, HIGH); } } void thrusterWest(int pwm, int isForward) { pwm = abs(pwm); pwm = btd092(pwm); analogWrite(pwmPinWest, 255 - pwm); if (isForward) { digitalWrite(directionPinWest1, HIGH); digitalWrite(directionPinWest2, LOW); } else { digitalWrite(directionPinWest1, LOW); digitalWrite(directionPinWest2, HIGH); } } void PWMCbForward(const std_msgs::Int32& msg) { if (msg.data > 0) { thrusterEast(msg.data, true); thrusterWest(msg.data, true); } else { thrusterEast(msg.data, false); thrusterWest(msg.data, false); } isMovingForward = true; } void PWMCbSideward(const std_msgs::Int32& msg) { if (msg.data > 0) { thrusterNorthSway(msg.data, true); thrusterSouthSway(msg.data, true); } else { thrusterNorthSway(msg.data, false); thrusterSouthSway(msg.data, false); } isMovingForward = false; } void PWMCbUpward(const std_msgs::Int32& msg) { if (msg.data > 0) { thrusterNorthUp(msg.data, true); thrusterSouthUp(msg.data, true); } else { thrusterNorthUp(msg.data, false); thrusterSouthUp(msg.data, false); } } void PWMCbTurn(const std_msgs::Int32& msg) { if (!isMovingForward) { if (msg.data > 0) { thrusterEast(msg.data, true); thrusterWest(msg.data, false); } else { thrusterEast(msg.data, false); thrusterWest(msg.data, true); } } else { if (msg.data > 0) { thrusterNorthSway(msg.data, false); thrusterSouthSway(msg.data, true); } else { thrusterNorthSway(msg.data, true); thrusterSouthSway(msg.data, false); } } } ros::Subscriber<std_msgs::Int32> subPwmForward("/pwm/forward", &PWMCbForward); ros::Subscriber<std_msgs::Int32> subPwmSideward("/pwm/sideward", &PWMCbSideward); ros::Subscriber<std_msgs::Int32> subPwmUpward("/pwm/upward", &PWMCbUpward); ros::Subscriber<std_msgs::Int32> subPwmTurn("/pwm/turn", &PWMCbTurn); ros::Publisher ps_voltage("zDistance", &voltage); void setup() { nh.initNode(); pinMode(pwmPinEast, OUTPUT); pinMode(directionPinEast1, OUTPUT); pinMode(directionPinEast2, OUTPUT); pinMode(pwmPinWest, OUTPUT); pinMode(directionPinWest1, OUTPUT); pinMode(directionPinWest2, OUTPUT); pinMode(directionPinSouthSway1, OUTPUT); pinMode(directionPinSouthSway2, OUTPUT); pinMode(pwmPinNorthSway, OUTPUT); pinMode(directionPinNorthSway2, OUTPUT); pinMode(pwmPinSouthSway, OUTPUT); pinMode(directionPinNorthSway1, OUTPUT); pinMode(directionPinSouthUp1, OUTPUT); pinMode(directionPinSouthUp2, OUTPUT); pinMode(pwmPinNorthUp, OUTPUT); pinMode(directionPinNorthUp2, OUTPUT); pinMode(pwmPinSouthUp, OUTPUT); pinMode(directionPinNorthUp1, OUTPUT); nh.subscribe(subPwmForward); nh.subscribe(subPwmSideward); nh.subscribe(subPwmUpward); nh.subscribe(subPwmTurn); nh.advertise(ps_voltage); Serial.begin(57600); std_msgs::Int32 msg; msg.data = 0; PWMCbForward(msg); PWMCbSideward(msg); PWMCbUpward(msg); PWMCbTurn(msg); } void loop() { v = analogRead(analogPinPressureSensor); voltage.data = v; ps_voltage.publish(&voltage); nh.spinOnce(); delay(1); } <commit_msg>changes after testing<commit_after>// Copyright 2016 AUV-IITK #include <ros.h> #include <Arduino.h> #include <std_msgs/Int32.h> #include <std_msgs/Float64.h> #include <math.h> #define pwmPinWest 3 #define pwmPinEast 2 #define directionPinWest1 30 #define directionPinWest2 31 #define directionPinEast1 33 #define directionPinEast2 32 #define pwmPinNorthSway 5 #define pwmPinSouthSway 4 #define directionPinNorthSway1 26 #define directionPinNorthSway2 27 #define directionPinSouthSway1 28 #define directionPinSouthSway2 29 #define pwmPinNorthUp 6 #define pwmPinSouthUp 7 #define directionPinNorthUp1 24 #define directionPinNorthUp2 25 #define directionPinSouthUp1 22 #define directionPinSouthUp2 23 #define analogPinPressureSensor A0 const float c092 = 506.22; const float s092 = -2.65; const float c093 = 448.62; const float s093 = -2.92; const float c099 = 397.65; // reference as their graph is at lowest const float s099 = -2.71; // reference as their graph is at lowest const float c113 = 539.85; const float s113 = -3.38; const float c117 = 441.32; const float s117 = -3.03; const float c122 = 547.39; const float s122 = -2.93; bool isMovingForward = true; float v; std_msgs::Float64 voltage; ros::NodeHandle nh; int btd092(int pwm) { pwm = (c099 + s099 * pwm - c092) / (s092); if (pwm < 147) return 0; if (pwm > 255) return 255; return pwm; } int btd093(int pwm) { pwm = (c099 + s099 * pwm - c093) / (s093); if (pwm < 147) return 0; if (pwm > 255) return 255; return pwm; } int btd099(int pwm) { if (pwm < 147) return 0; if (pwm > 255) return 255; return pwm; } int btd113(int pwm) { pwm = (c099 + s099 * pwm - c113) / (s113); if (pwm < 147) return 0; if (pwm > 255) return 255; return pwm; } int btd117(int pwm) { pwm = (c099 + s099 * pwm - c117) / (s117); if (pwm < 147) return 0; if (pwm > 255) return 255; return pwm; } int btd122(int pwm) { pwm = (c099 + s099 * pwm - c122) / (s122); if (pwm < 147) return 0; if (pwm > 255) return 255; return pwm; } void thrusterNorthUp(int pwm, int isUpward) { pwm = abs(pwm); pwm = btd117(pwm); analogWrite(pwmPinNorthUp, 255 - pwm); if (isUpward) { digitalWrite(directionPinNorthUp1, HIGH); digitalWrite(directionPinNorthUp2, LOW); } else { digitalWrite(directionPinNorthUp1, LOW); digitalWrite(directionPinNorthUp2, HIGH); } } void thrusterSouthUp(int pwm, int isUpward) { pwm = abs(pwm); pwm = btd093(pwm); analogWrite(pwmPinSouthUp, 255 - pwm); if (isUpward) { digitalWrite(directionPinSouthUp1, HIGH); digitalWrite(directionPinSouthUp2, LOW); } else { digitalWrite(directionPinSouthUp1, LOW); digitalWrite(directionPinSouthUp2, HIGH); } } void thrusterNorthSway(int pwm, int isRight) { pwm = abs(pwm); pwm = btd113(pwm); analogWrite(pwmPinNorthSway, 255 - pwm); if (isRight) { digitalWrite(directionPinNorthSway1, HIGH); digitalWrite(directionPinNorthSway2, LOW); } else { digitalWrite(directionPinNorthSway1, LOW); digitalWrite(directionPinNorthSway2, HIGH); } } void thrusterSouthSway(int pwm, int isRight) { pwm = abs(pwm); pwm = btd122(pwm); analogWrite(pwmPinSouthSway, 255 - pwm); if (isRight) { digitalWrite(directionPinSouthSway1, HIGH); digitalWrite(directionPinSouthSway2, LOW); } else { digitalWrite(directionPinSouthSway1, LOW); digitalWrite(directionPinSouthSway2, HIGH); } } void thrusterEast(int pwm, int isForward) { pwm = abs(pwm); pwm = btd092(pwm); analogWrite(pwmPinEast, 255 - pwm); if (isForward) { digitalWrite(directionPinEast1, HIGH); digitalWrite(directionPinEast2, LOW); } else { digitalWrite(directionPinEast1, LOW); digitalWrite(directionPinEast2, HIGH); } } void thrusterWest(int pwm, int isForward) { pwm = abs(pwm); pwm = btd099(pwm); analogWrite(pwmPinWest, 255 - pwm); if (isForward) { digitalWrite(directionPinWest1, HIGH); digitalWrite(directionPinWest2, LOW); } else { digitalWrite(directionPinWest1, LOW); digitalWrite(directionPinWest2, HIGH); } } void PWMCbForward(const std_msgs::Int32& msg) { if (msg.data > 0) { thrusterEast(msg.data, true); thrusterWest(msg.data, true); } else { thrusterEast(msg.data, false); thrusterWest(msg.data, false); } isMovingForward = true; } void PWMCbSideward(const std_msgs::Int32& msg) { if (msg.data > 0) { thrusterNorthSway(msg.data, true); thrusterSouthSway(msg.data, true); } else { thrusterNorthSway(msg.data, false); thrusterSouthSway(msg.data, false); } isMovingForward = false; } void PWMCbUpward(const std_msgs::Int32& msg) { if (msg.data > 0) { thrusterNorthUp(msg.data, true); thrusterSouthUp(msg.data, true); } else { thrusterNorthUp(msg.data, false); thrusterSouthUp(msg.data, false); } } void PWMCbTurn(const std_msgs::Int32& msg) { if (!isMovingForward) { if (msg.data > 0) { thrusterEast(msg.data, true); thrusterWest(msg.data, false); } else { thrusterEast(msg.data, false); thrusterWest(msg.data, true); } } else { if (msg.data > 0) { thrusterNorthSway(msg.data, false); thrusterSouthSway(msg.data, true); } else { thrusterNorthSway(msg.data, true); thrusterSouthSway(msg.data, false); } } } ros::Subscriber<std_msgs::Int32> subPwmForward("/pwm/forward", &PWMCbForward); ros::Subscriber<std_msgs::Int32> subPwmSideward("/pwm/sideward", &PWMCbSideward); ros::Subscriber<std_msgs::Int32> subPwmUpward("/pwm/upward", &PWMCbUpward); ros::Subscriber<std_msgs::Int32> subPwmTurn("/pwm/turn", &PWMCbTurn); ros::Publisher ps_voltage("zDistance", &voltage); void setup() { nh.initNode(); pinMode(pwmPinEast, OUTPUT); pinMode(directionPinEast1, OUTPUT); pinMode(directionPinEast2, OUTPUT); pinMode(pwmPinWest, OUTPUT); pinMode(directionPinWest1, OUTPUT); pinMode(directionPinWest2, OUTPUT); pinMode(directionPinSouthSway1, OUTPUT); pinMode(directionPinSouthSway2, OUTPUT); pinMode(pwmPinNorthSway, OUTPUT); pinMode(directionPinNorthSway2, OUTPUT); pinMode(pwmPinSouthSway, OUTPUT); pinMode(directionPinNorthSway1, OUTPUT); pinMode(directionPinSouthUp1, OUTPUT); pinMode(directionPinSouthUp2, OUTPUT); pinMode(pwmPinNorthUp, OUTPUT); pinMode(directionPinNorthUp2, OUTPUT); pinMode(pwmPinSouthUp, OUTPUT); pinMode(directionPinNorthUp1, OUTPUT); nh.subscribe(subPwmForward); nh.subscribe(subPwmSideward); nh.subscribe(subPwmUpward); nh.subscribe(subPwmTurn); nh.advertise(ps_voltage); Serial.begin(57600); std_msgs::Int32 msg; msg.data = 0; PWMCbForward(msg); PWMCbSideward(msg); PWMCbUpward(msg); PWMCbTurn(msg); } void loop() { v = analogRead(analogPinPressureSensor); voltage.data = v; ps_voltage.publish(&voltage); nh.spinOnce(); delay(100); } <|endoftext|>
<commit_before><commit_msg>Improve string_view interface<commit_after><|endoftext|>
<commit_before>#include <TF3.h> #include <TTree.h> #include <TStyle.h> #include <TStopwatch.h> #include "X.h" #include "Units.h" using namespace GeFiCa; X::X(int nx, const char *name, const char *title) : TNamed(name,title), V0(0), V1(2e3*volt), MaxIterations(5000), Nsor(0), Csor(1.95), Precision(1e-7*volt), fN(nx), fN1(nx), fN2(0), fN3(0) { if (fN<10) { Warning("X","fN<10, set it to 11"); fN=11; fN1=11; } fV=new double[fN]; fE1=new double[fN]; fE2=new double[fN]; fE3=new double[fN]; fC1=new double[fN]; fC2=new double[fN]; fC3=new double[fN]; fdC1p=new double[fN]; fdC1m=new double[fN]; fdC2p=new double[fN]; fdC2m=new double[fN]; fdC3p=new double[fN]; fdC3m=new double[fN]; fIsFixed=new bool[fN]; fIsDepleted=new bool[fN]; fImpurity=new double[fN]; for (int i=0;i<fN;i++) { fV[i]=0; fE1[i]=0; fE2[i]=0; fE3[i]=0; fC1[i]=0; fC2[i]=0; fC3[i]=0; fdC1m[i]=0; fdC1p[i]=0; fdC2m[i]=0; fdC2p[i]=0; fdC3m[i]=0; fdC3p[i]=0; fIsFixed[i]=false; fIsDepleted[i]=true; fImpurity[i]=0; } fTree=NULL; fImpDist=NULL; // pick up a good style to modify gROOT->SetStyle("Plain"); gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XYZ"); gStyle->SetTitleFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ"); gStyle->SetTitleOffset(-0.4,"Z"); gStyle->SetPadTopMargin(0.02); // create a smoother palette than the default one const int nRGBs = 5; const int nCont = 255; double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; double red[nRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; double blue[nRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont); gStyle->SetNumberContours(nCont); } //_____________________________________________________________________________ // X::~X() { if (fV) delete[] fV; if (fE1) delete[] fE1; if (fC1) delete[] fC1; if (fdC1p) delete[] fdC1p; if (fdC1m) delete[] fdC1m; if (fIsFixed) delete[] fIsFixed; if (fImpurity) delete[] fImpurity; if (fIsDepleted) delete[] fIsDepleted; } //_____________________________________________________________________________ // bool X::Analytic() { Info("Analytic", "There is no analytic solution for this setup"); return false; } //_____________________________________________________________________________ // X& X::operator+=(GeFiCa::X *other) { if (fN!=other->fN) { Warning("+=", "Only same type of detector can be added together! Do nothing."); return *this; } for (int i=0; i<fN; i++) { fV[i]=fV[i]+other->fV[i]; fImpurity[i]+=other->fImpurity[i]; } V0+=other->V0; V1+=other->V1; return *this; } //_____________________________________________________________________________ // X& X::operator*=(double p) { for (int i=0; i<fN; i++) fV[i]=fV[i]*p; V0*=p; V1*=p; return *this; } //_____________________________________________________________________________ // int X::GetIdxOfMaxV() { double max=fV[0]; int maxn=0; for(int i=1;i<fN;i++) { if(fV[i]>max) { maxn=i; max=fV[i]; } } return maxn; } //_____________________________________________________________________________ // int X::GetIdxOfMinV() { double min=fV[0]; int minn=0; for(int i=1;i<fN;i++) { if(fV[i]<min) { minn=i; min=fV[i]; } } return minn; } //_____________________________________________________________________________ // bool X::IsDepleted() { for(int i=0;i<fN;i++) { DoSOR2(i); // calculate one more time in case of //adding two fields together, one is depleted, the other is not if (!fIsDepleted[i]) return false; } return true; } //_____________________________________________________________________________ // void X::SetStepLength(double stepLength) { for (int i=fN;i-->0;) { fIsFixed[i]=false; fC1[i]=i*stepLength; fdC1p[i]=stepLength; fdC1m[i]=stepLength; } } //_____________________________________________________________________________ // int* X::FindSurroundingMatrix(int idx) { int *tmp=new int[3]; tmp[0]=idx; if(idx-1<0)tmp[1]=1; else tmp[1]=idx-1; if(idx+1>=fN)tmp[2]=fN-2; else tmp[2]=idx+1; return tmp; } //_____________________________________________________________________________ // bool X::CalculatePotential(EMethod method) { if (fdC1p[0]==0) Initialize(); // setup and initialize grid if it's not done if (method==kAnalytic) return Analytic(); Info("CalculatePotential","Start SOR..."); TStopwatch watch; watch.Start(); double cp=1; // current presision while (Nsor<MaxIterations) { if (Nsor%100==0) Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); double XUpSum=0; double XDownSum=0; for (int i=fN-1;i>=0;i--) { double old=fV[i]; DoSOR2(i); if(old>0)XDownSum+=old; else XDownSum-=old; double diff=fV[i]-old; if(diff>0)XUpSum+=(diff); else XUpSum-=(diff); } cp = XUpSum/XDownSum; Nsor++; if (cp<Precision) break; } for (int i=0; i<fN; i++) if (!CalculateField(i)) return false; Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); Info("CalculatePotential", "CPU time: %.1f s", watch.CpuTime()); return true; } //_____________________________________________________________________________ // void X::DoSOR2(int idx) { // 2nd-order Runge-Kutta Successive Over-Relaxation if (fIsFixed[idx])return ; double rho=-fImpurity[idx]*Qe; double h2=fdC1m[idx]; double h3=fdC1p[idx]; double p2=fV[idx-1]; double p3=fV[idx+1]; double tmp=-rho/epsilon*h2*h3/2 + (h3*fV[idx-1]+h2*fV[idx+1])/(h2+h3); //find minmium and maxnium of all five grid, the new one should not go overthem. //find min double min=p2; double max=p2; if(min>p3)min=p3; //find max if(max<p3)max=p3; //if tmp is greater or smaller than max and min, set tmp to it. //fV[idx]=Csor*(tmp-fV[idx])+fV[idx]; double oldP=fV[idx]; tmp=Csor*(tmp-oldP)+oldP; if(tmp<min) { fV[idx]=min; fIsDepleted[idx]=false; } else if(tmp>max) { fV[idx]=max; fIsDepleted[idx]=false; } else fIsDepleted[idx]=true; if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp; } //_____________________________________________________________________________ // int X::FindIdx(double tarx,int begin,int end) { //search using binary search if (begin>=end)return end; int mid=(begin+end)/2; if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid); else return FindIdx(tarx,mid+1,end); } //_____________________________________________________________________________ // double X::GetData(double x, double y, double z, double *data) { int idx=FindIdx(x,0,fN-1); if (idx==fN) return data[idx]; double ab=(-x+fC1[idx])/fdC1p[idx]; double aa=1-ab; return data[idx]*ab+data[idx-1]*aa; } //_____________________________________________________________________________ // bool X::CalculateField(int idx) { if (fdC1p[idx]==0 || fdC1m[idx]==0) return false; if (idx%fN1==0) // C1 lower boundary fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx]; else if (idx%fN1==fN1-1) // C1 upper boundary fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx]; else // bulk fE1[idx]=(fV[idx-1]-fV[idx+1])/(fdC1m[idx]+fdC1p[idx]); return true; } //_____________________________________________________________________________ // double X::GetC() { Info("GetC","Start..."); CalculatePotential(GeFiCa::kSOR2); // set impurity to zero double *tmpImpurity=fImpurity; for (int i=0;i<fN;i++) { if (fImpurity[i]!=0) { fImpurity=new double[fN]; for (int j=0;j<fN;j++) { fImpurity[j]=0; if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true; } break; } } // calculate potential without impurity CalculatePotential(GeFiCa::kSOR2); // set impurity back if(fImpurity!=tmpImpurity) delete []fImpurity; fImpurity=tmpImpurity; // calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2 double dV=V0-V1; if(dV<0)dV=-dV; double SumofElectricField=0; for(int i=0;i<fN-1;i++) { SumofElectricField+=fE1[i]*fE1[i]*fdC1p[i]*cm*cm; if (!fIsDepleted[i]) fIsFixed[i]=false; } double c=SumofElectricField*epsilon/dV/dV; Info("GetC","%.1f pF",c/pF); return c; } //_____________________________________________________________________________ // TTree* X::GetTree(bool createNew) { if (fTree) { if (createNew) delete fTree; else return fTree; } // define tree bool b,d; double v,te,e1,e2,e3,c1,c2,c3; fTree = new TTree("t","field data"); fTree->Branch("potential",&v,"v/D"); fTree->Branch("total E ",&te,"e/D"); // 1D data fTree->Branch("E1 ",&e1,"e1/D"); fTree->Branch("1st coordinate",&c1,"c1/D"); // initialize values if (fdC1p[0]==0) Initialize(); // setup & initialize grid if (fdC2p[0]!=0) { // if it is a 2D grid fTree->Branch("E2 ",&e2,"e2/D"); fTree->Branch("2nd coordinate",&c2,"c2/D"); } if (fdC3p[0]!=0) { // if it is a 3D grid fTree->Branch("E3 ",&e3,"e3/D"); fTree->Branch("3rd coordinate",&c3,"c3/D"); } fTree->Branch("boundary flag",&b,"b/O"); // boundary flag fTree->Branch("depletion flag",&d,"d/O"); // depletion flag // fill tree Info("GetTree","%d entries",fN); for (int i=0; i<fN; i++) { e1= fE1[i]; c1= fC1[i]; // 1D data if (fdC2p[i]!=0) { e2=fE2[i]; c2=fC2[i]; } // 2D data if (fdC3p[i]!=0) { e3=fE3[i]; c3=fC3[i]; } // 3D data v = fV[i]; b = fIsFixed[i]; d = fIsDepleted[i]; // common data if (fdC3p[i]!=0) te=TMath::Sqrt(e1*e1 + e2*e2 + e3*e3); else { if (fdC2p[i]!=0) te=TMath::Sqrt(e1*e1+e2*e2); else te=e1; } fTree->Fill(); } fTree->GetListOfBranches()->ls(); gDirectory->ls(); fTree->ResetBranchAddresses(); // disconnect from local variables return fTree; } //_____________________________________________________________________________ // void X::SetGridImpurity() { if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet for (int i=fN;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]); } <commit_msg>removed unnecessary unit in calculation<commit_after>#include <TF3.h> #include <TTree.h> #include <TStyle.h> #include <TStopwatch.h> #include "X.h" #include "Units.h" using namespace GeFiCa; X::X(int nx, const char *name, const char *title) : TNamed(name,title), V0(0), V1(2e3*volt), MaxIterations(5000), Nsor(0), Csor(1.95), Precision(1e-7*volt), fN(nx), fN1(nx), fN2(0), fN3(0) { if (fN<10) { Warning("X","fN<10, set it to 11"); fN=11; fN1=11; } fV=new double[fN]; fE1=new double[fN]; fE2=new double[fN]; fE3=new double[fN]; fC1=new double[fN]; fC2=new double[fN]; fC3=new double[fN]; fdC1p=new double[fN]; fdC1m=new double[fN]; fdC2p=new double[fN]; fdC2m=new double[fN]; fdC3p=new double[fN]; fdC3m=new double[fN]; fIsFixed=new bool[fN]; fIsDepleted=new bool[fN]; fImpurity=new double[fN]; for (int i=0;i<fN;i++) { fV[i]=0; fE1[i]=0; fE2[i]=0; fE3[i]=0; fC1[i]=0; fC2[i]=0; fC3[i]=0; fdC1m[i]=0; fdC1p[i]=0; fdC2m[i]=0; fdC2p[i]=0; fdC3m[i]=0; fdC3p[i]=0; fIsFixed[i]=false; fIsDepleted[i]=true; fImpurity[i]=0; } fTree=NULL; fImpDist=NULL; // pick up a good style to modify gROOT->SetStyle("Plain"); gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XYZ"); gStyle->SetTitleFont(132,"XYZ"); gStyle->SetLabelSize(0.05,"XYZ"); gStyle->SetTitleSize(0.05,"XYZ"); gStyle->SetTitleOffset(-0.4,"Z"); gStyle->SetPadTopMargin(0.02); // create a smoother palette than the default one const int nRGBs = 5; const int nCont = 255; double stops[nRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; double red[nRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; double green[nRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; double blue[nRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; TColor::CreateGradientColorTable(nRGBs, stops, red, green, blue, nCont); gStyle->SetNumberContours(nCont); } //_____________________________________________________________________________ // X::~X() { if (fV) delete[] fV; if (fE1) delete[] fE1; if (fC1) delete[] fC1; if (fdC1p) delete[] fdC1p; if (fdC1m) delete[] fdC1m; if (fIsFixed) delete[] fIsFixed; if (fImpurity) delete[] fImpurity; if (fIsDepleted) delete[] fIsDepleted; } //_____________________________________________________________________________ // bool X::Analytic() { Info("Analytic", "There is no analytic solution for this setup"); return false; } //_____________________________________________________________________________ // X& X::operator+=(GeFiCa::X *other) { if (fN!=other->fN) { Warning("+=", "Only same type of detector can be added together! Do nothing."); return *this; } for (int i=0; i<fN; i++) { fV[i]=fV[i]+other->fV[i]; fImpurity[i]+=other->fImpurity[i]; } V0+=other->V0; V1+=other->V1; return *this; } //_____________________________________________________________________________ // X& X::operator*=(double p) { for (int i=0; i<fN; i++) fV[i]=fV[i]*p; V0*=p; V1*=p; return *this; } //_____________________________________________________________________________ // int X::GetIdxOfMaxV() { double max=fV[0]; int maxn=0; for(int i=1;i<fN;i++) { if(fV[i]>max) { maxn=i; max=fV[i]; } } return maxn; } //_____________________________________________________________________________ // int X::GetIdxOfMinV() { double min=fV[0]; int minn=0; for(int i=1;i<fN;i++) { if(fV[i]<min) { minn=i; min=fV[i]; } } return minn; } //_____________________________________________________________________________ // bool X::IsDepleted() { for(int i=0;i<fN;i++) { DoSOR2(i); // calculate one more time in case of //adding two fields together, one is depleted, the other is not if (!fIsDepleted[i]) return false; } return true; } //_____________________________________________________________________________ // void X::SetStepLength(double stepLength) { for (int i=fN;i-->0;) { fIsFixed[i]=false; fC1[i]=i*stepLength; fdC1p[i]=stepLength; fdC1m[i]=stepLength; } } //_____________________________________________________________________________ // int* X::FindSurroundingMatrix(int idx) { int *tmp=new int[3]; tmp[0]=idx; if(idx-1<0)tmp[1]=1; else tmp[1]=idx-1; if(idx+1>=fN)tmp[2]=fN-2; else tmp[2]=idx+1; return tmp; } //_____________________________________________________________________________ // bool X::CalculatePotential(EMethod method) { if (fdC1p[0]==0) Initialize(); // setup and initialize grid if it's not done if (method==kAnalytic) return Analytic(); Info("CalculatePotential","Start SOR..."); TStopwatch watch; watch.Start(); double cp=1; // current presision while (Nsor<MaxIterations) { if (Nsor%100==0) Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); double XUpSum=0; double XDownSum=0; for (int i=fN-1;i>=0;i--) { double old=fV[i]; DoSOR2(i); if(old>0)XDownSum+=old; else XDownSum-=old; double diff=fV[i]-old; if(diff>0)XUpSum+=(diff); else XUpSum-=(diff); } cp = XUpSum/XDownSum; Nsor++; if (cp<Precision) break; } for (int i=0; i<fN; i++) if (!CalculateField(i)) return false; Printf("%4d steps, precision: %.1e (target: %.0e)", Nsor, cp, Precision); Info("CalculatePotential", "CPU time: %.1f s", watch.CpuTime()); return true; } //_____________________________________________________________________________ // void X::DoSOR2(int idx) { // 2nd-order Runge-Kutta Successive Over-Relaxation if (fIsFixed[idx])return ; double rho=-fImpurity[idx]*Qe; double h2=fdC1m[idx]; double h3=fdC1p[idx]; double p2=fV[idx-1]; double p3=fV[idx+1]; double tmp=-rho/epsilon*h2*h3/2 + (h3*fV[idx-1]+h2*fV[idx+1])/(h2+h3); //find minmium and maxnium of all five grid, the new one should not go overthem. //find min double min=p2; double max=p2; if(min>p3)min=p3; //find max if(max<p3)max=p3; //if tmp is greater or smaller than max and min, set tmp to it. //fV[idx]=Csor*(tmp-fV[idx])+fV[idx]; double oldP=fV[idx]; tmp=Csor*(tmp-oldP)+oldP; if(tmp<min) { fV[idx]=min; fIsDepleted[idx]=false; } else if(tmp>max) { fV[idx]=max; fIsDepleted[idx]=false; } else fIsDepleted[idx]=true; if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp; } //_____________________________________________________________________________ // int X::FindIdx(double tarx,int begin,int end) { //search using binary search if (begin>=end)return end; int mid=(begin+end)/2; if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid); else return FindIdx(tarx,mid+1,end); } //_____________________________________________________________________________ // double X::GetData(double x, double y, double z, double *data) { int idx=FindIdx(x,0,fN-1); if (idx==fN) return data[idx]; double ab=(-x+fC1[idx])/fdC1p[idx]; double aa=1-ab; return data[idx]*ab+data[idx-1]*aa; } //_____________________________________________________________________________ // bool X::CalculateField(int idx) { if (fdC1p[idx]==0 || fdC1m[idx]==0) return false; if (idx%fN1==0) // C1 lower boundary fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx]; else if (idx%fN1==fN1-1) // C1 upper boundary fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx]; else // bulk fE1[idx]=(fV[idx-1]-fV[idx+1])/(fdC1m[idx]+fdC1p[idx]); return true; } //_____________________________________________________________________________ // double X::GetC() { Info("GetC","Start..."); CalculatePotential(GeFiCa::kSOR2); // set impurity to zero double *tmpImpurity=fImpurity; for (int i=0;i<fN;i++) { if (fImpurity[i]!=0) { fImpurity=new double[fN]; for (int j=0;j<fN;j++) { fImpurity[j]=0; if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true; } break; } } // calculate potential without impurity CalculatePotential(GeFiCa::kSOR2); // set impurity back if(fImpurity!=tmpImpurity) delete []fImpurity; fImpurity=tmpImpurity; // calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2 double dV=V0-V1; if(dV<0)dV=-dV; double SumofElectricField=0; for(int i=0;i<fN-1;i++) { SumofElectricField+=fE1[i]*fE1[i]*fdC1p[i]; if (!fIsDepleted[i]) fIsFixed[i]=false; } double c=SumofElectricField*epsilon/dV/dV; Info("GetC","%.2f pF",c/pF); return c; } //_____________________________________________________________________________ // TTree* X::GetTree(bool createNew) { if (fTree) { if (createNew) delete fTree; else return fTree; } // define tree bool b,d; double v,te,e1,e2,e3,c1,c2,c3; fTree = new TTree("t","field data"); fTree->Branch("potential",&v,"v/D"); fTree->Branch("total E ",&te,"e/D"); // 1D data fTree->Branch("E1 ",&e1,"e1/D"); fTree->Branch("1st coordinate",&c1,"c1/D"); // initialize values if (fdC1p[0]==0) Initialize(); // setup & initialize grid if (fdC2p[0]!=0) { // if it is a 2D grid fTree->Branch("E2 ",&e2,"e2/D"); fTree->Branch("2nd coordinate",&c2,"c2/D"); } if (fdC3p[0]!=0) { // if it is a 3D grid fTree->Branch("E3 ",&e3,"e3/D"); fTree->Branch("3rd coordinate",&c3,"c3/D"); } fTree->Branch("boundary flag",&b,"b/O"); // boundary flag fTree->Branch("depletion flag",&d,"d/O"); // depletion flag // fill tree Info("GetTree","%d entries",fN); for (int i=0; i<fN; i++) { e1= fE1[i]; c1= fC1[i]; // 1D data if (fdC2p[i]!=0) { e2=fE2[i]; c2=fC2[i]; } // 2D data if (fdC3p[i]!=0) { e3=fE3[i]; c3=fC3[i]; } // 3D data v = fV[i]; b = fIsFixed[i]; d = fIsDepleted[i]; // common data if (fdC3p[i]!=0) te=TMath::Sqrt(e1*e1 + e2*e2 + e3*e3); else { if (fdC2p[i]!=0) te=TMath::Sqrt(e1*e1+e2*e2); else te=e1; } fTree->Fill(); } fTree->GetListOfBranches()->ls(); gDirectory->ls(); fTree->ResetBranchAddresses(); // disconnect from local variables return fTree; } //_____________________________________________________________________________ // void X::SetGridImpurity() { if (fImpDist && fImpurity[0]==0) // set impurity values if it's not done yet for (int i=fN;i-->0;) fImpurity[i]=fImpDist->Eval(fC1[i], fC2[i], fC3[i]); } <|endoftext|>
<commit_before>// Copyright (c) 2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <uint256.h> #include <arith_uint256.h> #include <ethereum/ethereum.h> #include <ethereum/sha3.h> #include <logging.h> #include <util/strencodings.h> #include <key_io.h> int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) { std::string partialPath; char pathPtrInt[2] = {encodedPartialPath[0], '\0'}; int partialPathInt = strtol(pathPtrInt, NULL, 10); if(partialPathInt == 0 || partialPathInt == 2){ partialPath = encodedPartialPath.substr(2); }else{ partialPath = encodedPartialPath.substr(1); } if(partialPath == path.substr(pathPtr, partialPath.size())){ return partialPath.size(); }else{ return -1; } } std::string hexToASCII(std::string hex) { // initialize the ASCII code string as empty. std::string ascii = ""; for (size_t i = 0; i < hex.length(); i += 2) { // extract two characters from hex string std::string part = hex.substr(i, 2); // change it into base 16 and // typecast as the character char ch = std::stoul(part, nullptr, 16); // add this char to final ASCII string ascii += ch; } return ascii; } bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) { try{ dev::RLP currentNode; const int len = parentNodes.itemCount(); dev::RLP nodeKey = root; int pathPtr = 0; const std::string pathString = dev::toHex(path); int nibbles; char pathPtrInt[2]; for (int i = 0 ; i < len ; i++) { currentNode = parentNodes[i]; if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){ return false; } if(pathPtr > (int)pathString.size()){ return false; } switch(currentNode.itemCount()){ case 17://branch node if(pathPtr == (int)pathString.size()){ if(currentNode[16].payload().contentsEqual(value.data().toVector())){ return true; }else{ return false; } } pathPtrInt[0] = pathString[pathPtr]; pathPtrInt[1] = '\0'; nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]])) pathPtr += 1; break; case 2: nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr); if(nibbles <= -1) return false; pathPtr += nibbles; if(pathPtr == (int)pathString.size()) { //leaf node if(currentNode[1].payload().contentsEqual(value.data().toVector())){ return true; } else { return false; } } else {//extension node nodeKey = currentNode[1]; } break; default: return false; } } } catch(...){ return false; } return false; } /** * Parse eth input string expected to contain smart contract method call data. If the method call is not what we * expected, or the length of the expected string is not what we expect then return false. * * @param vchInputExpectedMethodHash The expected method hash * @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits * @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits * @param vchInputData The input to parse * @param outputAmount The amount burned * @param nAsset The asset burned * @param witnessAddress The destination witness address for the minting * @return true if everything is valid */ bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector<unsigned char>& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) { // total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash if(vchInputData.size() < 164 || vchInputData.size() > 196) { return false; } // method hash is 4 bytes std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin(); std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4; const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod); // if the method hash doesn't match the expected method hash then return false if(vchMethodHash != vchInputExpectedMethodHash) { return false; } std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32); // reverse endian std::reverse(vchAmount.begin(), vchAmount.end()); arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount)); // local precision can range between 0 and 8 decimal places, so it should fit within a CAmount // we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred if(nLocalPrecision > nERC20Precision){ outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision); // ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision } else if(nLocalPrecision < nERC20Precision){ outputAmountArith /= pow(10, nERC20Precision-nLocalPrecision); } outputAmount = outputAmountArith.GetLow64(); // convert the vch into a uint32_t (nAsset) // should be in position 68 walking backwards nAsset = static_cast<uint32_t>(vchInputData[67]); nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8; nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16; nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24; // skip data field marker (32 bytes) + 31 bytes offset to the varint _byte const unsigned char &dataLength = vchInputData[131]; // bech32 addresses to 46 bytes (sys1 vs bc1), min length is 9 for min witness address https://en.bitcoin.it/wiki/BIP_0173 if(dataLength > 46 || dataLength < 9) { return false; } // witness address information starting at position 132 till the end witnessAddress = DecodeDestination(hexToASCII(HexStr(vchInputData.begin()+132, vchInputData.begin()+132 + dataLength)))); return true; }<commit_msg>compile<commit_after>// Copyright (c) 2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <uint256.h> #include <arith_uint256.h> #include <ethereum/ethereum.h> #include <ethereum/sha3.h> #include <logging.h> #include <util/strencodings.h> #include <key_io.h> int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) { std::string partialPath; char pathPtrInt[2] = {encodedPartialPath[0], '\0'}; int partialPathInt = strtol(pathPtrInt, NULL, 10); if(partialPathInt == 0 || partialPathInt == 2){ partialPath = encodedPartialPath.substr(2); }else{ partialPath = encodedPartialPath.substr(1); } if(partialPath == path.substr(pathPtr, partialPath.size())){ return partialPath.size(); }else{ return -1; } } std::string hexToASCII(std::string hex) { // initialize the ASCII code string as empty. std::string ascii = ""; for (size_t i = 0; i < hex.length(); i += 2) { // extract two characters from hex string std::string part = hex.substr(i, 2); // change it into base 16 and // typecast as the character char ch = std::stoul(part, nullptr, 16); // add this char to final ASCII string ascii += ch; } return ascii; } bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) { try{ dev::RLP currentNode; const int len = parentNodes.itemCount(); dev::RLP nodeKey = root; int pathPtr = 0; const std::string pathString = dev::toHex(path); int nibbles; char pathPtrInt[2]; for (int i = 0 ; i < len ; i++) { currentNode = parentNodes[i]; if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){ return false; } if(pathPtr > (int)pathString.size()){ return false; } switch(currentNode.itemCount()){ case 17://branch node if(pathPtr == (int)pathString.size()){ if(currentNode[16].payload().contentsEqual(value.data().toVector())){ return true; }else{ return false; } } pathPtrInt[0] = pathString[pathPtr]; pathPtrInt[1] = '\0'; nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]])) pathPtr += 1; break; case 2: nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr); if(nibbles <= -1) return false; pathPtr += nibbles; if(pathPtr == (int)pathString.size()) { //leaf node if(currentNode[1].payload().contentsEqual(value.data().toVector())){ return true; } else { return false; } } else {//extension node nodeKey = currentNode[1]; } break; default: return false; } } } catch(...){ return false; } return false; } /** * Parse eth input string expected to contain smart contract method call data. If the method call is not what we * expected, or the length of the expected string is not what we expect then return false. * * @param vchInputExpectedMethodHash The expected method hash * @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits * @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits * @param vchInputData The input to parse * @param outputAmount The amount burned * @param nAsset The asset burned * @param witnessAddress The destination witness address for the minting * @return true if everything is valid */ bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector<unsigned char>& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) { // total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash if(vchInputData.size() < 164 || vchInputData.size() > 196) { return false; } // method hash is 4 bytes std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin(); std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4; const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod); // if the method hash doesn't match the expected method hash then return false if(vchMethodHash != vchInputExpectedMethodHash) { return false; } std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32); // reverse endian std::reverse(vchAmount.begin(), vchAmount.end()); arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount)); // local precision can range between 0 and 8 decimal places, so it should fit within a CAmount // we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred if(nLocalPrecision > nERC20Precision){ outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision); // ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision } else if(nLocalPrecision < nERC20Precision){ outputAmountArith /= pow(10, nERC20Precision-nLocalPrecision); } outputAmount = outputAmountArith.GetLow64(); // convert the vch into a uint32_t (nAsset) // should be in position 68 walking backwards nAsset = static_cast<uint32_t>(vchInputData[67]); nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8; nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16; nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24; // skip data field marker (32 bytes) + 31 bytes offset to the varint _byte const unsigned char &dataLength = vchInputData[131]; // bech32 addresses to 46 bytes (sys1 vs bc1), min length is 9 for min witness address https://en.bitcoin.it/wiki/BIP_0173 if(dataLength > 46 || dataLength < 9) { return false; } // witness address information starting at position 132 till the end witnessAddress = DecodeDestination(hexToASCII(HexStr(vchInputData.begin()+132, vchInputData.begin()+132 + dataLength))); return true; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-07-17 13:08: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 DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ DBG_NAME(OComponentDefinition_Impl) OComponentDefinition_Impl::OComponentDefinition_Impl() { DBG_CTOR(OComponentDefinition_Impl,NULL); } // ----------------------------------------------------------------------------- OComponentDefinition_Impl::~OComponentDefinition_Impl() { DBG_DTOR(OComponentDefinition_Impl,NULL); } //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl& rDefinition( getDefinition() ); ODataSettings::registerPropertiesFor( &rDefinition ); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.is() ) { m_pColumns->disposing(); m_pColumns.reset(); } } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.is() ) { ::std::vector< ::rtl::OUString> aNames; const OComponentDefinition_Impl& rDefinition( getDefinition() ); aNames.reserve( rDefinition.size() ); OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin(); OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end(); for ( ; aIter != aEnd; ++aIter ) aNames.push_back( aIter->first ); m_pColumns = TColumnsHelper( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) ); m_pColumns->setParent(*this); } return m_pColumns.getRef(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { const OComponentDefinition_Impl& rDefinition( getDefinition() ); OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName ); if ( aFind != rDefinition.end() ) return new OTableColumnWrapper( aFind->second, aFind->second, sal_True ); return new OTableColumn( _rName ); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createColumnDescriptor() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { getDefinition().erase( _sName ); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor ) { ::rtl::OUString sName; _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName; Reference<XPropertySet> xColDesc = new OTableColumnDescriptor(); ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc ); getDefinition().insert( sName, xColDesc ); // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl) // which held another XChild weak, and forwarded all getParent requests to this other XChild. // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies, // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless. // // The intention for this parenting was that the column descriptor is able to find the data source, // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which // for instance causes #i65023#). We need another way to properly ensure this. notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS dba204c (1.9.4); FILE MERGED 2006/07/21 11:14:14 fs 1.9.4.2: still #i67635#: ooops don't access a NULL m_pColumns in disposing ... 2006/07/21 11:03:37 fs 1.9.4.1: #i67635# make m_pColumns an ::sdt::auto_ptr, again<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: ihi $ $Date: 2006-08-04 13:56:18 $ * * 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 DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ DBG_NAME(OComponentDefinition_Impl) OComponentDefinition_Impl::OComponentDefinition_Impl() { DBG_CTOR(OComponentDefinition_Impl,NULL); } // ----------------------------------------------------------------------------- OComponentDefinition_Impl::~OComponentDefinition_Impl() { DBG_DTOR(OComponentDefinition_Impl,NULL); } //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl& rDefinition( getDefinition() ); ODataSettings::registerPropertiesFor( &rDefinition ); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.get() ) m_pColumns->disposing(); } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.get() ) { ::std::vector< ::rtl::OUString> aNames; const OComponentDefinition_Impl& rDefinition( getDefinition() ); aNames.reserve( rDefinition.size() ); OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin(); OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end(); for ( ; aIter != aEnd; ++aIter ) aNames.push_back( aIter->first ); m_pColumns.reset( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) ); m_pColumns->setParent( *this ); } return m_pColumns.get(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { const OComponentDefinition_Impl& rDefinition( getDefinition() ); OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName ); if ( aFind != rDefinition.end() ) return new OTableColumnWrapper( aFind->second, aFind->second, sal_True ); return new OTableColumn( _rName ); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createColumnDescriptor() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { getDefinition().erase( _sName ); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor ) { ::rtl::OUString sName; _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName; Reference<XPropertySet> xColDesc = new OTableColumnDescriptor(); ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc ); getDefinition().insert( sName, xColDesc ); // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl) // which held another XChild weak, and forwarded all getParent requests to this other XChild. // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies, // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless. // // The intention for this parenting was that the column descriptor is able to find the data source, // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which // for instance causes #i65023#). We need another way to properly ensure this. notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before>/** \brief Utility for updating SQL schemata etc. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <algorithm> #include <iostream> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "DbConnection.h" #include "StringUtil.h" #include "util.h" namespace { void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table, unsigned * const version) { std::vector<std::string> parts; if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3)) LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!"); *database = parts[0]; *table = parts[1]; *version = StringUtil::ToUnsigned(parts[2]); } __attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) { const auto first_plus_pos(compound_table_name.find('+')); return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos); } // The filenames being compared are assumed to have the "structure database.table.version" bool FileNameCompare(const std::string &filename1, const std::string &filename2) { std::string database1, table1; unsigned version1; SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1); std::string database2, table2; unsigned version2; SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2); // Compare database names: if (database1 < database2) return true; if (database1 > database2) return false; // Compare table names: if (GetFirstTableName(table1) < GetFirstTableName(table2)) return true; if (GetFirstTableName(table1) > GetFirstTableName(table2)) return false; return version1 < version2; } void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) { FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+"); for (const auto &entry : directory) update_filenames->emplace_back(entry.getName()); std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare); } std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) { std::vector<std::string> all_table_names; StringUtil::Split(compound_table_name, '+', &all_table_names); return all_table_names; } void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) { std::string database, tables; unsigned update_version; SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version); db_connection->queryOrDie("START TRANSACTION"); bool can_update(true); for (const auto &table : GetAllTableNames(tables)) { unsigned current_version(0); db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) { db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('" + db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)"); LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions."); } else current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]); if (update_version <= current_version) { can_update = false; continue; } if (unlikely(not can_update)) LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!"); db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version) + " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'"); if (unlikely(update_version != current_version + 1)) LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version) + " for table \"" + database + "." + table + "\"!"); LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\"."); } if (can_update) { db_connection->queryFileOrDie(update_directory_path + "/" + update_filename); db_connection->queryOrDie("COMMIT"); } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 2) ::Usage("[--verbose] update_directory_path"); std::vector<std::string> update_filenames; const std::string update_directory_path(argv[1]); LoadAndSortUpdateFilenames(update_directory_path, &update_filenames); DbConnection db_connection; if (not db_connection.tableExists("ub_tools", "table_versions")) { db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, " "table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) " "CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); LOG_INFO("Created the ub_tools.table_versions table."); } for (const auto &update_filename : update_filenames) ApplyUpdate(&db_connection, update_directory_path, update_filename); return EXIT_SUCCESS; } <commit_msg>Tried to fix the problem of multiple updates.<commit_after>/** \brief Utility for updating SQL schemata etc. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <algorithm> #include <iostream> #include <utility> #include <vector> #include <cstdio> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "DbConnection.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("[--test] update_directory_path"); } void SplitIntoDatabaseTablesAndVersions(const std::string &update_filename, std::string * const database, std::vector<std::pair<std::string, unsigned>> * const tables_and_versions) { tables_and_versions->clear(); std::vector<std::string> parts; if (unlikely(StringUtil::Split(update_filename, '.', &parts, /* suppress_empty_components = */false) != 2)) LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table;version[+table;version]*\"! (1)"); *database = parts[0]; std::vector<std::string> parts2; StringUtil::Split(parts[1], '+', &parts2, /* suppress_empty_components = */false); for (const auto &part : parts2) { std::vector<std::string> parts3; if (unlikely(StringUtil::Split(part, '.', &parts3, /* suppress_empty_components = */false) != 2 or parts3[0].empty() or parts3[1].empty())) LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table;version[+table;version]*\"! (1)"); tables_and_versions->emplace_back(std::make_pair(parts3[0], StringUtil::ToUnsigned(parts3[1]))); } } // The filenames being compared are assumed to have the "structure database.table;version[+table;version]*" bool FileNameCompare(const std::string &filename1, const std::string &filename2) { std::string database1; std::vector<std::pair<std::string, unsigned>> tables_and_versions1; SplitIntoDatabaseTablesAndVersions(filename1, &database1, &tables_and_versions1); std::string database2; std::vector<std::pair<std::string, unsigned>> tables_and_versions2; SplitIntoDatabaseTablesAndVersions(filename2, &database2, &tables_and_versions2); // Compare database names: if (database1 < database2) return true; if (database1 > database2) return false; // Compare table names and versions. If we have more than one common table name, the ordering has to be the same for all // shared table names or we have an unresolvable situation! unsigned one_before_two(0), two_before_one(0); // Ordering between shared table names. for (const auto &table_and_version1 : tables_and_versions1) { const auto table_and_version2(std::find_if(tables_and_versions2.cbegin(), tables_and_versions2.cend(), [&table_and_version1](const std::pair<std::string, unsigned> &table_and_version) { return table_and_version.first == table_and_version1.first; })); if (table_and_version2 != tables_and_versions2.cend()) { if (unlikely(table_and_version1.second == table_and_version2->second)) LOG_ERROR("impossible filename comparsion \"" + filename1 + "\" with \"" + filename2 + "\"! (1)"); else if (table_and_version1.second < table_and_version2->second) ++one_before_two; else ++two_before_one; } } if (unlikely(one_before_two > 0 and two_before_one > 0)) LOG_ERROR("impossible filename comparsion \"" + filename1 + "\" with \"" + filename2 + "\"! (2)"); else if (one_before_two > 0) return true; else if (two_before_one > 0) return false; // ...fall back on alphanumeric comparison: return tables_and_versions1[0].first < tables_and_versions2[0].first; } void LoadAndSortUpdateFilenames(const bool test, const std::string &directory_path, std::vector<std::string> * const update_filenames) { FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+"); for (const auto &entry : directory) update_filenames->emplace_back(entry.getName()); std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare); if (test) { std::cerr << "Sorted filenames:\n"; for (const auto &filename : *update_filenames) std::cerr << filename << '\n'; std::exit(0); } } void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) { std::string database; std::vector<std::pair<std::string, unsigned>> tables_and_versions; SplitIntoDatabaseTablesAndVersions(update_filename, &database, &tables_and_versions); db_connection->queryOrDie("START TRANSACTION"); bool can_update(true); for (const auto &table_and_version : tables_and_versions) { unsigned current_version(0); db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table_and_version.first) + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) { db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('" + db_connection->escapeString(database) + "','" + db_connection->escapeString(table_and_version.first) + "',0)"); LOG_INFO("Created a new entry for " + database + "." + table_and_version.first + " in ub_tools.table_versions."); } else current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]); if (table_and_version.second <= current_version) { can_update = false; continue; } if (unlikely(not can_update)) LOG_ERROR("inconsistent update \"" + update_filename + "\"!"); db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(table_and_version.second) + " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table_and_version.first) + "'"); if (unlikely(table_and_version.second != current_version + 1)) LOG_ERROR("update version is " + std::to_string(table_and_version.second) + ", current version is " + std::to_string(current_version) + " for table \"" + database + "." + table_and_version.first + "\"!"); LOG_INFO("applying update \"" + database + "." + table_and_version.first + "." + std::to_string(table_and_version.second) + "\"."); } if (can_update) { db_connection->queryFileOrDie(update_directory_path + "/" + update_filename); db_connection->queryOrDie("COMMIT"); } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 2 and argc != 3) Usage(); bool test(false); if (argc == 3) { if (std::strcmp(argv[1], "--test") != 0) Usage(); test = true; --argc, ++argv; } std::vector<std::string> update_filenames; const std::string update_directory_path(argv[1]); LoadAndSortUpdateFilenames(test, update_directory_path, &update_filenames); DbConnection db_connection; if (not db_connection.tableExists("ub_tools", "table_versions")) { db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, " "table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) " "CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); LOG_INFO("Created the ub_tools.table_versions table."); } for (const auto &update_filename : update_filenames) ApplyUpdate(&db_connection, update_directory_path, update_filename); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "inspectable_web_contents_view_linux.h" #include "browser/browser_client.h" #include "browser/inspectable_web_contents_impl.h" #include "content/public/browser/web_contents_view.h" namespace brightray { InspectableWebContentsView* CreateInspectableContentsView(InspectableWebContentsImpl* inspectable_web_contents) { return new InspectableWebContentsViewLinux(inspectable_web_contents); } InspectableWebContentsViewLinux::InspectableWebContentsViewLinux(InspectableWebContentsImpl* inspectable_web_contents) : inspectable_web_contents_(inspectable_web_contents) { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::InspectableWebContentsViewLinux\n"); } InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux() { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux\n"); } gfx::NativeView InspectableWebContentsViewLinux::GetNativeView() const { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::~GetNativeView\n"); return NULL; } void InspectableWebContentsViewLinux::ShowDevTools() { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::ShowDevTools\n"); } void InspectableWebContentsViewLinux::CloseDevTools() { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::CloseDevTools\n"); } bool InspectableWebContentsViewLinux::SetDockSide(const std::string& side) { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::SetDockSide\n"); return false; } } <commit_msg>fix typo<commit_after>#include "inspectable_web_contents_view_linux.h" #include "browser/browser_client.h" #include "browser/inspectable_web_contents_impl.h" #include "content/public/browser/web_contents_view.h" namespace brightray { InspectableWebContentsView* CreateInspectableContentsView(InspectableWebContentsImpl* inspectable_web_contents) { return new InspectableWebContentsViewLinux(inspectable_web_contents); } InspectableWebContentsViewLinux::InspectableWebContentsViewLinux(InspectableWebContentsImpl* inspectable_web_contents) : inspectable_web_contents_(inspectable_web_contents) { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::InspectableWebContentsViewLinux\n"); } InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux() { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux\n"); } gfx::NativeView InspectableWebContentsViewLinux::GetNativeView() const { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::GetNativeView\n"); return NULL; } void InspectableWebContentsViewLinux::ShowDevTools() { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::ShowDevTools\n"); } void InspectableWebContentsViewLinux::CloseDevTools() { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::CloseDevTools\n"); } bool InspectableWebContentsViewLinux::SetDockSide(const std::string& side) { // TODO fprintf(stderr, "InspectableWebContentsViewLinux::SetDockSide\n"); return false; } } <|endoftext|>
<commit_before>// Copyright 2006-2008 the V8 project authors. 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "bootstrapper.h" #include "debug.h" #include "scopeinfo.h" namespace v8 { namespace internal { JSBuiltinsObject* Context::builtins() { GlobalObject* object = global(); if (object->IsJSGlobalObject()) { return JSGlobalObject::cast(object)->builtins(); } else { ASSERT(object->IsJSBuiltinsObject()); return JSBuiltinsObject::cast(object); } } Context* Context::global_context() { // Fast case: the global object for this context has been set. In // that case, the global object has a direct pointer to the global // context. if (global()->IsGlobalObject()) { return global()->global_context(); } // During bootstrapping, the global object might not be set and we // have to search the context chain to find the global context. Context* current = this; while (!current->IsGlobalContext()) { current = Context::cast(JSFunction::cast(current->closure())->context()); } return current; } JSObject* Context::global_proxy() { return global_context()->global_proxy_object(); } void Context::set_global_proxy(JSObject* object) { global_context()->set_global_proxy_object(object); } Handle<Object> Context::Lookup(Handle<String> name, ContextLookupFlags flags, int* index_, PropertyAttributes* attributes) { Handle<Context> context(this); // The context must be in frame slot 0 (if not debugging). if (kDebug && !Debug::InDebugger()) { StackFrameLocator locator; ASSERT(context->fcontext() == Context::cast( locator.FindJavaScriptFrame(0)->context())->fcontext()); } bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0; *index_ = -1; *attributes = ABSENT; if (FLAG_trace_contexts) { PrintF("Context::Lookup("); name->ShortPrint(); PrintF(")\n"); } do { if (FLAG_trace_contexts) { PrintF(" - looking in context %p", *context); if (context->IsGlobalContext()) PrintF(" (global context)"); PrintF("\n"); } // check extension/with object if (context->has_extension()) { Handle<JSObject> extension = Handle<JSObject>(context->extension()); if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0) { *attributes = extension->GetLocalPropertyAttribute(*name); } else { *attributes = extension->GetPropertyAttribute(*name); } if (*attributes != ABSENT) { // property found if (FLAG_trace_contexts) { PrintF("=> found property in context object %p\n", *extension); } return extension; } } if (context->is_function_context()) { // we have context-local slots // check non-parameter locals in context Handle<Code> code(context->closure()->code()); Variable::Mode mode; int index = ScopeInfo<>::ContextSlotIndex(*code, *name, &mode); ASSERT(index < 0 || index >= MIN_CONTEXT_SLOTS); if (index >= 0) { // slot found if (FLAG_trace_contexts) { PrintF("=> found local in context slot %d (mode = %d)\n", index, mode); } *index_ = index; // Note: Fixed context slots are statically allocated by the compiler. // Statically allocated variables always have a statically known mode, // which is the mode with which they were declared when added to the // scope. Thus, the DYNAMIC mode (which corresponds to dynamically // declared variables that were introduced through declaration nodes) // must not appear here. switch (mode) { case Variable::INTERNAL : // fall through case Variable::VAR : *attributes = NONE; break; case Variable::CONST : *attributes = READ_ONLY; break; case Variable::DYNAMIC : UNREACHABLE(); break; case Variable::TEMPORARY: UNREACHABLE(); break; } return context; } // check parameter locals in context int param_index = ScopeInfo<>::ParameterIndex(*code, *name); if (param_index >= 0) { // slot found int index = ScopeInfo<>::ContextSlotIndex(*code, Heap::arguments_shadow_symbol(), NULL); ASSERT(index >= 0); // arguments must exist and be in the heap context Handle<JSObject> arguments(JSObject::cast(context->get(index))); ASSERT(arguments->HasLocalProperty(Heap::length_symbol())); if (FLAG_trace_contexts) { PrintF("=> found parameter %d in arguments object\n", param_index); } *index_ = param_index; *attributes = NONE; return arguments; } // check intermediate context (holding only the function name variable) if (follow_context_chain) { int index = ScopeInfo<>::FunctionContextSlotIndex(*code, *name); if (index >= 0) { // slot found if (FLAG_trace_contexts) { PrintF("=> found intermediate function in context slot %d\n", index); } *index_ = index; *attributes = READ_ONLY; return context; } } } // proceed with enclosing context if (context->IsGlobalContext()) { follow_context_chain = false; } else if (context->is_function_context()) { context = Handle<Context>(Context::cast(context->closure()->context())); } else { context = Handle<Context>(context->previous()); } } while (follow_context_chain); // slot not found if (FLAG_trace_contexts) { PrintF("=> no property/slot found\n"); } return Handle<Object>::null(); } #ifdef DEBUG bool Context::IsBootstrappingOrContext(Object* object) { // During bootstrapping we allow all objects to pass as // contexts. This is necessary to fix circular dependencies. return Bootstrapper::IsActive() || object->IsContext(); } bool Context::IsBootstrappingOrGlobalObject(Object* object) { // During bootstrapping we allow all objects to pass as global // objects. This is necessary to fix circular dependencies. return Bootstrapper::IsActive() || object->IsGlobalObject(); } #endif } } // namespace v8::internal <commit_msg>Removing assert to make flexo happy.<commit_after>// Copyright 2006-2008 the V8 project authors. 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "bootstrapper.h" #include "debug.h" #include "scopeinfo.h" namespace v8 { namespace internal { JSBuiltinsObject* Context::builtins() { GlobalObject* object = global(); if (object->IsJSGlobalObject()) { return JSGlobalObject::cast(object)->builtins(); } else { ASSERT(object->IsJSBuiltinsObject()); return JSBuiltinsObject::cast(object); } } Context* Context::global_context() { // Fast case: the global object for this context has been set. In // that case, the global object has a direct pointer to the global // context. if (global()->IsGlobalObject()) { return global()->global_context(); } // During bootstrapping, the global object might not be set and we // have to search the context chain to find the global context. Context* current = this; while (!current->IsGlobalContext()) { current = Context::cast(JSFunction::cast(current->closure())->context()); } return current; } JSObject* Context::global_proxy() { return global_context()->global_proxy_object(); } void Context::set_global_proxy(JSObject* object) { global_context()->set_global_proxy_object(object); } Handle<Object> Context::Lookup(Handle<String> name, ContextLookupFlags flags, int* index_, PropertyAttributes* attributes) { Handle<Context> context(this); bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0; *index_ = -1; *attributes = ABSENT; if (FLAG_trace_contexts) { PrintF("Context::Lookup("); name->ShortPrint(); PrintF(")\n"); } do { if (FLAG_trace_contexts) { PrintF(" - looking in context %p", *context); if (context->IsGlobalContext()) PrintF(" (global context)"); PrintF("\n"); } // check extension/with object if (context->has_extension()) { Handle<JSObject> extension = Handle<JSObject>(context->extension()); if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0) { *attributes = extension->GetLocalPropertyAttribute(*name); } else { *attributes = extension->GetPropertyAttribute(*name); } if (*attributes != ABSENT) { // property found if (FLAG_trace_contexts) { PrintF("=> found property in context object %p\n", *extension); } return extension; } } if (context->is_function_context()) { // we have context-local slots // check non-parameter locals in context Handle<Code> code(context->closure()->code()); Variable::Mode mode; int index = ScopeInfo<>::ContextSlotIndex(*code, *name, &mode); ASSERT(index < 0 || index >= MIN_CONTEXT_SLOTS); if (index >= 0) { // slot found if (FLAG_trace_contexts) { PrintF("=> found local in context slot %d (mode = %d)\n", index, mode); } *index_ = index; // Note: Fixed context slots are statically allocated by the compiler. // Statically allocated variables always have a statically known mode, // which is the mode with which they were declared when added to the // scope. Thus, the DYNAMIC mode (which corresponds to dynamically // declared variables that were introduced through declaration nodes) // must not appear here. switch (mode) { case Variable::INTERNAL : // fall through case Variable::VAR : *attributes = NONE; break; case Variable::CONST : *attributes = READ_ONLY; break; case Variable::DYNAMIC : UNREACHABLE(); break; case Variable::TEMPORARY: UNREACHABLE(); break; } return context; } // check parameter locals in context int param_index = ScopeInfo<>::ParameterIndex(*code, *name); if (param_index >= 0) { // slot found int index = ScopeInfo<>::ContextSlotIndex(*code, Heap::arguments_shadow_symbol(), NULL); ASSERT(index >= 0); // arguments must exist and be in the heap context Handle<JSObject> arguments(JSObject::cast(context->get(index))); ASSERT(arguments->HasLocalProperty(Heap::length_symbol())); if (FLAG_trace_contexts) { PrintF("=> found parameter %d in arguments object\n", param_index); } *index_ = param_index; *attributes = NONE; return arguments; } // check intermediate context (holding only the function name variable) if (follow_context_chain) { int index = ScopeInfo<>::FunctionContextSlotIndex(*code, *name); if (index >= 0) { // slot found if (FLAG_trace_contexts) { PrintF("=> found intermediate function in context slot %d\n", index); } *index_ = index; *attributes = READ_ONLY; return context; } } } // proceed with enclosing context if (context->IsGlobalContext()) { follow_context_chain = false; } else if (context->is_function_context()) { context = Handle<Context>(Context::cast(context->closure()->context())); } else { context = Handle<Context>(context->previous()); } } while (follow_context_chain); // slot not found if (FLAG_trace_contexts) { PrintF("=> no property/slot found\n"); } return Handle<Object>::null(); } #ifdef DEBUG bool Context::IsBootstrappingOrContext(Object* object) { // During bootstrapping we allow all objects to pass as // contexts. This is necessary to fix circular dependencies. return Bootstrapper::IsActive() || object->IsContext(); } bool Context::IsBootstrappingOrGlobalObject(Object* object) { // During bootstrapping we allow all objects to pass as global // objects. This is necessary to fix circular dependencies. return Bootstrapper::IsActive() || object->IsGlobalObject(); } #endif } } // namespace v8::internal <|endoftext|>
<commit_before>#include "SkMatrix.h" #ifdef SK_SCALAR_IS_FIXED typedef int64_t SkDScalar; static SkScalar SkDScalar_toScalar(SkDScalar value) { SkDScalar result = (value + (1 << 15)) >> 16; int top = result >> 31; SkASSERT(top == 0 || top == -1); return (SkScalar)result; } static SkScalar div(SkDScalar numer, SkDScalar denom) { denom >>= 16; return numer / denom; } #else typedef double SkDScalar; static SkScalar SkDScalar_toScalar(SkDScalar value) { return static_cast<float>(value); } static SkScalar div(SkDScalar numer, SkDScalar denom) { return static_cast<float>(numer / denom); } #endif static SkDScalar SkDScalar_setMul(SkScalar a, SkScalar b) { return (SkDScalar)a * b; } static void computeOuterProduct(SkScalar op[4], const SkPoint pts0[3], const SkPoint& ave0, const SkPoint pts1[3], const SkPoint& ave1) { sk_bzero(op, 4 * sizeof(op[0])); for (int i = 0; i < 3; i++) { SkScalar x0 = pts0[i].fX - ave0.fX; SkScalar y0 = pts0[i].fY - ave0.fY; SkScalar x1 = pts1[i].fX - ave1.fX; SkScalar y1 = pts1[i].fY - ave1.fY; op[0] += SkScalarMul(x0, x1); op[1] += SkScalarMul(x0, y1); op[2] += SkScalarMul(y0, x1); op[3] += SkScalarMul(y0, y1); } } static SkDScalar ddot(SkScalar ax, SkScalar ay, SkScalar bx, SkScalar by) { return SkDScalar_setMul(ax, bx) + SkDScalar_setMul(ay, by); } static SkScalar dot(SkScalar ax, SkScalar ay, SkScalar bx, SkScalar by) { return SkDScalar_toScalar(ddot(ax, ay, bx, by)); } bool SkSetPoly3To3(SkMatrix* matrix, const SkPoint src[3], const SkPoint dst[3]) { const SkPoint& srcAve = src[0]; const SkPoint& dstAve = dst[0]; SkScalar srcOP[4], dstOP[4]; computeOuterProduct(srcOP, src, srcAve, src, srcAve); computeOuterProduct(dstOP, src, srcAve, dst, dstAve); SkDScalar det = SkDScalar_setMul(srcOP[0], srcOP[3]) - SkDScalar_setMul(srcOP[1], srcOP[2]); SkDScalar M[4]; const SkScalar srcOP0 = srcOP[3]; const SkScalar srcOP1 = -srcOP[1]; const SkScalar srcOP2 = -srcOP[2]; const SkScalar srcOP3 = srcOP[0]; M[0] = ddot(srcOP0, srcOP1, dstOP[0], dstOP[2]); M[1] = ddot(srcOP2, srcOP3, dstOP[0], dstOP[2]); M[2] = ddot(srcOP0, srcOP1, dstOP[1], dstOP[3]); M[3] = ddot(srcOP2, srcOP3, dstOP[1], dstOP[3]); matrix->reset(); matrix->setScaleX(div(M[0], det)); matrix->setSkewX( div(M[1], det)); matrix->setSkewY (div(M[2], det)); matrix->setScaleY(div(M[3], det)); matrix->setTranslateX(dstAve.fX - dot(srcAve.fX, srcAve.fY, matrix->getScaleX(), matrix->getSkewX())); matrix->setTranslateY(dstAve.fY - dot(srcAve.fX, srcAve.fY, matrix->getSkewY(), matrix->getScaleY())); return true; } <commit_msg>In experimental/SkSetPoly3To3_A.cpp, rename div() to divide() to resolve namespace collision in Windows.<commit_after>#include "SkMatrix.h" #ifdef SK_SCALAR_IS_FIXED typedef int64_t SkDScalar; static SkScalar SkDScalar_toScalar(SkDScalar value) { SkDScalar result = (value + (1 << 15)) >> 16; int top = result >> 31; SkASSERT(top == 0 || top == -1); return (SkScalar)result; } static SkScalar divide(SkDScalar numer, SkDScalar denom) { denom >>= 16; return numer / denom; } #else typedef double SkDScalar; static SkScalar SkDScalar_toScalar(SkDScalar value) { return static_cast<float>(value); } static SkScalar divide(SkDScalar numer, SkDScalar denom) { return static_cast<float>(numer / denom); } #endif static SkDScalar SkDScalar_setMul(SkScalar a, SkScalar b) { return (SkDScalar)a * b; } static void computeOuterProduct(SkScalar op[4], const SkPoint pts0[3], const SkPoint& ave0, const SkPoint pts1[3], const SkPoint& ave1) { sk_bzero(op, 4 * sizeof(op[0])); for (int i = 0; i < 3; i++) { SkScalar x0 = pts0[i].fX - ave0.fX; SkScalar y0 = pts0[i].fY - ave0.fY; SkScalar x1 = pts1[i].fX - ave1.fX; SkScalar y1 = pts1[i].fY - ave1.fY; op[0] += SkScalarMul(x0, x1); op[1] += SkScalarMul(x0, y1); op[2] += SkScalarMul(y0, x1); op[3] += SkScalarMul(y0, y1); } } static SkDScalar ddot(SkScalar ax, SkScalar ay, SkScalar bx, SkScalar by) { return SkDScalar_setMul(ax, bx) + SkDScalar_setMul(ay, by); } static SkScalar dot(SkScalar ax, SkScalar ay, SkScalar bx, SkScalar by) { return SkDScalar_toScalar(ddot(ax, ay, bx, by)); } bool SkSetPoly3To3(SkMatrix* matrix, const SkPoint src[3], const SkPoint dst[3]) { const SkPoint& srcAve = src[0]; const SkPoint& dstAve = dst[0]; SkScalar srcOP[4], dstOP[4]; computeOuterProduct(srcOP, src, srcAve, src, srcAve); computeOuterProduct(dstOP, src, srcAve, dst, dstAve); SkDScalar det = SkDScalar_setMul(srcOP[0], srcOP[3]) - SkDScalar_setMul(srcOP[1], srcOP[2]); SkDScalar M[4]; const SkScalar srcOP0 = srcOP[3]; const SkScalar srcOP1 = -srcOP[1]; const SkScalar srcOP2 = -srcOP[2]; const SkScalar srcOP3 = srcOP[0]; M[0] = ddot(srcOP0, srcOP1, dstOP[0], dstOP[2]); M[1] = ddot(srcOP2, srcOP3, dstOP[0], dstOP[2]); M[2] = ddot(srcOP0, srcOP1, dstOP[1], dstOP[3]); M[3] = ddot(srcOP2, srcOP3, dstOP[1], dstOP[3]); matrix->reset(); matrix->setScaleX(divide(M[0], det)); matrix->setSkewX( divide(M[1], det)); matrix->setSkewY (divide(M[2], det)); matrix->setScaleY(divide(M[3], det)); matrix->setTranslateX(dstAve.fX - dot(srcAve.fX, srcAve.fY, matrix->getScaleX(), matrix->getSkewX())); matrix->setTranslateY(dstAve.fY - dot(srcAve.fX, srcAve.fY, matrix->getSkewY(), matrix->getScaleY())); return true; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "parquet/printer.h" #include <cstdint> #include <cstdio> #include <memory> #include <ostream> #include <string> #include <vector> #include "arrow/util/key_value_metadata.h" #include "arrow/util/string.h" #include "parquet/column_scanner.h" #include "parquet/exception.h" #include "parquet/file_reader.h" #include "parquet/metadata.h" #include "parquet/schema.h" #include "parquet/statistics.h" #include "parquet/types.h" namespace parquet { class ColumnReader; // ---------------------------------------------------------------------- // ParquetFilePrinter::DebugPrint // the fixed initial size is just for an example #define COL_WIDTH 30 void ParquetFilePrinter::DebugPrint(std::ostream& stream, std::list<int> selected_columns, bool print_values, bool format_dump, bool print_key_value_metadata, const char* filename) { const FileMetaData* file_metadata = fileReader->metadata().get(); stream << "File Name: " << filename << "\n"; stream << "Version: " << ParquetVersionToString(file_metadata->version()) << "\n"; stream << "Created By: " << file_metadata->created_by() << "\n"; stream << "Total rows: " << file_metadata->num_rows() << "\n"; if (print_key_value_metadata && file_metadata->key_value_metadata()) { auto key_value_metadata = file_metadata->key_value_metadata(); int64_t size_of_key_value_metadata = key_value_metadata->size(); stream << "Key Value File Metadata: " << size_of_key_value_metadata << " entries\n"; for (int64_t i = 0; i < size_of_key_value_metadata; i++) { stream << " Key nr " << i << " " << key_value_metadata->key(i) << ": " << key_value_metadata->value(i) << "\n"; } } stream << "Number of RowGroups: " << file_metadata->num_row_groups() << "\n"; stream << "Number of Real Columns: " << file_metadata->schema()->group_node()->field_count() << "\n"; if (selected_columns.size() == 0) { for (int i = 0; i < file_metadata->num_columns(); i++) { selected_columns.push_back(i); } } else { for (auto i : selected_columns) { if (i < 0 || i >= file_metadata->num_columns()) { throw ParquetException("Selected column is out of range"); } } } stream << "Number of Columns: " << file_metadata->num_columns() << "\n"; stream << "Number of Selected Columns: " << selected_columns.size() << "\n"; for (auto i : selected_columns) { const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << "Column " << i << ": " << descr->path()->ToDotString() << " (" << TypeToString(descr->physical_type()); if (descr->converted_type() != ConvertedType::NONE) { stream << "/" << ConvertedTypeToString(descr->converted_type()); } if (descr->converted_type() == ConvertedType::DECIMAL) { stream << "(" << descr->type_precision() << "," << descr->type_scale() << ")"; } stream << ")" << std::endl; } for (int r = 0; r < file_metadata->num_row_groups(); ++r) { stream << "--- Row Group: " << r << " ---\n"; auto group_reader = fileReader->RowGroup(r); std::unique_ptr<RowGroupMetaData> group_metadata = file_metadata->RowGroup(r); stream << "--- Total Bytes: " << group_metadata->total_byte_size() << " ---\n"; stream << "--- Rows: " << group_metadata->num_rows() << " ---\n"; // Print column metadata for (auto i : selected_columns) { auto column_chunk = group_metadata->ColumnChunk(i); std::shared_ptr<Statistics> stats = column_chunk->statistics(); const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << "Column " << i << std::endl << " Values: " << column_chunk->num_values(); if (column_chunk->is_stats_set()) { std::string min = stats->EncodeMin(), max = stats->EncodeMax(); stream << ", Null Values: " << stats->null_count() << ", Distinct Values: " << stats->distinct_count() << std::endl << " Max: " << FormatStatValue(descr->physical_type(), max) << ", Min: " << FormatStatValue(descr->physical_type(), min); } else { stream << " Statistics Not Set"; } stream << std::endl << " Compression: " << ::arrow::internal::AsciiToUpper( Codec::GetCodecAsString(column_chunk->compression())) << ", Encodings:"; for (auto encoding : column_chunk->encodings()) { stream << " " << EncodingToString(encoding); } stream << std::endl << " Uncompressed Size: " << column_chunk->total_uncompressed_size() << ", Compressed Size: " << column_chunk->total_compressed_size() << std::endl; } if (!print_values) { continue; } stream << "--- Values ---\n"; static constexpr int bufsize = COL_WIDTH + 1; char buffer[bufsize]; // Create readers for selected columns and print contents std::vector<std::shared_ptr<Scanner>> scanners(selected_columns.size(), nullptr); int j = 0; for (auto i : selected_columns) { std::shared_ptr<ColumnReader> col_reader = group_reader->Column(i); // This is OK in this method as long as the RowGroupReader does not get // deleted auto& scanner = scanners[j++] = Scanner::Make(col_reader); if (format_dump) { stream << "Column " << i << std::endl; while (scanner->HasNext()) { scanner->PrintNext(stream, 0, true); stream << "\n"; } continue; } snprintf(buffer, bufsize, "%-*s", COL_WIDTH, file_metadata->schema()->Column(i)->name().c_str()); stream << buffer << '|'; } if (format_dump) { continue; } stream << "\n"; bool hasRow; do { hasRow = false; for (auto scanner : scanners) { if (scanner->HasNext()) { hasRow = true; scanner->PrintNext(stream, COL_WIDTH); stream << '|'; } } stream << "\n"; } while (hasRow); } } void ParquetFilePrinter::JSONPrint(std::ostream& stream, std::list<int> selected_columns, const char* filename) { const FileMetaData* file_metadata = fileReader->metadata().get(); stream << "{\n"; stream << " \"FileName\": \"" << filename << "\",\n"; stream << " \"Version\": \"" << ParquetVersionToString(file_metadata->version()) << "\",\n"; stream << " \"CreatedBy\": \"" << file_metadata->created_by() << "\",\n"; stream << " \"TotalRows\": \"" << file_metadata->num_rows() << "\",\n"; stream << " \"NumberOfRowGroups\": \"" << file_metadata->num_row_groups() << "\",\n"; stream << " \"NumberOfRealColumns\": \"" << file_metadata->schema()->group_node()->field_count() << "\",\n"; stream << " \"NumberOfColumns\": \"" << file_metadata->num_columns() << "\",\n"; if (selected_columns.size() == 0) { for (int i = 0; i < file_metadata->num_columns(); i++) { selected_columns.push_back(i); } } else { for (auto i : selected_columns) { if (i < 0 || i >= file_metadata->num_columns()) { throw ParquetException("Selected column is out of range"); } } } stream << " \"Columns\": [\n"; int c = 0; for (auto i : selected_columns) { const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << " { \"Id\": \"" << i << "\", \"Name\": \"" << descr->name() << "\"," << " \"PhysicalType\": \"" << TypeToString(descr->physical_type()) << "\"," << " \"ConvertedType\": \"" << ConvertedTypeToString(descr->converted_type()) << "\"," << " \"LogicalType\": " << (descr->logical_type())->ToJSON() << " }"; c++; if (c != static_cast<int>(selected_columns.size())) { stream << ",\n"; } } stream << "\n ],\n \"RowGroups\": [\n"; for (int r = 0; r < file_metadata->num_row_groups(); ++r) { stream << " {\n \"Id\": \"" << r << "\", "; auto group_reader = fileReader->RowGroup(r); std::unique_ptr<RowGroupMetaData> group_metadata = file_metadata->RowGroup(r); stream << " \"TotalBytes\": \"" << group_metadata->total_byte_size() << "\", "; stream << " \"Rows\": \"" << group_metadata->num_rows() << "\",\n"; // Print column metadata stream << " \"ColumnChunks\": [\n"; int c1 = 0; for (auto i : selected_columns) { auto column_chunk = group_metadata->ColumnChunk(i); std::shared_ptr<Statistics> stats = column_chunk->statistics(); const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << " {\"Id\": \"" << i << "\", \"Values\": \"" << column_chunk->num_values() << "\", " << "\"StatsSet\": "; if (column_chunk->is_stats_set()) { stream << "\"True\", \"Stats\": {"; std::string min = stats->EncodeMin(), max = stats->EncodeMax(); stream << "\"NumNulls\": \"" << stats->null_count() << "\", " << "\"DistinctValues\": \"" << stats->distinct_count() << "\", " << "\"Max\": \"" << FormatStatValue(descr->physical_type(), max) << "\", " << "\"Min\": \"" << FormatStatValue(descr->physical_type(), min) << "\" },"; } else { stream << "\"False\","; } stream << "\n \"Compression\": \"" << ::arrow::internal::AsciiToUpper( Codec::GetCodecAsString(column_chunk->compression())) << "\", \"Encodings\": \""; for (auto encoding : column_chunk->encodings()) { stream << EncodingToString(encoding) << " "; } stream << "\", " << "\"UncompressedSize\": \"" << column_chunk->total_uncompressed_size() << "\", \"CompressedSize\": \"" << column_chunk->total_compressed_size(); // end of a ColumnChunk stream << "\" }"; c1++; if (c1 != static_cast<int>(selected_columns.size())) { stream << ",\n"; } } stream << "\n ]\n }"; if ((r + 1) != static_cast<int>(file_metadata->num_row_groups())) { stream << ",\n"; } } stream << "\n ]\n}\n"; } } // namespace parquet <commit_msg>ARROW-10514: [C++][Parquet] Make the column name the same for both output formats of parquet reader<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "parquet/printer.h" #include <cstdint> #include <cstdio> #include <memory> #include <ostream> #include <string> #include <vector> #include "arrow/util/key_value_metadata.h" #include "arrow/util/string.h" #include "parquet/column_scanner.h" #include "parquet/exception.h" #include "parquet/file_reader.h" #include "parquet/metadata.h" #include "parquet/schema.h" #include "parquet/statistics.h" #include "parquet/types.h" namespace parquet { class ColumnReader; // ---------------------------------------------------------------------- // ParquetFilePrinter::DebugPrint // the fixed initial size is just for an example #define COL_WIDTH 30 void ParquetFilePrinter::DebugPrint(std::ostream& stream, std::list<int> selected_columns, bool print_values, bool format_dump, bool print_key_value_metadata, const char* filename) { const FileMetaData* file_metadata = fileReader->metadata().get(); stream << "File Name: " << filename << "\n"; stream << "Version: " << ParquetVersionToString(file_metadata->version()) << "\n"; stream << "Created By: " << file_metadata->created_by() << "\n"; stream << "Total rows: " << file_metadata->num_rows() << "\n"; if (print_key_value_metadata && file_metadata->key_value_metadata()) { auto key_value_metadata = file_metadata->key_value_metadata(); int64_t size_of_key_value_metadata = key_value_metadata->size(); stream << "Key Value File Metadata: " << size_of_key_value_metadata << " entries\n"; for (int64_t i = 0; i < size_of_key_value_metadata; i++) { stream << " Key nr " << i << " " << key_value_metadata->key(i) << ": " << key_value_metadata->value(i) << "\n"; } } stream << "Number of RowGroups: " << file_metadata->num_row_groups() << "\n"; stream << "Number of Real Columns: " << file_metadata->schema()->group_node()->field_count() << "\n"; if (selected_columns.size() == 0) { for (int i = 0; i < file_metadata->num_columns(); i++) { selected_columns.push_back(i); } } else { for (auto i : selected_columns) { if (i < 0 || i >= file_metadata->num_columns()) { throw ParquetException("Selected column is out of range"); } } } stream << "Number of Columns: " << file_metadata->num_columns() << "\n"; stream << "Number of Selected Columns: " << selected_columns.size() << "\n"; for (auto i : selected_columns) { const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << "Column " << i << ": " << descr->path()->ToDotString() << " (" << TypeToString(descr->physical_type()); if (descr->converted_type() != ConvertedType::NONE) { stream << "/" << ConvertedTypeToString(descr->converted_type()); } if (descr->converted_type() == ConvertedType::DECIMAL) { stream << "(" << descr->type_precision() << "," << descr->type_scale() << ")"; } stream << ")" << std::endl; } for (int r = 0; r < file_metadata->num_row_groups(); ++r) { stream << "--- Row Group: " << r << " ---\n"; auto group_reader = fileReader->RowGroup(r); std::unique_ptr<RowGroupMetaData> group_metadata = file_metadata->RowGroup(r); stream << "--- Total Bytes: " << group_metadata->total_byte_size() << " ---\n"; stream << "--- Rows: " << group_metadata->num_rows() << " ---\n"; // Print column metadata for (auto i : selected_columns) { auto column_chunk = group_metadata->ColumnChunk(i); std::shared_ptr<Statistics> stats = column_chunk->statistics(); const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << "Column " << i << std::endl << " Values: " << column_chunk->num_values(); if (column_chunk->is_stats_set()) { std::string min = stats->EncodeMin(), max = stats->EncodeMax(); stream << ", Null Values: " << stats->null_count() << ", Distinct Values: " << stats->distinct_count() << std::endl << " Max: " << FormatStatValue(descr->physical_type(), max) << ", Min: " << FormatStatValue(descr->physical_type(), min); } else { stream << " Statistics Not Set"; } stream << std::endl << " Compression: " << ::arrow::internal::AsciiToUpper( Codec::GetCodecAsString(column_chunk->compression())) << ", Encodings:"; for (auto encoding : column_chunk->encodings()) { stream << " " << EncodingToString(encoding); } stream << std::endl << " Uncompressed Size: " << column_chunk->total_uncompressed_size() << ", Compressed Size: " << column_chunk->total_compressed_size() << std::endl; } if (!print_values) { continue; } stream << "--- Values ---\n"; static constexpr int bufsize = COL_WIDTH + 1; char buffer[bufsize]; // Create readers for selected columns and print contents std::vector<std::shared_ptr<Scanner>> scanners(selected_columns.size(), nullptr); int j = 0; for (auto i : selected_columns) { std::shared_ptr<ColumnReader> col_reader = group_reader->Column(i); // This is OK in this method as long as the RowGroupReader does not get // deleted auto& scanner = scanners[j++] = Scanner::Make(col_reader); if (format_dump) { stream << "Column " << i << std::endl; while (scanner->HasNext()) { scanner->PrintNext(stream, 0, true); stream << "\n"; } continue; } snprintf(buffer, bufsize, "%-*s", COL_WIDTH, file_metadata->schema()->Column(i)->name().c_str()); stream << buffer << '|'; } if (format_dump) { continue; } stream << "\n"; bool hasRow; do { hasRow = false; for (auto scanner : scanners) { if (scanner->HasNext()) { hasRow = true; scanner->PrintNext(stream, COL_WIDTH); stream << '|'; } } stream << "\n"; } while (hasRow); } } void ParquetFilePrinter::JSONPrint(std::ostream& stream, std::list<int> selected_columns, const char* filename) { const FileMetaData* file_metadata = fileReader->metadata().get(); stream << "{\n"; stream << " \"FileName\": \"" << filename << "\",\n"; stream << " \"Version\": \"" << ParquetVersionToString(file_metadata->version()) << "\",\n"; stream << " \"CreatedBy\": \"" << file_metadata->created_by() << "\",\n"; stream << " \"TotalRows\": \"" << file_metadata->num_rows() << "\",\n"; stream << " \"NumberOfRowGroups\": \"" << file_metadata->num_row_groups() << "\",\n"; stream << " \"NumberOfRealColumns\": \"" << file_metadata->schema()->group_node()->field_count() << "\",\n"; stream << " \"NumberOfColumns\": \"" << file_metadata->num_columns() << "\",\n"; if (selected_columns.size() == 0) { for (int i = 0; i < file_metadata->num_columns(); i++) { selected_columns.push_back(i); } } else { for (auto i : selected_columns) { if (i < 0 || i >= file_metadata->num_columns()) { throw ParquetException("Selected column is out of range"); } } } stream << " \"Columns\": [\n"; int c = 0; for (auto i : selected_columns) { const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << " { \"Id\": \"" << i << "\"," << " \"Name\": \"" << descr->path()->ToDotString() << "\"," << " \"PhysicalType\": \"" << TypeToString(descr->physical_type()) << "\"," << " \"ConvertedType\": \"" << ConvertedTypeToString(descr->converted_type()) << "\"," << " \"LogicalType\": " << (descr->logical_type())->ToJSON() << " }"; c++; if (c != static_cast<int>(selected_columns.size())) { stream << ",\n"; } } stream << "\n ],\n \"RowGroups\": [\n"; for (int r = 0; r < file_metadata->num_row_groups(); ++r) { stream << " {\n \"Id\": \"" << r << "\", "; auto group_reader = fileReader->RowGroup(r); std::unique_ptr<RowGroupMetaData> group_metadata = file_metadata->RowGroup(r); stream << " \"TotalBytes\": \"" << group_metadata->total_byte_size() << "\", "; stream << " \"Rows\": \"" << group_metadata->num_rows() << "\",\n"; // Print column metadata stream << " \"ColumnChunks\": [\n"; int c1 = 0; for (auto i : selected_columns) { auto column_chunk = group_metadata->ColumnChunk(i); std::shared_ptr<Statistics> stats = column_chunk->statistics(); const ColumnDescriptor* descr = file_metadata->schema()->Column(i); stream << " {\"Id\": \"" << i << "\", \"Values\": \"" << column_chunk->num_values() << "\", " << "\"StatsSet\": "; if (column_chunk->is_stats_set()) { stream << "\"True\", \"Stats\": {"; std::string min = stats->EncodeMin(), max = stats->EncodeMax(); stream << "\"NumNulls\": \"" << stats->null_count() << "\", " << "\"DistinctValues\": \"" << stats->distinct_count() << "\", " << "\"Max\": \"" << FormatStatValue(descr->physical_type(), max) << "\", " << "\"Min\": \"" << FormatStatValue(descr->physical_type(), min) << "\" },"; } else { stream << "\"False\","; } stream << "\n \"Compression\": \"" << ::arrow::internal::AsciiToUpper( Codec::GetCodecAsString(column_chunk->compression())) << "\", \"Encodings\": \""; for (auto encoding : column_chunk->encodings()) { stream << EncodingToString(encoding) << " "; } stream << "\", " << "\"UncompressedSize\": \"" << column_chunk->total_uncompressed_size() << "\", \"CompressedSize\": \"" << column_chunk->total_compressed_size(); // end of a ColumnChunk stream << "\" }"; c1++; if (c1 != static_cast<int>(selected_columns.size())) { stream << ",\n"; } } stream << "\n ]\n }"; if ((r + 1) != static_cast<int>(file_metadata->num_row_groups())) { stream << ",\n"; } } stream << "\n ]\n}\n"; } } // namespace parquet <|endoftext|>
<commit_before>/** * bitcoind.js * Copyright (c) 2014, BitPay (MIT License) * * bitcoindjs.cc: * A bitcoind node.js binding. */ #include "nan.h" /** * Bitcoin headers */ #include "core.h" #include "addrman.h" #include "checkpoints.h" #include "crypter.h" #include "main.h" // #include "random.h" // #include "timedata.h" #include "walletdb.h" #include "alert.h" #include "checkqueue.h" #include "db.h" #include "miner.h" #include "rpcclient.h" #include "tinyformat.h" #include "wallet.h" #include "allocators.h" #include "clientversion.h" #include "hash.h" #include "mruset.h" #include "rpcprotocol.h" #include "txdb.h" #include "base58.h" #include "coincontrol.h" #include "init.h" #include "netbase.h" #include "rpcserver.h" #include "txmempool.h" #include "bloom.h" #include "coins.h" #include "key.h" #include "net.h" #include "script.h" #include "ui_interface.h" // #include "chainparamsbase.h" #include "compat.h" #include "keystore.h" #include "noui.h" #include "serialize.h" #include "uint256.h" #include "chainparams.h" #include "core.h" #include "leveldbwrapper.h" // #include "pow.h" #include "sync.h" #include "util.h" // #include "chainparamsseeds.h" // #include "core_io.h" #include "limitedmap.h" #include "protocol.h" #include "threadsafety.h" #include "version.h" /** * Bitcoin Globals * Relevant: * ~/bitcoin/src/init.cpp * ~/bitcoin/src/bitcoind.cpp * ~/bitcoin/src/main.h */ extern void (ThreadImport)(std::vector<boost::filesystem::path>); extern void (DetectShutdownThread)(boost::thread_group*); extern void (StartNode)(boost::thread_group&); extern int nScriptCheckThreads; // extern const int DEFAULT_SCRIPTCHECK_THREADS; // static!! #ifdef ENABLE_WALLET extern std::string strWalletFile; extern CWallet *pwalletMain; #endif #include <node.h> #include <string> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> using namespace node; using namespace v8; NAN_METHOD(StartBitcoind); static void async_work(uv_work_t *req); static void async_after(uv_work_t *req); static int start_node(void); static unsigned int parse_logs(char **); extern "C" void init(Handle<Object>); /** * async_data * Where the uv async request data resides. */ struct async_data { Persistent<Function> callback; bool err; std::string err_msg; char *result; }; /** * StartBitcoind * bitcoind.start(callback) */ NAN_METHOD(StartBitcoind) { NanScope(); if (args.Length() < 1 || !args[0]->IsFunction()) { return NanThrowError( "Usage: bitcoind.start(callback)"); } // Run on a separate thead: // int log_fd = parse_logs(NULL); // handle->Set(NanNew<String>("log"), NanNew<Number>(log_fd)); Local<Function> callback = Local<Function>::Cast(args[0]); async_data* data = new async_data(); data->err = false; data->callback = Persistent<Function>::New(callback); uv_work_t *req = new uv_work_t(); req->data = data; int status = uv_queue_work(uv_default_loop(), req, async_work, (uv_after_work_cb)async_after); assert(status == 0); NanReturnValue(Undefined()); } /** * async_work() * Call start_node() and start all our boost threads. */ static void async_work(uv_work_t *req) { async_data* data = static_cast<async_data*>(req->data); // undefined symbol: _ZTIN5boost6detail16thread_data_baseE start_node(); data->result = (char *)strdup("opened"); } /** * async_after() * Execute our callback. */ static void async_after(uv_work_t *req) { NanScope(); async_data* data = static_cast<async_data*>(req->data); if (data->err) { Local<Value> err = Exception::Error(String::New(data->err_msg.c_str())); const unsigned argc = 1; Local<Value> argv[1] = { err }; TryCatch try_catch; data->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } else { const unsigned argc = 2; Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(String::New(data->result)) }; TryCatch try_catch; data->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } data->callback.Dispose(); if (data->result != NULL) { free(data->result); } delete data; delete req; } /** * start_node(void) * A reimplementation of AppInit2 minus * the logging and argument parsing. */ static int start_node(void) { boost::thread_group threadGroup; boost::thread *detectShutdownThread = NULL; detectShutdownThread = new boost::thread( boost::bind(&DetectShutdownThread, &threadGroup)); for (int i = 0; i < nScriptCheckThreads - 1; i++) { threadGroup.create_thread(&ThreadScriptCheck); } std::vector<boost::filesystem::path> vImportFiles; threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); StartNode(threadGroup); #ifdef ENABLE_WALLET if (pwalletMain) { pwalletMain->ReacceptWalletTransactions(); threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); } #endif return 0; } /** * parse_logs(log_str)' * Flow: * - If bitcoind logs, parse, write to pfd[0]. * - If our own logs, write to stdoutd.. * TODO: Have this running in a separate thread. */ const char bitcoind_char[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* <- ' ', */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ':', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'b', 'c', 'd', 0, 0, 0, 0, 'i', 0, 0, 0, 0, 'n', 'o', 0, 0, 0, 0, 't', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static unsigned int parse_logs(char **log_str) { int pfd[2]; pipe(pfd); unsigned int read_fd = pfd[0]; unsigned int write_fd = pfd[1]; dup2(write_fd, STDOUT_FILENO); int log_pipe[2]; pipe(log_pipe); unsigned int read_log = log_pipe[0]; unsigned int write_log = log_pipe[1]; unsigned int rtotal = 0; ssize_t r = 0; size_t rcount = 80 * sizeof(char); char *buf = (char *)malloc(rcount); char cur[9]; unsigned int cp = 0; unsigned int reallocs = 0; while ((r = read(read_fd, buf + rtotal, rcount))) { unsigned int i; char *rbuf; // Grab the buffer at the start of the bytes that were read: rbuf = (char *)(buf + r); // If these are our logs, write them to stdout: for (i = 0; i < r; i++) { // A naive semi-boyer-moore string search (is it a bitcoind: char?): unsigned char ch = rbuf[i]; if (bitcoind_char[ch]) { cur[cp] = rbuf[0]; cp++; cur[cp] = '\0'; if (strcmp(cur, "bitcoind:") == 0) { size_t wcount = r; ssize_t w = 0; ssize_t wtotal = 0; // undo redirection close(read_fd); close(write_fd); w = write(STDOUT_FILENO, cur, cp); wtotal += w; while ((w = write(STDOUT_FILENO, rbuf + i + wtotal, wcount))) { if (w == 0 || (size_t)wtotal == rcount) break; wtotal += w; } // reopen redirection { int pfd[2]; pipe(pfd); read_fd = pfd[0]; write_fd = pfd[1]; dup2(write_fd, STDOUT_FILENO); } break; } else if (cp == sizeof cur) { cp = 0; cur[cp] = '\0'; } } } // If these logs are from bitcoind, write them to the log pipe: for (i = 0; i < r; i++) { if ((rbuf[i] == '\r' && rbuf[i] == '\n') || rbuf[i] == '\r' || rbuf[i] == '\n') { size_t wcount = r; ssize_t w = 0; ssize_t wtotal = 0; while ((w = write(write_log, rbuf + i + wtotal + 1, wcount))) { if (w == 0 || (size_t)wtotal == rcount) break; wtotal += w; } } } rtotal += r; while (rtotal > rcount) { reallocs++; rcount = (rcount * 2) / reallocs; buf = (char *)realloc(buf, rcount); } } if (log_str) { buf[rtotal] = '\0'; *log_str = buf; } else { free(buf); } return read_log; } /** * Init */ extern "C" void init(Handle<Object> target) { NanScope(); NODE_SET_METHOD(target, "start", StartBitcoind); } NODE_MODULE(bitcoindjs, init) <commit_msg>boost error comment<commit_after>/** * bitcoind.js * Copyright (c) 2014, BitPay (MIT License) * * bitcoindjs.cc: * A bitcoind node.js binding. */ #include "nan.h" /** * Bitcoin headers */ #include "core.h" #include "addrman.h" #include "checkpoints.h" #include "crypter.h" #include "main.h" // #include "random.h" // #include "timedata.h" #include "walletdb.h" #include "alert.h" #include "checkqueue.h" #include "db.h" #include "miner.h" #include "rpcclient.h" #include "tinyformat.h" #include "wallet.h" #include "allocators.h" #include "clientversion.h" #include "hash.h" #include "mruset.h" #include "rpcprotocol.h" #include "txdb.h" #include "base58.h" #include "coincontrol.h" #include "init.h" #include "netbase.h" #include "rpcserver.h" #include "txmempool.h" #include "bloom.h" #include "coins.h" #include "key.h" #include "net.h" #include "script.h" #include "ui_interface.h" // #include "chainparamsbase.h" #include "compat.h" #include "keystore.h" #include "noui.h" #include "serialize.h" #include "uint256.h" #include "chainparams.h" #include "core.h" #include "leveldbwrapper.h" // #include "pow.h" #include "sync.h" #include "util.h" // #include "chainparamsseeds.h" // #include "core_io.h" #include "limitedmap.h" #include "protocol.h" #include "threadsafety.h" #include "version.h" /** * Bitcoin Globals * Relevant: * ~/bitcoin/src/init.cpp * ~/bitcoin/src/bitcoind.cpp * ~/bitcoin/src/main.h */ extern void (ThreadImport)(std::vector<boost::filesystem::path>); extern void (DetectShutdownThread)(boost::thread_group*); extern void (StartNode)(boost::thread_group&); extern int nScriptCheckThreads; // extern const int DEFAULT_SCRIPTCHECK_THREADS; // static!! #ifdef ENABLE_WALLET extern std::string strWalletFile; extern CWallet *pwalletMain; #endif #include <node.h> #include <string> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> using namespace node; using namespace v8; NAN_METHOD(StartBitcoind); static void async_work(uv_work_t *req); static void async_after(uv_work_t *req); static int start_node(void); static unsigned int parse_logs(char **); extern "C" void init(Handle<Object>); /** * async_data * Where the uv async request data resides. */ struct async_data { Persistent<Function> callback; bool err; std::string err_msg; char *result; }; /** * StartBitcoind * bitcoind.start(callback) */ NAN_METHOD(StartBitcoind) { NanScope(); if (args.Length() < 1 || !args[0]->IsFunction()) { return NanThrowError( "Usage: bitcoind.start(callback)"); } // Run on a separate thead: // int log_fd = parse_logs(NULL); // handle->Set(NanNew<String>("log"), NanNew<Number>(log_fd)); Local<Function> callback = Local<Function>::Cast(args[0]); async_data* data = new async_data(); data->err = false; data->callback = Persistent<Function>::New(callback); uv_work_t *req = new uv_work_t(); req->data = data; int status = uv_queue_work(uv_default_loop(), req, async_work, (uv_after_work_cb)async_after); assert(status == 0); NanReturnValue(Undefined()); } /** * async_work() * Call start_node() and start all our boost threads. */ static void async_work(uv_work_t *req) { async_data* data = static_cast<async_data*>(req->data); // undefined symbol: _ZTIN5boost6detail16thread_data_baseE // https://www.google.com/search?q=%22undefined+symbol%3A+_ZTIN5boost6detail16thread_data_baseE%22 start_node(); data->result = (char *)strdup("opened"); } /** * async_after() * Execute our callback. */ static void async_after(uv_work_t *req) { NanScope(); async_data* data = static_cast<async_data*>(req->data); if (data->err) { Local<Value> err = Exception::Error(String::New(data->err_msg.c_str())); const unsigned argc = 1; Local<Value> argv[1] = { err }; TryCatch try_catch; data->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } else { const unsigned argc = 2; Local<Value> argv[2] = { Local<Value>::New(Null()), Local<Value>::New(String::New(data->result)) }; TryCatch try_catch; data->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } data->callback.Dispose(); if (data->result != NULL) { free(data->result); } delete data; delete req; } /** * start_node(void) * A reimplementation of AppInit2 minus * the logging and argument parsing. */ static int start_node(void) { boost::thread_group threadGroup; boost::thread *detectShutdownThread = NULL; detectShutdownThread = new boost::thread( boost::bind(&DetectShutdownThread, &threadGroup)); for (int i = 0; i < nScriptCheckThreads - 1; i++) { threadGroup.create_thread(&ThreadScriptCheck); } std::vector<boost::filesystem::path> vImportFiles; threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); StartNode(threadGroup); #ifdef ENABLE_WALLET if (pwalletMain) { pwalletMain->ReacceptWalletTransactions(); threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); } #endif return 0; } /** * parse_logs(log_str)' * Flow: * - If bitcoind logs, parse, write to pfd[0]. * - If our own logs, write to stdoutd.. * TODO: Have this running in a separate thread. */ const char bitcoind_char[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* <- ' ', */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ':', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'b', 'c', 'd', 0, 0, 0, 0, 'i', 0, 0, 0, 0, 'n', 'o', 0, 0, 0, 0, 't', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static unsigned int parse_logs(char **log_str) { int pfd[2]; pipe(pfd); unsigned int read_fd = pfd[0]; unsigned int write_fd = pfd[1]; dup2(write_fd, STDOUT_FILENO); int log_pipe[2]; pipe(log_pipe); unsigned int read_log = log_pipe[0]; unsigned int write_log = log_pipe[1]; unsigned int rtotal = 0; ssize_t r = 0; size_t rcount = 80 * sizeof(char); char *buf = (char *)malloc(rcount); char cur[9]; unsigned int cp = 0; unsigned int reallocs = 0; while ((r = read(read_fd, buf + rtotal, rcount))) { unsigned int i; char *rbuf; // Grab the buffer at the start of the bytes that were read: rbuf = (char *)(buf + r); // If these are our logs, write them to stdout: for (i = 0; i < r; i++) { // A naive semi-boyer-moore string search (is it a bitcoind: char?): unsigned char ch = rbuf[i]; if (bitcoind_char[ch]) { cur[cp] = rbuf[0]; cp++; cur[cp] = '\0'; if (strcmp(cur, "bitcoind:") == 0) { size_t wcount = r; ssize_t w = 0; ssize_t wtotal = 0; // undo redirection close(read_fd); close(write_fd); w = write(STDOUT_FILENO, cur, cp); wtotal += w; while ((w = write(STDOUT_FILENO, rbuf + i + wtotal, wcount))) { if (w == 0 || (size_t)wtotal == rcount) break; wtotal += w; } // reopen redirection { int pfd[2]; pipe(pfd); read_fd = pfd[0]; write_fd = pfd[1]; dup2(write_fd, STDOUT_FILENO); } break; } else if (cp == sizeof cur) { cp = 0; cur[cp] = '\0'; } } } // If these logs are from bitcoind, write them to the log pipe: for (i = 0; i < r; i++) { if ((rbuf[i] == '\r' && rbuf[i] == '\n') || rbuf[i] == '\r' || rbuf[i] == '\n') { size_t wcount = r; ssize_t w = 0; ssize_t wtotal = 0; while ((w = write(write_log, rbuf + i + wtotal + 1, wcount))) { if (w == 0 || (size_t)wtotal == rcount) break; wtotal += w; } } } rtotal += r; while (rtotal > rcount) { reallocs++; rcount = (rcount * 2) / reallocs; buf = (char *)realloc(buf, rcount); } } if (log_str) { buf[rtotal] = '\0'; *log_str = buf; } else { free(buf); } return read_log; } /** * Init */ extern "C" void init(Handle<Object> target) { NanScope(); NODE_SET_METHOD(target, "start", StartBitcoind); } NODE_MODULE(bitcoindjs, init) <|endoftext|>
<commit_before>// Copyright (c) 2019-2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/internal/capro/capro_message.hpp" #include "iceoryx_posh/internal/roudi/introspection/port_introspection.hpp" #include "test.hpp" using namespace ::testing; using namespace iox::capro; class CaproMessage_test : public Test { public: void SetUp(){}; void TearDown(){}; }; TEST_F(CaproMessage_test, CtorNoParams) { CaproMessage testObj = CaproMessage(); EXPECT_EQ(testObj.m_requestPort, nullptr); EXPECT_EQ(testObj.m_type, CaproMessageType::NOTYPE); EXPECT_EQ(testObj.m_subType, CaproMessageSubType::NOSUBTYPE); EXPECT_EQ(testObj.m_chunkQueueData, nullptr); EXPECT_EQ(testObj.m_historyCapacity, 0u); } TEST_F(CaproMessage_test, CtorParams) { uint16_t testServiceID = 1; uint16_t testEventID = 2; uint16_t testInstanceID = 3; ServiceDescription sd = ServiceDescription(testServiceID, testEventID, testInstanceID); iox::popo::ReceiverPortData recData; CaproMessage testObj = CaproMessage(CaproMessageType::OFFER, sd, CaproMessageSubType::SERVICE, &recData); EXPECT_EQ(testObj.m_requestPort, &recData); EXPECT_EQ(testObj.m_type, CaproMessageType::OFFER); EXPECT_EQ(testObj.m_subType, CaproMessageSubType::SERVICE); EXPECT_EQ(testObj.m_chunkQueueData, nullptr); EXPECT_EQ(testObj.m_historyCapacity, 0u); } TEST_F(CaproMessage_test, CtorDefaultArgs) { uint16_t testServiceID = 1; uint16_t testEventID = 2; uint16_t testInstanceID = 3; ServiceDescription sd = ServiceDescription(testServiceID, testEventID, testInstanceID); iox::popo::ReceiverPortData recData; CaproMessage testObj = CaproMessage(CaproMessageType::OFFER, sd); EXPECT_EQ(testObj.m_requestPort, nullptr); EXPECT_EQ(testObj.m_subType, CaproMessageSubType::NOSUBTYPE); }<commit_msg>iox-#168: fix review points<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/internal/capro/capro_message.hpp" #include "iceoryx_posh/internal/roudi/introspection/port_introspection.hpp" #include "test.hpp" using namespace ::testing; using namespace iox::capro; class CaproMessage_test : public Test { public: void SetUp(){}; void TearDown(){}; }; TEST_F(CaproMessage_test, CtorNoParams) { CaproMessage testObj = CaproMessage(); EXPECT_EQ(testObj.m_requestPort, nullptr); EXPECT_EQ(testObj.m_type, CaproMessageType::NOTYPE); EXPECT_EQ(testObj.m_subType, CaproMessageSubType::NOSUBTYPE); EXPECT_EQ(testObj.m_chunkQueueData, nullptr); EXPECT_EQ(testObj.m_historyCapacity, 0u); } TEST_F(CaproMessage_test, CtorParams) { uint16_t testServiceID = 1; uint16_t testEventID = 2; uint16_t testInstanceID = 3; ServiceDescription sd = ServiceDescription(testServiceID, testEventID, testInstanceID); iox::popo::ReceiverPortData recData; CaproMessage testObj = CaproMessage(CaproMessageType::OFFER, sd, CaproMessageSubType::SERVICE, &recData); EXPECT_EQ(testObj.m_requestPort, &recData); EXPECT_EQ(testObj.m_type, CaproMessageType::OFFER); EXPECT_EQ(testObj.m_subType, CaproMessageSubType::SERVICE); EXPECT_EQ(testObj.m_chunkQueueData, nullptr); EXPECT_EQ(testObj.m_historyCapacity, 0u); EXPECT_EQ(testObj.m_serviceDescription, sd); } TEST_F(CaproMessage_test, CtorDefaultArgs) { uint16_t testServiceID = 1; uint16_t testEventID = 2; uint16_t testInstanceID = 3; ServiceDescription sd = ServiceDescription(testServiceID, testEventID, testInstanceID); iox::popo::ReceiverPortData recData; CaproMessage testObj = CaproMessage(CaproMessageType::OFFER, sd); EXPECT_EQ(testObj.m_requestPort, nullptr); EXPECT_EQ(testObj.m_subType, CaproMessageSubType::NOSUBTYPE); }<|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <[email protected]> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_WILDCARD_POSITION_HPP #define CPPA_WILDCARD_POSITION_HPP #include <type_traits> #include "cppa/anything.hpp" #include "cppa/util/type_list.hpp" namespace cppa { /** * @brief Denotes the position of {@link cppa::anything anything} in a * template parameter pack. */ enum class wildcard_position { nil, trailing, leading, in_between, multiple }; /** * @brief Gets the position of {@link cppa::anything anything} from the * type list @p Types. * @tparam A template parameter pack as {@link cppa::util::type_list type_list}. */ template<typename Types> constexpr wildcard_position get_wildcard_position() { return util::tl_exists<Types, is_anything>::value ? ((util::tl_count<Types, is_anything>::value == 1) ? (std::is_same<typename util::tl_head<Types>::type, anything>::value ? wildcard_position::leading : (std::is_same<typename util::tl_back<Types>::type, anything>::value ? wildcard_position::trailing : wildcard_position::in_between)) : wildcard_position::multiple) : wildcard_position::nil; } } // namespace cppa #endif // CPPA_WILDCARD_POSITION_HPP <commit_msg>streamlined get_wildcard_position()<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <[email protected]> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_WILDCARD_POSITION_HPP #define CPPA_WILDCARD_POSITION_HPP #include <type_traits> #include "cppa/anything.hpp" #include "cppa/util/type_list.hpp" namespace cppa { /** * @brief Denotes the position of {@link cppa::anything anything} in a * template parameter pack. */ enum class wildcard_position { nil, trailing, leading, in_between, multiple }; /** * @brief Gets the position of {@link cppa::anything anything} from the * type list @p Types. * @tparam A template parameter pack as {@link cppa::util::type_list type_list}. */ template<typename Types> constexpr wildcard_position get_wildcard_position() { return util::tl_count<Types, is_anything>::value > 1 ? wildcard_position::multiple : (util::tl_count<Types, is_anything>::value == 1 ? (std::is_same<typename util::tl_head<Types>::type, anything>::value ? wildcard_position::leading : (std::is_same<typename util::tl_back<Types>::type, anything>::value ? wildcard_position::trailing : wildcard_position::in_between)) : wildcard_position::nil); } } // namespace cppa #endif // CPPA_WILDCARD_POSITION_HPP <|endoftext|>
<commit_before>/** * File : D.cpp * Author : Kazune Takahashi * Created : 2018-10-14 21:35:05 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M; double q; ll x[2010]; ll p[2010]; int main() { cin >> N >> M >> q; for (auto i = 0; i < M; i++) { cin >> x[i] >> p[i]; } p[M] = 0; x[M] = 1000010; M++; ll mini = 100000000000010; for (auto k = 0; k < M; k++) { ll A = 0; ll B = 0; for (auto i = 0; i < k; i++) { A += p[i]; B -= p[i] * x[i]; } for (auto i = k; i < M; i++) { A -= p[i]; B += p[i] * x[i]; } ll y = 0; if (A < 0 || k == 0) { y = x[k]; } else { y = x[k - 1]; } mini = min(mini, y * A + B); } cout << fixed << setprecision(12) << mini / q << endl; }<commit_msg>tried D.cpp to 'D'<commit_after>/** * File : D.cpp * Author : Kazune Takahashi * Created : 2018-10-14 21:35:05 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M; ll q; ll x[2010]; ll p[2010]; ll r[2010]; int ok[2010]; int main() { cin >> N >> M >> q; for (auto i = 0; i < M; i++) { cin >> x[i] >> p[i]; } for (auto i = 0; i < M; i++) { r[i] = p[i] * N / q; } ll rem = N; for (auto i = 0; i < M; i++) { rem -= r[i]; } for (auto i = 0; i < M; i++) { if (abs(p[i] * N - r[i] * q) > abs(p[i] * N - (r[i] + 1) * q)) { ok[i] = 2; } else if (abs(p[i] * N - r[i] * q) == abs(p[i] * N - (r[i] + 1) * q)) { ok[i] = 1; } else { ok[i] = 0; } } for (int i = M - 1; i >= 0; i--) { if (ok[i] == 2 && rem > 0) { r[i]++; rem--; } } for (int i = M - 1; i >= 0; i--) { if (ok[i] == 1 && rem > 0) { r[i]++; rem--; } } r[0] += rem; double E = 0; for (auto i = 0; i < M; i++) { E += abs(p[i] / (double)q - r[i] / (double)N) * x[i]; } cout << fixed << setprecision(12) << E * N << endl; }<|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <limits> #include <map> #include <regex> #include <string> #include <vector> #include <cmath> // TODO: Replace this as soon as possible with a more modern option // parser interface. #include <getopt.h> #include "distances/Wasserstein.hh" #include "persistenceDiagrams/IO.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistenceDiagrams/PersistenceIndicatorFunction.hh" #include "utilities/Filesystem.hh" using DataType = double; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using PersistenceIndicatorFunction = aleph::math::StepFunction<DataType>; /* Auxiliary structure for describing a data set. I need this in order to figure out the corresponding dimension of the persistence diagram. */ struct DataSet { std::string name; std::string filename; unsigned dimension; PersistenceDiagram persistenceDiagram; PersistenceIndicatorFunction persistenceIndicatorFunction; }; void storeMatrix( const std::vector< std::vector<double> >& M, std::ostream& out ) { if( M.empty() ) return; auto rows = M.size(); auto cols = M.front().size(); for( decltype(rows) row = 0; row < rows; row++ ) { for( decltype(cols) col = 0; col < cols; col++ ) { if( col != 0 ) out << " "; out << M[row][col]; } out << "\n"; } } // Calculates the distance between two data sets. This requires enumerating all // dimensions, and finding the corresponding persistence indicator function. If // no such function exists, the function uses the norm of the function. double distance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension ) { auto getPersistenceIndicatorFunction = [] ( const std::vector<DataSet>& dataSet, unsigned dimension ) { auto it = std::find_if( dataSet.begin(), dataSet.end(), [&dimension] ( const DataSet& dataSet ) { return dataSet.dimension == dimension; } ); if( it != dataSet.end() ) return PersistenceIndicatorFunction( it->persistenceIndicatorFunction ); else return PersistenceIndicatorFunction(); }; double d = 0.0; for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ ) { auto f = getPersistenceIndicatorFunction( dataSet1, dimension ); auto g = getPersistenceIndicatorFunction( dataSet2, dimension ); g = g * (-1.0); d = d + (f+g).integral(); } return d; } double wassersteinDistance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension, double power ) { auto getPersistenceDiagram = [] ( const std::vector<DataSet>& dataSet, unsigned dimension ) { auto it = std::find_if( dataSet.begin(), dataSet.end(), [&dimension] ( const DataSet& dataSet ) { return dataSet.dimension == dimension; } ); if( it != dataSet.end() ) return PersistenceDiagram( it->persistenceDiagram ); else return PersistenceDiagram(); }; double d = 0.0; for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ ) { auto D1 = getPersistenceDiagram( dataSet1, dimension ); auto D2 = getPersistenceDiagram( dataSet2, dimension ); d += aleph::distances::wassersteinDistance( D1, D2, power ); } d = std::pow( d, 1.0 / power ); return d; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "power" , required_argument, nullptr, 'p' }, { "wasserstein", no_argument , nullptr, 'w' }, { nullptr , 0 , nullptr, 0 } }; double power = 2.0; bool useWassersteinDistance = false; int option = 0; while( ( option = getopt_long( argc, argv, "p:w", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'p': power = std::stod( optarg ); break; case 'w': useWassersteinDistance = true; break; default: break; } } if( ( argc - optind ) <= 1 ) { // TODO: Show usage return -1; } // Maps filenames to indices. I need this to ensure that the internal // ordering of files coincides with the shell's ordering. std::map<std::string, unsigned> filenameMap; std::vector< std::vector<DataSet> > dataSets; // TODO: Make this regular expression more, well, 'expressive' and // support more methods of specifying a dimension. std::regex reDataSetPrefix( "(.*)_k([[:digit:]]+)\\.txt" ); std::smatch matches; // Get filenames & prefixes ------------------------------------------ unsigned minDimension = std::numeric_limits<unsigned>::max(); unsigned maxDimension = 0; { std::vector<std::string> filenames; filenames.reserve( argc - 1 ); unsigned index = 0; for( int i = optind; i < argc; i++ ) { filenames.push_back( argv[i] ); if( std::regex_match( filenames.back(), matches, reDataSetPrefix ) ) { auto name = matches[1]; if( filenameMap.find( name ) == filenameMap.end() ) filenameMap[ name ] = index++; } } dataSets.resize( filenameMap.size() ); for( auto&& filename : filenames ) { if( std::regex_match( filename, matches, reDataSetPrefix ) ) { auto name = matches[1]; auto dimension = unsigned( std::stoul( matches[2] ) ); dataSets.at( filenameMap[name] ).push_back( { name, filename, dimension, {}, {} } ); minDimension = std::min( minDimension, dimension ); maxDimension = std::max( maxDimension, dimension ); } } } // Load persistence diagrams & calculate indicator functions --------- std::vector<PersistenceDiagram> persistenceDiagrams; for( auto&& sets : dataSets ) { for( auto&& dataSet : sets ) { std::cerr << "* Processing '" << dataSet.filename << "'..."; dataSet.persistenceDiagram = aleph::load<DataType>( dataSet.filename ); // FIXME: This is only required in order to ensure that the // persistence indicator function has a finite integral; it // can be solved more elegantly by using a special value to // indicate infinite intervals. dataSet.persistenceDiagram.removeUnpaired(); dataSet.persistenceIndicatorFunction = aleph::persistenceIndicatorFunction( dataSet.persistenceDiagram ); std::cerr << "finished\n"; } } // Calculate all distances ------------------------------------------- std::vector< std::vector<double> > distances; distances.resize( dataSets.size(), std::vector<double>( dataSets.size() ) ); std::size_t row = 0; for( auto it1 = dataSets.begin(); it1 != dataSets.end(); ++it1, ++row ) { std::size_t col = row+1; for( auto it2 = std::next( it1 ); it2 != dataSets.end(); ++it2, ++col ) { double d = 0.0; if( useWassersteinDistance ) d = wassersteinDistance( *it1, *it2, minDimension, maxDimension, power ); else d = distance( *it1, *it2, minDimension, maxDimension ); distances[row][col] = d; distances[col][row] = d; } } std::cerr << "Storing matrix..."; storeMatrix( distances, std::cout ); std::cerr << "finished\n"; } <commit_msg>Fixed matrix output<commit_after>#include <algorithm> #include <iostream> #include <limits> #include <map> #include <regex> #include <string> #include <vector> #include <cmath> // TODO: Replace this as soon as possible with a more modern option // parser interface. #include <getopt.h> #include "distances/Wasserstein.hh" #include "persistenceDiagrams/IO.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistenceDiagrams/PersistenceIndicatorFunction.hh" #include "utilities/Filesystem.hh" using DataType = double; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using PersistenceIndicatorFunction = aleph::math::StepFunction<DataType>; /* Auxiliary structure for describing a data set. I need this in order to figure out the corresponding dimension of the persistence diagram. */ struct DataSet { std::string name; std::string filename; unsigned dimension; PersistenceDiagram persistenceDiagram; PersistenceIndicatorFunction persistenceIndicatorFunction; }; void storeMatrix( const std::vector< std::vector<double> >& M, std::ostream& out ) { if( M.empty() ) return; auto rows = M.size(); auto cols = M.front().size(); for( decltype(rows) row = 0; row < rows; row++ ) { for( decltype(cols) col = 0; col < cols; col++ ) { if( col != 0 ) out << " "; out << M[row][col]; } out << "\n"; } } // Calculates the distance between two data sets. This requires enumerating all // dimensions, and finding the corresponding persistence indicator function. If // no such function exists, the function uses the norm of the function. double distance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension ) { auto getPersistenceIndicatorFunction = [] ( const std::vector<DataSet>& dataSet, unsigned dimension ) { auto it = std::find_if( dataSet.begin(), dataSet.end(), [&dimension] ( const DataSet& dataSet ) { return dataSet.dimension == dimension; } ); if( it != dataSet.end() ) return PersistenceIndicatorFunction( it->persistenceIndicatorFunction ); else return PersistenceIndicatorFunction(); }; double d = 0.0; for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ ) { auto f = getPersistenceIndicatorFunction( dataSet1, dimension ); auto g = getPersistenceIndicatorFunction( dataSet2, dimension ); g = g * (-1.0); d = d + (f+g).integral(); } return d; } double wassersteinDistance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension, double power ) { auto getPersistenceDiagram = [] ( const std::vector<DataSet>& dataSet, unsigned dimension ) { auto it = std::find_if( dataSet.begin(), dataSet.end(), [&dimension] ( const DataSet& dataSet ) { return dataSet.dimension == dimension; } ); if( it != dataSet.end() ) return PersistenceDiagram( it->persistenceDiagram ); else return PersistenceDiagram(); }; double d = 0.0; for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ ) { auto D1 = getPersistenceDiagram( dataSet1, dimension ); auto D2 = getPersistenceDiagram( dataSet2, dimension ); d += aleph::distances::wassersteinDistance( D1, D2, power ); } d = std::pow( d, 1.0 / power ); return d; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "power" , required_argument, nullptr, 'p' }, { "wasserstein", no_argument , nullptr, 'w' }, { nullptr , 0 , nullptr, 0 } }; double power = 2.0; bool useWassersteinDistance = false; int option = 0; while( ( option = getopt_long( argc, argv, "p:w", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'p': power = std::stod( optarg ); break; case 'w': useWassersteinDistance = true; break; default: break; } } if( ( argc - optind ) <= 1 ) { // TODO: Show usage return -1; } // Maps filenames to indices. I need this to ensure that the internal // ordering of files coincides with the shell's ordering. std::map<std::string, unsigned> filenameMap; std::vector< std::vector<DataSet> > dataSets; // TODO: Make this regular expression more, well, 'expressive' and // support more methods of specifying a dimension. std::regex reDataSetPrefix( "(.*)_k([[:digit:]]+)\\.txt" ); std::smatch matches; // Get filenames & prefixes ------------------------------------------ unsigned minDimension = std::numeric_limits<unsigned>::max(); unsigned maxDimension = 0; { std::vector<std::string> filenames; filenames.reserve( argc - 1 ); unsigned index = 0; for( int i = optind; i < argc; i++ ) { filenames.push_back( argv[i] ); if( std::regex_match( filenames.back(), matches, reDataSetPrefix ) ) { auto name = matches[1]; if( filenameMap.find( name ) == filenameMap.end() ) filenameMap[ name ] = index++; } } dataSets.resize( filenameMap.size() ); for( auto&& filename : filenames ) { if( std::regex_match( filename, matches, reDataSetPrefix ) ) { auto name = matches[1]; auto dimension = unsigned( std::stoul( matches[2] ) ); dataSets.at( filenameMap[name] ).push_back( { name, filename, dimension, {}, {} } ); minDimension = std::min( minDimension, dimension ); maxDimension = std::max( maxDimension, dimension ); } } } // Load persistence diagrams & calculate indicator functions --------- std::vector<PersistenceDiagram> persistenceDiagrams; for( auto&& sets : dataSets ) { for( auto&& dataSet : sets ) { std::cerr << "* Processing '" << dataSet.filename << "'..."; dataSet.persistenceDiagram = aleph::load<DataType>( dataSet.filename ); // FIXME: This is only required in order to ensure that the // persistence indicator function has a finite integral; it // can be solved more elegantly by using a special value to // indicate infinite intervals. dataSet.persistenceDiagram.removeUnpaired(); dataSet.persistenceIndicatorFunction = aleph::persistenceIndicatorFunction( dataSet.persistenceDiagram ); std::cerr << "finished\n"; } } // Calculate all distances ------------------------------------------- std::vector< std::vector<double> > distances; distances.resize( dataSets.size(), std::vector<double>( dataSets.size() ) ); std::size_t row = 0; for( auto it1 = dataSets.begin(); it1 != dataSets.end(); ++it1, ++row ) { std::size_t col = 0; for( auto it2 = dataSets.begin(); it2 != dataSets.end(); ++it2, ++col ) { if( it1 == it2 ) { distances[row][row] = 0.0; continue; } double d = 0.0; if( useWassersteinDistance ) d = wassersteinDistance( *it1, *it2, minDimension, maxDimension, power ); else d = distance( *it1, *it2, minDimension, maxDimension ); distances[row][col] = d; distances[col][row] = d; } } std::cerr << "Storing matrix..."; storeMatrix( distances, std::cout ); std::cerr << "finished\n"; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Inn0va and Tracker1 * * 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 "main.h" std::unordered_map<int, std::pair <int, AMX*>> cmd; std::unordered_map<unsigned int, char *> Aliases; PLUGIN_FUNCTION COMMAND (AMX* amx, cell* params) { char *cmdtext = NULL; char *tokens = NULL; char Command[32]; amx_StrParam(amx, params[2], cmdtext); strtok_s(cmdtext, " ", &tokens); size_t cmdlen = strlen(cmdtext); for (size_t i = 1; i < cmdlen; cmdtext [i] = tolower(cmdtext[i++])); int hash = SuperFastHash(cmdtext, static_cast<int>(cmdlen)); auto tmp = cmd.find(hash); auto alias = Aliases.find(hash); if (alias != Aliases.end()) { strcpy_s(Command, sizeof(Command), alias->second); Command[0] = '_'; cmdtext = Command; } cmdtext[0] = '_'; if (*tokens) { deblank(tokens); int idx; cell amx_Address; if (tmp != cmd.end()) { std::pair<int, AMX *> temp = tmp->second; amx_PushString(temp.second, &amx_Address, NULL, tokens, NULL, NULL); amx_Push(temp.second, params[1]); amx_Exec(temp.second, NULL, temp.first); amx_Release(temp.second, amx_Address); return 1; } else { amx_FindPublic(amx, cmdtext, &idx); amx_PushString(amx, &amx_Address, NULL, tokens, NULL, NULL); amx_Push(amx, params [1]); amx_Exec(amx, NULL, idx); amx_Release(amx, amx_Address); cmd[hash] = std::pair<int, AMX*>(idx, amx); return 1; } } else { int idx; if (tmp != cmd.end()) { std::pair<int, AMX *> temp = tmp->second; amx_Push(temp.second, params[1]); amx_Exec(temp.second, NULL, temp.first); return 1; } else { amx_FindPublic(amx, cmdtext, &idx); amx_Push(amx, params [1]); amx_Exec(amx, NULL, idx); cmd[hash] = std::pair<int, AMX*>(idx, amx); return 1; } } return 0; } PLUGIN_FUNCTION RegisterAliases(AMX* amx, cell* params) { char *command, *orig; ptrdiff_t i = 1; amx_StrParam(amx, params[i++], orig); amx_StrParam(amx, params[i++], command); size_t cmdlen = strlen(command); while (command != NULL) { char *temp = new char[32]; strcpy_s(temp, 32, orig); for (size_t x = 0; x < strlen(temp); temp[x] = tolower(temp[x++])); for (size_t x = 0; x < cmdlen; command[x] = tolower(command[x++])); Aliases.insert(std::make_pair(SuperFastHash(command, static_cast<int>(cmdlen)), temp)); delete[] temp; command = NULL; temp = NULL; amx_StrParam(amx, params[i++], command); } return 0; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; logprintf("######################################"); logprintf("# @Debug Command Loaded #"); logprintf("# #"); logprintf("# @Author: Inn0va and Tracker1 #"); logprintf("# @Version: 0.3 #"); logprintf("# @Released: 10/12/2014 #"); logprintf("# #"); logprintf("######################################\n"); return 1; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { logprintf( "@Debug Command Unloaded" ) ; } AMX_NATIVE_INFO PluginNatives[] = { {"dCOMMAND", COMMAND}, {"dAliasReg", RegisterAliases}, {0, 0} }; PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { return amx_Register( amx, PluginNatives, -1 ) ; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { return AMX_ERR_NONE ; } <commit_msg>Update main.cpp<commit_after>/* * Copyright (C) 2014 Inn0va and Tracker1 * * 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 "main.h" std::unordered_map<int, std::pair <int, AMX*>> cmd; std::unordered_map<unsigned int, char *> Aliases; PLUGIN_FUNCTION COMMAND (AMX* amx, cell* params) { char *cmdtext = NULL; char *tokens = NULL; char Command[32]; amx_StrParam(amx, params[2], cmdtext); strtok_s(cmdtext, " ", &tokens); size_t cmdlen = strlen(cmdtext); for (size_t i = 1; i < cmdlen; cmdtext [i] = tolower(cmdtext[i++])); int hash = SuperFastHash(cmdtext, static_cast<int>(cmdlen)); auto tmp = cmd.find(hash); auto alias = Aliases.find(hash); if (alias != Aliases.end()) { strcpy_s(Command, sizeof(Command), alias->second); Command[0] = '_'; cmdtext = Command; } cmdtext[0] = '_'; if (*tokens) { deblank(tokens); int idx; cell amx_Address; if (tmp != cmd.end()) { std::pair<int, AMX *> temp = tmp->second; amx_PushString(temp.second, &amx_Address, NULL, tokens, NULL, NULL); amx_Push(temp.second, params[1]); amx_Exec(temp.second, NULL, temp.first); amx_Release(temp.second, amx_Address); return 1; } else { amx_FindPublic(amx, cmdtext, &idx); amx_PushString(amx, &amx_Address, NULL, tokens, NULL, NULL); amx_Push(amx, params [1]); amx_Exec(amx, NULL, idx); amx_Release(amx, amx_Address); cmd[hash] = std::pair<int, AMX*>(idx, amx); return 1; } } else { int idx; if (tmp != cmd.end()) { std::pair<int, AMX *> temp = tmp->second; amx_Push(temp.second, params[1]); amx_Exec(temp.second, NULL, temp.first); return 1; } else { amx_FindPublic(amx, cmdtext, &idx); amx_Push(amx, params [1]); amx_Exec(amx, NULL, idx); cmd[hash] = std::pair<int, AMX*>(idx, amx); return 1; } } return 0; } PLUGIN_FUNCTION RegisterAliases(AMX* amx, cell* params) { char *command, *orig; size_t i = 1; amx_StrParam(amx, params[i++], orig); amx_StrParam(amx, params[i++], command); size_t cmdlen = strlen(command); while (command != NULL) { char *temp = new char[32]; strcpy_s(temp, 32, orig); for (size_t x = 0; x < strlen(temp); temp[x] = tolower(temp[x++])); for (size_t x = 0; x < cmdlen; command[x] = tolower(command[x++])); Aliases.insert(std::make_pair(SuperFastHash(command, static_cast<int>(cmdlen)), temp)); delete[] temp; command = NULL; temp = NULL; amx_StrParam(amx, params[i++], command); } return 0; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; logprintf("######################################"); logprintf("# @Debug Command Loaded #"); logprintf("# #"); logprintf("# @Author: Inn0va and Tracker1 #"); logprintf("# @Version: 0.3 #"); logprintf("# @Released: 10/12/2014 #"); logprintf("# #"); logprintf("######################################\n"); return 1; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { logprintf( "@Debug Command Unloaded" ) ; } AMX_NATIVE_INFO PluginNatives[] = { {"dCOMMAND", COMMAND}, {"dAliasReg", RegisterAliases}, {0, 0} }; PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { return amx_Register( amx, PluginNatives, -1 ) ; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { return AMX_ERR_NONE ; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stbitem.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2006-05-02 16:04:23 $ * * 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 _SFXSTBITEM_HXX #define _SFXSTBITEM_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_SFX2_DLLAPI_H #include "sfx2/dllapi.h" #endif #ifndef _SFXPOOLITEM_HXX #include <svtools/poolitem.hxx> #endif #ifndef _SVTOOLS_STATUSBARCONTROLLER_HXX #include <svtools/statusbarcontroller.hxx> #endif //------------------------------------------------------------------ class SfxModule; class StatusBar; class SfxStatusBarControl; class SfxBindings; svt::StatusbarController* SAL_CALL SfxStatusBarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, StatusBar* pStatusBar, unsigned short nID, const ::rtl::OUString& aCommandURL ); typedef SfxStatusBarControl* (*SfxStatusBarControlCtor)( USHORT nSlotId, USHORT nId, StatusBar &rStb ); struct SfxStbCtrlFactory { SfxStatusBarControlCtor pCtor; TypeId nTypeId; USHORT nSlotId; SfxStbCtrlFactory( SfxStatusBarControlCtor pTheCtor, TypeId nTheTypeId, USHORT nTheSlotId ): pCtor(pTheCtor), nTypeId(nTheTypeId), nSlotId(nTheSlotId) {} }; //------------------------------------------------------------------ class CommandEvent; class MouseEvent; class UserDrawEvent; class SFX2_DLLPUBLIC SfxStatusBarControl: public svt::StatusbarController { USHORT nSlotId; USHORT nId; StatusBar* pBar; protected: // new controller API // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); // XStatusListener virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusbarController virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos, ::sal_Int32 nCommand, ::sal_Bool bMouseEvent, const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics, const ::com::sun::star::awt::Rectangle& rOutputRectangle, ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException); // Old sfx2 interface virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void Click(); virtual void DoubleClick(); virtual void Command( const CommandEvent& rCEvt ); virtual BOOL MouseButtonDown( const MouseEvent & ); virtual BOOL MouseMove( const MouseEvent & ); virtual BOOL MouseButtonUp( const MouseEvent & ); virtual void Paint( const UserDrawEvent &rUDEvt ); static USHORT convertAwtToVCLMouseButtons( sal_Int16 nAwtMouseButtons ); public: SfxStatusBarControl( USHORT nSlotID, USHORT nId, StatusBar& rBar ); virtual ~SfxStatusBarControl(); USHORT GetSlotId() const { return nSlotId; } USHORT GetId() const { return nId; } StatusBar& GetStatusBar() const { return *pBar; } void CaptureMouse(); void ReleaseMouse(); static SfxStatusBarControl* CreateControl( USHORT nSlotID, USHORT nId, StatusBar *pBar, SfxModule* ); static void RegisterStatusBarControl(SfxModule*, SfxStbCtrlFactory*); }; //------------------------------------------------------------------ #define SFX_DECL_STATUSBAR_CONTROL() \ static SfxStatusBarControl* CreateImpl( USHORT nSlotId, USHORT nId, StatusBar &rStb ); \ static void RegisterControl(USHORT nSlotId = 0, SfxModule *pMod=NULL) #define SFX_IMPL_STATUSBAR_CONTROL(Class, nItemClass) \ SfxStatusBarControl* __EXPORT Class::CreateImpl( USHORT nSlotId, USHORT nId, StatusBar &rStb ) \ { return new Class( nSlotId, nId, rStb ); } \ void Class::RegisterControl(USHORT nSlotId, SfxModule *pMod) \ { SfxStatusBarControl::RegisterStatusBarControl( pMod, new SfxStbCtrlFactory( \ Class::CreateImpl, TYPE(nItemClass), nSlotId ) ); } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.554); FILE MERGED 2008/04/01 15:38:18 thb 1.5.554.3: #i85898# Stripping all external header guards 2008/04/01 12:40:33 thb 1.5.554.2: #i85898# Stripping all external header guards 2008/03/31 13:37:54 rt 1.5.554.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: stbitem.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFXSTBITEM_HXX #define _SFXSTBITEM_HXX #include "sal/config.h" #include "sfx2/dllapi.h" #include <svtools/poolitem.hxx> #include <svtools/statusbarcontroller.hxx> //------------------------------------------------------------------ class SfxModule; class StatusBar; class SfxStatusBarControl; class SfxBindings; svt::StatusbarController* SAL_CALL SfxStatusBarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, StatusBar* pStatusBar, unsigned short nID, const ::rtl::OUString& aCommandURL ); typedef SfxStatusBarControl* (*SfxStatusBarControlCtor)( USHORT nSlotId, USHORT nId, StatusBar &rStb ); struct SfxStbCtrlFactory { SfxStatusBarControlCtor pCtor; TypeId nTypeId; USHORT nSlotId; SfxStbCtrlFactory( SfxStatusBarControlCtor pTheCtor, TypeId nTheTypeId, USHORT nTheSlotId ): pCtor(pTheCtor), nTypeId(nTheTypeId), nSlotId(nTheSlotId) {} }; //------------------------------------------------------------------ class CommandEvent; class MouseEvent; class UserDrawEvent; class SFX2_DLLPUBLIC SfxStatusBarControl: public svt::StatusbarController { USHORT nSlotId; USHORT nId; StatusBar* pBar; protected: // new controller API // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); // XStatusListener virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ); // XStatusbarController virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos, ::sal_Int32 nCommand, ::sal_Bool bMouseEvent, const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics, const ::com::sun::star::awt::Rectangle& rOutputRectangle, ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException); // Old sfx2 interface virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void Click(); virtual void DoubleClick(); virtual void Command( const CommandEvent& rCEvt ); virtual BOOL MouseButtonDown( const MouseEvent & ); virtual BOOL MouseMove( const MouseEvent & ); virtual BOOL MouseButtonUp( const MouseEvent & ); virtual void Paint( const UserDrawEvent &rUDEvt ); static USHORT convertAwtToVCLMouseButtons( sal_Int16 nAwtMouseButtons ); public: SfxStatusBarControl( USHORT nSlotID, USHORT nId, StatusBar& rBar ); virtual ~SfxStatusBarControl(); USHORT GetSlotId() const { return nSlotId; } USHORT GetId() const { return nId; } StatusBar& GetStatusBar() const { return *pBar; } void CaptureMouse(); void ReleaseMouse(); static SfxStatusBarControl* CreateControl( USHORT nSlotID, USHORT nId, StatusBar *pBar, SfxModule* ); static void RegisterStatusBarControl(SfxModule*, SfxStbCtrlFactory*); }; //------------------------------------------------------------------ #define SFX_DECL_STATUSBAR_CONTROL() \ static SfxStatusBarControl* CreateImpl( USHORT nSlotId, USHORT nId, StatusBar &rStb ); \ static void RegisterControl(USHORT nSlotId = 0, SfxModule *pMod=NULL) #define SFX_IMPL_STATUSBAR_CONTROL(Class, nItemClass) \ SfxStatusBarControl* __EXPORT Class::CreateImpl( USHORT nSlotId, USHORT nId, StatusBar &rStb ) \ { return new Class( nSlotId, nId, rStb ); } \ void Class::RegisterControl(USHORT nSlotId, SfxModule *pMod) \ { SfxStatusBarControl::RegisterStatusBarControl( pMod, new SfxStbCtrlFactory( \ Class::CreateImpl, TYPE(nItemClass), nSlotId ) ); } #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling 2>&1 | FileCheck %s #include <type_traits> #include <cstdlib> cling::runtime::gClingOpts->AllowRedefinition = 1; // ==== Test UsingDirectiveDecl/UsingDecl // These should not be nested into a `__cling_N5xxx' namespace (but placed at // the TU scope) so that the declaration they name is globally available. using namespace std; namespace NS { string baz("Cling"); } using NS::baz; baz //CHECK: (std::string &) "Cling" // ==== Redeclare `i' with a different type int i = 1 //CHECK-NEXT: (int) 1 double i = 3.141592 //CHECK-NEXT: (double) 3.1415920 // ==== Provide different definition for type struct MyStruct; struct MyStruct { unsigned u; }; MyStruct{1111U}.u //CHECK-NEXT: (unsigned int) 1111 struct MyStruct { int i, j; } foo{33, 0} //CHECK-NEXT: (struct MyStruct &) foo.i //CHECK-NEXT: (int) 33 struct MyStruct; // nop MyStruct{0, 99}.j //CHECK-NEXT: (int) 99 // ==== Make `foo' a typedef type typedef int foo; foo bar = 1 //CHECK-NEXT: (int) 1 typedef MyStruct foo; foo{11, 99}.i //CHECK-NEXT: (int) 11 bar // CHECK-NEXT: (int) 1 // ==== Give a new defintion for `foo'; test function overload char foo(int x) { return 'X'; } int foo() { return 0; } foo() //CHECK-NEXT: (int) 0 foo(0) //CHECK-NEXT: (char) 'X' double foo() { return 1; } foo() //CHECK-NEXT: (double) 1.0000000 // ==== (Re)define a class template template <typename T> struct S { T i; }; S<int> foo{99}; foo.i //CHECK-NEXT: (int) 99 template <typename T> struct S { T i, j; }; S<double>{0, 33.0}.j //CHECK-NEXT: (double) 33.000000 // ==== Test function templates template <typename T> typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return x; } template <typename T> typename std::enable_if<!std::is_same<T, int>::value, int>::type f(T x) { return 0x55aa; } f(33) //CHECK-NEXT: (int) 33 f(3.3f) //CHECK-NEXT: (int) 21930 template <typename T> typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return 0xaa55; } f(33) //CHECK-NEXT: (int) 43605 f(3.3f) //CHECK-NEXT: (int) 21930 //expected-no-diagnostics .q <commit_msg>[cling] added missing include in cling/test/CodeUnloading/DeclShadowing.C<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling 2>&1 | FileCheck %s #include <type_traits> #include <cstdlib> #include <string> cling::runtime::gClingOpts->AllowRedefinition = 1; // ==== Test UsingDirectiveDecl/UsingDecl // These should not be nested into a `__cling_N5xxx' namespace (but placed at // the TU scope) so that the declaration they name is globally available. using namespace std; namespace NS { string baz("Cling"); } using NS::baz; baz //CHECK: (std::string &) "Cling" // ==== Redeclare `i' with a different type int i = 1 //CHECK-NEXT: (int) 1 double i = 3.141592 //CHECK-NEXT: (double) 3.1415920 // ==== Provide different definition for type struct MyStruct; struct MyStruct { unsigned u; }; MyStruct{1111U}.u //CHECK-NEXT: (unsigned int) 1111 struct MyStruct { int i, j; } foo{33, 0} //CHECK-NEXT: (struct MyStruct &) foo.i //CHECK-NEXT: (int) 33 struct MyStruct; // nop MyStruct{0, 99}.j //CHECK-NEXT: (int) 99 // ==== Make `foo' a typedef type typedef int foo; foo bar = 1 //CHECK-NEXT: (int) 1 typedef MyStruct foo; foo{11, 99}.i //CHECK-NEXT: (int) 11 bar // CHECK-NEXT: (int) 1 // ==== Give a new defintion for `foo'; test function overload char foo(int x) { return 'X'; } int foo() { return 0; } foo() //CHECK-NEXT: (int) 0 foo(0) //CHECK-NEXT: (char) 'X' double foo() { return 1; } foo() //CHECK-NEXT: (double) 1.0000000 // ==== (Re)define a class template template <typename T> struct S { T i; }; S<int> foo{99}; foo.i //CHECK-NEXT: (int) 99 template <typename T> struct S { T i, j; }; S<double>{0, 33.0}.j //CHECK-NEXT: (double) 33.000000 // ==== Test function templates template <typename T> typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return x; } template <typename T> typename std::enable_if<!std::is_same<T, int>::value, int>::type f(T x) { return 0x55aa; } f(33) //CHECK-NEXT: (int) 33 f(3.3f) //CHECK-NEXT: (int) 21930 template <typename T> typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return 0xaa55; } f(33) //CHECK-NEXT: (int) 43605 f(3.3f) //CHECK-NEXT: (int) 21930 //expected-no-diagnostics .q <|endoftext|>
<commit_before>/* (c) Matthew Slocum 2015 secComponent.cpp secComponent is responsible for the encryption/decryption of messages. This file contains code from the public domain found at https://web.archive.org/web/20050110121238/http://www.xs4all.nl/~cg/ciphersaber/comp/c++.txt // ciphersabre-1 by graydon hoare // placed in public domain, jun 2000 This file contain sudo code from https://github.com/PSU-CS-300-Fall2015/ciphersaber2 this sudo code is licenced under the MIT Licence */ #include <iostream> #include <stdio.h> #include <string> #include <cstring> #include <stdlib.h> #include <vector> #include <fstream> #include "secComponent.h" using namespace std; secComponent::secComponent() { } //"Produce an RC4 keystream of length" n "with" r "rounds of key scheduling given key" k "of length" l //returns keystream string secComponent::rc4(int n, int r, char* k, int l) { //init array unsigned char S [256] = { }; for(int i=0; i<256; i++) { S[i]=i; } //do key scheduling int j=0; for(int ri=0; ri<r; ri++) { for(int i=0; i<256; i++) { j = (j + S[i] + k[i%l]) % 256; swap(S[i], S[j]); } } //produce the keystream string keystream; j=0; int ip; for(int i=0; i<n; i++) { ip = (i+1) % 256; j = (j+S[ip]) % 256; swap(S[ip], S[j]); keystream.append(to_string(S[(S[ip]+S[j]) % 256])); } return keystream; } //"Ciphersaber-2 encrypt message" m "with key" k "and" r "rounds of key scheduling" "outputting to" ciphertext //return length of ciphertext int secComponent::encrypt(string m, string k, int r, char * ciphertext) { //get length of message int n = m.length(); string iv = "1234567890"; //CHANGEME //create a holder(kp) for the key + iv char kp[10+k.length()]; //load the key into kp for(unsigned int i=0; i<k.length(); i++) { kp[i] = k[i]; } //load the iv into kp for(unsigned int i=k.length(); i<k.length()+10; i++) { kp[i] = iv[i-k.length()]; } //get a keystream string keystream = rc4(n, r, kp, k.length()+10); //load the iv into the payload for(int i=0; i<10; i++) { ciphertext[i] = iv[i]; } //encrypt the message with the keystream and save to output for(int i=0; i<n; i++) { ciphertext[i+10] = m[i] ^ keystream[i]; //replaced xor with ^ } //return size of ciphertext return n+10; } //"Ciphersaber-2 decrypt ciphertext" m "with key" k "and" r "rounds of key scheduling" "ouputting to" plaintext //returns length of plaintext int secComponent::decrypt(char* m, int m_len, string k, int r, char* plaintext) { //get length of m (unneccisary) int n = m_len; //load iv char iv [10]; for(int i=0; i<10; i++) { iv[i] = m[i]; } //get the message without the iv char msg_no_iv [m_len-10]; for(int k=0; k<m_len-10; k++) { msg_no_iv[k]=m[k+10]; } //prepend k to iv (store in kp) char kp[k.length()+10]; //put the key in for(unsigned int i=0; i<k.length(); i++) { kp[i] = k[i]; } //put the iv in for(unsigned int i=k.length(); i<k.length()+10; i++) { kp[i] = iv[i-k.length()]; } //get a keystream string keystream = rc4(n-10, r, kp, k.length()+10); //decrypt the message with the keystream and save to output for(int i=0; i<n-10; i++) { plaintext[i] = msg_no_iv[i] ^ keystream[i]; } //return the length of the plaintext return n-10; } <commit_msg>fixed bug in CS algorythm. things work now<commit_after>/* (c) Matthew Slocum 2015 secComponent.cpp secComponent is responsible for the encryption/decryption of messages. This file contains code from the public domain found at https://web.archive.org/web/20050110121238/http://www.xs4all.nl/~cg/ciphersaber/comp/c++.txt // ciphersabre-1 by graydon hoare // placed in public domain, jun 2000 This file contain sudo code from https://github.com/PSU-CS-300-Fall2015/ciphersaber2 this sudo code is licenced under the MIT Licence */ #include <iostream> #include <stdio.h> #include <string> #include <cstring> #include <stdlib.h> #include <vector> #include <fstream> #include "secComponent.h" using namespace std; secComponent::secComponent() { } //"Produce an RC4 keystream of length" n "with" r "rounds of key scheduling given key" k "of length" l //returns keystream void secComponent::rc4(int n, int r, char* k, int l, char* keystream) { //init array unsigned char S [256] = { }; for(int i=0; i<256; i++) { S[i]=i; } //do key scheduling int j=0; for(int ri=0; ri<r; ri++) { for(int i=0; i<256; i++) { j = (j + S[i] + k[i%l]) % 256; swap(S[i], S[j]); } } //produce the keystream //string keystream; j=0; int ip; for(int i=0; i<n; i++) { ip = (i+1) % 256; j = (j+S[ip]) % 256; swap(S[ip], S[j]); keystream[i] = S[(S[ip]+S[j]) % 256]; } //return keystream; } //"Ciphersaber-2 encrypt message" m "with key" k "and" r "rounds of key scheduling" "outputting to" ciphertext //return length of ciphertext int secComponent::encrypt(string m, string k, int r, char * ciphertext) { //get length of message int n = m.length(); //generate iv unsigned char iv [10]; ifstream rng("/dev/urandom"); if (!rng) { cerr << "canot open /dev/urandom" << endl; exit(1); } for (int i=0; i<10; ++i) { iv[i]=rng.get(); } //create a holder(kp) for the key + iv char kp[10+k.length()]; //load the key into kp for(unsigned int i=0; i<k.length(); i++) { kp[i] = k[i]; } //load the iv into kp for(unsigned int i=k.length(); i<k.length()+10; i++) { kp[i] = iv[i-k.length()]; } //get a keystream char keystream [1024]; rc4(n, r, kp, k.length()+10, keystream); //load the iv into the payload for(int i=0; i<10; i++) { ciphertext[i] = iv[i]; } //encrypt the message with the keystream and save to output for(int i=0; i<n; i++) { ciphertext[i+10] = m[i] ^ keystream[i]; //replaced xor with ^ } //return size of ciphertext return n+10; } //"Ciphersaber-2 decrypt ciphertext" m "with key" k "and" r "rounds of key scheduling" "ouputting to" plaintext //returns length of plaintext int secComponent::decrypt(char* m, int m_len, string k, int r, char* plaintext) { //get length of m (unneccisary) int n = m_len; //load iv char iv [10]; for(int i=0; i<10; i++) { iv[i] = m[i]; } //get the message without the iv char msg_no_iv [m_len-10]; for(int k=0; k<m_len-10; k++) { msg_no_iv[k]=m[k+10]; } //prepend k to iv (store in kp) char kp[k.length()+10]; //put the key in for(unsigned int i=0; i<k.length(); i++) { kp[i] = k[i]; } //put the iv in for(unsigned int i=k.length(); i<k.length()+10; i++) { kp[i] = iv[i-k.length()]; } //get a keystream char keystream [1024]; rc4(n, r, kp, k.length()+10, keystream); //decrypt the message with the keystream and save to output for(int i=0; i<n-10; i++) { plaintext[i] = msg_no_iv[i] ^ keystream[i]; } //return the length of the plaintext return n-10; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <future> // NOLINT #include <ostream> #include "paddle/fluid/framework/blocking_queue.h" #include "paddle/fluid/framework/data_type.h" #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/distributed/distributed.h" #include "paddle/fluid/operators/distributed_ops/send_recv_util.h" #include "paddle/fluid/platform/profiler.h" namespace paddle { namespace operators { class SendOp : public framework::OperatorBase { public: SendOp(const std::string& type, const framework::VariableNameMap& inputs, const framework::VariableNameMap& outputs, const framework::AttributeMap& attrs) : OperatorBase(type, inputs, outputs, attrs) {} void RunImpl(const framework::Scope& scope, const platform::Place& place) const override { auto ins = Inputs("X"); std::vector<std::string> epmap = Attr<std::vector<std::string>>("epmap"); int sync_send = Attr<int>("sync_mode"); platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto& ctx = *pool.Get(place); distributed::RPCClient* rpc_client = distributed::RPCClient::GetInstance<RPCCLIENT_T>( Attr<int>("trainer_id")); std::vector<distributed::VarHandlePtr> rets; for (size_t i = 0; i < ins.size(); i++) { if (NeedSend(scope, ins[i])) { VLOG(3) << "sending " << ins[i] << " to " << epmap[i]; rets.push_back(rpc_client->AsyncSendVar(epmap[i], ctx, scope, ins[i])); } else { VLOG(3) << "don't send no-initialied variable: " << ins[i]; } } if (sync_send) { for (size_t i = 0; i < rets.size(); i++) { VLOG(7) << "before sync_send " << ins[i] << "from " << epmap[i]; PADDLE_ENFORCE(rets[i]->Wait(), "internal error in RPCClient"); VLOG(7) << "after sync_send " << ins[i] << "from " << epmap[i]; } } } }; class SendOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() { AddInput("X", "(Tensor, SelectedRows) Input variables to be sent") .AsDuplicable(); AddOutput("Out", "(Any) Dummy outputs, used for control dependency") .AsDuplicable(); AddComment(R"DOC( Send operator This operator will send variables to listen_and_serve op at the parameter server. )DOC"); AddAttr<int>("sync_mode", "(int, default 0)" "sync send or async send.") .SetDefault(0); AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0); AddAttr<std::vector<std::string>>("epmap", "(string vector, default 127.0.0.1:6164)" "Server endpoints in the order of input " "variables for mapping") .SetDefault({"127.0.0.1:6164"}); AddAttr<std::vector<int64_t>>("sections", "(vector<int>) " "the length of each output along the " "specified axis.") .SetDefault(std::vector<int64_t>{}); AddAttr<std::vector<std::string>>( "send_varnames", "(vector<string>) " "the splited output varnames to send to pserver") .SetDefault(std::vector<std::string>{}); AddAttr<int>("num", "(int, default 0)" "Number of sub-tensors. This must evenly divide " "Input.dims()[axis]") .SetDefault(0); } }; class SendOpShapeInference : public framework::InferShapeBase { public: void operator()(framework::InferShapeContext* ctx) const override {} }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(send, ops::SendOp, paddle::framework::EmptyGradOpMaker, ops::SendOpMaker, ops::SendOpShapeInference); <commit_msg>update send_op<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <future> // NOLINT #include <ostream> #include "paddle/fluid/framework/blocking_queue.h" #include "paddle/fluid/framework/data_type.h" #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/distributed/distributed.h" #include "paddle/fluid/operators/distributed/parameter_send.h" #include "paddle/fluid/operators/distributed_ops/send_recv_util.h" #include "paddle/fluid/platform/profiler.h" namespace paddle { namespace operators { class SendOp : public framework::OperatorBase { public: SendOp(const std::string& type, const framework::VariableNameMap& inputs, const framework::VariableNameMap& outputs, const framework::AttributeMap& attrs) : OperatorBase(type, inputs, outputs, attrs) {} void RunImpl(const framework::Scope& scope, const platform::Place& place) const override { auto ins = Inputs("X"); auto epmap = Attr<std::vector<std::string>>("epmap"); int sync_send = Attr<int>("sync_mode"); auto send_varnames = Attr<std::vector<std::string>>("send_varnames"); auto height_sections = Attr<std::vector<int64_t>>("height_sections"); if (send_varnames.size() > 0) { PADDLE_ENFORCE_EQ(ins.size(), 1, ""); framework::RuntimeContext ctx(Inputs(), Outputs(), scope); platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto* dev_ctx = pool.Get(place); auto exe_ctx = framework::ExecutionContext(*this, scope, *dev_ctx, ctx); distributed::send<float>(ins[0], send_varnames, epmap, height_sections, exe_ctx, scope, static_cast<bool>(sync_send)); } else { platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); auto& ctx = *pool.Get(place); distributed::RPCClient* rpc_client = distributed::RPCClient::GetInstance<RPCCLIENT_T>( Attr<int>("trainer_id")); std::vector<distributed::VarHandlePtr> rets; for (size_t i = 0; i < ins.size(); i++) { if (NeedSend(scope, ins[i])) { VLOG(3) << "sending " << ins[i] << " to " << epmap[i]; rets.push_back( rpc_client->AsyncSendVar(epmap[i], ctx, scope, ins[i])); } else { VLOG(3) << "don't send no-initialied variable: " << ins[i]; } } if (sync_send) { for (size_t i = 0; i < rets.size(); i++) { VLOG(7) << "before sync_send " << ins[i] << "from " << epmap[i]; PADDLE_ENFORCE(rets[i]->Wait(), "internal error in RPCClient"); VLOG(7) << "after sync_send " << ins[i] << "from " << epmap[i]; } } } } }; class SendOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() { AddInput("X", "(Tensor, SelectedRows) Input variables to be sent") .AsDuplicable(); AddOutput("Out", "(Any) Dummy outputs, used for control dependency") .AsDuplicable(); AddComment(R"DOC( Send operator This operator will send variables to listen_and_serve op at the parameter server. )DOC"); AddAttr<int>("sync_mode", "(int, default 0)" "sync send or async send.") .SetDefault(0); AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0); AddAttr<std::vector<std::string>>("epmap", "(string vector, default 127.0.0.1:6164)" "Server endpoints in the order of input " "variables for mapping") .SetDefault({"127.0.0.1:6164"}); AddAttr<std::vector<int64_t>>("sections", "(vector<int>) " "the length of each output along the " "specified axis.") .SetDefault(std::vector<int64_t>{}); AddAttr<std::vector<std::string>>( "send_varnames", "(vector<string>) " "the splited output varnames to send to pserver") .SetDefault(std::vector<std::string>{}); AddAttr<int>("num", "(int, default 0)" "Number of sub-tensors. This must evenly divide " "Input.dims()[axis]") .SetDefault(0); } }; class SendOpShapeInference : public framework::InferShapeBase { public: void operator()(framework::InferShapeContext* ctx) const override {} }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(send, ops::SendOp, paddle::framework::EmptyGradOpMaker, ops::SendOpMaker, ops::SendOpShapeInference); <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbDEMConvertAdapter.h" #include "itkMacro.h" // OSSIM include #include "base/ossimKeywordNames.h" #include "base/ossimStdOutProgress.h" #include "base/ossimFilename.h" #include "base/ossimKeywordlist.h" #include "imaging/ossimJpegWriter.h" #include "imaging/ossimImageHandler.h" #include "imaging/ossimImageSource.h" #include "imaging/ossimImageHandlerRegistry.h" #include "imaging/ossimImageWriterFactoryRegistry.h" #include "imaging/ossimImageWriterFactory.h" #include "imaging/ossimImageFileWriter.h" #include "imaging/ossimCacheTileSource.h" #include "imaging/ossimBandSelector.h" #include "imaging/ossimCibCadrgTileSource.h" namespace otb { DEMConvertAdapter::DEMConvertAdapter() {} DEMConvertAdapter::~DEMConvertAdapter() {} int DEMConvertAdapter::Convert(std::string tempFilename, std::string output) { // Keyword list to initialize image writers with. ossimKeywordlist kwl; const char* PREFIX = "imagewriter."; // Define the output file type std::string output_type("general_raster_bsq_envi"); kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true); // Get an image handler for the input file. ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(ossimString(tempFilename)); // Initialize the if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { itkExceptionMacro("Error reading image: " << tempFilename << "Exiting application..."); return EXIT_FAILURE; } ih->initialize(); ossimRefPtr<ossimImageSource> source = ih.get(); ossimRefPtr<ossimBandSelector> bs = 0; // Get the image rectangle for the rrLevel selected. ossimIrect output_rect; output_rect = source->getBoundingRect(0); ossimRefPtr<ossimImageFileWriter> writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX); writer->connectMyInputTo(0, source.get()); writer->open(ossimFilename(output)); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { if( (ih->getOutputScalarType() != OSSIM_UCHAR) && (PTR_CAST(ossimJpegWriter, writer.get()) ) ) { writer->setScaleToEightBitFlag(true); } ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource; ossimIpt tileWidthHeight(ih->getImageTileWidth(), ih->getImageTileHeight()); // only use the cache if its stripped if(static_cast<ossim_uint32>(tileWidthHeight.x) == ih->getBoundingRect().width()) { cache->connectMyInputTo(0, source.get()); cache->setTileSize(tileWidthHeight); writer->connectMyInputTo(0, cache.get()); } else { writer->connectMyInputTo(0, source.get()); } writer->initialize(); writer->setAreaOfInterest(output_rect); // Set the output rectangle. try { writer->execute(); } catch(std::exception& e) { std::cerr << "std::exception thrown:" << std::endl; std::cerr << e.what() << std::endl; itkExceptionMacro("Error occurs writing the ouput image..."); return EXIT_FAILURE; } } else { itkExceptionMacro("Error detected in the image writer..."); return EXIT_FAILURE; } } } // namespace otb <commit_msg>BUG: missing return statement<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbDEMConvertAdapter.h" #include "itkMacro.h" // OSSIM include #include "base/ossimKeywordNames.h" #include "base/ossimStdOutProgress.h" #include "base/ossimFilename.h" #include "base/ossimKeywordlist.h" #include "imaging/ossimJpegWriter.h" #include "imaging/ossimImageHandler.h" #include "imaging/ossimImageSource.h" #include "imaging/ossimImageHandlerRegistry.h" #include "imaging/ossimImageWriterFactoryRegistry.h" #include "imaging/ossimImageWriterFactory.h" #include "imaging/ossimImageFileWriter.h" #include "imaging/ossimCacheTileSource.h" #include "imaging/ossimBandSelector.h" #include "imaging/ossimCibCadrgTileSource.h" namespace otb { DEMConvertAdapter::DEMConvertAdapter() {} DEMConvertAdapter::~DEMConvertAdapter() {} int DEMConvertAdapter::Convert(std::string tempFilename, std::string output) { // Keyword list to initialize image writers with. ossimKeywordlist kwl; const char* PREFIX = "imagewriter."; // Define the output file type std::string output_type("general_raster_bsq_envi"); kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true); // Get an image handler for the input file. ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(ossimString(tempFilename)); // Initialize the if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { itkExceptionMacro("Error reading image: " << tempFilename << "Exiting application..."); return EXIT_FAILURE; } ih->initialize(); ossimRefPtr<ossimImageSource> source = ih.get(); ossimRefPtr<ossimBandSelector> bs = 0; // Get the image rectangle for the rrLevel selected. ossimIrect output_rect; output_rect = source->getBoundingRect(0); ossimRefPtr<ossimImageFileWriter> writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX); writer->connectMyInputTo(0, source.get()); writer->open(ossimFilename(output)); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { if( (ih->getOutputScalarType() != OSSIM_UCHAR) && (PTR_CAST(ossimJpegWriter, writer.get()) ) ) { writer->setScaleToEightBitFlag(true); } ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource; ossimIpt tileWidthHeight(ih->getImageTileWidth(), ih->getImageTileHeight()); // only use the cache if its stripped if(static_cast<ossim_uint32>(tileWidthHeight.x) == ih->getBoundingRect().width()) { cache->connectMyInputTo(0, source.get()); cache->setTileSize(tileWidthHeight); writer->connectMyInputTo(0, cache.get()); } else { writer->connectMyInputTo(0, source.get()); } writer->initialize(); writer->setAreaOfInterest(output_rect); // Set the output rectangle. try { writer->execute(); } catch(std::exception& e) { std::cerr << "std::exception thrown:" << std::endl; std::cerr << e.what() << std::endl; itkExceptionMacro("Error occurs writing the ouput image..."); return EXIT_FAILURE; } } else { itkExceptionMacro("Error detected in the image writer..."); return EXIT_FAILURE; } return EXIT_SUCCESS; } } // namespace otb <|endoftext|>
<commit_before>#include "TerminalServer.hpp" using namespace et; namespace google {} namespace gflags {} using namespace google; using namespace gflags; int main(int argc, char **argv) { // Setup easylogging configurations el::Configurations defaultConf = LogHandler::setupLogHandler(&argc, &argv); // Parse command line arguments cxxopts::Options options("etserver", "Remote shell for the busy and impatient"); options.allow_unrecognised_options(); options.add_options() // ("help", "Print help") // ("version", "Print version") // ("port", "Port to listen on", cxxopts::value<int>()->default_value("0")) // ("daemon", "Daemonize the server") // ("cfgfile", "Location of the config file", cxxopts::value<std::string>()->default_value("")) // ("logtostdout", "log to stdout") // ("v,verbose", "Enable verbose logging", cxxopts::value<int>()->default_value("0")) // ; auto result = options.parse(argc, argv); if (result.count("help")) { cout << options.help({}) << endl; exit(0); } if (result.count("version")) { cout << "et version " << ET_VERSION << endl; exit(0); } if (result.count("daemon")) { if (DaemonCreator::create(true) == -1) { LOG(FATAL) << "Error creating daemon: " << strerror(errno); } } if (result.count("logtostdout")) { defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true"); } else { defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, "false"); // Redirect std streams to a file LogHandler::stderrToFile("/tmp/etserver"); } // default max log file size is 20MB for etserver string maxlogsize = "20971520"; int port = 0; if (result.count("cfgfile")) { // Load the config file CSimpleIniA ini(true, true, true); SI_Error rc = ini.LoadFile(result["cfgfile"].as<string>().c_str()); if (rc == 0) { if (!result.count("port")) { const char *portString = ini.GetValue("Networking", "Port", NULL); if (portString) { port = stoi(portString); } } // read verbose level const char *vlevel = ini.GetValue("Debug", "verbose", NULL); if (vlevel) { el::Loggers::setVerboseLevel(atoi(vlevel)); } // read silent setting const char *silent = ini.GetValue("Debug", "silent", NULL); if (silent && atoi(silent) != 0) { defaultConf.setGlobally(el::ConfigurationType::Enabled, "false"); } // read log file size limit const char *logsize = ini.GetValue("Debug", "logsize", NULL); if (logsize && atoi(logsize) != 0) { // make sure maxlogsize is a string of int value maxlogsize = string(logsize); } } else { LOG(FATAL) << "Invalid config file: " << result["cfgfile"].as<string>(); } } GOOGLE_PROTOBUF_VERIFY_VERSION; srand(1); if (port == 0) { port = 2022; } // Set log file for etserver process here. LogHandler::setupLogFile(&defaultConf, "/tmp/etserver-%datetime.log", maxlogsize); // Reconfigure default logger to apply settings above el::Loggers::reconfigureLogger("default", defaultConf); // set thread name el::Helpers::setThreadName("etserver-main"); // Install log rotation callback el::Helpers::installPreRollOutCallback(LogHandler::rolloutHandler); std::shared_ptr<SocketHandler> tcpSocketHandler(new TcpSocketHandler()); std::shared_ptr<PipeSocketHandler> pipeSocketHandler(new PipeSocketHandler()); TerminalServer terminalServer(tcpSocketHandler, SocketEndpoint(port), pipeSocketHandler, SocketEndpoint(ROUTER_FIFO_NAME)); terminalServer.run(); // Uninstall log rotation callback el::Helpers::uninstallPreRollOutCallback(); } <commit_msg>fix cfgfile flag<commit_after>#include "TerminalServer.hpp" using namespace et; namespace google {} namespace gflags {} using namespace google; using namespace gflags; int main(int argc, char **argv) { // Setup easylogging configurations el::Configurations defaultConf = LogHandler::setupLogHandler(&argc, &argv); // Parse command line arguments cxxopts::Options options("etserver", "Remote shell for the busy and impatient"); options.allow_unrecognised_options(); options.add_options() // ("help", "Print help") // ("version", "Print version") // ("port", "Port to listen on", cxxopts::value<int>()->default_value("0")) // ("daemon", "Daemonize the server") // ("cfgfile", "Location of the config file", cxxopts::value<std::string>()->default_value("")) // ("logtostdout", "log to stdout") // ("v,verbose", "Enable verbose logging", cxxopts::value<int>()->default_value("0")) // ; auto result = options.parse(argc, argv); if (result.count("help")) { cout << options.help({}) << endl; exit(0); } if (result.count("version")) { cout << "et version " << ET_VERSION << endl; exit(0); } if (result.count("daemon")) { if (DaemonCreator::create(true) == -1) { LOG(FATAL) << "Error creating daemon: " << strerror(errno); } } if (result.count("logtostdout")) { defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true"); } else { defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, "false"); // Redirect std streams to a file LogHandler::stderrToFile("/tmp/etserver"); } // default max log file size is 20MB for etserver string maxlogsize = "20971520"; int port = 0; if (result.count("cfgfile")) { // Load the config file CSimpleIniA ini(true, true, true); string cfgfilename = result["cfgfile"].as<string>(); SI_Error rc = ini.LoadFile(cfgfilename.c_str()); if (rc == 0) { if (!result.count("port")) { const char *portString = ini.GetValue("Networking", "Port", NULL); if (portString) { port = stoi(portString); } } // read verbose level const char *vlevel = ini.GetValue("Debug", "verbose", NULL); if (vlevel) { el::Loggers::setVerboseLevel(atoi(vlevel)); } // read silent setting const char *silent = ini.GetValue("Debug", "silent", NULL); if (silent && atoi(silent) != 0) { defaultConf.setGlobally(el::ConfigurationType::Enabled, "false"); } // read log file size limit const char *logsize = ini.GetValue("Debug", "logsize", NULL); if (logsize && atoi(logsize) != 0) { // make sure maxlogsize is a string of int value maxlogsize = string(logsize); } } else { LOG(FATAL) << "Invalid config file: " << cfgfilename; } } GOOGLE_PROTOBUF_VERIFY_VERSION; srand(1); if (port == 0) { port = 2022; } // Set log file for etserver process here. LogHandler::setupLogFile(&defaultConf, "/tmp/etserver-%datetime.log", maxlogsize); // Reconfigure default logger to apply settings above el::Loggers::reconfigureLogger("default", defaultConf); // set thread name el::Helpers::setThreadName("etserver-main"); // Install log rotation callback el::Helpers::installPreRollOutCallback(LogHandler::rolloutHandler); std::shared_ptr<SocketHandler> tcpSocketHandler(new TcpSocketHandler()); std::shared_ptr<PipeSocketHandler> pipeSocketHandler(new PipeSocketHandler()); TerminalServer terminalServer(tcpSocketHandler, SocketEndpoint(port), pipeSocketHandler, SocketEndpoint(ROUTER_FIFO_NAME)); terminalServer.run(); // Uninstall log rotation callback el::Helpers::uninstallPreRollOutCallback(); } <|endoftext|>
<commit_before>// 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 <iostream> #include <sstream> #include <process/defer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/http.hpp> #include <process/process.hpp> using namespace process; using namespace process::http; using std::string; class MyProcess : public Process<MyProcess> { public: MyProcess() {} virtual ~MyProcess() {} Future<int> func1() { promise.future().onAny( defer([=] (const Future<int>& future) { terminate(self()); })); return promise.future(); } void func2(int i) { promise.set(i); } Future<Response> vars(const Request& request) { string body = "... vars here ..."; OK response; response.headers["Content-Type"] = "text/plain"; std::ostringstream out; out << body.size(); response.headers["Content-Length"] = out.str(); response.body = body; return response; } void stop(const UPID& from, const string& body) { terminate(self()); } protected: virtual void initialize() { // route("/vars", &MyProcess::vars); route("/vars", [=] (const Request& request) { string body = "... vars here ..."; OK response; response.headers["Content-Type"] = "text/plain"; std::ostringstream out; out << body.size(); response.headers["Content-Length"] = out.str(); response.body = body; return response; }); // install("stop", &MyProcess::stop); install("stop", [=] (const UPID& from, const string& body) { terminate(self()); }); } private: Promise<int> promise; }; int main(int argc, char** argv) { MyProcess process; PID<MyProcess> pid = spawn(&process); PID<> pid2 = pid; // -------------------------------------- // Future<int> future = dispatch(pid, &MyProcess::func1); // dispatch(pid, &MyProcess::func2, 42); // std::cout << future.get() << std::endl; // post(pid, "stop"); // -------------------------------------- // Promise<bool> p; // dispatch(pid, &MyProcess::func1) // .then([=, &p] (int i) { // p.set(i == 42); // return p.future(); // }) // .then([=] (bool b) { // if (b) { // post(pid, "stop"); // } // return true; // No Future<void>. // }); // dispatch(pid, &MyProcess::func2, 42); // -------------------------------------- dispatch(pid, &MyProcess::func1); dispatch(pid, &MyProcess::func2, 42); wait(pid); return 0; } <commit_msg>Reformated libprocess example code.<commit_after>// 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 <iostream> #include <sstream> #include <string> #include <process/defer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/http.hpp> #include <process/process.hpp> using namespace process; using namespace process::http; using std::string; class MyProcess : public Process<MyProcess> { public: MyProcess() {} virtual ~MyProcess() {} Future<int> func1() { promise.future().onAny( defer([=](const Future<int>& future) { terminate(self()); })); return promise.future(); } void func2(int i) { promise.set(i); } Future<Response> vars(const Request& request) { string body = "... vars here ..."; OK response; response.headers["Content-Type"] = "text/plain"; std::ostringstream out; out << body.size(); response.headers["Content-Length"] = out.str(); response.body = body; return response; } void stop(const UPID& from, const string& body) { terminate(self()); } protected: virtual void initialize() { // route("/vars", &MyProcess::vars); route("/vars", [=](const Request& request) { string body = "... vars here ..."; OK response; response.headers["Content-Type"] = "text/plain"; std::ostringstream out; out << body.size(); response.headers["Content-Length"] = out.str(); response.body = body; return response; }); // install("stop", &MyProcess::stop); install("stop", [=](const UPID& from, const string& body) { terminate(self()); }); } private: Promise<int> promise; }; int main(int argc, char** argv) { MyProcess process; PID<MyProcess> pid = spawn(&process); PID<> pid2 = pid; //// -------------------------------------- // Future<int> future = dispatch(pid, &MyProcess::func1); // dispatch(pid, &MyProcess::func2, 42); // std::cout << future.get() << std::endl; // post(pid, "stop"); //// -------------------------------------- // Promise<bool> p; // dispatch(pid, &MyProcess::func1) // .then([=, &p] (int i) { // p.set(i == 42); // return p.future(); // }) // .then([=] (bool b) { // if (b) { // post(pid, "stop"); // } // return true; // No Future<void>. // }); // dispatch(pid, &MyProcess::func2, 42); //// -------------------------------------- dispatch(pid, &MyProcess::func1); dispatch(pid, &MyProcess::func2, 42); wait(pid); return 0; } <|endoftext|>
<commit_before>#include "std_incl.h" #include "ResultManager.h" #include "utils.h" ResultManager::ResultManager(const char *outfile, const char* frameInfoFile, ResultManagerConfig *cfg) { config = *cfg; outputFile = outfile; this->frameInfoFile = frameInfoFile; startFrame = 0; lastSaveFrame = 0; processedFrames = 0; capturedFrames = 0; localizationsDone = 0; qtrk = 0; thread = Threads::Create(ThreadLoop, this); quit=false; remove(outfile); remove(frameInfoFile); dbgprintf("Allocating ResultManager with %d beads and writeinterval %d\n", cfg->numBeads, cfg->writeInterval); } ResultManager::~ResultManager() { quit = true; Threads::WaitAndClose(thread); DeleteAllElems(frameResults); } void ResultManager::StoreResult(LocalizationResult *r) { int index = r->job.frame - startFrame; if (index >= frameResults.size()) { dbgprintf("dropping result. Result provided for unregistered frame %d. Current frames registered: %d\n", r->job.frame, startFrame + frameResults.size()); return; // add errors? } LocalizationResult scaled = *r; // Make roi-centered pos scaled.pos = scaled.pos - vector3f( qtrk->cfg.width*0.5f, qtrk->cfg.height*0.5f, 0); scaled.pos = ( scaled.pos + config.offset ) * config.scaling; FrameResult* fr = frameResults[index]; fr->results[r->job.zlutIndex] = scaled; fr->count++; // Advance fullFrames frameCountMutex.lock(); while (processedFrames - startFrame < frameResults.size() && frameResults[processedFrames-startFrame]->count == config.numBeads) processedFrames ++; localizationsDone ++; frameCountMutex.unlock(); } void ResultManager::Write() { FILE* f = fopen(outputFile.c_str(), "a"); FILE* finfo = fopen(frameInfoFile.c_str(), "a"); resultMutex.lock(); if (config.binaryOutput) { for (uint j=lastSaveFrame; j<processedFrames;j++) { auto fr = frameResults[j-startFrame]; fwrite(&j, sizeof(uint), 1, f); fwrite(&fr->timestamp, sizeof(double), 1, f); fwrite(&fr->timestamp, sizeof(double), 1, finfo); for (int i=0;i<config.numBeads;i++) { LocalizationResult *r = &fr->results[i]; fwrite(&r->pos, sizeof(vector3f), 1, f); } } } else { for (uint k=lastSaveFrame; k<processedFrames;k++) { auto fr = frameResults[k-startFrame]; fprintf(f,"%d\t%f\t", k, fr->timestamp); fprintf(finfo,"%d\t%f\t", k, fr->timestamp); for (int i=0;i<config.numFrameInfoColumns;i++) fprintf(finfo, "%.5f\t", fr->frameInfo[i]); fputs("\n", finfo); for (int i=0;i<config.numBeads;i++) { LocalizationResult *r = &fr->results[i]; fprintf(f, "%.5f\t%.5f\t%.5f\t", r->pos.x,r->pos.y,r->pos.z); } fputs("\n", f); } } dbgprintf("Saved frame %d to %d\n", lastSaveFrame, processedFrames); fclose(f); fclose(finfo); frameCountMutex.lock(); lastSaveFrame = processedFrames; frameCountMutex.unlock(); resultMutex.unlock(); } void ResultManager::SetTracker(QueuedTracker *qtrk) { trackerMutex.lock(); this->qtrk = qtrk; trackerMutex.unlock(); } bool ResultManager::Update() { trackerMutex.lock(); if (!qtrk) { trackerMutex.unlock(); return 0; } const int NResultBuf = 40; LocalizationResult resultbuf[NResultBuf]; int count = qtrk->PollFinished( resultbuf, NResultBuf ); resultMutex.lock(); for (int i=0;i<count;i++) StoreResult(&resultbuf[i]); resultMutex.unlock(); trackerMutex.unlock(); if (processedFrames - lastSaveFrame >= config.writeInterval) { Write(); } if (config.maxFramesInMemory>0 && frameResults.size () > config.maxFramesInMemory) { int del = frameResults.size()-config.maxFramesInMemory; dbgprintf("Removing %d frames from memory\n", del); for (int i=0;i<del;i++) delete frameResults[i]; frameResults.erase(frameResults.begin(), frameResults.begin()+del); frameCountMutex.lock(); startFrame += del; frameCountMutex.unlock(); } return count>0; } void ResultManager::ThreadLoop(void *param) { ResultManager* rm = (ResultManager*)param; while(true) { if (!rm->Update()) Threads::Sleep(20); if (rm->quit) break; } } int ResultManager::GetBeadPositions(int startFrame, int endFrame, int bead, LocalizationResult* results) { int start = startFrame - this->startFrame; if (endFrame > processedFrames) endFrame = processedFrames; int end = endFrame - this->startFrame; if (start < 0) return 0; resultMutex.lock(); for (int i=start;i<end;i++){ results[i-start] = frameResults[i]->results[bead]; } resultMutex.unlock(); return end-start; } void ResultManager::Flush() { Write(); resultMutex.lock(); // Dump stats about unfinished frames for debugging for (int i=0;i<frameResults.size();i++) { FrameResult *fr = frameResults[i]; dbgprintf("Frame %d. TS: %f, Count: %d\n", i, fr->timestamp, fr->count); if (fr->count != config.numBeads) { for (int j=0;j<fr->results.size();j++) { if( fr->results[j].job.locType == 0 ) dbgprintf("%d, ", j ); } dbgprintf("\n"); } } resultMutex.unlock(); } void ResultManager::GetFrameCounters(int* startFrame, int *processedFrames, int *lastSaveFrame, int *capturedFrames, int *localizationsDone) { frameCountMutex.lock(); if (startFrame) *startFrame = this->startFrame; if (processedFrames) *processedFrames = this->processedFrames; if (lastSaveFrame) *lastSaveFrame = this->lastSaveFrame; if (localizationsDone) *localizationsDone = this->localizationsDone; frameCountMutex.unlock(); if (capturedFrames) { resultMutex.lock(); *capturedFrames = this->capturedFrames; resultMutex.unlock(); } } int ResultManager::GetResults(LocalizationResult* results, int startFrame, int numFrames) { frameCountMutex.lock(); if (startFrame >= this->startFrame && numFrames+startFrame <= processedFrames) { resultMutex.lock(); for (int f=0;f<numFrames;f++) { int index = f + startFrame - this->startFrame; for (int j=0;j<config.numBeads;j++) results[config.numBeads*f+j] = frameResults[index]->results[j]; } resultMutex.unlock(); } frameCountMutex.unlock(); return numFrames; } int ResultManager::StoreFrameInfo(double timestamp, float* columns) { resultMutex.lock(); auto fr = new FrameResult( config.numBeads, config.numFrameInfoColumns); fr->timestamp = timestamp; for(int i=0;i<config.numFrameInfoColumns;i++) fr->frameInfo[i]=columns[i]; frameResults.push_back (fr); int nfr = ++capturedFrames; resultMutex.unlock(); return nfr; } int ResultManager::GetFrameCount() { resultMutex.lock(); int nfr = capturedFrames; resultMutex.unlock(); return nfr; } <commit_msg>C++: ResultManager: Test for valid output filename / frame info filename Fix OfflineQTrk build for new result manager<commit_after>#include "std_incl.h" #include "ResultManager.h" #include "utils.h" ResultManager::ResultManager(const char *outfile, const char* frameInfoFile, ResultManagerConfig *cfg) { config = *cfg; outputFile = outfile; this->frameInfoFile = frameInfoFile; startFrame = 0; lastSaveFrame = 0; processedFrames = 0; capturedFrames = 0; localizationsDone = 0; qtrk = 0; thread = Threads::Create(ThreadLoop, this); quit=false; remove(outfile); remove(frameInfoFile); dbgprintf("Allocating ResultManager with %d beads and writeinterval %d\n", cfg->numBeads, cfg->writeInterval); } ResultManager::~ResultManager() { quit = true; Threads::WaitAndClose(thread); DeleteAllElems(frameResults); } void ResultManager::StoreResult(LocalizationResult *r) { int index = r->job.frame - startFrame; if (index >= frameResults.size()) { dbgprintf("dropping result. Result provided for unregistered frame %d. Current frames registered: %d\n", r->job.frame, startFrame + frameResults.size()); return; // add errors? } LocalizationResult scaled = *r; // Make roi-centered pos scaled.pos = scaled.pos - vector3f( qtrk->cfg.width*0.5f, qtrk->cfg.height*0.5f, 0); scaled.pos = ( scaled.pos + config.offset ) * config.scaling; FrameResult* fr = frameResults[index]; fr->results[r->job.zlutIndex] = scaled; fr->count++; // Advance fullFrames frameCountMutex.lock(); while (processedFrames - startFrame < frameResults.size() && frameResults[processedFrames-startFrame]->count == config.numBeads) processedFrames ++; localizationsDone ++; frameCountMutex.unlock(); } void ResultManager::Write() { FILE* f = outputFile.empty () ? 0 : fopen(outputFile.c_str(), "a"); FILE* finfo = frameInfoFile.empty() ? 0 : fopen(frameInfoFile.c_str(), "a"); resultMutex.lock(); if (config.binaryOutput) { for (uint j=lastSaveFrame; j<processedFrames;j++) { auto fr = frameResults[j-startFrame]; if (f) { fwrite(&j, sizeof(uint), 1, f); fwrite(&fr->timestamp, sizeof(double), 1, f); for (int i=0;i<config.numBeads;i++) { LocalizationResult *r = &fr->results[i]; fwrite(&r->pos, sizeof(vector3f), 1, f); } } if (finfo) fwrite(&fr->timestamp, sizeof(double), 1, finfo); } } else { for (uint k=lastSaveFrame; k<processedFrames;k++) { auto fr = frameResults[k-startFrame]; if (f) { fprintf(f,"%d\t%f\t", k, fr->timestamp); for (int i=0;i<config.numBeads;i++) { LocalizationResult *r = &fr->results[i]; fprintf(f, "%.5f\t%.5f\t%.5f\t", r->pos.x,r->pos.y,r->pos.z); } fputs("\n", f); } if (finfo) { fprintf(finfo,"%d\t%f\t", k, fr->timestamp); for (int i=0;i<config.numFrameInfoColumns;i++) fprintf(finfo, "%.5f\t", fr->frameInfo[i]); fputs("\n", finfo); } } } dbgprintf("Saved frame %d to %d\n", lastSaveFrame, processedFrames); if(f) fclose(f); if(finfo) fclose(finfo); frameCountMutex.lock(); lastSaveFrame = processedFrames; frameCountMutex.unlock(); resultMutex.unlock(); } void ResultManager::SetTracker(QueuedTracker *qtrk) { trackerMutex.lock(); this->qtrk = qtrk; trackerMutex.unlock(); } bool ResultManager::Update() { trackerMutex.lock(); if (!qtrk) { trackerMutex.unlock(); return 0; } const int NResultBuf = 40; LocalizationResult resultbuf[NResultBuf]; int count = qtrk->PollFinished( resultbuf, NResultBuf ); resultMutex.lock(); for (int i=0;i<count;i++) StoreResult(&resultbuf[i]); resultMutex.unlock(); trackerMutex.unlock(); if (processedFrames - lastSaveFrame >= config.writeInterval) { Write(); } if (config.maxFramesInMemory>0 && frameResults.size () > config.maxFramesInMemory) { int del = frameResults.size()-config.maxFramesInMemory; dbgprintf("Removing %d frames from memory\n", del); for (int i=0;i<del;i++) delete frameResults[i]; frameResults.erase(frameResults.begin(), frameResults.begin()+del); frameCountMutex.lock(); startFrame += del; frameCountMutex.unlock(); } return count>0; } void ResultManager::ThreadLoop(void *param) { ResultManager* rm = (ResultManager*)param; while(true) { if (!rm->Update()) Threads::Sleep(20); if (rm->quit) break; } } int ResultManager::GetBeadPositions(int startFrame, int endFrame, int bead, LocalizationResult* results) { int start = startFrame - this->startFrame; if (endFrame > processedFrames) endFrame = processedFrames; int end = endFrame - this->startFrame; if (start < 0) return 0; resultMutex.lock(); for (int i=start;i<end;i++){ results[i-start] = frameResults[i]->results[bead]; } resultMutex.unlock(); return end-start; } void ResultManager::Flush() { Write(); resultMutex.lock(); // Dump stats about unfinished frames for debugging for (int i=0;i<frameResults.size();i++) { FrameResult *fr = frameResults[i]; dbgprintf("Frame %d. TS: %f, Count: %d\n", i, fr->timestamp, fr->count); if (fr->count != config.numBeads) { for (int j=0;j<fr->results.size();j++) { if( fr->results[j].job.locType == 0 ) dbgprintf("%d, ", j ); } dbgprintf("\n"); } } resultMutex.unlock(); } void ResultManager::GetFrameCounters(int* startFrame, int *processedFrames, int *lastSaveFrame, int *capturedFrames, int *localizationsDone) { frameCountMutex.lock(); if (startFrame) *startFrame = this->startFrame; if (processedFrames) *processedFrames = this->processedFrames; if (lastSaveFrame) *lastSaveFrame = this->lastSaveFrame; if (localizationsDone) *localizationsDone = this->localizationsDone; frameCountMutex.unlock(); if (capturedFrames) { resultMutex.lock(); *capturedFrames = this->capturedFrames; resultMutex.unlock(); } } int ResultManager::GetResults(LocalizationResult* results, int startFrame, int numFrames) { frameCountMutex.lock(); if (startFrame >= this->startFrame && numFrames+startFrame <= processedFrames) { resultMutex.lock(); for (int f=0;f<numFrames;f++) { int index = f + startFrame - this->startFrame; for (int j=0;j<config.numBeads;j++) results[config.numBeads*f+j] = frameResults[index]->results[j]; } resultMutex.unlock(); } frameCountMutex.unlock(); return numFrames; } int ResultManager::StoreFrameInfo(double timestamp, float* columns) { resultMutex.lock(); auto fr = new FrameResult( config.numBeads, config.numFrameInfoColumns); fr->timestamp = timestamp; for(int i=0;i<config.numFrameInfoColumns;i++) fr->frameInfo[i]=columns[i]; frameResults.push_back (fr); int nfr = ++capturedFrames; resultMutex.unlock(); return nfr; } int ResultManager::GetFrameCount() { resultMutex.lock(); int nfr = capturedFrames; resultMutex.unlock(); return nfr; } <|endoftext|>
<commit_before>// Filename: collisionHandlerFluidPusher.cxx // Created by: drose (16Mar02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "collisionHandlerFluidPusher.h" #include "collisionNode.h" #include "collisionEntry.h" #include "collisionPolygon.h" #include "config_collide.h" #include "dcast.h" TypeHandle CollisionHandlerFluidPusher::_type_handle; //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// CollisionHandlerFluidPusher:: CollisionHandlerFluidPusher() { _wants_all_potential_collidees = true; } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::add_entry // Access: Public, Virtual // Description: Called between a begin_group() .. end_group() // sequence for each collision that is detected. //////////////////////////////////////////////////////////////////// void CollisionHandlerFluidPusher:: add_entry(CollisionEntry *entry) { nassertv(entry != (CollisionEntry *)NULL); // skip over CollisionHandlerPhysical::add_entry, since it filters // out collidees by orientation; our collider can change direction // mid-frame, so it may collide with something that would have been // filtered out CollisionHandlerEvent::add_entry(entry); // filter out non-tangibles if (entry->get_from()->is_tangible() && (!entry->has_into() || entry->get_into()->is_tangible())) { _from_entries[entry->get_from_node_path()].push_back(entry); if (entry->collided()) { _has_contact = true; } } } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::handle_entries // Access: Protected, Virtual // Description: Calculates a reasonable final position for a // collider given a set of collidees //////////////////////////////////////////////////////////////////// bool CollisionHandlerFluidPusher:: handle_entries() { /* This pusher repeatedly calculates the first collision, calculates a new trajectory based on that collision, and repeats until the original motion is exhausted or the collider becomes "stuck". This solves the "acute collisions" problem where colliders could bounce their way through to the other side of a wall. Pseudocode: INPUTS PosA = collider's previous position PosB = collider's current position M = movement vector (PosB - PosA) BV = bounding sphere that includes collider at PosA and PosB CS = 'collision set', all 'collidables' within BV (collision polys, tubes, etc) VARIABLES N = movement vector since most recent collision (or start of frame) SCS = 'sub collision set', all collidables that could still be collided with C = single collider currently being collided with PosX = new position given movement along N interrupted by collision with C OUTPUTS final position is PosX 1. N = M, SCS = CS, PosX = PosB 2. compute, using SCS and N, which collidable C is the first collision 3. if no collision found, DONE 4. if movement in direction M is now blocked, then PosX = initial point of contact with C along N, DONE 5. calculate PosX (and new N) assuming that there will be no more collisions 6. remove C from SCS (assumes that you can't collide against a solid more than once per frame) 7. go to 2 */ bool okflag = true; // if all we got was potential collisions, don't bother if (!_has_contact) { return okflag; } // for every fluid mover being pushed... FromEntries::iterator fei; for (fei = _from_entries.begin(); fei != _from_entries.end(); ++fei) { NodePath from_node_path = fei->first; Entries *orig_entries = &fei->second; Colliders::iterator ci; ci = _colliders.find(from_node_path); if (ci == _colliders.end()) { // Hmm, someone added a CollisionNode to a traverser and gave // it this CollisionHandler pointer--but they didn't tell us // about the node. collide_cat.error() << "CollisionHandlerFluidPusher doesn't know about " << from_node_path << ", disabling.\n"; okflag = false; } else { ColliderDef &def = (*ci).second; // we do our math in this node's space NodePath wrt_node(*_root); // extract the collision entries into a vector that we can safely modify Entries entries(*orig_entries); // this is the original position delta for the entire frame, before collision response LVector3f M(from_node_path.get_pos_delta(wrt_node)); // this is used to track position deltas every time we collide against a solid LVector3f N(M); const LPoint3f orig_pos(from_node_path.get_pos(wrt_node)); CPT(TransformState) prev_trans(from_node_path.get_prev_transform(wrt_node)); const LPoint3f orig_prev_pos(prev_trans->get_pos()); // currently we only support spheres as the collider const CollisionSphere *sphere; DCAST_INTO_R(sphere, entries.front()->get_from(), 0); from_node_path.set_pos(wrt_node, 0,0,0); LPoint3f sphere_offset = (sphere->get_center() * from_node_path.get_transform(wrt_node)->get_mat()); from_node_path.set_pos(wrt_node, orig_pos); // this will hold the final calculated position at each iteration LPoint3f candidate_final_pos(orig_pos); // this holds the position before reacting to collisions LPoint3f uncollided_pos(candidate_final_pos); // unit vector facing back into original direction of motion LVector3f reverse_vec(-M); reverse_vec.normalize(); // unit vector pointing out to the right relative to the direction of motion, // looking into the direction of motion const LVector3f right_unit(LVector3f::up().cross(reverse_vec)); // iterate until the mover runs out of movement or gets stuck while (true) { const CollisionEntry *C = 0; // find the first (earliest) collision Entries::const_iterator cei; for (cei = entries.begin(); cei != entries.end(); ++cei) { const CollisionEntry *entry = (*cei); nassertr(entry != (CollisionEntry *)NULL, false); if (entry->collided() && ((C == 0) || (entry->get_t() < C->get_t()))) { nassertr(from_node_path == entry->get_from_node_path(), false); C = entry; break; } } // if no collisions, we're done if (C == 0) { break; } // move back to initial contact position LPoint3f contact_pos; LVector3f contact_normal; if (!C->get_all_contact_info(wrt_node, contact_pos, contact_normal)) { collide_cat.warning() << "Cannot shove on " << from_node_path << " for collision into " << C->get_into_node_path() << "; no contact pos/normal information.\n"; break; } // calculate the position of the target node at the point of contact contact_pos -= sphere_offset; uncollided_pos = candidate_final_pos; candidate_final_pos = contact_pos; LVector3f proj_surface_normal(contact_normal); LVector3f norm_proj_surface_normal(proj_surface_normal); norm_proj_surface_normal.normalize(); LVector3f blocked_movement(uncollided_pos - contact_pos); float push_magnitude(-blocked_movement.dot(proj_surface_normal)); if (push_magnitude < 0.0f) { // don't ever push into plane candidate_final_pos = contact_pos; } else { // calculate new position given that you collided with this thing // project the final position onto the plane of the obstruction candidate_final_pos = uncollided_pos + (norm_proj_surface_normal * push_magnitude); } from_node_path.set_pos(wrt_node, candidate_final_pos); CPT(TransformState) prev_trans(from_node_path.get_prev_transform(wrt_node)); prev_trans = prev_trans->set_pos(contact_pos); from_node_path.set_prev_transform(wrt_node, prev_trans); { const LPoint3f new_pos(from_node_path.get_pos(wrt_node)); CPT(TransformState) new_prev_trans(from_node_path.get_prev_transform(wrt_node)); const LPoint3f new_prev_pos(new_prev_trans->get_pos()); } // recalculate the position delta N = from_node_path.get_pos_delta(wrt_node); // calculate new collisions given new movement vector Entries::iterator ei; Entries new_entries; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); nassertr(entry != (CollisionEntry *)NULL, false); // skip the one we just collided against if (entry != C) { entry->_from_node_path = from_node_path; entry->reset_collided(); PT(CollisionEntry) result = entry->get_from()->test_intersection(**ei); if (result != (CollisionEntry *)NULL && result != (CollisionEntry *)0) { new_entries.push_back(result); } } } entries.swap(new_entries); } // put things back where they were from_node_path.set_pos(wrt_node, orig_pos); // restore the appropriate previous position prev_trans = from_node_path.get_prev_transform(wrt_node); prev_trans = prev_trans->set_pos(orig_prev_pos); from_node_path.set_prev_transform(wrt_node, prev_trans); LVector3f net_shove(candidate_final_pos - orig_pos); LVector3f force_normal(net_shove); force_normal.normalize(); // This is the part where the node actually gets moved: def._target.set_pos(wrt_node, candidate_final_pos); // We call this to allow derived classes to do other // fix-ups as they see fit: apply_net_shove(def, net_shove, force_normal); apply_linear_force(def, force_normal); } } return okflag; } <commit_msg>fixes determination of earliest collision<commit_after>// Filename: collisionHandlerFluidPusher.cxx // Created by: drose (16Mar02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "collisionHandlerFluidPusher.h" #include "collisionNode.h" #include "collisionEntry.h" #include "collisionPolygon.h" #include "config_collide.h" #include "dcast.h" TypeHandle CollisionHandlerFluidPusher::_type_handle; //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// CollisionHandlerFluidPusher:: CollisionHandlerFluidPusher() { _wants_all_potential_collidees = true; } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::add_entry // Access: Public, Virtual // Description: Called between a begin_group() .. end_group() // sequence for each collision that is detected. //////////////////////////////////////////////////////////////////// void CollisionHandlerFluidPusher:: add_entry(CollisionEntry *entry) { nassertv(entry != (CollisionEntry *)NULL); // skip over CollisionHandlerPhysical::add_entry, since it filters // out collidees by orientation; our collider can change direction // mid-frame, so it may collide with something that would have been // filtered out CollisionHandlerEvent::add_entry(entry); // filter out non-tangibles if (entry->get_from()->is_tangible() && (!entry->has_into() || entry->get_into()->is_tangible())) { _from_entries[entry->get_from_node_path()].push_back(entry); if (entry->collided()) { _has_contact = true; } } } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::handle_entries // Access: Protected, Virtual // Description: Calculates a reasonable final position for a // collider given a set of collidees //////////////////////////////////////////////////////////////////// bool CollisionHandlerFluidPusher:: handle_entries() { /* This pusher repeatedly calculates the first collision, calculates a new trajectory based on that collision, and repeats until the original motion is exhausted or the collider becomes "stuck". This solves the "acute collisions" problem where colliders could bounce their way through to the other side of a wall. Pseudocode: INPUTS PosA = collider's previous position PosB = collider's current position M = movement vector (PosB - PosA) BV = bounding sphere that includes collider at PosA and PosB CS = 'collision set', all 'collidables' within BV (collision polys, tubes, etc) VARIABLES N = movement vector since most recent collision (or start of frame) SCS = 'sub collision set', all collidables that could still be collided with C = single collider currently being collided with PosX = new position given movement along N interrupted by collision with C OUTPUTS final position is PosX 1. N = M, SCS = CS, PosX = PosB 2. compute, using SCS and N, which collidable C is the first collision 3. if no collision found, DONE 4. if movement in direction M is now blocked, then PosX = initial point of contact with C along N, DONE 5. calculate PosX (and new N) assuming that there will be no more collisions 6. remove C from SCS (assumes that you can't collide against a solid more than once per frame) 7. go to 2 */ bool okflag = true; // if all we got was potential collisions, don't bother if (!_has_contact) { return okflag; } // for every fluid mover being pushed... FromEntries::iterator fei; for (fei = _from_entries.begin(); fei != _from_entries.end(); ++fei) { NodePath from_node_path = fei->first; Entries *orig_entries = &fei->second; Colliders::iterator ci; ci = _colliders.find(from_node_path); if (ci == _colliders.end()) { // Hmm, someone added a CollisionNode to a traverser and gave // it this CollisionHandler pointer--but they didn't tell us // about the node. collide_cat.error() << "CollisionHandlerFluidPusher doesn't know about " << from_node_path << ", disabling.\n"; okflag = false; } else { ColliderDef &def = (*ci).second; // we do our math in this node's space NodePath wrt_node(*_root); // extract the collision entries into a vector that we can safely modify Entries entries(*orig_entries); // this is the original position delta for the entire frame, before collision response LVector3f M(from_node_path.get_pos_delta(wrt_node)); // this is used to track position deltas every time we collide against a solid LVector3f N(M); const LPoint3f orig_pos(from_node_path.get_pos(wrt_node)); CPT(TransformState) prev_trans(from_node_path.get_prev_transform(wrt_node)); const LPoint3f orig_prev_pos(prev_trans->get_pos()); // currently we only support spheres as the collider const CollisionSphere *sphere; DCAST_INTO_R(sphere, entries.front()->get_from(), 0); from_node_path.set_pos(wrt_node, 0,0,0); LPoint3f sphere_offset = (sphere->get_center() * from_node_path.get_transform(wrt_node)->get_mat()); from_node_path.set_pos(wrt_node, orig_pos); // this will hold the final calculated position at each iteration LPoint3f candidate_final_pos(orig_pos); // this holds the position before reacting to collisions LPoint3f uncollided_pos(candidate_final_pos); // unit vector facing back into original direction of motion LVector3f reverse_vec(-M); reverse_vec.normalize(); // unit vector pointing out to the right relative to the direction of motion, // looking into the direction of motion const LVector3f right_unit(LVector3f::up().cross(reverse_vec)); // iterate until the mover runs out of movement or gets stuck while (true) { const CollisionEntry *C = 0; // find the first (earliest) collision Entries::const_iterator cei; for (cei = entries.begin(); cei != entries.end(); ++cei) { const CollisionEntry *entry = (*cei); nassertr(entry != (CollisionEntry *)NULL, false); if (entry->collided() && ((C == 0) || (entry->get_t() < C->get_t()))) { nassertr(from_node_path == entry->get_from_node_path(), false); C = entry; } } // if no collisions, we're done if (C == 0) { break; } // move back to initial contact position LPoint3f contact_pos; LVector3f contact_normal; if (!C->get_all_contact_info(wrt_node, contact_pos, contact_normal)) { collide_cat.warning() << "Cannot shove on " << from_node_path << " for collision into " << C->get_into_node_path() << "; no contact pos/normal information.\n"; break; } // calculate the position of the target node at the point of contact contact_pos -= sphere_offset; uncollided_pos = candidate_final_pos; candidate_final_pos = contact_pos; LVector3f proj_surface_normal(contact_normal); LVector3f norm_proj_surface_normal(proj_surface_normal); norm_proj_surface_normal.normalize(); LVector3f blocked_movement(uncollided_pos - contact_pos); float push_magnitude(-blocked_movement.dot(proj_surface_normal)); if (push_magnitude < 0.0f) { // don't ever push into plane candidate_final_pos = contact_pos; } else { // calculate new position given that you collided with this thing // project the final position onto the plane of the obstruction candidate_final_pos = uncollided_pos + (norm_proj_surface_normal * push_magnitude); } from_node_path.set_pos(wrt_node, candidate_final_pos); CPT(TransformState) prev_trans(from_node_path.get_prev_transform(wrt_node)); prev_trans = prev_trans->set_pos(contact_pos); from_node_path.set_prev_transform(wrt_node, prev_trans); { const LPoint3f new_pos(from_node_path.get_pos(wrt_node)); CPT(TransformState) new_prev_trans(from_node_path.get_prev_transform(wrt_node)); const LPoint3f new_prev_pos(new_prev_trans->get_pos()); } // recalculate the position delta N = from_node_path.get_pos_delta(wrt_node); // calculate new collisions given new movement vector Entries::iterator ei; Entries new_entries; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); nassertr(entry != (CollisionEntry *)NULL, false); // skip the one we just collided against if (entry != C) { entry->_from_node_path = from_node_path; entry->reset_collided(); PT(CollisionEntry) result = entry->get_from()->test_intersection(**ei); if (result != (CollisionEntry *)NULL && result != (CollisionEntry *)0) { new_entries.push_back(result); } } } entries.swap(new_entries); } // put things back where they were from_node_path.set_pos(wrt_node, orig_pos); // restore the appropriate previous position prev_trans = from_node_path.get_prev_transform(wrt_node); prev_trans = prev_trans->set_pos(orig_prev_pos); from_node_path.set_prev_transform(wrt_node, prev_trans); LVector3f net_shove(candidate_final_pos - orig_pos); LVector3f force_normal(net_shove); force_normal.normalize(); // This is the part where the node actually gets moved: def._target.set_pos(wrt_node, candidate_final_pos); // We call this to allow derived classes to do other // fix-ups as they see fit: apply_net_shove(def, net_shove, force_normal); apply_linear_force(def, force_normal); } } return okflag; } <|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 "mitkPlaneGeometryDataToSurfaceFilter.h" #include "mitkSurface.h" #include "mitkGeometry3D.h" #include "mitkPlaneGeometryData.h" #include "mitkPlaneGeometry.h" #include "mitkAbstractTransformGeometry.h" #include <vtkPolyData.h> #include <vtkPlaneSource.h> #include <vtkTransformPolyDataFilter.h> #include <vtkCubeSource.h> #include <vtkTransformPolyDataFilter.h> #include <vtkTransform.h> #include <vtkGeneralTransform.h> #include <vtkPlane.h> #include <vtkPPolyDataNormals.h> #include <vtkCutter.h> #include <vtkStripper.h> #include <vtkTriangleFilter.h> #include <vtkBox.h> #include <vtkClipPolyData.h> #include <vtkTextureMapToPlane.h> mitk::PlaneGeometryDataToSurfaceFilter::PlaneGeometryDataToSurfaceFilter() : m_UseGeometryParametricBounds( true ), m_XResolution( 10 ), m_YResolution( 10 ), m_PlaceByGeometry( false ), m_UseBoundingBox( false ) { m_PlaneSource = vtkPlaneSource::New(); m_Transform = vtkTransform::New(); m_CubeSource = vtkCubeSource::New(); m_PolyDataTransformer = vtkTransformPolyDataFilter::New(); m_Plane = vtkPlane::New(); m_PlaneCutter = vtkCutter::New(); m_PlaneStripper = vtkStripper::New(); m_PlanePolyData = vtkPolyData::New(); m_NormalsUpdater = vtkPPolyDataNormals::New(); m_PlaneTriangler = vtkTriangleFilter::New(); m_TextureMapToPlane = vtkTextureMapToPlane::New(); m_Box = vtkBox::New(); m_PlaneClipper = vtkClipPolyData::New(); m_VtkTransformPlaneFilter = vtkTransformPolyDataFilter::New(); m_VtkTransformPlaneFilter->SetInputConnection(m_PlaneSource->GetOutputPort() ); } mitk::PlaneGeometryDataToSurfaceFilter::~PlaneGeometryDataToSurfaceFilter() { m_PlaneSource->Delete(); m_Transform->Delete(); m_CubeSource->Delete(); m_PolyDataTransformer->Delete(); m_Plane->Delete(); m_PlaneCutter->Delete(); m_PlaneStripper->Delete(); m_PlanePolyData->Delete(); m_NormalsUpdater->Delete(); m_PlaneTriangler->Delete(); m_TextureMapToPlane->Delete(); m_Box->Delete(); m_PlaneClipper->Delete(); m_VtkTransformPlaneFilter->Delete(); } void mitk::PlaneGeometryDataToSurfaceFilter::GenerateOutputInformation() { mitk::PlaneGeometryData::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(); if ( input.IsNull() || (input->GetPlaneGeometry() == NULL) || (input->GetPlaneGeometry()->IsValid() == false) || (m_UseBoundingBox && (m_BoundingBox.IsNull() || (m_BoundingBox->GetDiagonalLength2() < mitk::eps))) ) { return; } Point3D origin; Point3D right, bottom; vtkPolyData *planeSurface = NULL; // Does the PlaneGeometryData contain a PlaneGeometry? if ( dynamic_cast< PlaneGeometry * >( input->GetPlaneGeometry() ) != NULL ) { mitk::PlaneGeometry *planeGeometry = dynamic_cast< PlaneGeometry * >( input->GetPlaneGeometry() ); if ( m_PlaceByGeometry ) { // Let the output use the input geometry to appropriately transform the // coordinate system. mitk::Geometry3D::TransformType *affineTransform = planeGeometry->GetIndexToWorldTransform(); TimeGeometry *timeGeometry = output->GetTimeGeometry(); BaseGeometry *geometrie3d = timeGeometry->GetGeometryForTimeStep( 0 ); geometrie3d->SetIndexToWorldTransform( affineTransform ); } if ( !m_UseBoundingBox) { // We do not have a bounding box, so no clipping is required. if ( m_PlaceByGeometry ) { // Derive coordinate axes and origin from input geometry extent origin.Fill( 0.0 ); FillVector3D( right, planeGeometry->GetExtent(0), 0.0, 0.0 ); FillVector3D( bottom, 0.0, planeGeometry->GetExtent(1), 0.0 ); } else { // Take the coordinate axes and origin directly from the input geometry. origin = planeGeometry->GetOrigin(); right = planeGeometry->GetCornerPoint( false, true ); bottom = planeGeometry->GetCornerPoint( true, false ); } // Since the plane is planar, there is no need to subdivide the grid // (cf. AbstractTransformGeometry case) m_PlaneSource->SetXResolution( 1 ); m_PlaneSource->SetYResolution( 1 ); m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] ); m_PlaneSource->SetPoint1( right[0], right[1], right[2] ); m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] ); m_PlaneSource->Update(); planeSurface = m_PlaneSource->GetOutput(); } else { // Set up a cube with the extent and origin of the bounding box. This // cube will be clipped by a plane later on. The intersection of the // cube and the plane will be the surface we are interested in. Note // that the bounding box needs to be explicitly specified by the user // of this class, since it is not necessarily clear from the data // available herein which bounding box to use. In most cases, this // would be the bounding box of the input geometry's reference // geometry, but this is not an inevitable requirement. mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum(); mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum(); mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter(); m_CubeSource->SetXLength( boundingBoxMax[0] - boundingBoxMin[0] ); m_CubeSource->SetYLength( boundingBoxMax[1] - boundingBoxMin[1] ); m_CubeSource->SetZLength( boundingBoxMax[2] - boundingBoxMin[2] ); m_CubeSource->SetCenter( boundingBoxCenter[0], boundingBoxCenter[1], boundingBoxCenter[2] ); // Now we have to transform the cube, so that it will cut our plane // appropriately. (As can be seen below, the plane corresponds to the // z-plane in the coordinate system and is *not* transformed.) Therefore, // we get the inverse of the plane geometry's transform and concatenate // it with the transform of the reference geometry, if available. m_Transform->Identity(); m_Transform->Concatenate( planeGeometry->GetVtkTransform()->GetLinearInverse() ); BaseGeometry *referenceGeometry = planeGeometry->GetReferenceGeometry(); if ( referenceGeometry ) { m_Transform->Concatenate( referenceGeometry->GetVtkTransform() ); } // Transform the cube accordingly (s.a.) m_PolyDataTransformer->SetInputConnection( m_CubeSource->GetOutputPort() ); m_PolyDataTransformer->SetTransform( m_Transform ); // Initialize the plane to clip the cube with, as lying on the z-plane m_Plane->SetOrigin( 0.0, 0.0, 0.0 ); m_Plane->SetNormal( 0.0, 0.0, 1.0 ); // Cut the plane with the cube. m_PlaneCutter->SetInputConnection( m_PolyDataTransformer->GetOutputPort() ); m_PlaneCutter->SetCutFunction( m_Plane ); // The output of the cutter must be converted into appropriate poly data. m_PlaneStripper->SetInputConnection( m_PlaneCutter->GetOutputPort() ); m_PlaneStripper->Update(); if ( m_PlaneStripper->GetOutput()->GetNumberOfPoints() < 3 ) { return; } m_PlanePolyData->SetPoints( m_PlaneStripper->GetOutput()->GetPoints() ); m_PlanePolyData->SetPolys( m_PlaneStripper->GetOutput()->GetLines() ); m_PlaneTriangler->SetInputData( m_PlanePolyData ); // Get bounds of the resulting surface and use it to generate the texture // mapping information m_PlaneTriangler->Update(); m_PlaneTriangler->GetOutput()->ComputeBounds(); double *surfaceBounds = m_PlaneTriangler->GetOutput()->GetBounds(); origin[0] = surfaceBounds[0]; origin[1] = surfaceBounds[2]; origin[2] = surfaceBounds[4]; right[0] = surfaceBounds[1]; right[1] = surfaceBounds[2]; right[2] = surfaceBounds[4]; bottom[0] = surfaceBounds[0]; bottom[1] = surfaceBounds[3]; bottom[2] = surfaceBounds[4]; // Now we tell the data how it shall be textured afterwards; // description see above. m_TextureMapToPlane->SetInputConnection( m_PlaneTriangler->GetOutputPort() ); m_TextureMapToPlane->AutomaticPlaneGenerationOn(); m_TextureMapToPlane->SetOrigin( origin[0], origin[1], origin[2] ); m_TextureMapToPlane->SetPoint1( right[0], right[1], right[2] ); m_TextureMapToPlane->SetPoint2( bottom[0], bottom[1], bottom[2] ); // Need to call update so that output data and bounds are immediately // available m_TextureMapToPlane->Update(); // Return the output of this generation process planeSurface = dynamic_cast< vtkPolyData * >( m_TextureMapToPlane->GetOutput() ); } } // Does the PlaneGeometryData contain an AbstractTransformGeometry? else if ( mitk::AbstractTransformGeometry *abstractGeometry = dynamic_cast< AbstractTransformGeometry * >( input->GetPlaneGeometry() ) ) { // In the case of an AbstractTransformGeometry (which holds a possibly // non-rigid transform), we proceed slightly differently: since the // plane can be arbitrarily deformed, we need to transform it by the // abstract transform before clipping it. The setup for this is partially // done in the constructor. origin = abstractGeometry->GetPlane()->GetOrigin(); right = origin + abstractGeometry->GetPlane()->GetAxisVector( 0 ); bottom = origin + abstractGeometry->GetPlane()->GetAxisVector( 1 ); // Define the plane m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] ); m_PlaneSource->SetPoint1( right[0], right[1], right[2] ); m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] ); // Set the plane's resolution (unlike for non-deformable planes, the plane // grid needs to have a certain resolution so that the deformation has the // desired effect). if ( m_UseGeometryParametricBounds ) { m_PlaneSource->SetXResolution( (int)abstractGeometry->GetParametricExtent(0) ); m_PlaneSource->SetYResolution( (int)abstractGeometry->GetParametricExtent(1) ); } else { m_PlaneSource->SetXResolution( m_XResolution ); m_PlaneSource->SetYResolution( m_YResolution ); } if ( m_PlaceByGeometry ) { // Let the output use the input geometry to appropriately transform the // coordinate system. mitk::Geometry3D::TransformType *affineTransform = abstractGeometry->GetIndexToWorldTransform(); TimeGeometry *timeGeometry = output->GetTimeGeometry(); BaseGeometry *g3d = timeGeometry->GetGeometryForTimeStep( 0 ); g3d->SetIndexToWorldTransform( affineTransform ); vtkGeneralTransform *composedResliceTransform = vtkGeneralTransform::New(); composedResliceTransform->Identity(); composedResliceTransform->Concatenate( abstractGeometry->GetVtkTransform()->GetLinearInverse() ); composedResliceTransform->Concatenate( abstractGeometry->GetVtkAbstractTransform() ); // Use the non-rigid transform for transforming the plane. m_VtkTransformPlaneFilter->SetTransform( composedResliceTransform ); } else { // Use the non-rigid transform for transforming the plane. m_VtkTransformPlaneFilter->SetTransform( abstractGeometry->GetVtkAbstractTransform() ); } if ( m_UseBoundingBox ) { mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum(); mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum(); //mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter(); m_Box->SetXMin( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2] ); m_Box->SetXMax( boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2] ); } else { // Plane will not be clipped m_Box->SetXMin( -10000.0, -10000.0, -10000.0 ); m_Box->SetXMax( 10000.0, 10000.0, 10000.0 ); } m_Transform->Identity(); m_Transform->Concatenate( input->GetPlaneGeometry()->GetVtkTransform() ); m_Transform->PreMultiply(); m_Box->SetTransform( m_Transform ); m_PlaneClipper->SetInputConnection(m_VtkTransformPlaneFilter->GetOutputPort() ); m_PlaneClipper->SetClipFunction( m_Box ); m_PlaneClipper->GenerateClippedOutputOff(); // important to NOT generate normals data for clipped part m_PlaneClipper->InsideOutOn(); m_PlaneClipper->SetValue( 0.0 ); m_PlaneClipper->Update(); planeSurface = m_PlaneClipper->GetOutput(); } m_NormalsUpdater->SetInputData( planeSurface ); m_NormalsUpdater->AutoOrientNormalsOn(); // that's the trick! Brings consistency between // normals direction and front/back faces direction (see bug 1440) m_NormalsUpdater->ComputePointNormalsOn(); m_NormalsUpdater->Update(); output->SetVtkPolyData( m_NormalsUpdater->GetOutput() ); output->CalculateBoundingBox(); } void mitk::PlaneGeometryDataToSurfaceFilter::GenerateData() { mitk::Surface::Pointer output = this->GetOutput(); if (output.IsNull()) return; if (output->GetVtkPolyData()==NULL) return; // output->GetVtkPolyData()->Update(); //VTK6_TODO vtk pipeline } const mitk::PlaneGeometryData *mitk::PlaneGeometryDataToSurfaceFilter::GetInput() { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::PlaneGeometryData * > ( this->ProcessObject::GetInput(0) ); } const mitk::PlaneGeometryData * mitk::PlaneGeometryDataToSurfaceFilter ::GetInput(unsigned int idx) { return static_cast< const mitk::PlaneGeometryData * > ( this->ProcessObject::GetInput(idx) ); } void mitk::PlaneGeometryDataToSurfaceFilter ::SetInput(const mitk::PlaneGeometryData *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput( 0, const_cast< mitk::PlaneGeometryData * >( input ) ); } void mitk::PlaneGeometryDataToSurfaceFilter ::SetInput(unsigned int index, const mitk::PlaneGeometryData *input) { if( index+1 > this->GetNumberOfInputs() ) { this->SetNumberOfRequiredInputs( index + 1 ); } // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(index, const_cast< mitk::PlaneGeometryData *>( input ) ); } void mitk::PlaneGeometryDataToSurfaceFilter ::SetBoundingBox( const mitk::BoundingBox *boundingBox ) { m_BoundingBox = boundingBox; this->UseBoundingBoxOn(); } const mitk::BoundingBox * mitk::PlaneGeometryDataToSurfaceFilter ::GetBoundingBox() const { return m_BoundingBox.GetPointer(); } <commit_msg>Changed logic for PlaneGeometryDataToSurfaceFilter: different behavior for ABstTransfGeometry<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 "mitkPlaneGeometryDataToSurfaceFilter.h" #include "mitkSurface.h" #include "mitkGeometry3D.h" #include "mitkPlaneGeometryData.h" #include "mitkPlaneGeometry.h" #include "mitkAbstractTransformGeometry.h" #include <vtkPolyData.h> #include <vtkPlaneSource.h> #include <vtkTransformPolyDataFilter.h> #include <vtkCubeSource.h> #include <vtkTransformPolyDataFilter.h> #include <vtkTransform.h> #include <vtkGeneralTransform.h> #include <vtkPlane.h> #include <vtkPPolyDataNormals.h> #include <vtkCutter.h> #include <vtkStripper.h> #include <vtkTriangleFilter.h> #include <vtkBox.h> #include <vtkClipPolyData.h> #include <vtkTextureMapToPlane.h> mitk::PlaneGeometryDataToSurfaceFilter::PlaneGeometryDataToSurfaceFilter() : m_UseGeometryParametricBounds( true ), m_XResolution( 10 ), m_YResolution( 10 ), m_PlaceByGeometry( false ), m_UseBoundingBox( false ) { m_PlaneSource = vtkPlaneSource::New(); m_Transform = vtkTransform::New(); m_CubeSource = vtkCubeSource::New(); m_PolyDataTransformer = vtkTransformPolyDataFilter::New(); m_Plane = vtkPlane::New(); m_PlaneCutter = vtkCutter::New(); m_PlaneStripper = vtkStripper::New(); m_PlanePolyData = vtkPolyData::New(); m_NormalsUpdater = vtkPPolyDataNormals::New(); m_PlaneTriangler = vtkTriangleFilter::New(); m_TextureMapToPlane = vtkTextureMapToPlane::New(); m_Box = vtkBox::New(); m_PlaneClipper = vtkClipPolyData::New(); m_VtkTransformPlaneFilter = vtkTransformPolyDataFilter::New(); m_VtkTransformPlaneFilter->SetInputConnection(m_PlaneSource->GetOutputPort() ); } mitk::PlaneGeometryDataToSurfaceFilter::~PlaneGeometryDataToSurfaceFilter() { m_PlaneSource->Delete(); m_Transform->Delete(); m_CubeSource->Delete(); m_PolyDataTransformer->Delete(); m_Plane->Delete(); m_PlaneCutter->Delete(); m_PlaneStripper->Delete(); m_PlanePolyData->Delete(); m_NormalsUpdater->Delete(); m_PlaneTriangler->Delete(); m_TextureMapToPlane->Delete(); m_Box->Delete(); m_PlaneClipper->Delete(); m_VtkTransformPlaneFilter->Delete(); } void mitk::PlaneGeometryDataToSurfaceFilter::GenerateOutputInformation() { mitk::PlaneGeometryData::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(); if ( input.IsNull() || (input->GetPlaneGeometry() == NULL) || (input->GetPlaneGeometry()->IsValid() == false) || (m_UseBoundingBox && (m_BoundingBox.IsNull() || (m_BoundingBox->GetDiagonalLength2() < mitk::eps))) ) { return; } Point3D origin; Point3D right, bottom; vtkPolyData *planeSurface = NULL; // Does the PlaneGeometryData contain an AbstractTransformGeometry? if ( mitk::AbstractTransformGeometry *abstractGeometry = dynamic_cast< AbstractTransformGeometry * >( input->GetPlaneGeometry() ) ) { // In the case of an AbstractTransformGeometry (which holds a possibly // non-rigid transform), we proceed slightly differently: since the // plane can be arbitrarily deformed, we need to transform it by the // abstract transform before clipping it. The setup for this is partially // done in the constructor. origin = abstractGeometry->GetPlane()->GetOrigin(); right = origin + abstractGeometry->GetPlane()->GetAxisVector( 0 ); bottom = origin + abstractGeometry->GetPlane()->GetAxisVector( 1 ); // Define the plane m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] ); m_PlaneSource->SetPoint1( right[0], right[1], right[2] ); m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] ); // Set the plane's resolution (unlike for non-deformable planes, the plane // grid needs to have a certain resolution so that the deformation has the // desired effect). if ( m_UseGeometryParametricBounds ) { m_PlaneSource->SetXResolution( (int)abstractGeometry->GetParametricExtent(0) ); m_PlaneSource->SetYResolution( (int)abstractGeometry->GetParametricExtent(1) ); } else { m_PlaneSource->SetXResolution( m_XResolution ); m_PlaneSource->SetYResolution( m_YResolution ); } if ( m_PlaceByGeometry ) { // Let the output use the input geometry to appropriately transform the // coordinate system. mitk::Geometry3D::TransformType *affineTransform = abstractGeometry->GetIndexToWorldTransform(); TimeGeometry *timeGeometry = output->GetTimeGeometry(); BaseGeometry *g3d = timeGeometry->GetGeometryForTimeStep( 0 ); g3d->SetIndexToWorldTransform( affineTransform ); vtkGeneralTransform *composedResliceTransform = vtkGeneralTransform::New(); composedResliceTransform->Identity(); composedResliceTransform->Concatenate( abstractGeometry->GetVtkTransform()->GetLinearInverse() ); composedResliceTransform->Concatenate( abstractGeometry->GetVtkAbstractTransform() ); // Use the non-rigid transform for transforming the plane. m_VtkTransformPlaneFilter->SetTransform( composedResliceTransform ); } else { // Use the non-rigid transform for transforming the plane. m_VtkTransformPlaneFilter->SetTransform( abstractGeometry->GetVtkAbstractTransform() ); } if ( m_UseBoundingBox ) { mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum(); mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum(); //mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter(); m_Box->SetXMin( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2] ); m_Box->SetXMax( boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2] ); } else { // Plane will not be clipped m_Box->SetXMin( -10000.0, -10000.0, -10000.0 ); m_Box->SetXMax( 10000.0, 10000.0, 10000.0 ); } m_Transform->Identity(); m_Transform->Concatenate( input->GetPlaneGeometry()->GetVtkTransform() ); m_Transform->PreMultiply(); m_Box->SetTransform( m_Transform ); m_PlaneClipper->SetInputConnection(m_VtkTransformPlaneFilter->GetOutputPort() ); m_PlaneClipper->SetClipFunction( m_Box ); m_PlaneClipper->GenerateClippedOutputOff(); // important to NOT generate normals data for clipped part m_PlaneClipper->InsideOutOn(); m_PlaneClipper->SetValue( 0.0 ); m_PlaneClipper->Update(); planeSurface = m_PlaneClipper->GetOutput(); } // Does the PlaneGeometryData contain a PlaneGeometry? else if ( dynamic_cast< PlaneGeometry * >( input->GetPlaneGeometry() ) != NULL ) { mitk::PlaneGeometry *planeGeometry = dynamic_cast< PlaneGeometry * >( input->GetPlaneGeometry() ); if ( m_PlaceByGeometry ) { // Let the output use the input geometry to appropriately transform the // coordinate system. mitk::Geometry3D::TransformType *affineTransform = planeGeometry->GetIndexToWorldTransform(); TimeGeometry *timeGeometry = output->GetTimeGeometry(); BaseGeometry *geometrie3d = timeGeometry->GetGeometryForTimeStep( 0 ); geometrie3d->SetIndexToWorldTransform( affineTransform ); } if ( !m_UseBoundingBox) { // We do not have a bounding box, so no clipping is required. if ( m_PlaceByGeometry ) { // Derive coordinate axes and origin from input geometry extent origin.Fill( 0.0 ); FillVector3D( right, planeGeometry->GetExtent(0), 0.0, 0.0 ); FillVector3D( bottom, 0.0, planeGeometry->GetExtent(1), 0.0 ); } else { // Take the coordinate axes and origin directly from the input geometry. origin = planeGeometry->GetOrigin(); right = planeGeometry->GetCornerPoint( false, true ); bottom = planeGeometry->GetCornerPoint( true, false ); } // Since the plane is planar, there is no need to subdivide the grid // (cf. AbstractTransformGeometry case) m_PlaneSource->SetXResolution( 1 ); m_PlaneSource->SetYResolution( 1 ); m_PlaneSource->SetOrigin( origin[0], origin[1], origin[2] ); m_PlaneSource->SetPoint1( right[0], right[1], right[2] ); m_PlaneSource->SetPoint2( bottom[0], bottom[1], bottom[2] ); m_PlaneSource->Update(); planeSurface = m_PlaneSource->GetOutput(); } else { // Set up a cube with the extent and origin of the bounding box. This // cube will be clipped by a plane later on. The intersection of the // cube and the plane will be the surface we are interested in. Note // that the bounding box needs to be explicitly specified by the user // of this class, since it is not necessarily clear from the data // available herein which bounding box to use. In most cases, this // would be the bounding box of the input geometry's reference // geometry, but this is not an inevitable requirement. mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum(); mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum(); mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter(); m_CubeSource->SetXLength( boundingBoxMax[0] - boundingBoxMin[0] ); m_CubeSource->SetYLength( boundingBoxMax[1] - boundingBoxMin[1] ); m_CubeSource->SetZLength( boundingBoxMax[2] - boundingBoxMin[2] ); m_CubeSource->SetCenter( boundingBoxCenter[0], boundingBoxCenter[1], boundingBoxCenter[2] ); // Now we have to transform the cube, so that it will cut our plane // appropriately. (As can be seen below, the plane corresponds to the // z-plane in the coordinate system and is *not* transformed.) Therefore, // we get the inverse of the plane geometry's transform and concatenate // it with the transform of the reference geometry, if available. m_Transform->Identity(); m_Transform->Concatenate( planeGeometry->GetVtkTransform()->GetLinearInverse() ); BaseGeometry *referenceGeometry = planeGeometry->GetReferenceGeometry(); if ( referenceGeometry ) { m_Transform->Concatenate( referenceGeometry->GetVtkTransform() ); } // Transform the cube accordingly (s.a.) m_PolyDataTransformer->SetInputConnection( m_CubeSource->GetOutputPort() ); m_PolyDataTransformer->SetTransform( m_Transform ); // Initialize the plane to clip the cube with, as lying on the z-plane m_Plane->SetOrigin( 0.0, 0.0, 0.0 ); m_Plane->SetNormal( 0.0, 0.0, 1.0 ); // Cut the plane with the cube. m_PlaneCutter->SetInputConnection( m_PolyDataTransformer->GetOutputPort() ); m_PlaneCutter->SetCutFunction( m_Plane ); // The output of the cutter must be converted into appropriate poly data. m_PlaneStripper->SetInputConnection( m_PlaneCutter->GetOutputPort() ); m_PlaneStripper->Update(); if ( m_PlaneStripper->GetOutput()->GetNumberOfPoints() < 3 ) { return; } m_PlanePolyData->SetPoints( m_PlaneStripper->GetOutput()->GetPoints() ); m_PlanePolyData->SetPolys( m_PlaneStripper->GetOutput()->GetLines() ); m_PlaneTriangler->SetInputData( m_PlanePolyData ); // Get bounds of the resulting surface and use it to generate the texture // mapping information m_PlaneTriangler->Update(); m_PlaneTriangler->GetOutput()->ComputeBounds(); double *surfaceBounds = m_PlaneTriangler->GetOutput()->GetBounds(); origin[0] = surfaceBounds[0]; origin[1] = surfaceBounds[2]; origin[2] = surfaceBounds[4]; right[0] = surfaceBounds[1]; right[1] = surfaceBounds[2]; right[2] = surfaceBounds[4]; bottom[0] = surfaceBounds[0]; bottom[1] = surfaceBounds[3]; bottom[2] = surfaceBounds[4]; // Now we tell the data how it shall be textured afterwards; // description see above. m_TextureMapToPlane->SetInputConnection( m_PlaneTriangler->GetOutputPort() ); m_TextureMapToPlane->AutomaticPlaneGenerationOn(); m_TextureMapToPlane->SetOrigin( origin[0], origin[1], origin[2] ); m_TextureMapToPlane->SetPoint1( right[0], right[1], right[2] ); m_TextureMapToPlane->SetPoint2( bottom[0], bottom[1], bottom[2] ); // Need to call update so that output data and bounds are immediately // available m_TextureMapToPlane->Update(); // Return the output of this generation process planeSurface = dynamic_cast< vtkPolyData * >( m_TextureMapToPlane->GetOutput() ); } } m_NormalsUpdater->SetInputData( planeSurface ); m_NormalsUpdater->AutoOrientNormalsOn(); // that's the trick! Brings consistency between // normals direction and front/back faces direction (see bug 1440) m_NormalsUpdater->ComputePointNormalsOn(); m_NormalsUpdater->Update(); output->SetVtkPolyData( m_NormalsUpdater->GetOutput() ); output->CalculateBoundingBox(); } void mitk::PlaneGeometryDataToSurfaceFilter::GenerateData() { mitk::Surface::Pointer output = this->GetOutput(); if (output.IsNull()) return; if (output->GetVtkPolyData()==NULL) return; // output->GetVtkPolyData()->Update(); //VTK6_TODO vtk pipeline } const mitk::PlaneGeometryData *mitk::PlaneGeometryDataToSurfaceFilter::GetInput() { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::PlaneGeometryData * > ( this->ProcessObject::GetInput(0) ); } const mitk::PlaneGeometryData * mitk::PlaneGeometryDataToSurfaceFilter ::GetInput(unsigned int idx) { return static_cast< const mitk::PlaneGeometryData * > ( this->ProcessObject::GetInput(idx) ); } void mitk::PlaneGeometryDataToSurfaceFilter ::SetInput(const mitk::PlaneGeometryData *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput( 0, const_cast< mitk::PlaneGeometryData * >( input ) ); } void mitk::PlaneGeometryDataToSurfaceFilter ::SetInput(unsigned int index, const mitk::PlaneGeometryData *input) { if( index+1 > this->GetNumberOfInputs() ) { this->SetNumberOfRequiredInputs( index + 1 ); } // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(index, const_cast< mitk::PlaneGeometryData *>( input ) ); } void mitk::PlaneGeometryDataToSurfaceFilter ::SetBoundingBox( const mitk::BoundingBox *boundingBox ) { m_BoundingBox = boundingBox; this->UseBoundingBoxOn(); } const mitk::BoundingBox * mitk::PlaneGeometryDataToSurfaceFilter ::GetBoundingBox() const { return m_BoundingBox.GetPointer(); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * XSECURIResolverGenericUnix := A URI Resolver that will work "out of * the box" with UNIX. Re-implements * much Xerces code, but allows us to * handle HTTP redirects as is required by * the DSIG Standard * * Author(s): Berin Lautenbach * * $Id$ * * $Log$ * Revision 1.6 2004/01/26 00:29:48 blautenb * Check for Xerces new way of handling NULL hostnames in URIs * * Revision 1.5 2003/09/11 11:29:12 blautenb * Fix Xerces namespace usage in *NIX build * * Revision 1.4 2003/07/05 10:30:38 blautenb * Copyright update * * Revision 1.3 2003/05/10 07:23:36 blautenb * Updates to support anonymous references * * Revision 1.2 2003/02/20 10:35:10 blautenb * Fix for broken Xerces XMLUri * * Revision 1.1 2003/02/12 11:21:03 blautenb * UNIX generic URI resolver * * */ #include "XSECURIResolverGenericUnix.hpp" #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUri.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/BinFileInputStream.hpp> XERCES_CPP_NAMESPACE_USE #include <xsec/framework/XSECError.hpp> #include <xsec/utils/unixutils/XSECBinHTTPURIInputStream.hpp> static const XMLCh gFileScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_f, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_l, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; static const XMLCh gHttpScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_h, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_p, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 static const XMLCh DOTDOT_SLASH[] = { XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #endif XSECURIResolverGenericUnix::XSECURIResolverGenericUnix() : mp_baseURI(NULL) { }; XSECURIResolverGenericUnix::~XSECURIResolverGenericUnix() { if (mp_baseURI != NULL) delete[] mp_baseURI; } // ----------------------------------------------------------------------- // Resolve a URI that is passed in // ----------------------------------------------------------------------- BinInputStream * XSECURIResolverGenericUnix::resolveURI(const XMLCh * uri) { XSEC_USING_XERCES(BinInputStream); XSEC_USING_XERCES(XMLUri); XSEC_USING_XERCES(XMLUni); XSEC_USING_XERCES(Janitor); XSEC_USING_XERCES(BinFileInputStream); XMLUri * xmluri; if (uri == NULL) { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - anonymous references not supported in default URI Resolvers"); } // Create the appropriate XMLUri objects if (mp_baseURI != NULL) { XMLUri * turi; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 // XMLUri relative paths are broken, so we need to strip out ".." XMLCh * b = XMLString::replicate(mp_baseURI); ArrayJanitor<XMLCh> j_b(b); XMLCh * r = XMLString::replicate(uri); ArrayJanitor<XMLCh> j_r(r); int index = 0; while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) { // Strip the last segment of the base int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash); if (lastIndex > 0) b[lastIndex] = 0; index += 3; } XSECnew(turi, XMLUri(b)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, &(r[index]))); #else XSECnew(turi, XMLUri(mp_baseURI)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, uri)); #endif } else { XSECnew(xmluri, XMLUri(uri)); } Janitor<XMLUri> j_xmluri(xmluri); // Determine what kind of URI this is and how to handle it. if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) { // This is a file. We only really understand if this is localhost // XMLUri has already cleaned of escape characters (%xx) if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) { // Localhost BinFileInputStream* retStrm = new BinFileInputStream(xmluri->getPath()); if (!retStrm->getIsOpen()) { delete retStrm; return 0; } return retStrm; } else { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unable to open non-localhost file"); } } // Is the scheme a HTTP? if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) { // Pass straight to our local XSECBinHTTPUriInputStream XSECBinHTTPURIInputStream *ret; XSECnew(ret, XSECBinHTTPURIInputStream(*xmluri)); return ret; } throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unknown URI scheme"); } // ----------------------------------------------------------------------- // Clone me // ----------------------------------------------------------------------- XSECURIResolver * XSECURIResolverGenericUnix::clone(void) { XSECURIResolverGenericUnix * ret; ret = new XSECURIResolverGenericUnix(); if (this->mp_baseURI != NULL) ret->mp_baseURI = XMLString::replicate(this->mp_baseURI); else ret->mp_baseURI = NULL; return ret; } // ----------------------------------------------------------------------- // Set a base URI to map any incoming files against // ----------------------------------------------------------------------- void XSECURIResolverGenericUnix::setBaseURI(const XMLCh * uri) { if (mp_baseURI != NULL) delete[] mp_baseURI; mp_baseURI = XMLString::replicate(uri); } <commit_msg>Add Space handling to UNIX URL handling<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * XSECURIResolverGenericUnix := A URI Resolver that will work "out of * the box" with UNIX. Re-implements * much Xerces code, but allows us to * handle HTTP redirects as is required by * the DSIG Standard * * Author(s): Berin Lautenbach * * $Id$ * * $Log$ * Revision 1.7 2004/02/03 11:00:03 blautenb * Add Space handling to UNIX URL handling * * Revision 1.6 2004/01/26 00:29:48 blautenb * Check for Xerces new way of handling NULL hostnames in URIs * * Revision 1.5 2003/09/11 11:29:12 blautenb * Fix Xerces namespace usage in *NIX build * * Revision 1.4 2003/07/05 10:30:38 blautenb * Copyright update * * Revision 1.3 2003/05/10 07:23:36 blautenb * Updates to support anonymous references * * Revision 1.2 2003/02/20 10:35:10 blautenb * Fix for broken Xerces XMLUri * * Revision 1.1 2003/02/12 11:21:03 blautenb * UNIX generic URI resolver * * */ #include "XSECURIResolverGenericUnix.hpp" #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUri.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/BinFileInputStream.hpp> XERCES_CPP_NAMESPACE_USE #include <xsec/framework/XSECError.hpp> #include <xsec/utils/XSECDOMUtils.hpp> #include <xsec/utils/unixutils/XSECBinHTTPURIInputStream.hpp> static const XMLCh gFileScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_f, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_l, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; static const XMLCh gHttpScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_h, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_p, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 static const XMLCh DOTDOT_SLASH[] = { XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #endif XSECURIResolverGenericUnix::XSECURIResolverGenericUnix() : mp_baseURI(NULL) { }; XSECURIResolverGenericUnix::~XSECURIResolverGenericUnix() { if (mp_baseURI != NULL) delete[] mp_baseURI; } // ----------------------------------------------------------------------- // Resolve a URI that is passed in // ----------------------------------------------------------------------- BinInputStream * XSECURIResolverGenericUnix::resolveURI(const XMLCh * uri) { XSEC_USING_XERCES(BinInputStream); XSEC_USING_XERCES(XMLUri); XSEC_USING_XERCES(XMLUni); XSEC_USING_XERCES(Janitor); XSEC_USING_XERCES(BinFileInputStream); XMLUri * xmluri; if (uri == NULL) { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - anonymous references not supported in default URI Resolvers"); } // Create the appropriate XMLUri objects if (mp_baseURI != NULL) { XMLUri * turi; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 // XMLUri relative paths are broken, so we need to strip out ".." XMLCh * b = XMLString::replicate(mp_baseURI); ArrayJanitor<XMLCh> j_b(b); XMLCh * r = XMLString::replicate(uri); ArrayJanitor<XMLCh> j_r(r); int index = 0; while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) { // Strip the last segment of the base int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash); if (lastIndex > 0) b[lastIndex] = 0; index += 3; } XSECnew(turi, XMLUri(b)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, &(r[index]))); #else XSECnew(turi, XMLUri(mp_baseURI)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, uri)); #endif } else { XSECnew(xmluri, XMLUri(uri)); } Janitor<XMLUri> j_xmluri(xmluri); // Determine what kind of URI this is and how to handle it. if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) { // This is a file. We only really understand if this is localhost // XMLUri has already cleaned of escape characters (%xx) if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) { // Clean hex escapes XMLCh * realPath = cleanURIEscapes(xmluri->getPath()); ArrayJanitor<XMLCh> j_realPath(realPath); // Localhost BinFileInputStream* retStrm = new BinFileInputStream(realPath); if (!retStrm->getIsOpen()) { delete retStrm; return 0; } return retStrm; } else { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unable to open non-localhost file"); } } // Is the scheme a HTTP? if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) { // Pass straight to our local XSECBinHTTPUriInputStream XSECBinHTTPURIInputStream *ret; XSECnew(ret, XSECBinHTTPURIInputStream(*xmluri)); return ret; } throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unknown URI scheme"); } // ----------------------------------------------------------------------- // Clone me // ----------------------------------------------------------------------- XSECURIResolver * XSECURIResolverGenericUnix::clone(void) { XSECURIResolverGenericUnix * ret; ret = new XSECURIResolverGenericUnix(); if (this->mp_baseURI != NULL) ret->mp_baseURI = XMLString::replicate(this->mp_baseURI); else ret->mp_baseURI = NULL; return ret; } // ----------------------------------------------------------------------- // Set a base URI to map any incoming files against // ----------------------------------------------------------------------- void XSECURIResolverGenericUnix::setBaseURI(const XMLCh * uri) { if (mp_baseURI != NULL) delete[] mp_baseURI; mp_baseURI = XMLString::replicate(uri); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_event_router_forwarder.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_event_router.h" #include "chrome/browser/profiles/profile_manager.h" #include "googleurl/src/gurl.h" ExtensionEventRouterForwarder::ExtensionEventRouterForwarder() { } ExtensionEventRouterForwarder::~ExtensionEventRouterForwarder() { } void ExtensionEventRouterForwarder::BroadcastEventToRenderers( const std::string& event_name, const std::string& event_args, const GURL& event_url) { HandleEvent("", event_name, event_args, 0, true, event_url); } void ExtensionEventRouterForwarder::DispatchEventToRenderers( const std::string& event_name, const std::string& event_args, ProfileId profile_id, bool use_profile_to_restrict_events, const GURL& event_url) { if (profile_id == Profile::kInvalidProfileId) return; HandleEvent("", event_name, event_args, profile_id, use_profile_to_restrict_events, event_url); } void ExtensionEventRouterForwarder::BroadcastEventToExtension( const std::string& extension_id, const std::string& event_name, const std::string& event_args, const GURL& event_url) { HandleEvent(extension_id, event_name, event_args, 0, true, event_url); } void ExtensionEventRouterForwarder::DispatchEventToExtension( const std::string& extension_id, const std::string& event_name, const std::string& event_args, ProfileId profile_id, bool use_profile_to_restrict_events, const GURL& event_url) { if (profile_id == Profile::kInvalidProfileId) return; HandleEvent(extension_id, event_name, event_args, profile_id, use_profile_to_restrict_events, event_url); } void ExtensionEventRouterForwarder::HandleEvent( const std::string& extension_id, const std::string& event_name, const std::string& event_args, ProfileId profile_id, bool use_profile_to_restrict_events, const GURL& event_url) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionEventRouterForwarder::HandleEvent, extension_id, event_name, event_args, profile_id, use_profile_to_restrict_events, event_url)); return; } if (!g_browser_process || !g_browser_process->profile_manager()) return; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = NULL; if (profile_id != Profile::kInvalidProfileId) { profile = profile_manager->GetProfileWithId(profile_id); if (!profile) return; } if (profile) { CallExtensionEventRouter( profile, extension_id, event_name, event_args, use_profile_to_restrict_events ? profile : NULL, event_url); } else { std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles()); for (size_t i = 0; i < profiles.size(); ++i) { CallExtensionEventRouter( profiles[i], extension_id, event_name, event_args, use_profile_to_restrict_events ? profiles[i] : NULL, event_url); } } } void ExtensionEventRouterForwarder::CallExtensionEventRouter( Profile* profile, const std::string& extension_id, const std::string& event_name, const std::string& event_args, Profile* restrict_to_profile, const GURL& event_url) { #if defined(OS_CHROMEOS) // Extension does not exist for chromeos login. This needs to be // removed once we have an extension service for login screen. // crosbug.com/12856. if (!profile->GetExtensionEventRouter()) return; #endif if (extension_id.empty()) { profile->GetExtensionEventRouter()-> DispatchEventToRenderers( event_name, event_args, restrict_to_profile, event_url); } else { profile->GetExtensionEventRouter()-> DispatchEventToExtension( extension_id, event_name, event_args, restrict_to_profile, event_url); } } <commit_msg>Fix a crash while running chrome frame net tests. The crash occurs while dereferencing a NULL ExtensionEventRouter object pointer retrieved from the profile. ChromeFrame net tests run the browser as a single process executable. Extensions may not exist in these cases.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_event_router_forwarder.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_event_router.h" #include "chrome/browser/profiles/profile_manager.h" #include "googleurl/src/gurl.h" ExtensionEventRouterForwarder::ExtensionEventRouterForwarder() { } ExtensionEventRouterForwarder::~ExtensionEventRouterForwarder() { } void ExtensionEventRouterForwarder::BroadcastEventToRenderers( const std::string& event_name, const std::string& event_args, const GURL& event_url) { HandleEvent("", event_name, event_args, 0, true, event_url); } void ExtensionEventRouterForwarder::DispatchEventToRenderers( const std::string& event_name, const std::string& event_args, ProfileId profile_id, bool use_profile_to_restrict_events, const GURL& event_url) { if (profile_id == Profile::kInvalidProfileId) return; HandleEvent("", event_name, event_args, profile_id, use_profile_to_restrict_events, event_url); } void ExtensionEventRouterForwarder::BroadcastEventToExtension( const std::string& extension_id, const std::string& event_name, const std::string& event_args, const GURL& event_url) { HandleEvent(extension_id, event_name, event_args, 0, true, event_url); } void ExtensionEventRouterForwarder::DispatchEventToExtension( const std::string& extension_id, const std::string& event_name, const std::string& event_args, ProfileId profile_id, bool use_profile_to_restrict_events, const GURL& event_url) { if (profile_id == Profile::kInvalidProfileId) return; HandleEvent(extension_id, event_name, event_args, profile_id, use_profile_to_restrict_events, event_url); } void ExtensionEventRouterForwarder::HandleEvent( const std::string& extension_id, const std::string& event_name, const std::string& event_args, ProfileId profile_id, bool use_profile_to_restrict_events, const GURL& event_url) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionEventRouterForwarder::HandleEvent, extension_id, event_name, event_args, profile_id, use_profile_to_restrict_events, event_url)); return; } if (!g_browser_process || !g_browser_process->profile_manager()) return; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = NULL; if (profile_id != Profile::kInvalidProfileId) { profile = profile_manager->GetProfileWithId(profile_id); if (!profile) return; } if (profile) { CallExtensionEventRouter( profile, extension_id, event_name, event_args, use_profile_to_restrict_events ? profile : NULL, event_url); } else { std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles()); for (size_t i = 0; i < profiles.size(); ++i) { CallExtensionEventRouter( profiles[i], extension_id, event_name, event_args, use_profile_to_restrict_events ? profiles[i] : NULL, event_url); } } } void ExtensionEventRouterForwarder::CallExtensionEventRouter( Profile* profile, const std::string& extension_id, const std::string& event_name, const std::string& event_args, Profile* restrict_to_profile, const GURL& event_url) { // We may not have an extension in cases like chromeos login // (crosbug.com/12856), chrome_frame_net_tests.exe which reuses the chrome // browser single process framework. if (!profile->GetExtensionEventRouter()) return; if (extension_id.empty()) { profile->GetExtensionEventRouter()-> DispatchEventToRenderers( event_name, event_args, restrict_to_profile, event_url); } else { profile->GetExtensionEventRouter()-> DispatchEventToExtension( extension_id, event_name, event_args, restrict_to_profile, event_url); } } <|endoftext|>
<commit_before>/* Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #pragma once #include <cstdint> #include <string> #include "GossipDefines.hpp" #include "Management/Quest.h" #include "Units/Players/Player.h" class SERVER_DECL GossipMenu { public: GossipMenu(uint64_t senderGuid, uint32_t textId, uint32_t sessionLanguage = 0, uint32_t gossipId = 0); //MIT starts void addItem(uint8_t icon, uint32_t textId, uint32_t id, std::string text = "", uint32_t boxMoney = 0, std::string boxMessage = "", bool isCoded = false); void removeItem(uint32_t id); void addQuest(QuestProperties const* questProperties, uint8_t icon); void removeQuest(uint32_t questId); uint32_t getTextID() const { return m_textId; } uint32_t getLanguage() const { return m_sessionLanguage; } void setTextID(uint32_t textid) { m_textId = textid; } void setLanguage(uint32_t language) { m_sessionLanguage = language; } void sendGossipPacket(Player* player) const; static void sendSimpleMenu(uint64_t guid, uint32_t textId, Player* player); static void sendQuickMenu(uint64_t guid, uint32_t textId, Player* player, uint32_t itemId, uint8_t itemIcon, std::string itemText, uint32_t requiredMoney = 0, std::string moneyText = "", bool extra = false); static void senGossipComplete(Player* player); uint32_t m_textId; uint32_t m_sessionLanguage; uint32_t m_gossipId; uint64_t m_senderGuid; std::map<uint32_t, GossipItem> _gossipItemMap; std::map<uint32_t, GossipQuestItem> _gossipQuestMap; }; <commit_msg>code style<commit_after>/* Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #pragma once #include <cstdint> #include <string> #include "GossipDefines.hpp" #include "Management/Quest.h" #include "Units/Players/Player.h" class SERVER_DECL GossipMenu { public: GossipMenu(uint64_t senderGuid, uint32_t textId, uint32_t sessionLanguage = 0, uint32_t gossipId = 0); void addItem(uint8_t icon, uint32_t textId, uint32_t id, std::string text = "", uint32_t boxMoney = 0, std::string boxMessage = "", bool isCoded = false); void removeItem(uint32_t id); void addQuest(QuestProperties const* questProperties, uint8_t icon); void removeQuest(uint32_t questId); uint32_t getTextID() const { return m_textId; } uint32_t getLanguage() const { return m_sessionLanguage; } void setTextID(uint32_t textid) { m_textId = textid; } void setLanguage(uint32_t language) { m_sessionLanguage = language; } void sendGossipPacket(Player* player) const; static void sendSimpleMenu(uint64_t guid, uint32_t textId, Player* player); static void sendQuickMenu(uint64_t guid, uint32_t textId, Player* player, uint32_t itemId, uint8_t itemIcon, std::string itemText, uint32_t requiredMoney = 0, std::string moneyText = "", bool extra = false); static void senGossipComplete(Player* player); uint32_t m_textId; uint32_t m_sessionLanguage; uint32_t m_gossipId; uint64_t m_senderGuid; std::map<uint32_t, GossipItem> _gossipItemMap; std::map<uint32_t, GossipQuestItem> _gossipQuestMap; }; <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/views/browser_actions_container.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_action.h" #include "chrome/common/extensions/extension_resource.h" class BrowserActionsContainerTest : public ExtensionBrowserTest { public: BrowserActionsContainerTest() : browser_(NULL) { } virtual ~BrowserActionsContainerTest() {} virtual Browser* CreateBrowser(Profile* profile) { browser_ = InProcessBrowserTest::CreateBrowser(profile); browser_actions_bar_.reset(new BrowserActionTestUtil(browser_)); return browser_; } Browser* browser() { return browser_; } BrowserActionTestUtil* browser_actions_bar() { return browser_actions_bar_.get(); } // Make sure extension with index |extension_index| has an icon. void EnsureExtensionHasIcon(int extension_index) { if (!browser_actions_bar_->HasIcon(extension_index)) { // The icon is loaded asynchronously and a notification is then sent to // observers. So we wait on it. browser_actions_bar_->WaitForBrowserActionUpdated(extension_index); } EXPECT_TRUE(browser_actions_bar()->HasIcon(extension_index)); } private: scoped_ptr<BrowserActionTestUtil> browser_actions_bar_; Browser* browser_; // Weak. }; // Test the basic functionality. IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, Basic) { BrowserActionsContainer::disable_animations_during_testing_ = true; // Load an extension with no browser action. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("none"))); // This extension should not be in the model (has no browser action). EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions()); // Load an extension with a browser action. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("basics"))); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); // Unload the extension. std::string id = browser_actions_bar()->GetExtensionId(0); UnloadExtension(id); EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions()); } // TODO(mpcomplete): http://code.google.com/p/chromium/issues/detail?id=38992 // Disabled, http://crbug.com/38992. IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, DISABLED_Visibility) { BrowserActionsContainer::disable_animations_during_testing_ = true; // Load extension A (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("basics"))); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); std::string idA = browser_actions_bar()->GetExtensionId(0); // Load extension B (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("add_popup"))); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions()); std::string idB = browser_actions_bar()->GetExtensionId(1); EXPECT_NE(idA, idB); // Load extension C (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("remove_popup"))); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(2); EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions()); std::string idC = browser_actions_bar()->GetExtensionId(2); // Change container to show only one action, rest in overflow: A, [B, C]. browser_actions_bar()->SetIconVisibilityCount(1); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); // Disable extension A (should disappear). State becomes: B [C]. DisableExtension(idA); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0)); // Enable A again. A should get its spot in the same location and the bar // should not grow (chevron is showing). For details: http://crbug.com/35349. // State becomes: A, [B, C]. EnableExtension(idA); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0)); // Disable C (in overflow). State becomes: A, [B]. DisableExtension(idC); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0)); // Enable C again. State becomes: A, [B, C]. EnableExtension(idC); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0)); // Now we have 3 extensions. Make sure they are all visible. State: A, B, C. browser_actions_bar()->SetIconVisibilityCount(3); EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions()); // Disable extension A (should disappear). State becomes: B, C. DisableExtension(idA); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0)); // Disable extension B (should disappear). State becomes: C. DisableExtension(idB); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idC, browser_actions_bar()->GetExtensionId(0)); // Enable B (makes B and C showing now). State becomes: B, C. EnableExtension(idB); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0)); // Enable A (makes A, B and C showing now). State becomes: B, C, A. EnableExtension(idA); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(2)); } IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, ForceHide) { BrowserActionsContainer::disable_animations_during_testing_ = true; // Load extension A (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("basics"))); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); std::string idA = browser_actions_bar()->GetExtensionId(0); // Force hide this browser action. ExtensionsService* service = browser()->profile()->GetExtensionsService(); service->SetBrowserActionVisibility(service->GetExtensionById(idA, false), false); EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions()); ReloadExtension(idA); // The browser action should become visible again. EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); } IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, TestCrash57536) { std::cout << "Test starting\n" << std::flush; ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); std::cout << "Loading extension\n" << std::flush; // Load extension A (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("crash_57536"))); const Extension* extension = service->extensions()->at(size_before); std::cout << "Creating bitmap\n" << std::flush; // Create and cache and empty bitmap. SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, Extension::kBrowserActionIconMaxSize, Extension::kBrowserActionIconMaxSize); bitmap.allocPixels(); std::cout << "Set as cached image\n" << std::flush; gfx::Size size(Extension::kBrowserActionIconMaxSize, Extension::kBrowserActionIconMaxSize); extension->SetCachedImage( extension->GetResource(extension->browser_action()->default_icon_path()), bitmap, size); std::cout << "Disabling extension\n" << std::flush; DisableExtension(extension->id()); std::cout << "Enabling extension\n" << std::flush; EnableExtension(extension->id()); std::cout << "Test ending\n" << std::flush; } <commit_msg>Reenable BrowserActionsContainerTest.Visibility with timing info, since I suspect the problem is that the test is just a bit too long for the timeout value we use.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/views/browser_actions_container.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_action.h" #include "chrome/common/extensions/extension_resource.h" class BrowserActionsContainerTest : public ExtensionBrowserTest { public: BrowserActionsContainerTest() : browser_(NULL) { } virtual ~BrowserActionsContainerTest() {} virtual Browser* CreateBrowser(Profile* profile) { browser_ = InProcessBrowserTest::CreateBrowser(profile); browser_actions_bar_.reset(new BrowserActionTestUtil(browser_)); return browser_; } Browser* browser() { return browser_; } BrowserActionTestUtil* browser_actions_bar() { return browser_actions_bar_.get(); } // Make sure extension with index |extension_index| has an icon. void EnsureExtensionHasIcon(int extension_index) { if (!browser_actions_bar_->HasIcon(extension_index)) { // The icon is loaded asynchronously and a notification is then sent to // observers. So we wait on it. browser_actions_bar_->WaitForBrowserActionUpdated(extension_index); } EXPECT_TRUE(browser_actions_bar()->HasIcon(extension_index)); } private: scoped_ptr<BrowserActionTestUtil> browser_actions_bar_; Browser* browser_; // Weak. }; // Test the basic functionality. IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, Basic) { BrowserActionsContainer::disable_animations_during_testing_ = true; // Load an extension with no browser action. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("none"))); // This extension should not be in the model (has no browser action). EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions()); // Load an extension with a browser action. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("basics"))); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); // Unload the extension. std::string id = browser_actions_bar()->GetExtensionId(0); UnloadExtension(id); EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions()); } // TODO(mpcomplete): http://code.google.com/p/chromium/issues/detail?id=38992 IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, Visibility) { BrowserActionsContainer::disable_animations_during_testing_ = true; base::TimeTicks start_time = base::TimeTicks::Now(); // Load extension A (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("basics"))); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); std::string idA = browser_actions_bar()->GetExtensionId(0); LOG(INFO) << "Load extension A done : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Load extension B (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("add_popup"))); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions()); std::string idB = browser_actions_bar()->GetExtensionId(1); LOG(INFO) << "Load extension B done : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; EXPECT_NE(idA, idB); // Load extension C (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("remove_popup"))); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(2); EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions()); std::string idC = browser_actions_bar()->GetExtensionId(2); LOG(INFO) << "Load extension C done : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Change container to show only one action, rest in overflow: A, [B, C]. browser_actions_bar()->SetIconVisibilityCount(1); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); LOG(INFO) << "Icon visibility count 1: " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Disable extension A (should disappear). State becomes: B [C]. DisableExtension(idA); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Disable extension A : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Enable A again. A should get its spot in the same location and the bar // should not grow (chevron is showing). For details: http://crbug.com/35349. // State becomes: A, [B, C]. EnableExtension(idA); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Enable extension A : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Disable C (in overflow). State becomes: A, [B]. DisableExtension(idC); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Disable extension C : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Enable C again. State becomes: A, [B, C]. EnableExtension(idC); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Enable extension C : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Now we have 3 extensions. Make sure they are all visible. State: A, B, C. browser_actions_bar()->SetIconVisibilityCount(3); EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions()); LOG(INFO) << "Checkpoint : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Disable extension A (should disappear). State becomes: B, C. DisableExtension(idA); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Disable extension A : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Disable extension B (should disappear). State becomes: C. DisableExtension(idB); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idC, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Disable extension B : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Enable B (makes B and C showing now). State becomes: B, C. EnableExtension(idB); EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idB, browser_actions_bar()->GetExtensionId(0)); LOG(INFO) << "Enable extension B : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; // Enable A (makes A, B and C showing now). State becomes: B, C, A. EnableExtension(idA); EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions()); EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions()); EXPECT_EQ(idA, browser_actions_bar()->GetExtensionId(2)); LOG(INFO) << "Test complete : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, ForceHide) { BrowserActionsContainer::disable_animations_during_testing_ = true; // Load extension A (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("basics"))); EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions()); EnsureExtensionHasIcon(0); EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); std::string idA = browser_actions_bar()->GetExtensionId(0); // Force hide this browser action. ExtensionsService* service = browser()->profile()->GetExtensionsService(); service->SetBrowserActionVisibility(service->GetExtensionById(idA, false), false); EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions()); ReloadExtension(idA); // The browser action should become visible again. EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions()); } IN_PROC_BROWSER_TEST_F(BrowserActionsContainerTest, TestCrash57536) { LOG(INFO) << "Test starting\n" << std::flush; ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); LOG(INFO) << "Loading extension\n" << std::flush; // Load extension A (contains browser action). ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("browser_action") .AppendASCII("crash_57536"))); const Extension* extension = service->extensions()->at(size_before); LOG(INFO) << "Creating bitmap\n" << std::flush; // Create and cache and empty bitmap. SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, Extension::kBrowserActionIconMaxSize, Extension::kBrowserActionIconMaxSize); bitmap.allocPixels(); LOG(INFO) << "Set as cached image\n" << std::flush; gfx::Size size(Extension::kBrowserActionIconMaxSize, Extension::kBrowserActionIconMaxSize); extension->SetCachedImage( extension->GetResource(extension->browser_action()->default_icon_path()), bitmap, size); LOG(INFO) << "Disabling extension\n" << std::flush; DisableExtension(extension->id()); LOG(INFO) << "Enabling extension\n" << std::flush; EnableExtension(extension->id()); LOG(INFO) << "Test ending\n" << std::flush; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/in_process_webkit/browser_webkitclient_impl.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/browser/in_process_webkit/dom_storage_message_filter.h" #include "chrome/browser/in_process_webkit/indexed_db_key_utility_client.h" #include "chrome/common/indexed_db_key.h" #include "chrome/common/serialized_script_value.h" #include "third_party/WebKit/WebKit/chromium/public/WebData.h" #include "third_party/WebKit/WebKit/chromium/public/WebSerializedScriptValue.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "webkit/glue/webkit_glue.h" BrowserWebKitClientImpl::BrowserWebKitClientImpl() { file_utilities_.set_sandbox_enabled(false); } BrowserWebKitClientImpl::~BrowserWebKitClientImpl() { } WebKit::WebClipboard* BrowserWebKitClientImpl::clipboard() { NOTREACHED(); return NULL; } WebKit::WebMimeRegistry* BrowserWebKitClientImpl::mimeRegistry() { NOTREACHED(); return NULL; } WebKit::WebFileUtilities* BrowserWebKitClientImpl::fileUtilities() { return &file_utilities_; } WebKit::WebSandboxSupport* BrowserWebKitClientImpl::sandboxSupport() { NOTREACHED(); return NULL; } bool BrowserWebKitClientImpl::sandboxEnabled() { return false; } unsigned long long BrowserWebKitClientImpl::visitedLinkHash( const char* canonical_url, size_t length) { NOTREACHED(); return 0; } bool BrowserWebKitClientImpl::isLinkVisited(unsigned long long link_hash) { NOTREACHED(); return false; } WebKit::WebMessagePortChannel* BrowserWebKitClientImpl::createMessagePortChannel() { NOTREACHED(); return NULL; } void BrowserWebKitClientImpl::setCookies( const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies, const WebKit::WebString& value) { NOTREACHED(); } WebKit::WebString BrowserWebKitClientImpl::cookies( const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies) { NOTREACHED(); return WebKit::WebString(); } void BrowserWebKitClientImpl::prefetchHostName(const WebKit::WebString&) { NOTREACHED(); } WebKit::WebString BrowserWebKitClientImpl::defaultLocale() { NOTREACHED(); return WebKit::WebString(); } WebKit::WebThemeEngine* BrowserWebKitClientImpl::themeEngine() { NOTREACHED(); return NULL; } WebKit::WebURLLoader* BrowserWebKitClientImpl::createURLLoader() { NOTREACHED(); return NULL; } WebKit::WebSocketStreamHandle* BrowserWebKitClientImpl::createSocketStreamHandle() { NOTREACHED(); return NULL; } void BrowserWebKitClientImpl::getPluginList(bool refresh, WebKit::WebPluginListBuilder* builder) { NOTREACHED(); } WebKit::WebData BrowserWebKitClientImpl::loadResource(const char* name) { NOTREACHED(); return WebKit::WebData(); } WebKit::WebStorageNamespace* BrowserWebKitClientImpl::createLocalStorageNamespace( const WebKit::WebString& path, unsigned quota) { // The "WebStorage" interface is used for renderer WebKit -> browser WebKit // communication only. "WebStorageClient" will be used for browser WebKit -> // renderer WebKit. So this will never be implemented. NOTREACHED(); return 0; } void BrowserWebKitClientImpl::dispatchStorageEvent( const WebKit::WebString& key, const WebKit::WebString& old_value, const WebKit::WebString& new_value, const WebKit::WebString& origin, const WebKit::WebURL& url, bool is_local_storage) { // TODO(jorlow): Implement if (!is_local_storage) return; DOMStorageMessageFilter::DispatchStorageEvent(key, old_value, new_value, origin, url, is_local_storage); } WebKit::WebSharedWorkerRepository* BrowserWebKitClientImpl::sharedWorkerRepository() { NOTREACHED(); return NULL; } int BrowserWebKitClientImpl::databaseDeleteFile( const WebKit::WebString& vfs_file_name, bool sync_dir) { const FilePath path = webkit_glue::WebStringToFilePath(vfs_file_name); return file_util::Delete(path, false) ? 0 : 1; } void BrowserWebKitClientImpl::idbShutdown() { if (indexed_db_key_utility_client_.get()) indexed_db_key_utility_client_->EndUtilityProcess(); } void BrowserWebKitClientImpl::createIDBKeysFromSerializedValuesAndKeyPath( const WebKit::WebVector<WebKit::WebSerializedScriptValue>& values, const WebKit::WebString& keyPath, WebKit::WebVector<WebKit::WebIDBKey>& keys) { if (!indexed_db_key_utility_client_.get()) { indexed_db_key_utility_client_ = new IndexedDBKeyUtilityClient(); indexed_db_key_utility_client_->StartUtilityProcess(); } std::vector<SerializedScriptValue> std_values; size_t size = values.size(); std_values.reserve(size); for (size_t i = 0; i < size; ++i) std_values.push_back(SerializedScriptValue(values[i])); std::vector<IndexedDBKey> std_keys; indexed_db_key_utility_client_->CreateIDBKeysFromSerializedValuesAndKeyPath( std_values, keyPath, &std_keys); keys = std_keys; } <commit_msg>Crash when using indexed db in second incognito window.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/in_process_webkit/browser_webkitclient_impl.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/browser/in_process_webkit/dom_storage_message_filter.h" #include "chrome/browser/in_process_webkit/indexed_db_key_utility_client.h" #include "chrome/common/indexed_db_key.h" #include "chrome/common/serialized_script_value.h" #include "third_party/WebKit/WebKit/chromium/public/WebData.h" #include "third_party/WebKit/WebKit/chromium/public/WebSerializedScriptValue.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "webkit/glue/webkit_glue.h" BrowserWebKitClientImpl::BrowserWebKitClientImpl() { file_utilities_.set_sandbox_enabled(false); } BrowserWebKitClientImpl::~BrowserWebKitClientImpl() { } WebKit::WebClipboard* BrowserWebKitClientImpl::clipboard() { NOTREACHED(); return NULL; } WebKit::WebMimeRegistry* BrowserWebKitClientImpl::mimeRegistry() { NOTREACHED(); return NULL; } WebKit::WebFileUtilities* BrowserWebKitClientImpl::fileUtilities() { return &file_utilities_; } WebKit::WebSandboxSupport* BrowserWebKitClientImpl::sandboxSupport() { NOTREACHED(); return NULL; } bool BrowserWebKitClientImpl::sandboxEnabled() { return false; } unsigned long long BrowserWebKitClientImpl::visitedLinkHash( const char* canonical_url, size_t length) { NOTREACHED(); return 0; } bool BrowserWebKitClientImpl::isLinkVisited(unsigned long long link_hash) { NOTREACHED(); return false; } WebKit::WebMessagePortChannel* BrowserWebKitClientImpl::createMessagePortChannel() { NOTREACHED(); return NULL; } void BrowserWebKitClientImpl::setCookies( const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies, const WebKit::WebString& value) { NOTREACHED(); } WebKit::WebString BrowserWebKitClientImpl::cookies( const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies) { NOTREACHED(); return WebKit::WebString(); } void BrowserWebKitClientImpl::prefetchHostName(const WebKit::WebString&) { NOTREACHED(); } WebKit::WebString BrowserWebKitClientImpl::defaultLocale() { NOTREACHED(); return WebKit::WebString(); } WebKit::WebThemeEngine* BrowserWebKitClientImpl::themeEngine() { NOTREACHED(); return NULL; } WebKit::WebURLLoader* BrowserWebKitClientImpl::createURLLoader() { NOTREACHED(); return NULL; } WebKit::WebSocketStreamHandle* BrowserWebKitClientImpl::createSocketStreamHandle() { NOTREACHED(); return NULL; } void BrowserWebKitClientImpl::getPluginList(bool refresh, WebKit::WebPluginListBuilder* builder) { NOTREACHED(); } WebKit::WebData BrowserWebKitClientImpl::loadResource(const char* name) { NOTREACHED(); return WebKit::WebData(); } WebKit::WebStorageNamespace* BrowserWebKitClientImpl::createLocalStorageNamespace( const WebKit::WebString& path, unsigned quota) { // The "WebStorage" interface is used for renderer WebKit -> browser WebKit // communication only. "WebStorageClient" will be used for browser WebKit -> // renderer WebKit. So this will never be implemented. NOTREACHED(); return 0; } void BrowserWebKitClientImpl::dispatchStorageEvent( const WebKit::WebString& key, const WebKit::WebString& old_value, const WebKit::WebString& new_value, const WebKit::WebString& origin, const WebKit::WebURL& url, bool is_local_storage) { // TODO(jorlow): Implement if (!is_local_storage) return; DOMStorageMessageFilter::DispatchStorageEvent(key, old_value, new_value, origin, url, is_local_storage); } WebKit::WebSharedWorkerRepository* BrowserWebKitClientImpl::sharedWorkerRepository() { NOTREACHED(); return NULL; } int BrowserWebKitClientImpl::databaseDeleteFile( const WebKit::WebString& vfs_file_name, bool sync_dir) { const FilePath path = webkit_glue::WebStringToFilePath(vfs_file_name); return file_util::Delete(path, false) ? 0 : 1; } void BrowserWebKitClientImpl::idbShutdown() { if (indexed_db_key_utility_client_.get()) { indexed_db_key_utility_client_->EndUtilityProcess(); indexed_db_key_utility_client_ = NULL; } } void BrowserWebKitClientImpl::createIDBKeysFromSerializedValuesAndKeyPath( const WebKit::WebVector<WebKit::WebSerializedScriptValue>& values, const WebKit::WebString& keyPath, WebKit::WebVector<WebKit::WebIDBKey>& keys) { if (!indexed_db_key_utility_client_.get()) { indexed_db_key_utility_client_ = new IndexedDBKeyUtilityClient(); indexed_db_key_utility_client_->StartUtilityProcess(); } std::vector<SerializedScriptValue> std_values; size_t size = values.size(); std_values.reserve(size); for (size_t i = 0; i < size; ++i) std_values.push_back(SerializedScriptValue(values[i])); std::vector<IndexedDBKey> std_keys; indexed_db_key_utility_client_->CreateIDBKeysFromSerializedValuesAndKeyPath( std_values, keyPath, &std_keys); keys = std_keys; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/status_icons/status_tray_win.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/status_icons/status_icon_observer.h" #include "chrome/browser/ui/views/status_icons/status_icon_win.h" #include "grit/theme_resources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/resource/resource_bundle.h" class SkBitmap; class MockStatusIconObserver : public StatusIconObserver { public: MOCK_METHOD0(OnStatusIconClicked, void()); }; TEST(StatusTrayWinTest, CreateTray) { // Just tests creation/destruction. StatusTrayWin tray; } TEST(StatusTrayWinTest, CreateIconAndMenu) { // Create an icon, set the images, tooltip, and context menu, then shut it // down. StatusTrayWin tray; StatusIcon* icon = tray.CreateStatusIcon(); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); gfx::ImageSkia* image = rb.GetImageSkiaNamed(IDR_STATUS_TRAY_ICON); icon->SetImage(*image); icon->SetPressedImage(*image); icon->SetToolTip(ASCIIToUTF16("tool tip")); ui::SimpleMenuModel* menu = new ui::SimpleMenuModel(NULL); menu->AddItem(0, L"foo"); icon->SetContextMenu(menu); } #if !defined(USE_AURA) // http://crbug.com/156370 TEST(StatusTrayWinTest, ClickOnIcon) { // Create an icon, send a fake click event, make sure observer is called. StatusTrayWin tray; StatusIconWin* icon = static_cast<StatusIconWin*>(tray.CreateStatusIcon()); MockStatusIconObserver observer; icon->AddObserver(&observer); EXPECT_CALL(observer, OnStatusIconClicked()); // Mimic a click. tray.WndProc(NULL, icon->message_id(), icon->icon_id(), WM_LBUTTONDOWN); // Mimic a right-click - observer should not be called. tray.WndProc(NULL, icon->message_id(), icon->icon_id(), WM_RBUTTONDOWN); icon->RemoveObserver(&observer); } // !defined(USE_AURA) <commit_msg>oops<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/status_icons/status_tray_win.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/status_icons/status_icon_observer.h" #include "chrome/browser/ui/views/status_icons/status_icon_win.h" #include "grit/theme_resources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/resource/resource_bundle.h" class SkBitmap; class MockStatusIconObserver : public StatusIconObserver { public: MOCK_METHOD0(OnStatusIconClicked, void()); }; TEST(StatusTrayWinTest, CreateTray) { // Just tests creation/destruction. StatusTrayWin tray; } TEST(StatusTrayWinTest, CreateIconAndMenu) { // Create an icon, set the images, tooltip, and context menu, then shut it // down. StatusTrayWin tray; StatusIcon* icon = tray.CreateStatusIcon(); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); gfx::ImageSkia* image = rb.GetImageSkiaNamed(IDR_STATUS_TRAY_ICON); icon->SetImage(*image); icon->SetPressedImage(*image); icon->SetToolTip(ASCIIToUTF16("tool tip")); ui::SimpleMenuModel* menu = new ui::SimpleMenuModel(NULL); menu->AddItem(0, L"foo"); icon->SetContextMenu(menu); } #if !defined(USE_AURA) // http://crbug.com/156370 TEST(StatusTrayWinTest, ClickOnIcon) { // Create an icon, send a fake click event, make sure observer is called. StatusTrayWin tray; StatusIconWin* icon = static_cast<StatusIconWin*>(tray.CreateStatusIcon()); MockStatusIconObserver observer; icon->AddObserver(&observer); EXPECT_CALL(observer, OnStatusIconClicked()); // Mimic a click. tray.WndProc(NULL, icon->message_id(), icon->icon_id(), WM_LBUTTONDOWN); // Mimic a right-click - observer should not be called. tray.WndProc(NULL, icon->message_id(), icon->icon_id(), WM_RBUTTONDOWN); icon->RemoveObserver(&observer); } #endif // !defined(USE_AURA) <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <fstream> #include <vector> #include <set> #include <string> #include <sstream> #include <iterator> #include <regex> #include <chrono> #include <unistd.h> #include <sched.h> #include "interference.h" #include "interference_mpi.h" #include "counter.hpp" std::string PREFIX; std::string sched; std::string output_format; std::vector<int> affinity; int localid; int ranks; bool mvapich_hack = false; std::vector<int> parse_affinity(std::string cpu_string) { std::vector<int> cpus; // static boost::regex r("(\\d+|\\d+-\\d+)?"); std::regex r("^(\\d+-\\d+|\\d+)(,\\d+-\\d+|,\\d+)?(,\\d+-\\d+|,\\d+)*$"); // Do regex match and convert the interesting part to // int. std::smatch what; if (!std::regex_match(cpu_string, what, r)) { throw std::runtime_error("Can't parse CPU string"); } std::string::const_iterator start = cpu_string.begin(); std::string::const_iterator end = cpu_string.end(); while (std::regex_search(start, end, what, r)) { // what[1] single or a range of cpus if (!what[1].matched) throw std::runtime_error("Can't parse CPU string"); std::string stest(what[1].first, what[1].second); auto minus = stest.find('-'); if (minus == std::string::npos) { int value; try { value = std::stoi(stest); } catch (std::exception &e) { throw std::runtime_error("Can't parse CPU string"); } cpus.push_back(value); } else { auto s = std::stoi(stest.substr(0, minus)); auto e = std::stoi(stest.substr(minus+1)); if (s > e) throw std::runtime_error("Can't parse CPU string"); for (int cpu = s; cpu<=e; cpu++) cpus.push_back(cpu); } start = what[2].first; if (*start == ',') start++; } std::sort(cpus.begin(), cpus.end()); cpus.erase(std::unique(cpus.begin(), cpus.end()), cpus.end()); return cpus; } void parse_env() { // Here we should set scheduler auto env = std::getenv("INTERFERENCE_PREFIX"); if (!env) throw std::runtime_error("INTERFERENCE_PREFIX should be set"); PREFIX = env; auto sched_ptr = std::getenv("INTERFERENCE_SCHED"); if (!sched_ptr) throw std::runtime_error("INTERFERENCE_SCHED should be set"); sched = std::string(sched_ptr); auto affinity_ptr = std::getenv("INTERFERENCE_AFFINITY"); if (!affinity_ptr) throw std::runtime_error("INTERFERENCE_AFFINITY should be set"); affinity = parse_affinity(affinity_ptr); auto localid_name_ptr = std::getenv("INTERFERENCE_LOCALID"); if (localid_name_ptr) { auto localid_ptr = std::getenv(localid_name_ptr); if (!localid_ptr) throw std::runtime_error("INTERFERENCE_LOCALID points to nonexistent variable"); localid = std::stol(localid_ptr); } else { // Probably this concept makes no sense in here localid = 0; } auto output_format_ptr = std::getenv("INTERFERENCE_OUTPUT"); if (output_format_ptr) { output_format = std::string(output_format_ptr); if (output_format != "json") throw std::runtime_error("INTERFERENCE_OUTPUT requests unknown format"); } else { output_format = "csv"; } if (std::getenv("INTERFERENCE_HACK")) mvapich_hack = true; } /** * Set affinity to a particular cpu */ static void set_own_affinity(const cpu_set_t &cpu_set) { int ret = sched_setaffinity(getpid(), sizeof(cpu_set), &cpu_set); if (ret) throw std::runtime_error("Failed to set affinity"); } static void set_own_affinity(int cpu) { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); CPU_SET(cpu, &cpu_set); set_own_affinity(cpu_set); } static void set_own_affinity(const std::vector<int> &cpus) { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); for (auto c : cpus) CPU_SET(c, &cpu_set); set_own_affinity(cpu_set); } class WallClock : public IntervalCounter<wall_time_t> { public: using IntervalCounter<wall_time_t>::IntervalCounter; void get_value(wall_time_t &val) { val = std::chrono::system_clock::now(); } void exchange() { auto diff = end - start; long diff_long = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count(); _values.resize(_ranks); gather_longs(diff_long, _values.data()); } }; class ProcReader : public IntervalCounter<milli_time_t> { std::vector<std::string> get_stat_strings() { std::ifstream proc("/proc/self/stat"); std::string line; std::getline(proc, line); std::istringstream iss(line); std::vector<std::string> tokens; std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(tokens)); return tokens; } public: using IntervalCounter<milli_time_t>::IntervalCounter; void get_value(milli_time_t &val) { std::vector<std::string> tokens = get_stat_strings(); val = milli_time_t(std::stol(tokens[13]) * 1000 / sysconf(_SC_CLK_TCK)); } void exchange() { auto diff = end - start; _values.resize(_ranks); gather_longs(diff.count(), _values.data()); } }; class CPUaccounter : public SingleCounter<long> { public: using SingleCounter<long>::SingleCounter; void start_accounting() { if (sched == "pinned") { _value = affinity[localid % affinity.size()]; set_own_affinity(_value); } else if (sched == "cfs") { _value = -1; set_own_affinity(affinity); } } }; class LocalId : public SingleCounter<long> { public: using SingleCounter<long>::SingleCounter; void start_accounting() { _value = localid; } }; class HostNameAccounter : public SingleCounter<std::string> { public: using SingleCounter<std::string>::SingleCounter; void start_accounting() { // Assume no overflow happens _value.resize(name_len); gethostname(_value.data(), name_len); _value[name_len - 1] = '\0'; } }; class IterAccounter : public SingleCounter<long> { public: using SingleCounter<long>::SingleCounter; void start_accounting() { _value = 1; } }; class InterferenceAccounter : public Accounter { public: InterferenceAccounter(int ranks) : Accounter(ranks) { typedef std::unique_ptr<Counter> counter_ptr; _counters.push_back(counter_ptr(new IterAccounter(ranks, "ITER"))); _counters.push_back(counter_ptr(new HostNameAccounter(ranks, "NODE"))); _counters.push_back(counter_ptr(new LocalId(ranks, "LOCALID"))); _counters.push_back(counter_ptr(new CPUaccounter(ranks, "CPU"))); _counters.push_back(counter_ptr(new WallClock(ranks, "WTIME"))); _counters.push_back(counter_ptr(new ProcReader(ranks, "UTIME"))); } void dump_csv(const CounterMap &map) { for (int i = 0; i < _ranks; i++) { std::cout << PREFIX << " ,RANK: " << i; for (const auto &cnt : map) { std::cout << " ," << cnt.first << ": " << cnt.second[i]; } std::cout << std::endl; } } void dump_json(const CounterMap &map) { } void dump(const std::string &output, const std::set<std::string> &filter = std::set<std::string>()) { int my_rank = get_my_rank(); if (my_rank != 0) return; auto map = generate_map(filter); if (output == "csv") { dump_csv(map); } else if (output == "json") { dump_json(map); } else { throw std::runtime_error("Unknown output format: " + output); } } }; std::unique_ptr<InterferenceAccounter> accounter; void interference_start() { parse_env(); ranks = get_ranks(); accounter = std::unique_ptr<InterferenceAccounter>(new InterferenceAccounter(ranks)); accounter->start_accounting(); } void interference_end() { // Here we should read stat accounter->end_accounting(); accounter->dump(output_format); if (mvapich_hack) { barrier(); std::flush(std::cout); exit(0); } } <commit_msg>Add json output<commit_after>#include <cstdlib> #include <iostream> #include <fstream> #include <vector> #include <set> #include <string> #include <sstream> #include <iterator> #include <regex> #include <chrono> #include <unistd.h> #include <sched.h> #include "interference.h" #include "interference_mpi.h" #include "counter.hpp" #include "nlohmann/json.hpp" using json = nlohmann::json; std::string PREFIX; std::string sched; std::string output_format; std::vector<int> affinity; int localid; int ranks; bool mvapich_hack = false; std::vector<int> parse_affinity(std::string cpu_string) { std::vector<int> cpus; // static boost::regex r("(\\d+|\\d+-\\d+)?"); std::regex r("^(\\d+-\\d+|\\d+)(,\\d+-\\d+|,\\d+)?(,\\d+-\\d+|,\\d+)*$"); // Do regex match and convert the interesting part to // int. std::smatch what; if (!std::regex_match(cpu_string, what, r)) { throw std::runtime_error("Can't parse CPU string"); } std::string::const_iterator start = cpu_string.begin(); std::string::const_iterator end = cpu_string.end(); while (std::regex_search(start, end, what, r)) { // what[1] single or a range of cpus if (!what[1].matched) throw std::runtime_error("Can't parse CPU string"); std::string stest(what[1].first, what[1].second); auto minus = stest.find('-'); if (minus == std::string::npos) { int value; try { value = std::stoi(stest); } catch (std::exception &e) { throw std::runtime_error("Can't parse CPU string"); } cpus.push_back(value); } else { auto s = std::stoi(stest.substr(0, minus)); auto e = std::stoi(stest.substr(minus+1)); if (s > e) throw std::runtime_error("Can't parse CPU string"); for (int cpu = s; cpu<=e; cpu++) cpus.push_back(cpu); } start = what[2].first; if (*start == ',') start++; } std::sort(cpus.begin(), cpus.end()); cpus.erase(std::unique(cpus.begin(), cpus.end()), cpus.end()); return cpus; } void parse_env() { // Here we should set scheduler auto env = std::getenv("INTERFERENCE_PREFIX"); if (!env) throw std::runtime_error("INTERFERENCE_PREFIX should be set"); PREFIX = env; auto sched_ptr = std::getenv("INTERFERENCE_SCHED"); if (!sched_ptr) throw std::runtime_error("INTERFERENCE_SCHED should be set"); sched = std::string(sched_ptr); auto affinity_ptr = std::getenv("INTERFERENCE_AFFINITY"); if (!affinity_ptr) throw std::runtime_error("INTERFERENCE_AFFINITY should be set"); affinity = parse_affinity(affinity_ptr); auto localid_name_ptr = std::getenv("INTERFERENCE_LOCALID"); if (localid_name_ptr) { auto localid_ptr = std::getenv(localid_name_ptr); if (!localid_ptr) throw std::runtime_error("INTERFERENCE_LOCALID points to nonexistent variable"); localid = std::stol(localid_ptr); } else { // Probably this concept makes no sense in here localid = 0; } auto output_format_ptr = std::getenv("INTERFERENCE_OUTPUT"); if (output_format_ptr) { output_format = std::string(output_format_ptr); if (output_format != "json" && output_format != "csv") throw std::runtime_error("INTERFERENCE_OUTPUT requests unknown format"); } else { output_format = "csv"; } if (std::getenv("INTERFERENCE_HACK")) mvapich_hack = true; } /** * Set affinity to a particular cpu */ static void set_own_affinity(const cpu_set_t &cpu_set) { int ret = sched_setaffinity(getpid(), sizeof(cpu_set), &cpu_set); if (ret) throw std::runtime_error("Failed to set affinity"); } static void set_own_affinity(int cpu) { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); CPU_SET(cpu, &cpu_set); set_own_affinity(cpu_set); } static void set_own_affinity(const std::vector<int> &cpus) { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); for (auto c : cpus) CPU_SET(c, &cpu_set); set_own_affinity(cpu_set); } class WallClock : public IntervalCounter<wall_time_t> { public: using IntervalCounter<wall_time_t>::IntervalCounter; void get_value(wall_time_t &val) { val = std::chrono::system_clock::now(); } void exchange() { auto diff = end - start; long diff_long = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count(); _values.resize(_ranks); gather_longs(diff_long, _values.data()); } }; class ProcReader : public IntervalCounter<milli_time_t> { std::vector<std::string> get_stat_strings() { std::ifstream proc("/proc/self/stat"); std::string line; std::getline(proc, line); std::istringstream iss(line); std::vector<std::string> tokens; std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(tokens)); return tokens; } public: using IntervalCounter<milli_time_t>::IntervalCounter; void get_value(milli_time_t &val) { std::vector<std::string> tokens = get_stat_strings(); val = milli_time_t(std::stol(tokens[13]) * 1000 / sysconf(_SC_CLK_TCK)); } void exchange() { auto diff = end - start; _values.resize(_ranks); gather_longs(diff.count(), _values.data()); } }; class CPUaccounter : public SingleCounter<long> { public: using SingleCounter<long>::SingleCounter; void start_accounting() { if (sched == "pinned") { _value = affinity[localid % affinity.size()]; set_own_affinity(_value); } else if (sched == "cfs") { _value = -1; set_own_affinity(affinity); } } }; class LocalId : public SingleCounter<long> { public: using SingleCounter<long>::SingleCounter; void start_accounting() { _value = localid; } }; class HostNameAccounter : public SingleCounter<std::string> { public: using SingleCounter<std::string>::SingleCounter; void start_accounting() { // Assume no overflow happens _value.resize(name_len); gethostname(_value.data(), name_len); _value[name_len - 1] = '\0'; } }; class IterAccounter : public SingleCounter<long> { public: using SingleCounter<long>::SingleCounter; void start_accounting() { _value = 1; } }; class InterferenceAccounter : public Accounter { public: InterferenceAccounter(int ranks) : Accounter(ranks) { typedef std::unique_ptr<Counter> counter_ptr; _counters.push_back(counter_ptr(new IterAccounter(ranks, "ITER"))); _counters.push_back(counter_ptr(new HostNameAccounter(ranks, "NODE"))); _counters.push_back(counter_ptr(new LocalId(ranks, "LOCALID"))); _counters.push_back(counter_ptr(new CPUaccounter(ranks, "CPU"))); _counters.push_back(counter_ptr(new WallClock(ranks, "WTIME"))); _counters.push_back(counter_ptr(new ProcReader(ranks, "UTIME"))); } void dump_csv(const CounterMap &map) { for (int i = 0; i < _ranks; i++) { std::cout << PREFIX << " ,RANK: " << i; for (const auto &cnt : map) { std::cout << " ," << cnt.first << ": " << cnt.second[i]; } std::cout << std::endl; } } void dump_json(const CounterMap &map) { json j; for (int i = 0; i < _ranks; i++) { json row; for (const auto &cnt : map) { row[cnt.first] = cnt.second[i]; } j.push_back(row); } std::cout << j.dump() << std::endl; } void dump(const std::string &output, const std::set<std::string> &filter = std::set<std::string>()) { int my_rank = get_my_rank(); if (my_rank != 0) return; auto map = generate_map(filter); if (output == "csv") { dump_csv(map); } else if (output == "json") { dump_json(map); } else { throw std::runtime_error("Unknown output format: " + output); } } }; std::unique_ptr<InterferenceAccounter> accounter; void interference_start() { parse_env(); ranks = get_ranks(); accounter = std::unique_ptr<InterferenceAccounter>(new InterferenceAccounter(ranks)); accounter->start_accounting(); } void interference_end() { // Here we should read stat accounter->end_accounting(); accounter->dump(output_format); if (mvapich_hack) { barrier(); std::flush(std::cout); exit(0); } } <|endoftext|>
<commit_before>#include <xpcc/architecture/platform.hpp> #include <xpcc/architecture.hpp> #include "../stm32f4_discovery.hpp" #include <xpcc/driver/display/max7219matrix.hpp> /** * Example to demonstrate a XPCC graphics display made * of three 8x8 LED matrices driven by MAX7219 chips. * * The modules are daisy-chained using SPI. * * The demo */ // Software SPI is simple and fast typedef xpcc::stm32::GpioOutputE1 Data; typedef xpcc::stm32::GpioOutputE3 Cs; typedef xpcc::stm32::GpioOutputE5 Clk; typedef xpcc::SoftwareSpiSimpleMaster< Clk, Data > Spi; // The array of 3 modules which all are placed horizontally xpcc::Max7219matrix<Spi, Cs, 3, 1> ledMatrixDisplay; // ---------------------------------------------------------------------------- MAIN_FUNCTION { defaultSystemClock::enable(); LedOrange::setOutput(xpcc::Gpio::High); LedGreen::setOutput(xpcc::Gpio::Low); LedRed::setOutput(xpcc::Gpio::High); LedBlue::setOutput(xpcc::Gpio::High); Data::setOutput(); Cs::setOutput(); Clk::setOutput(); Spi::initialize< 10000000 >(); ledMatrixDisplay.initialize(); ledMatrixDisplay.setFont(xpcc::font::FixedWidth5x8); ledMatrixDisplay.setCursor(0, 0); while (1) { for (int16_t sec = 9999; sec >= 0; --sec) { // Use the LED Matrix as a normal xpcc buffered graphics display ledMatrixDisplay.clear(); ledMatrixDisplay.printf("%04d", sec); ledMatrixDisplay.update(); xpcc::delay_ms(100); LedOrange::toggle(); } } return 0; } <commit_msg>Update MAX7219 LED matrix example<commit_after>#include <xpcc/architecture/platform.hpp> #include <xpcc/architecture.hpp> #include <xpcc/processing.hpp> #include "../stm32f4_discovery.hpp" #include <xpcc/driver/display/max7219matrix.hpp> /** * Example to demonstrate a XPCC graphics display made * of three 8x8 LED matrices driven by MAX7219 chips. * * The modules are daisy-chained using SPI. * * The demo shows a counter counting from 9999 down to 0. * * The first of three MAX7219 based LED Matrix displays is connected * as following: * * PE1 Data * PE3 Cs * PE5 Clk * * GND and +3V3 are connected to the display module. * The other modules are daisy-chained. * */ // Software SPI is simple and fast typedef xpcc::stm32::GpioOutputE1 Data; typedef xpcc::stm32::GpioOutputE3 Cs; typedef xpcc::stm32::GpioOutputE5 Clk; typedef xpcc::SoftwareSpiSimpleMaster< Clk, Data > Spi; // The array of 3 modules which all are placed horizontally xpcc::Max7219matrix<Spi, Cs, 3, 1> ledMatrixDisplay; // ---------------------------------------------------------------------------- MAIN_FUNCTION { defaultSystemClock::enable(); LedOrange::setOutput(xpcc::Gpio::High); Data::setOutput(); Cs::setOutput(); Clk::setOutput(); Spi::initialize< 10000000 >(); ledMatrixDisplay.initialize(); ledMatrixDisplay.setFont(xpcc::font::FixedWidth5x8); ledMatrixDisplay.setCursor(0, 0); xpcc::PeriodicTimer<> countdownTimer(100); while (1) { if (countdownTimer.isExpired()) { for (int16_t sec = 9999; sec >= 0; --sec) { // Use the LED Matrix as a normal xpcc buffered graphics display ledMatrixDisplay.clear(); ledMatrixDisplay.printf("%04d", sec); ledMatrixDisplay.update(); LedOrange::toggle(); } } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_SeriesToAxis.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:38:24 $ * * 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_chart2.hxx" #include "tp_SeriesToAxis.hxx" #include "ResId.hxx" #include "TabPages.hrc" #include "chartview/ChartSfxItemIds.hxx" #include "NoWarningThisInCTOR.hxx" // header for class SfxBoolItem #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif // header for SfxInt32Item #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif //............................................................................. namespace chart { //............................................................................. SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) : SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs), aGrpAxis(this, SchResId(GRP_OPT_AXIS)), aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)), aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)), aGrpBar(this, SchResId(GB_BAR)), aFTGap(this,SchResId(FT_GAP)), aMTGap(this,SchResId(MT_GAP)), aFTOverlap(this,SchResId(FT_OVERLAP)), aMTOverlap(this,SchResId(MT_OVERLAP)), aCBConnect(this,SchResId(CB_CONNECTOR)) { FreeResource(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SchOptionTabPage::~SchOptionTabPage() { } /************************************************************************* |* |* Erzeugung |* \*************************************************************************/ SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs) { return new SchOptionTabPage(pWindow, rOutAttrs); } /************************************************************************* |* |* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen |* \*************************************************************************/ BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs) { if(aRbtAxis2.IsChecked()) rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y)); else rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y)); if(aMTGap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue()))); if(aMTOverlap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue()))); if(aCBConnect.IsVisible()) rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked())); return TRUE; } /************************************************************************* |* |* Initialisierung |* \*************************************************************************/ void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs) { const SfxPoolItem *pPoolItem = NULL; aRbtAxis1.Check(TRUE); aRbtAxis2.Check(FALSE); if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET) { long nVal=((const SfxInt32Item*)pPoolItem)->GetValue(); if(nVal==CHART_AXIS_SECONDARY_Y) { aRbtAxis2.Check(TRUE); aRbtAxis1.Check(FALSE); } } long nTmp; if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTGap.SetValue(nTmp); } else { aMTGap.Show(FALSE); aFTGap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTOverlap.SetValue(nTmp); } else { aMTOverlap.Show(FALSE); aFTOverlap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET) { BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue(); aCBConnect.Check(bCheck); } else { aCBConnect.Show(FALSE); } } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS chart14 (1.8.12); FILE MERGED 2007/09/26 09:15:00 bm 1.8.12.2: #i26795# adapt semantics in UI: ! group bars -> side by side 2007/08/31 14:17:34 bm 1.8.12.1: #i26795# implement feature: display bars on different axes side-by-side<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_SeriesToAxis.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-10-22 16:48:53 $ * * 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_chart2.hxx" #include "tp_SeriesToAxis.hxx" #include "ResId.hxx" #include "TabPages.hrc" #include "chartview/ChartSfxItemIds.hxx" #include "NoWarningThisInCTOR.hxx" // header for class SfxBoolItem #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif // header for SfxInt32Item #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif //............................................................................. namespace chart { //............................................................................. SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) : SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs), aGrpAxis(this, SchResId(GRP_OPT_AXIS)), aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)), aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)), aGrpBar(this, SchResId(GB_BAR)), aFTGap(this,SchResId(FT_GAP)), aMTGap(this,SchResId(MT_GAP)), aFTOverlap(this,SchResId(FT_OVERLAP)), aMTOverlap(this,SchResId(MT_OVERLAP)), aCBConnect(this,SchResId(CB_CONNECTOR)), aCBAxisSideBySide(this,SchResId(CB_BARS_SIDE_BY_SIDE)) { FreeResource(); aRbtAxis1.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl )); aRbtAxis2.SetClickHdl( LINK( this, SchOptionTabPage, EnableHdl )); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SchOptionTabPage::~SchOptionTabPage() { } IMPL_LINK( SchOptionTabPage, EnableHdl, RadioButton *, EMPTYARG ) { if( m_nAllSeriesAxisIndex == 0 ) aCBAxisSideBySide.Enable( aRbtAxis2.IsChecked()); else if( m_nAllSeriesAxisIndex == 1 ) aCBAxisSideBySide.Enable( aRbtAxis1.IsChecked()); return 0; } /************************************************************************* |* |* Erzeugung |* \*************************************************************************/ SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs) { return new SchOptionTabPage(pWindow, rOutAttrs); } /************************************************************************* |* |* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen |* \*************************************************************************/ BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs) { if(aRbtAxis2.IsChecked()) rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y)); else rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y)); if(aMTGap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue()))); if(aMTOverlap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue()))); if(aCBConnect.IsVisible()) rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked())); // model property is "group bars per axis", UI feature is the other way // round: "show bars side by side" if(aCBAxisSideBySide.IsVisible()) rOutAttrs.Put(SfxBoolItem(SCHATTR_GROUP_BARS_PER_AXIS, ! aCBAxisSideBySide.IsChecked())); return TRUE; } /************************************************************************* |* |* Initialisierung |* \*************************************************************************/ void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs) { const SfxPoolItem *pPoolItem = NULL; aRbtAxis1.Check(TRUE); aRbtAxis2.Check(FALSE); if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET) { long nVal=((const SfxInt32Item*)pPoolItem)->GetValue(); if(nVal==CHART_AXIS_SECONDARY_Y) { aRbtAxis2.Check(TRUE); aRbtAxis1.Check(FALSE); } } long nTmp; if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTGap.SetValue(nTmp); } else { aMTGap.Show(FALSE); aFTGap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTOverlap.SetValue(nTmp); } else { aMTOverlap.Show(FALSE); aFTOverlap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET) { BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue(); aCBConnect.Check(bCheck); } else { aCBConnect.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_AXIS_FOR_ALL_SERIES, TRUE, &pPoolItem) == SFX_ITEM_SET) { m_nAllSeriesAxisIndex = static_cast< const SfxInt32Item * >( pPoolItem )->GetValue(); aCBAxisSideBySide.Disable(); } if (rInAttrs.GetItemState(SCHATTR_GROUP_BARS_PER_AXIS, TRUE, &pPoolItem) == SFX_ITEM_SET) { // model property is "group bars per axis", UI feature is the other way // round: "show bars side by side" BOOL bCheck = ! static_cast< const SfxBoolItem * >( pPoolItem )->GetValue(); aCBAxisSideBySide.Check( bCheck ); } else { aCBAxisSideBySide.Show(FALSE); } } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync <commit_msg>Upload only a fixed percentage of unrecoverable errors. We do this to throttle the number of uploads we have currently.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.15; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync <|endoftext|>
<commit_before>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2017 Taras Kushnir <[email protected]> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "basickeywordsmodel.h" #include <QReadWriteLock> #include <QReadLocker> #include <QWriteLocker> #include "../SpellCheck/spellcheckitem.h" #include "../SpellCheck/spellsuggestionsitem.h" #include "../SpellCheck/spellcheckiteminfo.h" #include "../Helpers/keywordshelpers.h" #include "../Helpers/stringhelper.h" #include "flags.h" #include "../Common/defines.h" #include "../Helpers/indiceshelper.h" #include "../Common/flags.h" #include "basickeywordsmodelimpl.h" namespace Common { BasicKeywordsModel::BasicKeywordsModel(Hold &hold, QObject *parent): AbstractListModel(parent), m_Impl(new BasicKeywordsModelImpl(hold)) {} #ifdef CORE_TESTS const QString &BasicKeywordsModel::getKeywordAt(int index) const { return m_Impl->accessKeywordUnsafe(index).m_Value; } std::vector<Keyword> &BasicKeywordsModel::getRawKeywords() { return m_Impl->m_KeywordsList; } #endif #ifdef INTEGRATION_TESTS bool BasicKeywordsModel::hasDuplicateAt(size_t i) const { return m_Impl->accessKeywordUnsafe(i).m_HasDuplicate; } #endif void BasicKeywordsModel::removeItemsFromRanges(const QVector<QPair<int, int> > &ranges) { LOG_INFO << "#"; int rangesLength = Helpers::getRangesLength(ranges); { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); AbstractListModel::doRemoveItemsFromRanges(ranges); } AbstractListModel::doEmitItemsRemovedAtIndices(ranges, rangesLength); } void BasicKeywordsModel::removeInnerItem(int row) { QString removedKeyword; bool wasCorrect = false; m_Impl->takeKeywordAtUnsafe(row, removedKeyword, wasCorrect); LOG_INTEGRATION_TESTS << "keyword:" << removedKeyword << "was correct:" << wasCorrect; Q_UNUSED(removedKeyword); Q_UNUSED(wasCorrect); } int BasicKeywordsModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_Impl->getKeywordsCount(); } QVariant BasicKeywordsModel::data(const QModelIndex &index, int role) const { QReadLocker readLocker(m_Impl->accessLock()); Q_UNUSED(readLocker); const int row = index.row(); if (row < 0 || row >= (int)m_Impl->getKeywordsSizeUnsafe()) { return QVariant(); } auto &keyword = m_Impl->accessKeywordUnsafe(row); switch (role) { case KeywordRole: return keyword.m_Value; case IsCorrectRole: return keyword.m_IsCorrect; case HasDuplicateRole: return keyword.m_HasDuplicates; default: return QVariant(); } } QHash<int, QByteArray> BasicKeywordsModel::roleNames() const { QHash<int, QByteArray> roles; roles[KeywordRole] = "keyword"; roles[IsCorrectRole] = "iscorrect"; roles[HasDuplicateRole] = "hasduplicate"; return roles; } int BasicKeywordsModel::getKeywordsCount() { return m_Impl->getKeywordsCount(); } QSet<QString> BasicKeywordsModel::getKeywordsSet() { return m_Impl->getKeywordsSet(); } QString BasicKeywordsModel::getKeywordsString() { return m_Impl->getKeywordsString(); } bool BasicKeywordsModel::appendKeyword(const QString &keyword) { bool added = false; size_t index = 0; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); added = m_Impl->appendKeywordUnsafe(keyword, index); } if (added) { beginInsertRows(QModelIndex(), (int)index, (int)index); endInsertRows(); } return added; } bool BasicKeywordsModel::removeKeywordAt(size_t index, QString &removedKeyword) { bool wasCorrect = false, removed = false; m_Impl->lockKeywordsWrite(); { if (index < m_Impl->getKeywordsSizeUnsafe()) { m_Impl->takeKeywordAtUnsafe(index, removedKeyword, wasCorrect); removed = true; } } m_Impl->unlockKeywords(); if (removed) { beginRemoveRows(QModelIndex(), (int)index, (int)index); endRemoveRows(); if (!wasCorrect) { notifyKeywordsSpellingChanged(); } emit hasDuplicatesChanged(); } return removed; } bool BasicKeywordsModel::removeLastKeyword(QString &removedKeyword) { bool wasCorrect = false, removed = false; size_t indexLast = 0; m_Impl->lockKeywordsWrite(); { const size_t size = m_Impl->getKeywordsSizeUnsafe(); if (size > 0) { indexLast = size - 1; m_Impl->takeKeywordAtUnsafe(indexLast, removedKeyword, wasCorrect); removed = true; } } m_Impl->unlockKeywords(); if (removed) { beginRemoveRows(QModelIndex(), (int)indexLast, (int)indexLast); endRemoveRows(); if (!wasCorrect) { notifyKeywordsSpellingChanged(); } emit hasDuplicatesChanged(); } return removed; } void BasicKeywordsModel::setKeywords(const QStringList &keywordsList) { bool anyChange = false; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); anyChange = m_Impl->clearKeywordsUnsafe(); size_t start = 0, end = 0; size_t size = m_Impl->appendKeywordsUnsafe(keywordsList, start, end); if (size > 0) { anyChange = true; } } if (anyChange) { beginResetModel(); endResetModel(); } } size_t BasicKeywordsModel::appendKeywords(const QStringList &keywordsList) { size_t size = 0; size_t start = 0, end = 0; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); size = m_Impl->appendKeywordsUnsafe(keywordsList, start, end); } if (size > 0) { beginInsertRows(QModelIndex(), (int)start, (int)end); endInsertRows(); } return size; } bool BasicKeywordsModel::editKeyword(size_t index, const QString &replacement) { bool result = false; m_Impl->lockKeywordsWrite(); { if (index < m_Impl->getKeywordsSizeUnsafe()) { result = m_Impl->editKeywordUnsafe(index, replacement); } else { LOG_WARNING << "Failed to edit keyword with index" << index; } } m_Impl->unlockKeywords(); if (result) { QModelIndex i = this->index((int)index); emit dataChanged(i, i, QVector<int>() << KeywordRole); } return result; } bool BasicKeywordsModel::clearKeywords() { bool result = false; m_Impl->lockKeywordsWrite(); { result = m_Impl->clearKeywordsUnsafe(); } m_Impl->unlockKeywords(); if (result) { beginResetModel(); endResetModel(); notifyKeywordsSpellingChanged(); emit hasDuplicatesChanged(); } return result; } bool BasicKeywordsModel::expandPreset(size_t keywordIndex, const QStringList &presetList) { LOG_INFO << keywordIndex; bool expanded = false; size_t start = 0, end = 0; size_t addedCount = 0; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); if (keywordIndex < m_Impl->getKeywordsSizeUnsafe()) { LOG_INFO << "index" << keywordIndex << "list:" << presetList; QString removedKeyword; bool wasCorrect = false; m_Impl->takeKeywordAtUnsafe(keywordIndex, removedKeyword, wasCorrect); LOG_INFO << "replaced keyword" << removedKeyword; Q_UNUSED(wasCorrect); size_t addedCount = m_Impl->appendKeywordsUnsafe(presetList, start, end); LOG_INFO << addedCount << "new added"; expanded = true; } } if (expanded) { beginRemoveRows(QModelIndex(), (int)keywordIndex, (int)keywordIndex); endRemoveRows(); if (addedCount > 0) { beginInsertRows(QModelIndex(), (int)start, (int)end); endInsertRows(); } } return expanded; } bool BasicKeywordsModel::appendPreset(const QStringList &presetList) { LOG_DEBUG << "#"; bool result = appendKeywords(presetList) > 0; return result; } bool BasicKeywordsModel::hasKeywords(const QStringList &keywordsList) { return m_Impl->hasKeywords(keywordsList); } bool BasicKeywordsModel::areKeywordsEmpty() { return m_Impl->areKeywordsEmpty(); } bool BasicKeywordsModel::replace(const QString &replaceWhat, const QString &replaceTo, Common::SearchFlags flags) { LOG_INTEGR_TESTS_OR_DEBUG << replaceWhat << "->" << replaceTo << "with flags:" << (int)flags; Q_ASSERT(!replaceWhat.isEmpty()); Q_ASSERT(((int)flags & (int)Common::SearchFlags::Metadata) != 0); bool anyChanged = false; QVector<int> indicesToUpdate, indicesToRemove; QVector<QPair<int, int> > rangesToRemove; const bool needToCheckKeywords = Common::HasFlag(flags, Common::SearchFlags::Keywords); if (needToCheckKeywords) { QWriteLocker locker(m_Impl->accessLock()); Q_UNUSED(locker); if (m_Impl->replaceInKeywordsUnsafe(replaceWhat, replaceTo, flags, indicesToRemove, indicesToUpdate)) { Helpers::indicesToRanges(indicesToRemove, rangesToRemove); AbstractListModel::doRemoveItemsFromRanges(rangesToRemove); anyChanged = true; } } if (anyChanged) { AbstractListModel::emitRemovedSignalsForRanges(rangesToRemove); int size = m_Impl->getKeywordsCount(); // update all because of easiness instead of calculated correct shifts after removal this->updateItemsInRanges({{0, size - 1}}, QVector<int>() << KeywordRole); } return anyChanged; } bool BasicKeywordsModel::removeKeywords(const QSet<QString> &keywords, bool caseSensitive) { bool anyRemoved = false; QVector<QPair<int, int> > rangesToRemove; { QWriteLocker locker(m_Impl->accessLock()); Q_UNUSED(locker); QVector<int> indicesToRemove; if (m_Impl->removeKeywordsUnsafe(keywords, caseSensitive, indicesToRemove)) { Helpers::indicesToRanges(indicesToRemove, rangesToRemove); AbstractListModel::doRemoveItemsFromRanges(rangesToRemove); anyRemoved = true; } } if (anyRemoved) { AbstractListModel::emitRemovedSignalsForRanges(rangesToRemove); } return anyRemoved; } QString BasicKeywordsModel::retrieveKeyword(size_t wordIndex) { return m_Impl->retrieveKeyword(wordIndex); } QStringList BasicKeywordsModel::getKeywords() { return m_Impl->getKeywords(); } void BasicKeywordsModel::setKeywordsSpellCheckResults(const std::vector<std::shared_ptr<SpellCheck::SpellCheckQueryItem> > &items) { m_Impl->setKeywordsSpellCheckResults(items); } std::vector<KeywordItem> BasicKeywordsModel::retrieveMisspelledKeywords() { return m_Impl->retrieveMisspelledKeywords(); } std::vector<KeywordItem> BasicKeywordsModel::retrieveDuplicatedKeywords() { return m_Impl->retrieveDuplicatedKeywords(); } Common::KeywordReplaceResult BasicKeywordsModel::fixKeywordSpelling(size_t index, const QString &existing, const QString &replacement) { Common::KeywordReplaceResult result = m_Impl->fixKeywordSpelling(index, existing, replacement); if (result == Common::KeywordReplaceResult::Succeeded) { QModelIndex i = this->index((int)index); // combined roles from legacy editKeyword() and replace() emit dataChanged(i, i, QVector<int>() << KeywordRole << IsCorrectRole << HasDuplicateRole); } return result; } bool BasicKeywordsModel::processFailedKeywordReplacements(const std::vector<std::shared_ptr<SpellCheck::KeywordSpellSuggestions> > &candidatesForRemoval) { bool anyReplaced = false; QVector<QPair<int, int> > rangesToRemove; { QWriteLocker locker(m_Impl->accessLock()); Q_UNUSED(locker); QVector<int> indicesToRemove; if (m_Impl->processFailedKeywordReplacementsUnsafe(candidatesForRemoval, indicesToRemove)) { Q_ASSERT(!indicesToRemove.isEmpty()); Helpers::indicesToRanges(indicesToRemove, rangesToRemove); AbstractListModel::doRemoveItemsFromRanges(rangesToRemove); anyReplaced = true; } } AbstractListModel::emitRemovedSignalsForRanges(rangesToRemove); return anyReplaced; } void BasicKeywordsModel::connectSignals(SpellCheck::SpellCheckItem *item) { QObject::connect(item, &SpellCheck::SpellCheckItem::resultsReady, this, &BasicKeywordsModel::onSpellCheckRequestReady); } void BasicKeywordsModel::afterReplaceCallback() { LOG_DEBUG << "#"; emit notifyKeywordsSpellingChanged(); emit afterSpellingErrorsFixed(); emit hasDuplicatesChanged(); } bool BasicKeywordsModel::containsKeyword(const QString &searchTerm, Common::SearchFlags searchFlags) { return m_Impl->containsKeyword(searchTerm, searchFlags); } bool BasicKeywordsModel::containsKeywords(const QStringList &keywordsList) { return m_Impl->containsKeywords(keywordsList); } bool BasicKeywordsModel::isEmpty() { return m_Impl->isEmpty(); } bool BasicKeywordsModel::hasKeywordsSpellError() { return m_Impl->hasKeywordsSpellError(); } bool BasicKeywordsModel::hasKeywordsDuplicates() { return m_Impl->hasKeywordsDuplicates(); } bool BasicKeywordsModel::hasSpellErrors() { return m_Impl->hasSpellErrors(); } bool BasicKeywordsModel::hasDuplicates() { return m_Impl->hasDuplicates(); } void BasicKeywordsModel::notifySpellCheckResults(Common::SpellCheckFlags flags) { if (Common::HasFlag(flags, Common::SpellCheckFlags::Keywords)) { notifyKeywordsSpellingChanged(); } emit hasDuplicatesChanged(); } void BasicKeywordsModel::notifyKeywordsSpellingChanged() { emit keywordsSpellingChanged(); } void BasicKeywordsModel::acquire() { m_Impl->acquire(); } bool BasicKeywordsModel::release() { return m_Impl->release(); } bool BasicKeywordsModel::hasKeyword(const QString &keyword) { return m_Impl->hasKeyword(keyword); } bool BasicKeywordsModel::canEditKeyword(int index, const QString &replacement) { return m_Impl->canEditKeyword(index, replacement); } void BasicKeywordsModel::onSpellCheckRequestReady(Common::SpellCheckFlags flags, int index) { if (Common::HasFlag(flags, Common::SpellCheckFlags::Keywords)) { updateKeywordsHighlighting(index); } notifySpellCheckResults(flags); emit spellingInfoUpdated(); } void BasicKeywordsModel::updateKeywordsHighlighting(int index) { const int count = getKeywordsCount(); if (index == -1) { if (count > 0) { QModelIndex start = this->index(0); QModelIndex end = this->index(count - 1); emit dataChanged(start, end, QVector<int>() << IsCorrectRole << HasDuplicateRole); } } else { if (0 <= index && index < count) { QModelIndex i = this->index(index); emit dataChanged(i, i, QVector<int>() << IsCorrectRole << HasDuplicateRole); } } } } <commit_msg>Fix for integration tests<commit_after>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2017 Taras Kushnir <[email protected]> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "basickeywordsmodel.h" #include <QReadWriteLock> #include <QReadLocker> #include <QWriteLocker> #include "../SpellCheck/spellcheckitem.h" #include "../SpellCheck/spellsuggestionsitem.h" #include "../SpellCheck/spellcheckiteminfo.h" #include "../Helpers/keywordshelpers.h" #include "../Helpers/stringhelper.h" #include "flags.h" #include "defines.h" #include "../Helpers/indiceshelper.h" #include "basickeywordsmodelimpl.h" namespace Common { BasicKeywordsModel::BasicKeywordsModel(Hold &hold, QObject *parent): AbstractListModel(parent), m_Impl(new BasicKeywordsModelImpl(hold)) {} #ifdef CORE_TESTS const QString &BasicKeywordsModel::getKeywordAt(int index) const { return m_Impl->accessKeywordUnsafe(index).m_Value; } std::vector<Keyword> &BasicKeywordsModel::getRawKeywords() { return m_Impl->m_KeywordsList; } #endif #ifdef INTEGRATION_TESTS bool BasicKeywordsModel::hasDuplicateAt(size_t i) const { return m_Impl->accessKeywordUnsafe(i).m_HasDuplicates; } #endif void BasicKeywordsModel::removeItemsFromRanges(const QVector<QPair<int, int> > &ranges) { LOG_INFO << "#"; int rangesLength = Helpers::getRangesLength(ranges); { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); AbstractListModel::doRemoveItemsFromRanges(ranges); } AbstractListModel::doEmitItemsRemovedAtIndices(ranges, rangesLength); } void BasicKeywordsModel::removeInnerItem(int row) { QString removedKeyword; bool wasCorrect = false; m_Impl->takeKeywordAtUnsafe(row, removedKeyword, wasCorrect); LOG_INTEGRATION_TESTS << "keyword:" << removedKeyword << "was correct:" << wasCorrect; Q_UNUSED(removedKeyword); Q_UNUSED(wasCorrect); } int BasicKeywordsModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_Impl->getKeywordsCount(); } QVariant BasicKeywordsModel::data(const QModelIndex &index, int role) const { QReadLocker readLocker(m_Impl->accessLock()); Q_UNUSED(readLocker); const int row = index.row(); if (row < 0 || row >= (int)m_Impl->getKeywordsSizeUnsafe()) { return QVariant(); } auto &keyword = m_Impl->accessKeywordUnsafe(row); switch (role) { case KeywordRole: return keyword.m_Value; case IsCorrectRole: return keyword.m_IsCorrect; case HasDuplicateRole: return keyword.m_HasDuplicates; default: return QVariant(); } } QHash<int, QByteArray> BasicKeywordsModel::roleNames() const { QHash<int, QByteArray> roles; roles[KeywordRole] = "keyword"; roles[IsCorrectRole] = "iscorrect"; roles[HasDuplicateRole] = "hasduplicate"; return roles; } int BasicKeywordsModel::getKeywordsCount() { return m_Impl->getKeywordsCount(); } QSet<QString> BasicKeywordsModel::getKeywordsSet() { return m_Impl->getKeywordsSet(); } QString BasicKeywordsModel::getKeywordsString() { return m_Impl->getKeywordsString(); } bool BasicKeywordsModel::appendKeyword(const QString &keyword) { bool added = false; size_t index = 0; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); added = m_Impl->appendKeywordUnsafe(keyword, index); } if (added) { beginInsertRows(QModelIndex(), (int)index, (int)index); endInsertRows(); } return added; } bool BasicKeywordsModel::removeKeywordAt(size_t index, QString &removedKeyword) { bool wasCorrect = false, removed = false; m_Impl->lockKeywordsWrite(); { if (index < m_Impl->getKeywordsSizeUnsafe()) { m_Impl->takeKeywordAtUnsafe(index, removedKeyword, wasCorrect); removed = true; } } m_Impl->unlockKeywords(); if (removed) { beginRemoveRows(QModelIndex(), (int)index, (int)index); endRemoveRows(); if (!wasCorrect) { notifyKeywordsSpellingChanged(); } emit hasDuplicatesChanged(); } return removed; } bool BasicKeywordsModel::removeLastKeyword(QString &removedKeyword) { bool wasCorrect = false, removed = false; size_t indexLast = 0; m_Impl->lockKeywordsWrite(); { const size_t size = m_Impl->getKeywordsSizeUnsafe(); if (size > 0) { indexLast = size - 1; m_Impl->takeKeywordAtUnsafe(indexLast, removedKeyword, wasCorrect); removed = true; } } m_Impl->unlockKeywords(); if (removed) { beginRemoveRows(QModelIndex(), (int)indexLast, (int)indexLast); endRemoveRows(); if (!wasCorrect) { notifyKeywordsSpellingChanged(); } emit hasDuplicatesChanged(); } return removed; } void BasicKeywordsModel::setKeywords(const QStringList &keywordsList) { bool anyChange = false; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); anyChange = m_Impl->clearKeywordsUnsafe(); size_t start = 0, end = 0; size_t size = m_Impl->appendKeywordsUnsafe(keywordsList, start, end); if (size > 0) { anyChange = true; } } if (anyChange) { beginResetModel(); endResetModel(); } } size_t BasicKeywordsModel::appendKeywords(const QStringList &keywordsList) { size_t size = 0; size_t start = 0, end = 0; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); size = m_Impl->appendKeywordsUnsafe(keywordsList, start, end); } if (size > 0) { beginInsertRows(QModelIndex(), (int)start, (int)end); endInsertRows(); } return size; } bool BasicKeywordsModel::editKeyword(size_t index, const QString &replacement) { bool result = false; m_Impl->lockKeywordsWrite(); { if (index < m_Impl->getKeywordsSizeUnsafe()) { result = m_Impl->editKeywordUnsafe(index, replacement); } else { LOG_WARNING << "Failed to edit keyword with index" << index; } } m_Impl->unlockKeywords(); if (result) { QModelIndex i = this->index((int)index); emit dataChanged(i, i, QVector<int>() << KeywordRole); } return result; } bool BasicKeywordsModel::clearKeywords() { bool result = false; m_Impl->lockKeywordsWrite(); { result = m_Impl->clearKeywordsUnsafe(); } m_Impl->unlockKeywords(); if (result) { beginResetModel(); endResetModel(); notifyKeywordsSpellingChanged(); emit hasDuplicatesChanged(); } return result; } bool BasicKeywordsModel::expandPreset(size_t keywordIndex, const QStringList &presetList) { LOG_INFO << keywordIndex; bool expanded = false; size_t start = 0, end = 0; size_t addedCount = 0; { QWriteLocker writeLocker(m_Impl->accessLock()); Q_UNUSED(writeLocker); if (keywordIndex < m_Impl->getKeywordsSizeUnsafe()) { LOG_INFO << "index" << keywordIndex << "list:" << presetList; QString removedKeyword; bool wasCorrect = false; m_Impl->takeKeywordAtUnsafe(keywordIndex, removedKeyword, wasCorrect); LOG_INFO << "replaced keyword" << removedKeyword; Q_UNUSED(wasCorrect); size_t addedCount = m_Impl->appendKeywordsUnsafe(presetList, start, end); LOG_INFO << addedCount << "new added"; expanded = true; } } if (expanded) { beginRemoveRows(QModelIndex(), (int)keywordIndex, (int)keywordIndex); endRemoveRows(); if (addedCount > 0) { beginInsertRows(QModelIndex(), (int)start, (int)end); endInsertRows(); } } return expanded; } bool BasicKeywordsModel::appendPreset(const QStringList &presetList) { LOG_DEBUG << "#"; bool result = appendKeywords(presetList) > 0; return result; } bool BasicKeywordsModel::hasKeywords(const QStringList &keywordsList) { return m_Impl->hasKeywords(keywordsList); } bool BasicKeywordsModel::areKeywordsEmpty() { return m_Impl->areKeywordsEmpty(); } bool BasicKeywordsModel::replace(const QString &replaceWhat, const QString &replaceTo, Common::SearchFlags flags) { LOG_INTEGR_TESTS_OR_DEBUG << replaceWhat << "->" << replaceTo << "with flags:" << (int)flags; Q_ASSERT(!replaceWhat.isEmpty()); Q_ASSERT(((int)flags & (int)Common::SearchFlags::Metadata) != 0); bool anyChanged = false; QVector<int> indicesToUpdate, indicesToRemove; QVector<QPair<int, int> > rangesToRemove; const bool needToCheckKeywords = Common::HasFlag(flags, Common::SearchFlags::Keywords); if (needToCheckKeywords) { QWriteLocker locker(m_Impl->accessLock()); Q_UNUSED(locker); if (m_Impl->replaceInKeywordsUnsafe(replaceWhat, replaceTo, flags, indicesToRemove, indicesToUpdate)) { Helpers::indicesToRanges(indicesToRemove, rangesToRemove); AbstractListModel::doRemoveItemsFromRanges(rangesToRemove); anyChanged = true; } } if (anyChanged) { AbstractListModel::emitRemovedSignalsForRanges(rangesToRemove); int size = m_Impl->getKeywordsCount(); // update all because of easiness instead of calculated correct shifts after removal this->updateItemsInRanges({{0, size - 1}}, QVector<int>() << KeywordRole); } return anyChanged; } bool BasicKeywordsModel::removeKeywords(const QSet<QString> &keywords, bool caseSensitive) { bool anyRemoved = false; QVector<QPair<int, int> > rangesToRemove; { QWriteLocker locker(m_Impl->accessLock()); Q_UNUSED(locker); QVector<int> indicesToRemove; if (m_Impl->removeKeywordsUnsafe(keywords, caseSensitive, indicesToRemove)) { Helpers::indicesToRanges(indicesToRemove, rangesToRemove); AbstractListModel::doRemoveItemsFromRanges(rangesToRemove); anyRemoved = true; } } if (anyRemoved) { AbstractListModel::emitRemovedSignalsForRanges(rangesToRemove); } return anyRemoved; } QString BasicKeywordsModel::retrieveKeyword(size_t wordIndex) { return m_Impl->retrieveKeyword(wordIndex); } QStringList BasicKeywordsModel::getKeywords() { return m_Impl->getKeywords(); } void BasicKeywordsModel::setKeywordsSpellCheckResults(const std::vector<std::shared_ptr<SpellCheck::SpellCheckQueryItem> > &items) { m_Impl->setKeywordsSpellCheckResults(items); } std::vector<KeywordItem> BasicKeywordsModel::retrieveMisspelledKeywords() { return m_Impl->retrieveMisspelledKeywords(); } std::vector<KeywordItem> BasicKeywordsModel::retrieveDuplicatedKeywords() { return m_Impl->retrieveDuplicatedKeywords(); } Common::KeywordReplaceResult BasicKeywordsModel::fixKeywordSpelling(size_t index, const QString &existing, const QString &replacement) { Common::KeywordReplaceResult result = m_Impl->fixKeywordSpelling(index, existing, replacement); if (result == Common::KeywordReplaceResult::Succeeded) { QModelIndex i = this->index((int)index); // combined roles from legacy editKeyword() and replace() emit dataChanged(i, i, QVector<int>() << KeywordRole << IsCorrectRole << HasDuplicateRole); } return result; } bool BasicKeywordsModel::processFailedKeywordReplacements(const std::vector<std::shared_ptr<SpellCheck::KeywordSpellSuggestions> > &candidatesForRemoval) { bool anyReplaced = false; QVector<QPair<int, int> > rangesToRemove; { QWriteLocker locker(m_Impl->accessLock()); Q_UNUSED(locker); QVector<int> indicesToRemove; if (m_Impl->processFailedKeywordReplacementsUnsafe(candidatesForRemoval, indicesToRemove)) { Q_ASSERT(!indicesToRemove.isEmpty()); Helpers::indicesToRanges(indicesToRemove, rangesToRemove); AbstractListModel::doRemoveItemsFromRanges(rangesToRemove); anyReplaced = true; } } AbstractListModel::emitRemovedSignalsForRanges(rangesToRemove); return anyReplaced; } void BasicKeywordsModel::connectSignals(SpellCheck::SpellCheckItem *item) { QObject::connect(item, &SpellCheck::SpellCheckItem::resultsReady, this, &BasicKeywordsModel::onSpellCheckRequestReady); } void BasicKeywordsModel::afterReplaceCallback() { LOG_DEBUG << "#"; emit notifyKeywordsSpellingChanged(); emit afterSpellingErrorsFixed(); emit hasDuplicatesChanged(); } bool BasicKeywordsModel::containsKeyword(const QString &searchTerm, Common::SearchFlags searchFlags) { return m_Impl->containsKeyword(searchTerm, searchFlags); } bool BasicKeywordsModel::containsKeywords(const QStringList &keywordsList) { return m_Impl->containsKeywords(keywordsList); } bool BasicKeywordsModel::isEmpty() { return m_Impl->isEmpty(); } bool BasicKeywordsModel::hasKeywordsSpellError() { return m_Impl->hasKeywordsSpellError(); } bool BasicKeywordsModel::hasKeywordsDuplicates() { return m_Impl->hasKeywordsDuplicates(); } bool BasicKeywordsModel::hasSpellErrors() { return m_Impl->hasSpellErrors(); } bool BasicKeywordsModel::hasDuplicates() { return m_Impl->hasDuplicates(); } void BasicKeywordsModel::notifySpellCheckResults(Common::SpellCheckFlags flags) { if (Common::HasFlag(flags, Common::SpellCheckFlags::Keywords)) { notifyKeywordsSpellingChanged(); } emit hasDuplicatesChanged(); } void BasicKeywordsModel::notifyKeywordsSpellingChanged() { emit keywordsSpellingChanged(); } void BasicKeywordsModel::acquire() { m_Impl->acquire(); } bool BasicKeywordsModel::release() { return m_Impl->release(); } bool BasicKeywordsModel::hasKeyword(const QString &keyword) { return m_Impl->hasKeyword(keyword); } bool BasicKeywordsModel::canEditKeyword(int index, const QString &replacement) { return m_Impl->canEditKeyword(index, replacement); } void BasicKeywordsModel::onSpellCheckRequestReady(Common::SpellCheckFlags flags, int index) { if (Common::HasFlag(flags, Common::SpellCheckFlags::Keywords)) { updateKeywordsHighlighting(index); } notifySpellCheckResults(flags); emit spellingInfoUpdated(); } void BasicKeywordsModel::updateKeywordsHighlighting(int index) { const int count = getKeywordsCount(); if (index == -1) { if (count > 0) { QModelIndex start = this->index(0); QModelIndex end = this->index(count - 1); emit dataChanged(start, end, QVector<int>() << IsCorrectRole << HasDuplicateRole); } } else { if (0 <= index && index < count) { QModelIndex i = this->index(index); emit dataChanged(i, i, QVector<int>() << IsCorrectRole << HasDuplicateRole); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: salvd.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2004-05-10 16:00:04 $ * * 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): _______________________________________ * * ************************************************************************/ #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #ifndef _SV_SALVD_H #include <salvd.h> #endif // -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics, long nDX, long nDY, USHORT nBitCount ) { X11SalVirtualDevice *pVDev = new X11SalVirtualDevice(); if( !nBitCount && pGraphics ) nBitCount = pGraphics->GetBitCount(); if( !pVDev->Init( GetSalData()->GetDisplay(), nDX, nDY, nBitCount ) ) { delete pVDev; return NULL; } pVDev->InitGraphics( pVDev ); return pVDev; } void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice ) { delete pDevice; } // -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void X11SalGraphics::Init( X11SalVirtualDevice *pDevice ) { SalDisplay *pDisplay = pDevice->GetDisplay(); int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth(); int nDeviceDepth = pDevice->GetDepth(); if( nDeviceDepth == nVisualDepth ) m_pColormap = &pDisplay->GetColormap(); else if( nDeviceDepth == 1 ) m_pDeleteColormap = m_pColormap = new SalColormap(); hDrawable_ = pDevice->GetDrawable(); m_pVDev = pDevice; m_pFrame = NULL; bWindow_ = pDisplay->IsDisplay(); bVirDev_ = TRUE; nPenPixel_ = GetPixel( nPenColor_ ); nTextPixel_ = GetPixel( nTextColor_ ); nBrushPixel_ = GetPixel( nBrushColor_ ); } // -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay, long nDX, long nDY, USHORT nBitCount ) { pDisplay_ = pDisplay; pGraphics_ = new X11SalGraphics(); pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL() nDX_ = nDX; nDY_ = nDY; nDepth_ = nBitCount; hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX_, nDY_, GetDepth() ); pGraphics_->Init( this ); return hDrawable_ != None ? TRUE : FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::X11SalVirtualDevice() { pDisplay_ = (SalDisplay*)ILLEGAL_POINTER; pGraphics_ = NULL; hDrawable_ = None; nDX_ = 0; nDY_ = 0; nDepth_ = 0; bGraphics_ = FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::~X11SalVirtualDevice() { if( pGraphics_ ) delete pGraphics_; if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); } SalGraphics* X11SalVirtualDevice::GetGraphics() { if( bGraphics_ ) return NULL; if( pGraphics_ ) bGraphics_ = TRUE; return pGraphics_; } void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* ) { bGraphics_ = FALSE; } BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY ) { if( !nDX ) nDX = 1; if( !nDY ) nDY = 1; Pixmap h = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX, nDY, nDepth_ ); if( !h ) { if( !GetDrawable() ) { hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), 1, 1, nDepth_ ); nDX_ = 1; nDY_ = 1; } return FALSE; } if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); hDrawable_ = h; nDX_ = nDX; nDY_ = nDY; if( pGraphics_ ) InitGraphics( this ); return TRUE; } <commit_msg>INTEGRATION: CWS presentationengine01 (1.8.50); FILE MERGED 2004/08/17 12:08:19 aw 1.8.50.1: #110496# adaptions for CreateVirtualDevice for UNX<commit_after>/************************************************************************* * * $RCSfile: salvd.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-11-26 20:45:01 $ * * 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): _______________________________________ * * ************************************************************************/ #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #ifndef _SV_SALVD_H #include <salvd.h> #endif // -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData ) { X11SalVirtualDevice *pVDev = new X11SalVirtualDevice(); if( !nBitCount && pGraphics ) nBitCount = pGraphics->GetBitCount(); if( !pVDev->Init( GetSalData()->GetDisplay(), nDX, nDY, nBitCount ) ) { delete pVDev; return NULL; } pVDev->InitGraphics( pVDev ); return pVDev; } void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice ) { delete pDevice; } // -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void X11SalGraphics::Init( X11SalVirtualDevice *pDevice ) { SalDisplay *pDisplay = pDevice->GetDisplay(); int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth(); int nDeviceDepth = pDevice->GetDepth(); if( nDeviceDepth == nVisualDepth ) m_pColormap = &pDisplay->GetColormap(); else if( nDeviceDepth == 1 ) m_pDeleteColormap = m_pColormap = new SalColormap(); hDrawable_ = pDevice->GetDrawable(); m_pVDev = pDevice; m_pFrame = NULL; bWindow_ = pDisplay->IsDisplay(); bVirDev_ = TRUE; nPenPixel_ = GetPixel( nPenColor_ ); nTextPixel_ = GetPixel( nTextColor_ ); nBrushPixel_ = GetPixel( nBrushColor_ ); } // -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay, long nDX, long nDY, USHORT nBitCount ) { pDisplay_ = pDisplay; pGraphics_ = new X11SalGraphics(); pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL() nDX_ = nDX; nDY_ = nDY; nDepth_ = nBitCount; hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX_, nDY_, GetDepth() ); pGraphics_->Init( this ); return hDrawable_ != None ? TRUE : FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::X11SalVirtualDevice() { pDisplay_ = (SalDisplay*)ILLEGAL_POINTER; pGraphics_ = NULL; hDrawable_ = None; nDX_ = 0; nDY_ = 0; nDepth_ = 0; bGraphics_ = FALSE; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X11SalVirtualDevice::~X11SalVirtualDevice() { if( pGraphics_ ) delete pGraphics_; if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); } SalGraphics* X11SalVirtualDevice::GetGraphics() { if( bGraphics_ ) return NULL; if( pGraphics_ ) bGraphics_ = TRUE; return pGraphics_; } void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* ) { bGraphics_ = FALSE; } BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY ) { if( !nDX ) nDX = 1; if( !nDY ) nDY = 1; Pixmap h = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), nDX, nDY, nDepth_ ); if( !h ) { if( !GetDrawable() ) { hDrawable_ = XCreatePixmap( GetXDisplay(), pDisplay_->GetDrawable(), 1, 1, nDepth_ ); nDX_ = 1; nDY_ = 1; } return FALSE; } if( GetDrawable() ) XFreePixmap( GetXDisplay(), GetDrawable() ); hDrawable_ = h; nDX_ = nDX; nDY_ = nDY; if( pGraphics_ ) InitGraphics( this ); return TRUE; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <map> #include <cassert> #include <sstream> #include <algorithm> #include <fstream> #include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <boost/algorithm/string.hpp> using std::string; using std::ostream; using std::ofstream; namespace po=boost::program_options; const string HELP_K = "help"; const string CONFIG_K = "config"; const string INPUT_K = "input"; const string OUTPUT_K = "output"; const string OPERATION_K = "operation"; const string SELECT_K = "select"; const string SPLIT_K = "split"; const string TRANSPOSE_K = "transpose"; const string COMBINE_K = "combine"; const string FORMAT_K = "format"; const string PREFIX_K = "prefix"; const string VALUE_K = "value"; const string KEYS_K = "keys"; const string JSON_K = "json"; const string GNUPLOT_K = "gnuplot"; const string OUTPUT_FORMAT_K = OUTPUT_K + "." + FORMAT_K; const string OUTPUT_PREFIX_K = OUTPUT_K + "." + PREFIX_K; const string INPUT_VALUE_K = INPUT_K + "." + VALUE_K; int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg ); int command_line( int argc, char ** argv, po::variables_map & vm ); int transform( po::variables_map & vm, boost::property_tree::ptree & p ); void parse_data( boost::property_tree::ptree & cfg ); typedef void (*parser_op)( boost::property_tree::ptree & parameters ); // select keys from each input file into a void select_op( boost::property_tree::ptree & parameters ); void select_op_gnuplot( boost::property_tree::ptree & params ); // combine all keys from each input file into a single output file void combine_op( boost::property_tree::ptree & parameters ); void combine_op_json( boost::property_tree::ptree & parameters ); void transpose_op( boost::property_tree::ptree & params ); void write_json( const std::string & path, boost::property_tree::ptree & results ); void write_gnuplot( const std::string & path, const std::string & header, boost::property_tree::ptree & results ); int main( int argc, char ** argv ) { boost::property_tree::ptree cfg; int res = 0; if( (res = parse_configuration( argc, argv, cfg )) ) { return res; } BOOST_FOREACH( auto& c, cfg ) { std::cerr << c.first << std::endl; parse_data( c.second ); } } void parse_data( boost::property_tree::ptree & cfg ) { string op = cfg.get< string >( OPERATION_K, ""); if( op.empty() ) return; if( op == SELECT_K ) { select_op( cfg ); } else if ( op == COMBINE_K ) { // combine_op( cfg ); } else if( op == TRANSPOSE_K ) { // transpose_op( cfg ); } } int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg ) { po::variables_map vm; int res = command_line( argc, argv, vm ); if( res ) { return res; } string config_file = vm[ CONFIG_K ].as< string >(); if( config_file.empty() ) { res = transform( vm, cfg ); } else { boost::property_tree::read_json( config_file, cfg ); } return res; } int command_line( int argc, char ** argv, po::variables_map & vm ) { po::options_description gen( "General" ); gen.add_options() ((HELP_K + ",h").c_str(), "Print this" ) ; po::options_description io_params("I/O Parameters"); io_params.add_options() ( (CONFIG_K + ",c" ).c_str(), po::value< string >()->default_value(""), "Configuration file containing files to be parsed" ) ; po::options_description cmdline; cmdline.add( gen ).add( io_params ); po::store( po::command_line_parser( argc, argv ).options(cmdline).run(), vm ); if( vm.count( HELP_K ) ) { std::cout << cmdline << std::endl; return 1; } return 0; } int transform( po::variables_map & vm, boost::property_tree::ptree & p ) { return 0; } void select_op( boost::property_tree::ptree & params ) { string frmt = params.get< string >( OUTPUT_FORMAT_K, "" ); string output = params.get< string >( OUTPUT_PREFIX_K, "" ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { // string tmp = tmp_path + "." + k; // results.add_child( k, infile.get_child( k ) ); // if( boost::iequals( frmt, JSON_K ) ) { write_json( output, infile.get_child(k) ); } else if( boost::iequals( frmt, GNUPLOT_K ) ) { write_gnuplot( output, k, infile.get_child(k) ); } } } } } } /* void combine_op_json( boost::property_tree::ptree & params ) { boost::property_tree::ptree results; assert( params.get_child_optional( INPUT_K ) != boost::none ); assert( params.get_child_optional( KEYS_K ) != boost::none ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { string tmp = tmp_path + "." + k; results.add_child( tmp, infile.get_child( k ) ); } } } } if( output.empty() ) { boost::property_tree::write_json(std::cout, results ); } else { boost::property_tree::write_json( output + "." + JSON_K, results ); } } void select_op_gnuplot( boost::property_tree::ptree & params ) { } void transpose_op( boost::property_tree::ptree & params ) { assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none ); string frmt = params.get< string >( OUTPUT_FORMAT_K, "" ); string output = params.get< string >( OUTPUT_PREFIX_K, "" ); if( boost::iequals( frmt, GNUPLOT_K ) ) { assert( params.get_child_optional( INPUT_K ) != boost::none ); assert( params.get_child_optional( KEYS_K ) != boost::none ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); typedef std::vector< string > row_type; typedef std::map< string, std::vector< row_type > > value_map_type; value_map_type data; if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { // string tmp = tmp_path + "." + k; value_map_type::iterator it = data.find( k ); if( it == data.end() ) { std::pair< value_map_type::iterator, bool > res = data.insert( std::make_pair(k, std::vector<row_type>() )); assert( res.second ); it = res.first; } unsigned int max_columns = 0; unsigned int j = 0; BOOST_FOREACH( auto& dval, infile.get_child(k) ) { unsigned int i = 0; row_type r; BOOST_FOREACH( auto& pval, dval.second ) { std::ostringstream oss; oss << pval.second.data(); r.push_back( oss.str() ); ++i; } if( i > max_columns ) { max_columns = i; } it->second.push_back(r); ++j; } } } } if( output.empty() ) { BOOST_FOREACH( auto& dval, data) { std::cout << "# " << dval.first << std::endl; unsigned int i = 0; BOOST_FOREACH( auto& r, dval.second ) { std::cout << i++; BOOST_FOREACH( auto& c, r ) { std::cout << "," << c; } std::cout << std::endl; } std::cout << std::endl; } } } } } void combine_op( boost::property_tree::ptree & params ) { assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none ); string frmt = params.get< string >( OUTPUT_FORMAT_K, "" ); string output = params.get< string >( OUTPUT_PREFIX_K, "" ); if( boost::iequals( frmt, JSON_K ) ) { boost::property_tree::ptree results; assert( params.get_child_optional( INPUT_K ) != boost::none ); assert( params.get_child_optional( KEYS_K ) != boost::none ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { string tmp = tmp_path + "." + k; results.add_child( tmp, infile.get_child( k ) ); } } } } } }*/ void write_json( const string & path, boost::property_tree::ptree & results ) { if( path.empty() ) { boost::property_tree::write_json( std::cout, results ); } else { boost::property_tree::write_json( path + "." + JSON_K, results ); } } /* void write( ostream * out, boost::property_tree::ptree::value_type & node ) { if( node.first.empty() ) { (*out) << "\n"; BOOST_FOREACH( auto & pval, node.second ) { std::ostringstream oss; oss << pval.second.data(); (*out) << oss.str() << ","; } } else { (*out) << "." << node.first; BOOST_FOREACH( auto& c, node.second ) { write( out, c ); (*out) << "\n"; } } }*/ void write_data( ostream * out, boost::property_tree::ptree & data ) { unsigned int i = 0; BOOST_FOREACH( auto& c, data ) { if( c.second.empty() ) { std::ostringstream oss; oss << c.second.data(); (*out) << "," << oss.str(); } else { (*out) << ++i; write_data( out, c.second); (*out) << "\n"; } } } void write( ostream * out, string path, boost::property_tree::ptree & tr ) { unsigned int i = 0; BOOST_FOREACH( auto& c, tr ) { if( c.first.empty() ) { (*out) << ++i; write_data(out, c.second); (*out) << "\n"; } else { write( out, path + "." + c.first, c.second ); } } } void write_gnuplot( const string & path, const string & header, boost::property_tree::ptree & results ) { ostream * out; if( path.empty() ) { out = &std::cout; } else { out = new ofstream(path + ".dat"); } (*out) << "# " << header << "\n"; write(out, "", results ); if( out != &std::cout ) { ((ofstream *)out)->close(); } } <commit_msg>Added case for empty node<commit_after>#include <iostream> #include <string> #include <vector> #include <map> #include <cassert> #include <sstream> #include <algorithm> #include <fstream> #include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <boost/algorithm/string.hpp> using std::string; using std::ostream; using std::ofstream; namespace po=boost::program_options; const string HELP_K = "help"; const string CONFIG_K = "config"; const string INPUT_K = "input"; const string OUTPUT_K = "output"; const string OPERATION_K = "operation"; const string SELECT_K = "select"; const string SPLIT_K = "split"; const string TRANSPOSE_K = "transpose"; const string COMBINE_K = "combine"; const string FORMAT_K = "format"; const string PREFIX_K = "prefix"; const string VALUE_K = "value"; const string KEYS_K = "keys"; const string JSON_K = "json"; const string GNUPLOT_K = "gnuplot"; const string OUTPUT_FORMAT_K = OUTPUT_K + "." + FORMAT_K; const string OUTPUT_PREFIX_K = OUTPUT_K + "." + PREFIX_K; const string INPUT_VALUE_K = INPUT_K + "." + VALUE_K; int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg ); int command_line( int argc, char ** argv, po::variables_map & vm ); int transform( po::variables_map & vm, boost::property_tree::ptree & p ); void parse_data( boost::property_tree::ptree & cfg ); typedef void (*parser_op)( boost::property_tree::ptree & parameters ); // select keys from each input file into a void select_op( boost::property_tree::ptree & parameters ); void select_op_gnuplot( boost::property_tree::ptree & params ); // combine all keys from each input file into a single output file void combine_op( boost::property_tree::ptree & parameters ); void combine_op_json( boost::property_tree::ptree & parameters ); void transpose_op( boost::property_tree::ptree & params ); void write_json( const std::string & path, boost::property_tree::ptree & results ); void write_gnuplot( const std::string & path, const std::string & header, boost::property_tree::ptree & results ); int main( int argc, char ** argv ) { boost::property_tree::ptree cfg; int res = 0; if( (res = parse_configuration( argc, argv, cfg )) ) { return res; } BOOST_FOREACH( auto& c, cfg ) { std::cerr << c.first << std::endl; parse_data( c.second ); } } void parse_data( boost::property_tree::ptree & cfg ) { string op = cfg.get< string >( OPERATION_K, ""); if( op.empty() ) return; if( op == SELECT_K ) { select_op( cfg ); } else if ( op == COMBINE_K ) { // combine_op( cfg ); } else if( op == TRANSPOSE_K ) { // transpose_op( cfg ); } } int parse_configuration( int argc, char ** argv, boost::property_tree::ptree & cfg ) { po::variables_map vm; int res = command_line( argc, argv, vm ); if( res ) { return res; } string config_file = vm[ CONFIG_K ].as< string >(); if( config_file.empty() ) { res = transform( vm, cfg ); } else { boost::property_tree::read_json( config_file, cfg ); } return res; } int command_line( int argc, char ** argv, po::variables_map & vm ) { po::options_description gen( "General" ); gen.add_options() ((HELP_K + ",h").c_str(), "Print this" ) ; po::options_description io_params("I/O Parameters"); io_params.add_options() ( (CONFIG_K + ",c" ).c_str(), po::value< string >()->default_value(""), "Configuration file containing files to be parsed" ) ; po::options_description cmdline; cmdline.add( gen ).add( io_params ); po::store( po::command_line_parser( argc, argv ).options(cmdline).run(), vm ); if( vm.count( HELP_K ) ) { std::cout << cmdline << std::endl; return 1; } return 0; } int transform( po::variables_map & vm, boost::property_tree::ptree & p ) { return 0; } void select_op( boost::property_tree::ptree & params ) { string frmt = params.get< string >( OUTPUT_FORMAT_K, "" ); string output = params.get< string >( OUTPUT_PREFIX_K, "" ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { // string tmp = tmp_path + "." + k; // results.add_child( k, infile.get_child( k ) ); // if( boost::iequals( frmt, JSON_K ) ) { write_json( output, infile.get_child(k) ); } else if( boost::iequals( frmt, GNUPLOT_K ) ) { write_gnuplot( output, k, infile.get_child(k) ); } } } } } } /* void combine_op_json( boost::property_tree::ptree & params ) { boost::property_tree::ptree results; assert( params.get_child_optional( INPUT_K ) != boost::none ); assert( params.get_child_optional( KEYS_K ) != boost::none ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { string tmp = tmp_path + "." + k; results.add_child( tmp, infile.get_child( k ) ); } } } } if( output.empty() ) { boost::property_tree::write_json(std::cout, results ); } else { boost::property_tree::write_json( output + "." + JSON_K, results ); } } void select_op_gnuplot( boost::property_tree::ptree & params ) { } void transpose_op( boost::property_tree::ptree & params ) { assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none ); string frmt = params.get< string >( OUTPUT_FORMAT_K, "" ); string output = params.get< string >( OUTPUT_PREFIX_K, "" ); if( boost::iequals( frmt, GNUPLOT_K ) ) { assert( params.get_child_optional( INPUT_K ) != boost::none ); assert( params.get_child_optional( KEYS_K ) != boost::none ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); typedef std::vector< string > row_type; typedef std::map< string, std::vector< row_type > > value_map_type; value_map_type data; if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { // string tmp = tmp_path + "." + k; value_map_type::iterator it = data.find( k ); if( it == data.end() ) { std::pair< value_map_type::iterator, bool > res = data.insert( std::make_pair(k, std::vector<row_type>() )); assert( res.second ); it = res.first; } unsigned int max_columns = 0; unsigned int j = 0; BOOST_FOREACH( auto& dval, infile.get_child(k) ) { unsigned int i = 0; row_type r; BOOST_FOREACH( auto& pval, dval.second ) { std::ostringstream oss; oss << pval.second.data(); r.push_back( oss.str() ); ++i; } if( i > max_columns ) { max_columns = i; } it->second.push_back(r); ++j; } } } } if( output.empty() ) { BOOST_FOREACH( auto& dval, data) { std::cout << "# " << dval.first << std::endl; unsigned int i = 0; BOOST_FOREACH( auto& r, dval.second ) { std::cout << i++; BOOST_FOREACH( auto& c, r ) { std::cout << "," << c; } std::cout << std::endl; } std::cout << std::endl; } } } } } void combine_op( boost::property_tree::ptree & params ) { assert( params.get_child_optional( OUTPUT_FORMAT_K ) != boost::none ); string frmt = params.get< string >( OUTPUT_FORMAT_K, "" ); string output = params.get< string >( OUTPUT_PREFIX_K, "" ); if( boost::iequals( frmt, JSON_K ) ) { boost::property_tree::ptree results; assert( params.get_child_optional( INPUT_K ) != boost::none ); assert( params.get_child_optional( KEYS_K ) != boost::none ); std::vector< string > keys; BOOST_FOREACH( auto& v, params.get_child( KEYS_K ) ) { std::ostringstream oss; oss << v.second.data(); keys.push_back( oss.str() ); } BOOST_FOREACH( auto& v, params.get_child( INPUT_K ) ) { std::ostringstream oss; oss << v.second.data(); string path = oss.str(); if( boost::algorithm::iends_with(path, "." + JSON_K) ) { std::cerr << "Parsing input JSON file: " << path << std::endl; string tmp_path = path.substr(0, path.size() - (JSON_K.size() + 1)); boost::property_tree::ptree infile; boost::property_tree::read_json( path, infile ); BOOST_FOREACH( auto& k, keys ) { if( infile.get_child_optional( k ) != boost::none ) { string tmp = tmp_path + "." + k; results.add_child( tmp, infile.get_child( k ) ); } } } } } }*/ void write_json( const string & path, boost::property_tree::ptree & results ) { if( path.empty() ) { boost::property_tree::write_json( std::cout, results ); } else { boost::property_tree::write_json( path + "." + JSON_K, results ); } } /* void write( ostream * out, boost::property_tree::ptree::value_type & node ) { if( node.first.empty() ) { (*out) << "\n"; BOOST_FOREACH( auto & pval, node.second ) { std::ostringstream oss; oss << pval.second.data(); (*out) << oss.str() << ","; } } else { (*out) << "." << node.first; BOOST_FOREACH( auto& c, node.second ) { write( out, c ); (*out) << "\n"; } } }*/ void write_data( ostream * out, boost::property_tree::ptree & data ) { unsigned int i = 0; if( data.empty() ) { (*out) << i << "," << data.data() << "\n"; } else { BOOST_FOREACH( auto& c, data ) { if( c.second.empty() ) { (*out) << "," << c.second.data(); } else { (*out) << ++i; write_data( out, c.second); (*out) << "\n"; } } } } void write( ostream * out, string path, boost::property_tree::ptree & tr ) { unsigned int i = 0; if( tr.empty() ) { (*out) << ++i << "," << tr.data() << "\n"; } else { BOOST_FOREACH( auto& c, tr ) { if( c.first.empty() ) { (*out) << ++i; write_data(out, c.second); (*out) << "\n"; } else { write( out, path + "." + c.first, c.second ); } } } } void write_gnuplot( const string & path, const string & header, boost::property_tree::ptree & results ) { ostream * out; if( path.empty() ) { out = &std::cout; } else { out = new ofstream(path + ".dat"); } (*out) << "# " << header << "\n"; write(out, "", results ); if( out != &std::cout ) { ((ofstream *)out)->close(); } } <|endoftext|>
<commit_before>/* * This file is part of signon * * Copyright (C) 2010 Nokia Corporation. * * Contact: Alberto Mardegan <[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. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "timeouts.h" #include <QDBusConnection> #include <QDBusMessage> #include <QDBusObjectPath> #include <QDebug> #include <signond/signoncommon.h> using namespace SignOn; /* * test timeout 20 seconds * */ #define test_timeout 20000 void TimeoutsTest::initTestCase() { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert(QLatin1String("SSO_IDENTITY_TIMEOUT"), QLatin1String("5")); daemonProcess = new QProcess(); daemonProcess->setProcessEnvironment(env); daemonProcess->start("signond"); daemonProcess->waitForStarted(10 * 1000); /* * 1 second is still required as the signon daemon needs time to be started * */ sleep(1); } void TimeoutsTest::cleanupTestCase() { daemonProcess->kill(); daemonProcess->waitForFinished(); delete daemonProcess; } void TimeoutsTest::init() { completed = false; } void TimeoutsTest::identityTimeout() { QEventLoop loop; QTimer::singleShot(test_timeout, &loop, SLOT(quit())); QObject::connect(this, SIGNAL(finished()), &loop, SLOT(quit())); QMap<MethodName,MechanismsList> methods; methods.insert("dummy", QStringList() << "mech1" << "mech2"); IdentityInfo info = IdentityInfo(QLatin1String("timeout test"), QLatin1String("timeout@test"), methods); Identity *identity = Identity::newIdentity(info); QVERIFY(identity != NULL); QObject::connect(identity, SIGNAL(credentialsStored(const quint32)), this, SLOT(credentialsStored(const quint32))); QObject::connect(identity, SIGNAL(error(Identity::IdentityError,const QString&)), this, SLOT(identityError(Identity::IdentityError,const QString&))); identity->storeCredentials(); loop.exec(); QVERIFY(identity->id() != SSO_NEW_IDENTITY); QDBusConnection conn = SIGNOND_BUS; QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE, "registerStoredIdentity"); QList<QVariant> args; args << identity->id(); msg.setArguments(args); QDBusMessage reply = conn.call(msg); QVERIFY(reply.type() == QDBusMessage::ReplyMessage); QDBusObjectPath objectPath = reply.arguments()[0].value<QDBusObjectPath>(); QString path = objectPath.path(); qDebug() << "Got path" << path; QVERIFY(!path.isEmpty()); bool success; QTest::qSleep(100); success = triggerDisposableCleanup(); QVERIFY(success); /* The identity object must exist now */ QVERIFY(identityAlive(path)); QTest::qSleep(6 * 1000); success = triggerDisposableCleanup(); QVERIFY(success); /* After SSO_IDENTITY_TIMEOUT seconds, the identity must have been * destroyed */ QVERIFY(!identityAlive(path)); } void TimeoutsTest::identityRegisterTwice() { QEventLoop loop; QTimer::singleShot(test_timeout, &loop, SLOT(quit())); QObject::connect(this, SIGNAL(finished()), &loop, SLOT(quit())); QMap<MethodName,MechanismsList> methods; methods.insert("dummy", QStringList() << "mech1" << "mech2"); IdentityInfo info = IdentityInfo(QLatin1String("timeout test"), QLatin1String("timeout@test"), methods); Identity *identity = Identity::newIdentity(info); QVERIFY(identity != NULL); QObject::connect(identity, SIGNAL(credentialsStored(const quint32)), this, SLOT(credentialsStored(const quint32))); QObject::connect(identity, SIGNAL(error(Identity::IdentityError,const QString&)), this, SLOT(identityError(Identity::IdentityError,const QString&))); identity->storeCredentials(); loop.exec(); QVERIFY(identity->id() != SSO_NEW_IDENTITY); QDBusConnection conn = SIGNOND_BUS; QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE, "registerStoredIdentity"); QList<QVariant> args; args << identity->id(); msg.setArguments(args); QDBusMessage reply = conn.call(msg); QVERIFY(reply.type() == QDBusMessage::ReplyMessage); QDBusObjectPath objectPath = reply.arguments()[0].value<QDBusObjectPath>(); QString path = objectPath.path(); qDebug() << "Got path" << path; QVERIFY(!path.isEmpty()); bool success; QTest::qSleep(100); success = triggerDisposableCleanup(); QVERIFY(success); /* The identity object must exist now */ QVERIFY(identityAlive(path)); QTest::qSleep(6 * 1000); /* now we register the same identity again. The expected behavior is that * the registration succeeds, possibly returning the same object path as * before. * This is to test a regression (NB#182914) which was happening because * signond was deleting the expired Identity immediately after returning * its object path to the client. */ reply = conn.call(msg); QVERIFY(reply.type() == QDBusMessage::ReplyMessage); objectPath = reply.arguments()[0].value<QDBusObjectPath>(); path = objectPath.path(); qDebug() << "Got path" << path; QVERIFY(!path.isEmpty()); QVERIFY(identityAlive(path)); } void TimeoutsTest::identityError(Identity::IdentityError code, const QString &message) { qDebug() << Q_FUNC_INFO << message; QFAIL("Unexpected error!"); emit finished(); Q_UNUSED(code); } bool TimeoutsTest::triggerDisposableCleanup() { QDBusConnection conn = SIGNOND_BUS; /* create a new identity just to trigger the cleanup of disposable * objects */ QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE, "registerNewIdentity"); QDBusMessage reply = conn.call(msg); return (reply.type() == QDBusMessage::ReplyMessage); } bool TimeoutsTest::identityAlive(const QString &path) { QDBusConnection conn = SIGNOND_BUS; QString interface = QLatin1String("com.nokia.SingleSignOn.Identity"); QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, path, interface, "queryInfo"); QDBusMessage reply = conn.call(msg); return (reply.type() == QDBusMessage::ReplyMessage); } void TimeoutsTest::credentialsStored(const quint32 id) { QVERIFY(id != 0); emit finished(); } void TimeoutsTest::runAllTests() { initTestCase(); init(); identityTimeout(); identityRegisterTwice(); cleanupTestCase(); } <commit_msg>Kill signond before starting it<commit_after>/* * This file is part of signon * * Copyright (C) 2010 Nokia Corporation. * * Contact: Alberto Mardegan <[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. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "timeouts.h" #include <QDBusConnection> #include <QDBusMessage> #include <QDBusObjectPath> #include <QDebug> #include <signond/signoncommon.h> using namespace SignOn; /* * test timeout 20 seconds * */ #define test_timeout 20000 void TimeoutsTest::initTestCase() { /* Kill any running instances of signond */ QProcess::execute("pkill -9 signond"); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert(QLatin1String("SSO_IDENTITY_TIMEOUT"), QLatin1String("5")); daemonProcess = new QProcess(); daemonProcess->setProcessEnvironment(env); daemonProcess->start("signond"); daemonProcess->waitForStarted(10 * 1000); /* * 1 second is still required as the signon daemon needs time to be started * */ sleep(1); } void TimeoutsTest::cleanupTestCase() { daemonProcess->kill(); daemonProcess->waitForFinished(); delete daemonProcess; } void TimeoutsTest::init() { completed = false; } void TimeoutsTest::identityTimeout() { QEventLoop loop; QTimer::singleShot(test_timeout, &loop, SLOT(quit())); QObject::connect(this, SIGNAL(finished()), &loop, SLOT(quit())); QMap<MethodName,MechanismsList> methods; methods.insert("dummy", QStringList() << "mech1" << "mech2"); IdentityInfo info = IdentityInfo(QLatin1String("timeout test"), QLatin1String("timeout@test"), methods); Identity *identity = Identity::newIdentity(info); QVERIFY(identity != NULL); QObject::connect(identity, SIGNAL(credentialsStored(const quint32)), this, SLOT(credentialsStored(const quint32))); QObject::connect(identity, SIGNAL(error(Identity::IdentityError,const QString&)), this, SLOT(identityError(Identity::IdentityError,const QString&))); identity->storeCredentials(); loop.exec(); QVERIFY(identity->id() != SSO_NEW_IDENTITY); QDBusConnection conn = SIGNOND_BUS; QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE, "registerStoredIdentity"); QList<QVariant> args; args << identity->id(); msg.setArguments(args); QDBusMessage reply = conn.call(msg); QVERIFY(reply.type() == QDBusMessage::ReplyMessage); QDBusObjectPath objectPath = reply.arguments()[0].value<QDBusObjectPath>(); QString path = objectPath.path(); qDebug() << "Got path" << path; QVERIFY(!path.isEmpty()); bool success; QTest::qSleep(100); success = triggerDisposableCleanup(); QVERIFY(success); /* The identity object must exist now */ QVERIFY(identityAlive(path)); QTest::qSleep(6 * 1000); success = triggerDisposableCleanup(); QVERIFY(success); /* After SSO_IDENTITY_TIMEOUT seconds, the identity must have been * destroyed */ QVERIFY(!identityAlive(path)); } void TimeoutsTest::identityRegisterTwice() { QEventLoop loop; QTimer::singleShot(test_timeout, &loop, SLOT(quit())); QObject::connect(this, SIGNAL(finished()), &loop, SLOT(quit())); QMap<MethodName,MechanismsList> methods; methods.insert("dummy", QStringList() << "mech1" << "mech2"); IdentityInfo info = IdentityInfo(QLatin1String("timeout test"), QLatin1String("timeout@test"), methods); Identity *identity = Identity::newIdentity(info); QVERIFY(identity != NULL); QObject::connect(identity, SIGNAL(credentialsStored(const quint32)), this, SLOT(credentialsStored(const quint32))); QObject::connect(identity, SIGNAL(error(Identity::IdentityError,const QString&)), this, SLOT(identityError(Identity::IdentityError,const QString&))); identity->storeCredentials(); loop.exec(); QVERIFY(identity->id() != SSO_NEW_IDENTITY); QDBusConnection conn = SIGNOND_BUS; QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE, "registerStoredIdentity"); QList<QVariant> args; args << identity->id(); msg.setArguments(args); QDBusMessage reply = conn.call(msg); QVERIFY(reply.type() == QDBusMessage::ReplyMessage); QDBusObjectPath objectPath = reply.arguments()[0].value<QDBusObjectPath>(); QString path = objectPath.path(); qDebug() << "Got path" << path; QVERIFY(!path.isEmpty()); bool success; QTest::qSleep(100); success = triggerDisposableCleanup(); QVERIFY(success); /* The identity object must exist now */ QVERIFY(identityAlive(path)); QTest::qSleep(6 * 1000); /* now we register the same identity again. The expected behavior is that * the registration succeeds, possibly returning the same object path as * before. * This is to test a regression (NB#182914) which was happening because * signond was deleting the expired Identity immediately after returning * its object path to the client. */ reply = conn.call(msg); QVERIFY(reply.type() == QDBusMessage::ReplyMessage); objectPath = reply.arguments()[0].value<QDBusObjectPath>(); path = objectPath.path(); qDebug() << "Got path" << path; QVERIFY(!path.isEmpty()); QVERIFY(identityAlive(path)); } void TimeoutsTest::identityError(Identity::IdentityError code, const QString &message) { qDebug() << Q_FUNC_INFO << message; QFAIL("Unexpected error!"); emit finished(); Q_UNUSED(code); } bool TimeoutsTest::triggerDisposableCleanup() { QDBusConnection conn = SIGNOND_BUS; /* create a new identity just to trigger the cleanup of disposable * objects */ QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, SIGNOND_DAEMON_OBJECTPATH, SIGNOND_DAEMON_INTERFACE, "registerNewIdentity"); QDBusMessage reply = conn.call(msg); return (reply.type() == QDBusMessage::ReplyMessage); } bool TimeoutsTest::identityAlive(const QString &path) { QDBusConnection conn = SIGNOND_BUS; QString interface = QLatin1String("com.nokia.SingleSignOn.Identity"); QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE, path, interface, "queryInfo"); QDBusMessage reply = conn.call(msg); return (reply.type() == QDBusMessage::ReplyMessage); } void TimeoutsTest::credentialsStored(const quint32 id) { QVERIFY(id != 0); emit finished(); } void TimeoutsTest::runAllTests() { initTestCase(); init(); identityTimeout(); identityRegisterTwice(); cleanupTestCase(); } <|endoftext|>
<commit_before>void AddTaskVZEROQA(Int_t runNumber) { // Creates a QA task exploiting simple symmetries phi, eta +/-, charge ... // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskQAsym", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTasQAsym", "This task requires an input event handler"); return NULL; } TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // Configure analysis //=========================================================================== AliAnaVZEROQA* task = new AliAnaVZEROQA("AliAnaVZEROQA"); mgr->AddTask(task); AliAnalysisDataContainer *cout = mgr->CreateContainer("QAVZEROHists",TList::Class(), AliAnalysisManager::kOutputContainer, Form("run%d_VZEROQA.root",runNumber)); mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (task, 1, cout); } <commit_msg>VZEROQA from library.<commit_after>AliAnalysisTaskSE* AddTaskVZEROQA(Int_t runNumber) { // Creates a QA task exploiting simple symmetries phi, eta +/-, charge ... // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskQAsym", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTasQAsym", "This task requires an input event handler"); return NULL; } TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // Configure analysis //=========================================================================== AliAnaVZEROQA* task = new AliAnaVZEROQA("AliAnaVZEROQA"); mgr->AddTask(task); AliAnalysisDataContainer *cout = mgr->CreateContainer("QAVZEROHists",TList::Class(), AliAnalysisManager::kOutputContainer, "VZERO.Performance.root"); mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (task, 1, cout); return task; } <|endoftext|>
<commit_before><commit_msg>Fix PrerenderInterceptor leaks.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM, Dennis Luxen, others 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. 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. */ #include "restriction_parser.hpp" #include "extraction_way.hpp" #include "scripting_environment.hpp" #include "../data_structures/external_memory_node.hpp" #include "../Util/lua_util.hpp" #include "../Util/osrm_exception.hpp" #include "../Util/simple_logger.hpp" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> #include <boost/ref.hpp> #include <boost/regex.hpp> namespace { int lua_error_callback(lua_State *lua_state) { luabind::object error_msg(luabind::from_stack(lua_state, -1)); std::ostringstream error_stream; error_stream << error_msg; throw osrm::exception("ERROR occured in profile script:\n" + error_stream.str()); } } RestrictionParser::RestrictionParser(lua_State *lua_state) : /*lua_state(scripting_environment.getLuaState()),*/ use_turn_restrictions(true) { ReadUseRestrictionsSetting(lua_state); if (use_turn_restrictions) { ReadRestrictionExceptions(lua_state); } } void RestrictionParser::ReadUseRestrictionsSetting(lua_State *lua_state) { if (0 == luaL_dostring(lua_state, "return use_turn_restrictions\n") && lua_isboolean(lua_state, -1)) { use_turn_restrictions = lua_toboolean(lua_state, -1); } if (use_turn_restrictions) { SimpleLogger().Write() << "Using turn restrictions"; } else { SimpleLogger().Write() << "Ignoring turn restrictions"; } } void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) { if (lua_function_exists(lua_state, "get_exceptions")) { luabind::set_pcall_callback(&lua_error_callback); // get list of turn restriction exceptions luabind::call_function<void>(lua_state, "get_exceptions", boost::ref(restriction_exceptions)); const unsigned exception_count = restriction_exceptions.size(); SimpleLogger().Write() << "Found " << exception_count << " exceptions to turn restrictions:"; for (const std::string &str : restriction_exceptions) { SimpleLogger().Write() << " " << str; } } else { SimpleLogger().Write() << "Found no exceptions to turn restrictions"; } } mapbox::util::optional<InputRestrictionContainer> RestrictionParser::TryParse(const osmium::Relation &relation) const { // return if turn restrictions should be ignored if (!use_turn_restrictions) { return mapbox::util::optional<InputRestrictionContainer>(); } osmium::tags::KeyPrefixFilter filter(false); filter.add(true, "restriction"); const osmium::TagList &tag_list = relation.tags(); osmium::tags::KeyPrefixFilter::iterator fi_begin(filter, tag_list.begin(), tag_list.end()); osmium::tags::KeyPrefixFilter::iterator fi_end(filter, tag_list.end(), tag_list.end()); // if it's a restriction, continue; if (std::distance(fi_begin, fi_end) == 0) { return mapbox::util::optional<InputRestrictionContainer>(); } // check if the restriction should be ignored const char *except = relation.get_value_by_key("except"); if (except != nullptr && ShouldIgnoreRestriction(except)) { return mapbox::util::optional<InputRestrictionContainer>(); } bool is_only_restriction = false; for (auto iter = fi_begin; iter != fi_end; ++iter) { if (std::string("restriction") == iter->key() || std::string("restriction::hgv") == iter->key()) { const std::string restriction_value(iter->value()); if (restriction_value.find("only_") == 0) { is_only_restriction = true; } } } InputRestrictionContainer restriction_container(is_only_restriction); for (const auto &member : relation.members()) { const char *role = member.role(); if (strcmp("from", role) != 0 && strcmp("to", role) != 0 && strcmp("via", role) != 0) { continue; } switch (member.type()) { case osmium::item_type::node: // Make sure nodes appear only in the role if a via node if (0 == strcmp("from", role) || 0 == strcmp("to", role)) { continue; } BOOST_ASSERT(0 == strcmp("via", role)); // set the via node id // SimpleLogger().Write() << "via: " << member.ref(); restriction_container.restriction.via.node = member.ref(); break; case osmium::item_type::way: BOOST_ASSERT(0 == strcmp("from", role) || 0 == strcmp("to", role) || 0 == strcmp("via", role)); if (0 == strcmp("from", role)) { // SimpleLogger().Write() << "from: " << member.ref(); restriction_container.restriction.from.way = member.ref(); } else if (0 == strcmp("to", role)) { // SimpleLogger().Write() << "to: " << member.ref(); restriction_container.restriction.to.way = member.ref(); } else if (0 == strcmp("via", role)) { // not yet suppported // restriction_container.restriction.via.way = member.ref(); } break; case osmium::item_type::relation: // not yet supported, but who knows what the future holds... continue; break; default: BOOST_ASSERT(false); break; } } // SimpleLogger().Write() << (restriction_container.restriction.flags.is_only ? "only" : "no") // << "-restriction " // << "<" << restriction_container.restriction.from.node << "->" // << restriction_container.restriction.via.node << "->" << // restriction_container.restriction.to.node // << ">"; return mapbox::util::optional<InputRestrictionContainer>(restriction_container); } bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_string) const { // should this restriction be ignored? yes if there's an overlap between: // a) the list of modes in the except tag of the restriction // (except_tag_string), eg: except=bus;bicycle // b) the lua profile defines a hierachy of modes, // eg: [access, vehicle, bicycle] if (except_tag_string.empty()) { return false; } // Be warned, this is quadratic work here, but we assume that // only a few exceptions are actually defined. std::vector<std::string> exceptions; boost::algorithm::split_regex(exceptions, except_tag_string, boost::regex("[;][ ]*")); for (std::string &current_string : exceptions) { const auto string_iterator = std::find(restriction_exceptions.begin(), restriction_exceptions.end(), current_string); if (restriction_exceptions.end() != string_iterator) { return true; } } return false; } <commit_msg>use std::any_of() algorithm instead of hand-rolled logic<commit_after>/* Copyright (c) 2015, Project OSRM, Dennis Luxen, others 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. 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. */ #include "restriction_parser.hpp" #include "extraction_way.hpp" #include "scripting_environment.hpp" #include "../data_structures/external_memory_node.hpp" #include "../Util/lua_util.hpp" #include "../Util/osrm_exception.hpp" #include "../Util/simple_logger.hpp" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> #include <boost/ref.hpp> #include <boost/regex.hpp> #include <algorithm> namespace { int lua_error_callback(lua_State *lua_state) { luabind::object error_msg(luabind::from_stack(lua_state, -1)); std::ostringstream error_stream; error_stream << error_msg; throw osrm::exception("ERROR occured in profile script:\n" + error_stream.str()); } } RestrictionParser::RestrictionParser(lua_State *lua_state) : /*lua_state(scripting_environment.getLuaState()),*/ use_turn_restrictions(true) { ReadUseRestrictionsSetting(lua_state); if (use_turn_restrictions) { ReadRestrictionExceptions(lua_state); } } void RestrictionParser::ReadUseRestrictionsSetting(lua_State *lua_state) { if (0 == luaL_dostring(lua_state, "return use_turn_restrictions\n") && lua_isboolean(lua_state, -1)) { use_turn_restrictions = lua_toboolean(lua_state, -1); } if (use_turn_restrictions) { SimpleLogger().Write() << "Using turn restrictions"; } else { SimpleLogger().Write() << "Ignoring turn restrictions"; } } void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) { if (lua_function_exists(lua_state, "get_exceptions")) { luabind::set_pcall_callback(&lua_error_callback); // get list of turn restriction exceptions luabind::call_function<void>(lua_state, "get_exceptions", boost::ref(restriction_exceptions)); const unsigned exception_count = restriction_exceptions.size(); SimpleLogger().Write() << "Found " << exception_count << " exceptions to turn restrictions:"; for (const std::string &str : restriction_exceptions) { SimpleLogger().Write() << " " << str; } } else { SimpleLogger().Write() << "Found no exceptions to turn restrictions"; } } mapbox::util::optional<InputRestrictionContainer> RestrictionParser::TryParse(const osmium::Relation &relation) const { // return if turn restrictions should be ignored if (!use_turn_restrictions) { return mapbox::util::optional<InputRestrictionContainer>(); } osmium::tags::KeyPrefixFilter filter(false); filter.add(true, "restriction"); const osmium::TagList &tag_list = relation.tags(); osmium::tags::KeyPrefixFilter::iterator fi_begin(filter, tag_list.begin(), tag_list.end()); osmium::tags::KeyPrefixFilter::iterator fi_end(filter, tag_list.end(), tag_list.end()); // if it's a restriction, continue; if (std::distance(fi_begin, fi_end) == 0) { return mapbox::util::optional<InputRestrictionContainer>(); } // check if the restriction should be ignored const char *except = relation.get_value_by_key("except"); if (except != nullptr && ShouldIgnoreRestriction(except)) { return mapbox::util::optional<InputRestrictionContainer>(); } bool is_only_restriction = false; for (auto iter = fi_begin; iter != fi_end; ++iter) { if (std::string("restriction") == iter->key() || std::string("restriction::hgv") == iter->key()) { const std::string restriction_value(iter->value()); if (restriction_value.find("only_") == 0) { is_only_restriction = true; } } } InputRestrictionContainer restriction_container(is_only_restriction); for (const auto &member : relation.members()) { const char *role = member.role(); if (strcmp("from", role) != 0 && strcmp("to", role) != 0 && strcmp("via", role) != 0) { continue; } switch (member.type()) { case osmium::item_type::node: // Make sure nodes appear only in the role if a via node if (0 == strcmp("from", role) || 0 == strcmp("to", role)) { continue; } BOOST_ASSERT(0 == strcmp("via", role)); // set the via node id // SimpleLogger().Write() << "via: " << member.ref(); restriction_container.restriction.via.node = member.ref(); break; case osmium::item_type::way: BOOST_ASSERT(0 == strcmp("from", role) || 0 == strcmp("to", role) || 0 == strcmp("via", role)); if (0 == strcmp("from", role)) { // SimpleLogger().Write() << "from: " << member.ref(); restriction_container.restriction.from.way = member.ref(); } else if (0 == strcmp("to", role)) { // SimpleLogger().Write() << "to: " << member.ref(); restriction_container.restriction.to.way = member.ref(); } else if (0 == strcmp("via", role)) { // not yet suppported // restriction_container.restriction.via.way = member.ref(); } break; case osmium::item_type::relation: // not yet supported, but who knows what the future holds... continue; break; default: BOOST_ASSERT(false); break; } } // SimpleLogger().Write() << (restriction_container.restriction.flags.is_only ? "only" : "no") // << "-restriction " // << "<" << restriction_container.restriction.from.node << "->" // << restriction_container.restriction.via.node << "->" << // restriction_container.restriction.to.node // << ">"; return mapbox::util::optional<InputRestrictionContainer>(restriction_container); } bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_string) const { // should this restriction be ignored? yes if there's an overlap between: // a) the list of modes in the except tag of the restriction // (except_tag_string), eg: except=bus;bicycle // b) the lua profile defines a hierachy of modes, // eg: [access, vehicle, bicycle] if (except_tag_string.empty()) { return false; } // Be warned, this is quadratic work here, but we assume that // only a few exceptions are actually defined. std::vector<std::string> exceptions; boost::algorithm::split_regex(exceptions, except_tag_string, boost::regex("[;][ ]*")); return std::any_of(std::begin(exceptions), std::end(exceptions), [&](const std::string &current_string) { if (restriction_exceptions.end() != std::find(restriction_exceptions.begin(), restriction_exceptions.end(), current_string)) { return true; } return false; }); } <|endoftext|>
<commit_before>// @(#)root/reflex:$Id$ // Author: Stefan Roiser 2004 // Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD # define REFLEX_BUILD #endif #include "Reflex/Kernel.h" #include "Reflex/Scope.h" #include "Reflex/internal/ScopeName.h" #include "Reflex/PropertyList.h" #include "Reflex/Type.h" #include "Reflex/Base.h" #include "Reflex/Member.h" #include "Reflex/Object.h" #include "Reflex/PropertyList.h" #include "Reflex/MemberTemplate.h" #include "Reflex/Any.h" #include "Fundamental.h" #include "Namespace.h" #include "Typedef.h" #include "Class.h" #include <typeinfo> namespace { // Helper to factor out common code class FundamentalDeclarator { public: FundamentalDeclarator(const char* name, size_t size, const std::type_info& ti, Reflex::REPRESTYPE repres) { Reflex::TypeBase* tb = new Reflex::TypeBase(name, size, Reflex::FUNDAMENTAL, ti, Reflex::Type(), repres); tb->Properties().AddProperty("Description", "fundamental type"); fType = tb->ThisType(); } FundamentalDeclarator& Typedef(const char* name) { new Reflex::Typedef(name, fType, Reflex::FUNDAMENTAL, fType); return *this; } private: Reflex::Type fType; }; // sizeof(void) doesn't work; we want it to return 0. // This template with the specialization does just that. template <typename T> struct GetSizeOf { size_t operator ()() const { return sizeof(T); } }; template <> struct GetSizeOf<void> { size_t operator ()() const { return 0; } }; // Helper function constructing the declarator template <typename T> FundamentalDeclarator DeclFundamental(const char* name, Reflex::REPRESTYPE repres) { return FundamentalDeclarator(name, GetSizeOf<T>() (), typeid(T), repres); } Reflex::Instance instantiate; } //------------------------------------------------------------------------------- Reflex::Instance* Reflex::Instance::fgSingleton = 0; bool Reflex::Instance::fgHasShutdown = false; //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- Reflex::Instance& Reflex::Instance::CreateReflexInstance() { //------------------------------------------------------------------------------- // Initialize the singleton. static Reflex::Instance instance((Reflex::Instance*) 0); return instance; } //------------------------------------------------------------------------------- Reflex::Instance::Instance() { //------------------------------------------------------------------------------- // Ensure that Reflex is properly initialized. CreateReflexInstance(); } //------------------------------------------------------------------------------- bool Reflex::Instance::HasShutdown() { //------------------------------------------------------------------------------- // Return true, if we shutdown Reflex (i.e. delete all the containers) return fgHasShutdown; } //------------------------------------------------------------------------------- Reflex::Instance::Instance(Instance*) { //------------------------------------------------------------------------------- // Initialisation of Reflex.Setup of global scope, fundamental types. fgSingleton = this; /** initialisation of the global namespace */ Namespace::GlobalScope(); // initialising fundamental types // char [3.9.1.1] DeclFundamental<char>("char", REPRES_CHAR); // signed integer types [3.9.1.2] DeclFundamental<signed char>("signed char", REPRES_SIGNED_CHAR); DeclFundamental<short int>("short int", REPRES_SHORT_INT) .Typedef("short") .Typedef("signed short") .Typedef("short signed") .Typedef("signed short int") .Typedef("short signed int"); DeclFundamental<int>("int", REPRES_INT) .Typedef("signed") .Typedef("signed int"); DeclFundamental<long int>("long int", REPRES_LONG_INT) .Typedef("long") .Typedef("signed long") .Typedef("long signed") .Typedef("signed long int") .Typedef("long signed int"); // unsigned integer types [3.9.1.3] DeclFundamental<unsigned char>("unsigned char", REPRES_UNSIGNED_CHAR); DeclFundamental<unsigned short int>("unsigned short int", REPRES_UNSIGNED_SHORT_INT) .Typedef("unsigned short") .Typedef("short unsigned int"); DeclFundamental<unsigned int>("unsigned int", REPRES_UNSIGNED_INT) .Typedef("unsigned"); DeclFundamental<unsigned long int>("unsigned long int", REPRES_UNSIGNED_LONG_INT) .Typedef("unsigned long") .Typedef("long unsigned") .Typedef("long unsigned int"); /* w_chart [3.9.1.5] DeclFundamental<w_chart>("w_chart", REPRES_WCHART); */ // bool [3.9.1.6] DeclFundamental<bool>("bool", REPRES_BOOL); // floating point types [3.9.1.8] DeclFundamental<float>("float", REPRES_FLOAT); DeclFundamental<double>("double", REPRES_DOUBLE); DeclFundamental<long double>("long double", REPRES_LONG_DOUBLE); // void [3.9.1.9] DeclFundamental<void>("void", REPRES_VOID); // Large integer definition depends of the platform #if defined(_WIN32) && !defined(__CINT__) typedef __int64 longlong; typedef unsigned __int64 ulonglong; #else typedef long long int longlong; /* */ typedef unsigned long long int /**/ ulonglong; #endif // non fundamental types but also supported at initialisation DeclFundamental<longlong>("long long", REPRES_LONGLONG) .Typedef("long long int"); DeclFundamental<ulonglong>("unsigned long long", REPRES_ULONGLONG) .Typedef("long long unsigned") .Typedef("unsigned long long int") .Typedef("long long unsigned int"); } //------------------------------------------------------------------------------- void Reflex::Instance::Shutdown() { //------------------------------------------------------------------------------- // Function to be called at tear down of Reflex, removes all memory allocations. MemberTemplateName::CleanUp(); TypeTemplateName::CleanUp(); TypeName::CleanUp(); ScopeName::CleanUp(); fgHasShutdown = true; } //------------------------------------------------------------------------------- Reflex::Instance::~Instance() { //------------------------------------------------------------------------------- // Destructor. This will shutdown Reflex only if this instance is the 'main' // instance. if (fgSingleton == this) { Shutdown(); } } //------------------------------------------------------------------------------- const Reflex::StdString_Cont_Type_t& Reflex::Dummy::StdStringCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of std strings. return Get<StdString_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Type_Cont_Type_t& Reflex::Dummy::TypeCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Types. return Get<Type_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Base_Cont_Type_t& Reflex::Dummy::BaseCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Bases. return Get<Base_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Scope_Cont_Type_t& Reflex::Dummy::ScopeCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Scopes. return Get<Scope_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Object_Cont_Type_t& Reflex::Dummy::ObjectCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Objects. return Get<Object_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Member_Cont_Type_t& Reflex::Dummy::MemberCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Members. return Get<Member_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::TypeTemplate_Cont_Type_t& Reflex::Dummy::TypeTemplateCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of TypeTemplates. return Get<TypeTemplate_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::MemberTemplate_Cont_Type_t& Reflex::Dummy::MemberTemplateCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of MemberTemplates. return Get<MemberTemplate_Cont_Type_t>(); } //------------------------------------------------------------------------------- Reflex::Any& Reflex::Dummy::Any() { //------------------------------------------------------------------------------- // static wrapper for an empty Any object static Reflex::Any i; if (i) { i.Clear(); } return i; } //------------------------------------------------------------------------------- const Reflex::Object& Reflex::Dummy::Object() { //------------------------------------------------------------------------------- // static wrapper for an empty Object return Get<Reflex::Object>(); } //------------------------------------------------------------------------------- const Reflex::Type& Reflex::Dummy::Type() { //------------------------------------------------------------------------------- // static wrapper for an empty Type return Get<Reflex::Type>(); } //------------------------------------------------------------------------------- const Reflex::TypeTemplate& Reflex::Dummy::TypeTemplate() { //------------------------------------------------------------------------------- // static wrapper for an empty TypeTemplate return Get<Reflex::TypeTemplate>(); } //------------------------------------------------------------------------------- const Reflex::Base& Reflex::Dummy::Base() { //------------------------------------------------------------------------------- // static wrapper for an empty Base return Get<Reflex::Base>(); } //------------------------------------------------------------------------------- const Reflex::PropertyList& Reflex::Dummy::PropertyList() { //------------------------------------------------------------------------------- // static wrapper for an empty PropertyList return Get<Reflex::PropertyList>(); } //------------------------------------------------------------------------------- const Reflex::Member& Reflex::Dummy::Member() { //------------------------------------------------------------------------------- // static wrapper for an empty Member return Get<Reflex::Member>(); } //------------------------------------------------------------------------------- const Reflex::MemberTemplate& Reflex::Dummy::MemberTemplate() { //------------------------------------------------------------------------------- // static wrapper for an empty MemberTemplate return Get<Reflex::MemberTemplate>(); } //------------------------------------------------------------------------------- const Reflex::Scope& Reflex::Dummy::Scope() { //------------------------------------------------------------------------------- // static wrapper for an empty Scope return Get<Reflex::Scope>(); } //------------------------------------------------------------------------------- const std::string& Reflex::Argv0() { //------------------------------------------------------------------------------- // Return the name of the package. static std::string str = "REFLEX"; return str; } <commit_msg>Coding convention<commit_after>// @(#)root/reflex:$Id$ // Author: Stefan Roiser 2004 // Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD # define REFLEX_BUILD #endif #include "Reflex/Kernel.h" #include "Reflex/Scope.h" #include "Reflex/internal/ScopeName.h" #include "Reflex/PropertyList.h" #include "Reflex/Type.h" #include "Reflex/Base.h" #include "Reflex/Member.h" #include "Reflex/Object.h" #include "Reflex/PropertyList.h" #include "Reflex/MemberTemplate.h" #include "Reflex/Any.h" #include "Fundamental.h" #include "Namespace.h" #include "Typedef.h" #include "Class.h" #include <typeinfo> namespace { // Helper to factor out common code class TFundamentalDeclarator { public: TFundamentalDeclarator(const char* name, size_t size, const std::type_info& ti, Reflex::REPRESTYPE repres) { Reflex::TypeBase* tb = new Reflex::TypeBase(name, size, Reflex::FUNDAMENTAL, ti, Reflex::Type(), repres); tb->Properties().AddProperty("Description", "fundamental type"); fType = tb->ThisType(); } TFundamentalDeclarator& Typedef(const char* name) { new Reflex::Typedef(name, fType, Reflex::FUNDAMENTAL, fType); return *this; } private: Reflex::Type fType; }; // sizeof(void) doesn't work; we want it to return 0. // This template with the specialization does just that. template <typename T> struct GetSizeOf { size_t operator ()() const { return sizeof(T); } }; template <> struct GetSizeOf<void> { size_t operator ()() const { return 0; } }; // Helper function constructing the declarator template <typename T> TFundamentalDeclarator DeclFundamental(const char* name, Reflex::REPRESTYPE repres) { return TFundamentalDeclarator(name, GetSizeOf<T>() (), typeid(T), repres); } Reflex::Instance instantiate; } //------------------------------------------------------------------------------- Reflex::Instance* Reflex::Instance::fgSingleton = 0; bool Reflex::Instance::fgHasShutdown = false; //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- Reflex::Instance& Reflex::Instance::CreateReflexInstance() { //------------------------------------------------------------------------------- // Initialize the singleton. static Reflex::Instance instance((Reflex::Instance*) 0); return instance; } //------------------------------------------------------------------------------- Reflex::Instance::Instance() { //------------------------------------------------------------------------------- // Ensure that Reflex is properly initialized. CreateReflexInstance(); } //------------------------------------------------------------------------------- bool Reflex::Instance::HasShutdown() { //------------------------------------------------------------------------------- // Return true, if we shutdown Reflex (i.e. delete all the containers) return fgHasShutdown; } //------------------------------------------------------------------------------- Reflex::Instance::Instance(Instance*) { //------------------------------------------------------------------------------- // Initialisation of Reflex.Setup of global scope, fundamental types. fgSingleton = this; /** initialisation of the global namespace */ Namespace::GlobalScope(); // initialising fundamental types // char [3.9.1.1] DeclFundamental<char>("char", REPRES_CHAR); // signed integer types [3.9.1.2] DeclFundamental<signed char>("signed char", REPRES_SIGNED_CHAR); DeclFundamental<short int>("short int", REPRES_SHORT_INT) .Typedef("short") .Typedef("signed short") .Typedef("short signed") .Typedef("signed short int") .Typedef("short signed int"); DeclFundamental<int>("int", REPRES_INT) .Typedef("signed") .Typedef("signed int"); DeclFundamental<long int>("long int", REPRES_LONG_INT) .Typedef("long") .Typedef("signed long") .Typedef("long signed") .Typedef("signed long int") .Typedef("long signed int"); // unsigned integer types [3.9.1.3] DeclFundamental<unsigned char>("unsigned char", REPRES_UNSIGNED_CHAR); DeclFundamental<unsigned short int>("unsigned short int", REPRES_UNSIGNED_SHORT_INT) .Typedef("unsigned short") .Typedef("short unsigned int"); DeclFundamental<unsigned int>("unsigned int", REPRES_UNSIGNED_INT) .Typedef("unsigned"); DeclFundamental<unsigned long int>("unsigned long int", REPRES_UNSIGNED_LONG_INT) .Typedef("unsigned long") .Typedef("long unsigned") .Typedef("long unsigned int"); /* w_chart [3.9.1.5] DeclFundamental<w_chart>("w_chart", REPRES_WCHART); */ // bool [3.9.1.6] DeclFundamental<bool>("bool", REPRES_BOOL); // floating point types [3.9.1.8] DeclFundamental<float>("float", REPRES_FLOAT); DeclFundamental<double>("double", REPRES_DOUBLE); DeclFundamental<long double>("long double", REPRES_LONG_DOUBLE); // void [3.9.1.9] DeclFundamental<void>("void", REPRES_VOID); // Large integer definition depends of the platform #if defined(_WIN32) && !defined(__CINT__) typedef __int64 longlong; typedef unsigned __int64 ulonglong; #else typedef long long int longlong; /* */ typedef unsigned long long int /**/ ulonglong; #endif // non fundamental types but also supported at initialisation DeclFundamental<longlong>("long long", REPRES_LONGLONG) .Typedef("long long int"); DeclFundamental<ulonglong>("unsigned long long", REPRES_ULONGLONG) .Typedef("long long unsigned") .Typedef("unsigned long long int") .Typedef("long long unsigned int"); } //------------------------------------------------------------------------------- void Reflex::Instance::Shutdown() { //------------------------------------------------------------------------------- // Function to be called at tear down of Reflex, removes all memory allocations. MemberTemplateName::CleanUp(); TypeTemplateName::CleanUp(); TypeName::CleanUp(); ScopeName::CleanUp(); fgHasShutdown = true; } //------------------------------------------------------------------------------- Reflex::Instance::~Instance() { //------------------------------------------------------------------------------- // Destructor. This will shutdown Reflex only if this instance is the 'main' // instance. if (fgSingleton == this) { Shutdown(); } } //------------------------------------------------------------------------------- const Reflex::StdString_Cont_Type_t& Reflex::Dummy::StdStringCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of std strings. return Get<StdString_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Type_Cont_Type_t& Reflex::Dummy::TypeCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Types. return Get<Type_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Base_Cont_Type_t& Reflex::Dummy::BaseCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Bases. return Get<Base_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Scope_Cont_Type_t& Reflex::Dummy::ScopeCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Scopes. return Get<Scope_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Object_Cont_Type_t& Reflex::Dummy::ObjectCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Objects. return Get<Object_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::Member_Cont_Type_t& Reflex::Dummy::MemberCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of Members. return Get<Member_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::TypeTemplate_Cont_Type_t& Reflex::Dummy::TypeTemplateCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of TypeTemplates. return Get<TypeTemplate_Cont_Type_t>(); } //------------------------------------------------------------------------------- const Reflex::MemberTemplate_Cont_Type_t& Reflex::Dummy::MemberTemplateCont() { //------------------------------------------------------------------------------- // static wrapper for an empty container of MemberTemplates. return Get<MemberTemplate_Cont_Type_t>(); } //------------------------------------------------------------------------------- Reflex::Any& Reflex::Dummy::Any() { //------------------------------------------------------------------------------- // static wrapper for an empty Any object static Reflex::Any i; if (i) { i.Clear(); } return i; } //------------------------------------------------------------------------------- const Reflex::Object& Reflex::Dummy::Object() { //------------------------------------------------------------------------------- // static wrapper for an empty Object return Get<Reflex::Object>(); } //------------------------------------------------------------------------------- const Reflex::Type& Reflex::Dummy::Type() { //------------------------------------------------------------------------------- // static wrapper for an empty Type return Get<Reflex::Type>(); } //------------------------------------------------------------------------------- const Reflex::TypeTemplate& Reflex::Dummy::TypeTemplate() { //------------------------------------------------------------------------------- // static wrapper for an empty TypeTemplate return Get<Reflex::TypeTemplate>(); } //------------------------------------------------------------------------------- const Reflex::Base& Reflex::Dummy::Base() { //------------------------------------------------------------------------------- // static wrapper for an empty Base return Get<Reflex::Base>(); } //------------------------------------------------------------------------------- const Reflex::PropertyList& Reflex::Dummy::PropertyList() { //------------------------------------------------------------------------------- // static wrapper for an empty PropertyList return Get<Reflex::PropertyList>(); } //------------------------------------------------------------------------------- const Reflex::Member& Reflex::Dummy::Member() { //------------------------------------------------------------------------------- // static wrapper for an empty Member return Get<Reflex::Member>(); } //------------------------------------------------------------------------------- const Reflex::MemberTemplate& Reflex::Dummy::MemberTemplate() { //------------------------------------------------------------------------------- // static wrapper for an empty MemberTemplate return Get<Reflex::MemberTemplate>(); } //------------------------------------------------------------------------------- const Reflex::Scope& Reflex::Dummy::Scope() { //------------------------------------------------------------------------------- // static wrapper for an empty Scope return Get<Reflex::Scope>(); } //------------------------------------------------------------------------------- const std::string& Reflex::Argv0() { //------------------------------------------------------------------------------- // Return the name of the package. static std::string str = "REFLEX"; return str; } <|endoftext|>
<commit_before>/** * @file metric_test.cpp * * Unit tests for the 'LMetric' class. */ #include <mlpack/core.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace std; using namespace mlpack::metric; BOOST_AUTO_TEST_SUITE(LMetricTest); BOOST_AUTO_TEST_CASE(L1MetricTest) { arma::vec a1(5); a1.randn(); arma::vec b1(5); b1.randn(); arma::Col<size_t> a2(5); a2 << 1 << 2 << 1 << 0 << 5; arma::Col<size_t> b2(5); b2 << 2 << 5 << 2 << 0 << 1; ManhattanDistance lMetric; BOOST_REQUIRE_CLOSE((double) arma::sum(arma::abs(a1 - b1)), lMetric.Evaluate(a1, b1), 1e-5); BOOST_REQUIRE_CLOSE((double) arma::sum(arma::abs(a2 - b2)), lMetric.Evaluate(a2, b2), 1e-5); } BOOST_AUTO_TEST_CASE(L2MetricTest) { arma::vec a1(5); a1.randn(); arma::vec b1(5); b1.randn(); arma::Col<size_t> a2(5); a2 << 1 << 2 << 1 << 0 << 5; arma::Col<size_t> b2(5); b2 << 2 << 5 << 2 << 0 << 1; EuclideanDistance lMetric; BOOST_REQUIRE_CLOSE((double) sqrt(arma::sum(arma::square(a1 - b1))), lMetric.Evaluate(a1, b1), 1e-5); BOOST_REQUIRE_CLOSE((double) sqrt(arma::sum(arma::square(a2 - b2))), lMetric.Evaluate(a2, b2), 1e-5); } BOOST_AUTO_TEST_CASE(LINFMetricTest) { arma::vec a1(5); a1.randn(); arma::vec b1(5); b1.randn(); arma::Col<size_t> a2(5); a2 << 1 << 2 << 1 << 0 << 5; arma::Col<size_t> b2(5); b2 << 2 << 5 << 2 << 0 << 1; EuclideanDistance lMetric; BOOST_REQUIRE_CLOSE((double) arma::max(arma::abs(a1 - b1)), lMetric.Evaluate(a1, b1), 1e-5); BOOST_REQUIRE_CLOSE((double) arma::max(arma::abs(a2 - b2)), lMetric.Evaluate(a2, b2), 1e-5); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>metric_test.cpp -- arma::sum changed to arma::accu; LINFMetricTest corrected.<commit_after>/** * @file metric_test.cpp * * Unit tests for the 'LMetric' class. */ #include <mlpack/core.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace std; using namespace mlpack::metric; BOOST_AUTO_TEST_SUITE(LMetricTest); BOOST_AUTO_TEST_CASE(L1MetricTest) { arma::vec a1(5); a1.randn(); arma::vec b1(5); b1.randn(); arma::Col<size_t> a2(5); a2 << 1 << 2 << 1 << 0 << 5; arma::Col<size_t> b2(5); b2 << 2 << 5 << 2 << 0 << 1; ManhattanDistance lMetric; BOOST_REQUIRE_CLOSE((double) arma::accu(arma::abs(a1 - b1)), lMetric.Evaluate(a1, b1), 1e-5); BOOST_REQUIRE_CLOSE((double) arma::accu(arma::abs(a2 - b2)), lMetric.Evaluate(a2, b2), 1e-5); } BOOST_AUTO_TEST_CASE(L2MetricTest) { arma::vec a1(5); a1.randn(); arma::vec b1(5); b1.randn(); arma::Col<size_t> a2(5); a2 << 1 << 2 << 1 << 0 << 5; arma::Col<size_t> b2(5); b2 << 2 << 5 << 2 << 0 << 1; EuclideanDistance lMetric; BOOST_REQUIRE_CLOSE((double) sqrt(arma::accu(arma::square(a1 - b1))), lMetric.Evaluate(a1, b1), 1e-5); BOOST_REQUIRE_CLOSE((double) sqrt(arma::accu(arma::square(a2 - b2))), lMetric.Evaluate(a2, b2), 1e-5); } BOOST_AUTO_TEST_CASE(LINFMetricTest) { arma::vec a1(5); a1.randn(); arma::vec b1(5); b1.randn(); arma::Col<size_t> a2(5); a2 << 1 << 2 << 1 << 0 << 5; arma::Col<size_t> b2(5); b2 << 2 << 5 << 2 << 0 << 1; ChebyshevDistance lMetric; BOOST_REQUIRE_CLOSE((double) arma::max(arma::abs(a1 - b1)), lMetric.Evaluate(a1, b1), 1e-5); BOOST_REQUIRE_CLOSE((double) arma::max(arma::abs(a2 - b2)), lMetric.Evaluate(a2, b2), 1e-5); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: loadlisteneradapter.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-25 16:03:02 $ * * 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 EXPRESS 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 EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX #include "loadlisteneradapter.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif //......................................................................... namespace bib { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::form; //===================================================================== //= OComponentListener //===================================================================== //--------------------------------------------------------------------- OComponentListener::~OComponentListener() { { ::osl::MutexGuard aGuard( m_rMutex ); if ( m_pAdapter ) m_pAdapter->dispose(); } } //--------------------------------------------------------------------- void OComponentListener::_disposing( const EventObject& _rSource ) throw( RuntimeException) { // nothing to do here, overrride if you're interested in } //--------------------------------------------------------------------- void OComponentListener::setAdapter( OComponentAdapterBase* pAdapter ) { { ::osl::MutexGuard aGuard( m_rMutex ); if ( m_pAdapter ) { m_pAdapter->release(); m_pAdapter = NULL; } } if ( pAdapter ) { ::osl::MutexGuard aGuard( m_rMutex ); m_pAdapter = pAdapter; m_pAdapter->acquire(); } } //===================================================================== //= OComponentAdapterBase //===================================================================== //--------------------------------------------------------------------- OComponentAdapterBase::OComponentAdapterBase( const Reference< XComponent >& _rxComp, sal_Bool _bAutoRelease ) :m_xComponent( _rxComp ) ,m_pListener( NULL ) ,m_nLockCount( 0 ) ,m_bListening( sal_False ) ,m_bAutoRelease( _bAutoRelease ) { OSL_ENSURE( m_xComponent.is(), "OComponentAdapterBase::OComponentAdapterBase: invalid component!" ); } //--------------------------------------------------------------------- void OComponentAdapterBase::Init( OComponentListener* _pListener ) { OSL_ENSURE( !m_pListener, "OComponentAdapterBase::Init: already initialized!" ); OSL_ENSURE( _pListener, "OComponentAdapterBase::Init: invalid listener!" ); m_pListener = _pListener; if ( m_pListener ) m_pListener->setAdapter( this ); startComponentListening( ); m_bListening = sal_True; } //--------------------------------------------------------------------- OComponentAdapterBase::~OComponentAdapterBase() { } //--------------------------------------------------------------------- void OComponentAdapterBase::lock() { ++m_nLockCount; } //--------------------------------------------------------------------- void OComponentAdapterBase::unlock() { --m_nLockCount; } //--------------------------------------------------------------------- void OComponentAdapterBase::dispose() { if ( m_bListening ) { ::vos::ORef< OComponentAdapterBase > xPreventDelete(this); disposing(); m_pListener->setAdapter(NULL); m_pListener = NULL; m_bListening = sal_False; if (m_bAutoRelease) m_xComponent = NULL; } } // XEventListener //--------------------------------------------------------------------- void OComponentAdapterBase::disposing() { // nothing to do here } //--------------------------------------------------------------------- void SAL_CALL OComponentAdapterBase::disposing( const EventObject& _rSource ) throw( RuntimeException ) { if ( m_pListener ) { // tell the listener if ( !locked() ) m_pListener->_disposing( _rSource ); // disconnect the listener if ( m_pListener ) // may have been reset whilest calling into _disposing m_pListener->setAdapter( NULL ); } m_pListener = NULL; m_bListening = sal_False; if ( m_bAutoRelease ) m_xComponent = NULL; } //===================================================================== //= OLoadListenerAdapter //===================================================================== //--------------------------------------------------------------------- OLoadListenerAdapter::OLoadListenerAdapter( const Reference< XLoadable >& _rxLoadable, sal_Bool _bAutoRelease ) :OComponentAdapterBase( Reference< XComponent >( _rxLoadable, UNO_QUERY ), _bAutoRelease ) { } //--------------------------------------------------------------------- void OLoadListenerAdapter::startComponentListening() { Reference< XLoadable > xLoadable( getComponent(), UNO_QUERY ); OSL_ENSURE( xLoadable.is(), "OLoadListenerAdapter::OLoadListenerAdapter: invalid object!" ); if ( xLoadable.is() ) xLoadable->addLoadListener( this ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::acquire( ) throw () { OLoadListenerAdapter_Base::acquire(); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::release( ) throw () { OLoadListenerAdapter_Base::release(); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::disposing( const EventObject& _rSource ) throw( RuntimeException) { OComponentAdapterBase::disposing( _rSource ); } //--------------------------------------------------------------------- void OLoadListenerAdapter::disposing() { Reference< XLoadable > xLoadable( getComponent(), UNO_QUERY ); if ( xLoadable.is() ) xLoadable->removeLoadListener( this ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::loaded( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_loaded( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::unloading( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_unloading( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::unloaded( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_unloaded( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::reloading( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_reloading( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::reloaded( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_reloaded( _rEvent ); } //......................................................................... } // namespace bib //......................................................................... <commit_msg>INTEGRATION: CWS ooo19126 (1.2.504); FILE MERGED 2005/09/05 12:58:47 rt 1.2.504.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: loadlisteneradapter.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:19:07 $ * * 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 EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX #include "loadlisteneradapter.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif //......................................................................... namespace bib { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::form; //===================================================================== //= OComponentListener //===================================================================== //--------------------------------------------------------------------- OComponentListener::~OComponentListener() { { ::osl::MutexGuard aGuard( m_rMutex ); if ( m_pAdapter ) m_pAdapter->dispose(); } } //--------------------------------------------------------------------- void OComponentListener::_disposing( const EventObject& _rSource ) throw( RuntimeException) { // nothing to do here, overrride if you're interested in } //--------------------------------------------------------------------- void OComponentListener::setAdapter( OComponentAdapterBase* pAdapter ) { { ::osl::MutexGuard aGuard( m_rMutex ); if ( m_pAdapter ) { m_pAdapter->release(); m_pAdapter = NULL; } } if ( pAdapter ) { ::osl::MutexGuard aGuard( m_rMutex ); m_pAdapter = pAdapter; m_pAdapter->acquire(); } } //===================================================================== //= OComponentAdapterBase //===================================================================== //--------------------------------------------------------------------- OComponentAdapterBase::OComponentAdapterBase( const Reference< XComponent >& _rxComp, sal_Bool _bAutoRelease ) :m_xComponent( _rxComp ) ,m_pListener( NULL ) ,m_nLockCount( 0 ) ,m_bListening( sal_False ) ,m_bAutoRelease( _bAutoRelease ) { OSL_ENSURE( m_xComponent.is(), "OComponentAdapterBase::OComponentAdapterBase: invalid component!" ); } //--------------------------------------------------------------------- void OComponentAdapterBase::Init( OComponentListener* _pListener ) { OSL_ENSURE( !m_pListener, "OComponentAdapterBase::Init: already initialized!" ); OSL_ENSURE( _pListener, "OComponentAdapterBase::Init: invalid listener!" ); m_pListener = _pListener; if ( m_pListener ) m_pListener->setAdapter( this ); startComponentListening( ); m_bListening = sal_True; } //--------------------------------------------------------------------- OComponentAdapterBase::~OComponentAdapterBase() { } //--------------------------------------------------------------------- void OComponentAdapterBase::lock() { ++m_nLockCount; } //--------------------------------------------------------------------- void OComponentAdapterBase::unlock() { --m_nLockCount; } //--------------------------------------------------------------------- void OComponentAdapterBase::dispose() { if ( m_bListening ) { ::vos::ORef< OComponentAdapterBase > xPreventDelete(this); disposing(); m_pListener->setAdapter(NULL); m_pListener = NULL; m_bListening = sal_False; if (m_bAutoRelease) m_xComponent = NULL; } } // XEventListener //--------------------------------------------------------------------- void OComponentAdapterBase::disposing() { // nothing to do here } //--------------------------------------------------------------------- void SAL_CALL OComponentAdapterBase::disposing( const EventObject& _rSource ) throw( RuntimeException ) { if ( m_pListener ) { // tell the listener if ( !locked() ) m_pListener->_disposing( _rSource ); // disconnect the listener if ( m_pListener ) // may have been reset whilest calling into _disposing m_pListener->setAdapter( NULL ); } m_pListener = NULL; m_bListening = sal_False; if ( m_bAutoRelease ) m_xComponent = NULL; } //===================================================================== //= OLoadListenerAdapter //===================================================================== //--------------------------------------------------------------------- OLoadListenerAdapter::OLoadListenerAdapter( const Reference< XLoadable >& _rxLoadable, sal_Bool _bAutoRelease ) :OComponentAdapterBase( Reference< XComponent >( _rxLoadable, UNO_QUERY ), _bAutoRelease ) { } //--------------------------------------------------------------------- void OLoadListenerAdapter::startComponentListening() { Reference< XLoadable > xLoadable( getComponent(), UNO_QUERY ); OSL_ENSURE( xLoadable.is(), "OLoadListenerAdapter::OLoadListenerAdapter: invalid object!" ); if ( xLoadable.is() ) xLoadable->addLoadListener( this ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::acquire( ) throw () { OLoadListenerAdapter_Base::acquire(); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::release( ) throw () { OLoadListenerAdapter_Base::release(); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::disposing( const EventObject& _rSource ) throw( RuntimeException) { OComponentAdapterBase::disposing( _rSource ); } //--------------------------------------------------------------------- void OLoadListenerAdapter::disposing() { Reference< XLoadable > xLoadable( getComponent(), UNO_QUERY ); if ( xLoadable.is() ) xLoadable->removeLoadListener( this ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::loaded( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_loaded( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::unloading( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_unloading( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::unloaded( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_unloaded( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::reloading( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_reloading( _rEvent ); } //--------------------------------------------------------------------- void SAL_CALL OLoadListenerAdapter::reloaded( const EventObject& _rEvent ) throw (RuntimeException) { if ( !locked() && getLoadListener( ) ) getLoadListener( )->_reloaded( _rEvent ); } //......................................................................... } // namespace bib //......................................................................... <|endoftext|>
<commit_before>// INCOMPLETE SAMPLE - USE AT YOUR OWN PERIL #include <sstream> #include <string> #include "clang/AST/AST.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "clang/Rewrite/Core/Rewriter.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; static llvm::cl::OptionCategory ToolingSampleCategory("Tooling Sample"); class IfStmtHandler : public MatchFinder::MatchCallback { public: IfStmtHandler(Replacements *Replace) : Replace(Replace) {} virtual void run(const MatchFinder::MatchResult &Result) { if (const IfStmt *FS = Result.Nodes.getNodeAs<clang::IfStmt>("ifStmt")) FS->dump(); } private: Replacements *Replace; }; class FuncDefHandler : public MatchFinder::MatchCallback { public: FuncDefHandler(Replacements *Replace) : Replace(Replace) {} virtual void run(const MatchFinder::MatchResult &Result) { if (const FunctionDecl *FS = Result.Nodes.getNodeAs<clang::FunctionDecl>("funcDef")) FS->dump(); } private: Replacements *Replace; }; int main(int argc, const char **argv) { CommonOptionsParser op(argc, argv, ToolingSampleCategory); RefactoringTool Tool(op.getCompilations(), op.getSourcePathList()); IfStmtHandler HandlerForIf(&Tool.getReplacements()); FuncDefHandler HandlerForFuncDef(&Tool.getReplacements()); MatchFinder Finder; Finder.addMatcher(ifStmt().bind("ifStmt"), &HandlerForIf); Finder.addMatcher(functionDecl(isDefinition()).bind("funcDef"), &HandlerForFuncDef); return Tool.run(newFrontendActionFactory(&Finder).get()); } <commit_msg>Doing the replacemens - Rewriter not working yet<commit_after>// INCOMPLETE SAMPLE - USE AT YOUR OWN PERIL #include <sstream> #include <string> #include "clang/AST/AST.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "clang/Rewrite/Core/Rewriter.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; static llvm::cl::OptionCategory ToolingSampleCategory("Tooling Sample"); class IfStmtHandler : public MatchFinder::MatchCallback { public: IfStmtHandler(Replacements *Replace) : Replace(Replace) {} virtual void run(const MatchFinder::MatchResult &Result) { if (const IfStmt *IfS = Result.Nodes.getNodeAs<clang::IfStmt>("ifStmt")) { const Stmt *Then = IfS->getThen(); Replacement Rep(*(Result.SourceManager), Then->getLocStart(), 0, "// the 'if' part\n"); Replace->insert(Rep); if (const Stmt *Else = IfS->getElse()) { Replacement Rep(*(Result.SourceManager), Else->getLocStart(), 0, "// the 'else' part\n"); Replace->insert(Rep); } } } private: Replacements *Replace; }; class FuncDefHandler : public MatchFinder::MatchCallback { public: FuncDefHandler(Replacements *Replace) : Replace(Replace) {} virtual void run(const MatchFinder::MatchResult &Result) { if (const FunctionDecl *FS = Result.Nodes.getNodeAs<clang::FunctionDecl>("funcDef")) FS->dump(); } private: Replacements *Replace; }; int main(int argc, const char **argv) { CommonOptionsParser op(argc, argv, ToolingSampleCategory); RefactoringTool Tool(op.getCompilations(), op.getSourcePathList()); IfStmtHandler HandlerForIf(&Tool.getReplacements()); FuncDefHandler HandlerForFuncDef(&Tool.getReplacements()); MatchFinder Finder; Finder.addMatcher(ifStmt().bind("ifStmt"), &HandlerForIf); Finder.addMatcher(functionDecl(isDefinition()).bind("funcDef"), &HandlerForFuncDef); if (int Result = Tool.run(newFrontendActionFactory(&Finder).get())) { return Result; } LangOptions DefaultLangOptions; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &DiagnosticPrinter, false); SourceManager Sources(Diagnostics, Tool.getFiles()); Rewriter Rewrite(Sources, DefaultLangOptions); Tool.applyAllReplacements(Rewrite); Rewrite.getEditBuffer(Sources.getMainFileID()).write(llvm::outs()); return 0; } <|endoftext|>
<commit_before><commit_msg>Fix flakey test by making sure WebUI dialog is shut down before test completion.<commit_after><|endoftext|>
<commit_before>#include "output_collector.h" #include <cassert> #include "common/file_stream.h" #include "common/logging.h" namespace marian { OutputCollector::OutputCollector() : nextId_(0), outStrm_(new OutputFileStream(std::cout)) {} void OutputCollector::Write(long sourceId, const std::string& best1, const std::string& bestn, bool nbest) { boost::mutex::scoped_lock lock(mutex_); if(sourceId == nextId_) { if(printing_ && printing_->shouldBePrinted(sourceId)) LOG(info, "Best translation {} : {}", sourceId, best1); if(nbest) ((std::ostream&)*outStrm_) << bestn << std::endl; else ((std::ostream&)*outStrm_) << best1 << std::endl; ++nextId_; Outputs::const_iterator iter, iterNext; iter = outputs_.begin(); while(iter != outputs_.end()) { long currId = iter->first; if(currId == nextId_) { // 1st element in the map is the next const auto& currOutput = iter->second; if(printing_ && printing_->shouldBePrinted(sourceId)) LOG(info, "Best translation {} : {}", currId, currOutput.first); if(nbest) ((std::ostream&)*outStrm_) << currOutput.second << std::endl; else ((std::ostream&)*outStrm_) << currOutput.first << std::endl; ++nextId_; // delete current record, move iter on 1 iterNext = iter; ++iterNext; outputs_.erase(iter); iter = iterNext; } else { // not the next. stop iterating assert(nextId_ < currId); break; } } } else { // save for later outputs_[sourceId] = std::make_pair(best1, bestn); } } StringCollector::StringCollector() : maxId_(-1) {} void StringCollector::add(long sourceId, const std::string& best1, const std::string& bestn) { boost::mutex::scoped_lock lock(mutex_); LOG(info, "Best translation {} : {}", sourceId, best1); outputs_[sourceId] = std::make_pair(best1, bestn); if(maxId_ <= sourceId) maxId_ = sourceId; } std::vector<std::string> StringCollector::collect(bool nbest) { std::vector<std::string> outputs; for(int id = 0; id <= maxId_; ++id) outputs.emplace_back(nbest ? outputs_[id].second : outputs_[id].first); return outputs; } } <commit_msg>Fix displaying best translations<commit_after>#include "output_collector.h" #include <cassert> #include "common/file_stream.h" #include "common/logging.h" namespace marian { OutputCollector::OutputCollector() : nextId_(0), outStrm_(new OutputFileStream(std::cout)) {} void OutputCollector::Write(long sourceId, const std::string& best1, const std::string& bestn, bool nbest) { boost::mutex::scoped_lock lock(mutex_); if(sourceId == nextId_) { if(!printing_ || printing_->shouldBePrinted(sourceId)) LOG(info, "Best translation {} : {}", sourceId, best1); if(nbest) ((std::ostream&)*outStrm_) << bestn << std::endl; else ((std::ostream&)*outStrm_) << best1 << std::endl; ++nextId_; Outputs::const_iterator iter, iterNext; iter = outputs_.begin(); while(iter != outputs_.end()) { long currId = iter->first; if(currId == nextId_) { // 1st element in the map is the next const auto& currOutput = iter->second; if(!printing_ || printing_->shouldBePrinted(sourceId)) LOG(info, "Best translation {} : {}", currId, currOutput.first); if(nbest) ((std::ostream&)*outStrm_) << currOutput.second << std::endl; else ((std::ostream&)*outStrm_) << currOutput.first << std::endl; ++nextId_; // delete current record, move iter on 1 iterNext = iter; ++iterNext; outputs_.erase(iter); iter = iterNext; } else { // not the next. stop iterating assert(nextId_ < currId); break; } } } else { // save for later outputs_[sourceId] = std::make_pair(best1, bestn); } } StringCollector::StringCollector() : maxId_(-1) {} void StringCollector::add(long sourceId, const std::string& best1, const std::string& bestn) { boost::mutex::scoped_lock lock(mutex_); LOG(info, "Best translation {} : {}", sourceId, best1); outputs_[sourceId] = std::make_pair(best1, bestn); if(maxId_ <= sourceId) maxId_ = sourceId; } std::vector<std::string> StringCollector::collect(bool nbest) { std::vector<std::string> outputs; for(int id = 0; id <= maxId_; ++id) outputs.emplace_back(nbest ? outputs_[id].second : outputs_[id].first); return outputs; } } <|endoftext|>
<commit_before>/* urlpicpreviewplugin.cpp Copyright (c) 2005 by Heiko Schaefer <[email protected]> Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; version 2 of the License. * * * ************************************************************************* */ // Qt #include <qimage.h> #include <qregexp.h> // KDE #include <kurl.h> #include <kdebug.h> #include <kconfig.h> #include <kimageio.h> #include <kapplication.h> #include <kgenericfactory.h> // KIO #include <kio/netaccess.h> // Kopete #include "kopeteuiglobal.h" #include "urlpicpreviewplugin.h" #include "urlpicpreviewglobals.h" #include "kopetechatsessionmanager.h" typedef KGenericFactory<URLPicPreviewPlugin> URLPicPreviewPluginFactory; K_EXPORT_COMPONENT_FACTORY(kopete_urlpicpreview, URLPicPreviewPluginFactory("kopete_urlpicpreview")) URLPicPreviewPlugin::URLPicPreviewPlugin(QObject* parent, const char* name, const QStringList& /* args */) : Kopete::Plugin(URLPicPreviewPluginFactory::instance(), parent, name), m_pic(NULL) { kdDebug(0) << k_funcinfo << endl; Kopete::ChatSessionManager * chatSessionManager = Kopete::ChatSessionManager::self(); connect(chatSessionManager, SIGNAL(aboutToDisplay(Kopete::Message&)), this, SLOT(aboutToDisplay(Kopete::Message&))); // register file formats KImageIO::registerFormats(); m_pic = new QImage; } URLPicPreviewPlugin::~URLPicPreviewPlugin() { kdDebug(0) << k_funcinfo << "Removing temporary files..." << endl; for(uint i = 0; i < m_tmpFileRegistry.count(); i++) { KIO::NetAccess::removeTempFile(m_tmpFileRegistry[i]); } disconnect(this, SLOT(aboutToDisplay(Kopete::Message&))); delete m_pic; kdDebug(0) << k_funcinfo << endl; } /*! \fn URLPicPreviewPlugin::aboutToDiplay(Kopete::Message& message) */ void URLPicPreviewPlugin::aboutToDisplay(Kopete::Message& message) { if(message.direction() == Kopete::Message::Inbound) { // prepare parsed message body message.setBody(prepareBody(message.parsedBody()), Kopete::Message::ParsedHTML); } } /** * @brief Recursively searches the message, downloads and replaces all found imgages * * @param parsedBody the parsed body of the message * * @return a new message body with the images as preview */ QString URLPicPreviewPlugin::prepareBody(const QString& parsedBody, int previewCount) { kdDebug(0) << k_funcinfo << "Searching for URLs to pictures" << endl; KConfig * config = kapp->config(); config->setGroup(CONFIG_GROUP); static const QString rex = "(<a href=\")([^\"]*)(\" )?([^<]*)(</a>)(.*)$"; // Caps: 1 2 3 4 5 6 QRegExp ex(rex); QString myParsedBody = parsedBody; kdDebug(0) << k_funcinfo << "Analyzing message: \"" << myParsedBody << "\"" << endl; if(ex.search(myParsedBody) == -1 || (previewCount >= config->readNumEntry("PreviewAmount", 2))) { kdDebug(0) << k_funcinfo << "No more URLs found in message." << endl; return myParsedBody; } QString foundURL = ex.cap(2); KURL url(foundURL); QString tmpFile; kdDebug(0) << k_funcinfo << "Found an URL: " << foundURL << endl; if(url.isValid()) { kdDebug(0) << k_funcinfo << "URL \"" << foundURL << "\" is valid." << endl; if(KIO::NetAccess::mimetype(url, Kopete::UI::Global::mainWidget()).startsWith("image/")) { if(KIO::NetAccess::download(url, tmpFile, Kopete::UI::Global::mainWidget())) { if(config->readBoolEntry("Scaling", true)) { int width = config->readNumEntry("PreviewScaleWidth", 256); kdDebug(0) << k_funcinfo << "Try to scale the image to width: " << width << endl; if(m_pic->load(tmpFile)) { // resize but keep aspect ratio if(m_pic->width() > width) { if(!(m_pic->scaleWidth(width)).save(tmpFile, "PNG")) { kdWarning(0) << k_funcinfo << "Couldn't save scaled image (Format: " << QImage::imageFormat(tmpFile) << ") " << tmpFile << endl; } } } else { kdWarning(0) << k_funcinfo << "Couldn't load image " << tmpFile << endl; } } myParsedBody.replace(QRegExp(rex), QString("<a href=\"%1\" title=\"%2\">%3</a><br /><img align=\"center\" src=\"%4\" title=\"" + i18n("Preview of:") + " %5\" /><br />").arg(foundURL).arg(foundURL).arg(foundURL).arg(tmpFile).arg(foundURL)); if(config->readBoolEntry("PreviewRestriction", true)) { previewCount++; kdDebug(0) << k_funcinfo << "Updating previewCount: " << previewCount << endl; } kdDebug(0) << k_funcinfo << "Registering temporary file for deletion." << endl; m_tmpFileRegistry.append(tmpFile); return myParsedBody + prepareBody(ex.cap(6), previewCount); } } else { kdWarning(0) << k_funcinfo << foundURL << " is not an image file. Ignoring." << endl; } } else { kdWarning(0) << k_funcinfo << "URL \"" << foundURL << "\" is invalid. Ignoring." << endl; } return myParsedBody.replace(QRegExp(rex), ex.cap(1) + ex.cap(2) + ex.cap(3) + ex.cap(4) + ex.cap(5)) + prepareBody(ex.cap(6), previewCount); } #include "urlpicpreviewplugin.moc" <commit_msg>URLs without a filename are ignored<commit_after>/* urlpicpreviewplugin.cpp Copyright (c) 2005 by Heiko Schaefer <[email protected]> Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; version 2 of the License. * * * ************************************************************************* */ // Qt #include <qimage.h> #include <qregexp.h> // KDE #include <kurl.h> #include <kdebug.h> #include <kconfig.h> #include <kimageio.h> #include <kapplication.h> #include <kgenericfactory.h> // KIO #include <kio/netaccess.h> // Kopete #include "kopeteuiglobal.h" #include "urlpicpreviewplugin.h" #include "urlpicpreviewglobals.h" #include "kopetechatsessionmanager.h" typedef KGenericFactory<URLPicPreviewPlugin> URLPicPreviewPluginFactory; K_EXPORT_COMPONENT_FACTORY(kopete_urlpicpreview, URLPicPreviewPluginFactory("kopete_urlpicpreview")) URLPicPreviewPlugin::URLPicPreviewPlugin(QObject* parent, const char* name, const QStringList& /* args */) : Kopete::Plugin(URLPicPreviewPluginFactory::instance(), parent, name), m_pic(NULL) { kdDebug(0) << k_funcinfo << endl; Kopete::ChatSessionManager * chatSessionManager = Kopete::ChatSessionManager::self(); connect(chatSessionManager, SIGNAL(aboutToDisplay(Kopete::Message&)), this, SLOT(aboutToDisplay(Kopete::Message&))); // register file formats KImageIO::registerFormats(); m_pic = new QImage; } URLPicPreviewPlugin::~URLPicPreviewPlugin() { kdDebug(0) << k_funcinfo << "Removing temporary files..." << endl; for(uint i = 0; i < m_tmpFileRegistry.count(); i++) { KIO::NetAccess::removeTempFile(m_tmpFileRegistry[i]); } disconnect(this, SLOT(aboutToDisplay(Kopete::Message&))); delete m_pic; kdDebug(0) << k_funcinfo << endl; } /*! \fn URLPicPreviewPlugin::aboutToDiplay(Kopete::Message& message) */ void URLPicPreviewPlugin::aboutToDisplay(Kopete::Message& message) { if(message.direction() == Kopete::Message::Inbound) { // prepare parsed message body message.setBody(prepareBody(message.parsedBody()), Kopete::Message::ParsedHTML); } } /** * @brief Recursively searches the message, downloads and replaces all found imgages * * @param parsedBody the parsed body of the message * * @return a new message body with the images as preview */ QString URLPicPreviewPlugin::prepareBody(const QString& parsedBody, int previewCount) { kdDebug(0) << k_funcinfo << "Searching for URLs to pictures" << endl; KConfig * config = kapp->config(); config->setGroup(CONFIG_GROUP); static const QString rex = "(<a href=\")([^\"]*)(\" )?([^<]*)(</a>)(.*)$"; // Caps: 1 2 3 4 5 6 QRegExp ex(rex); QString myParsedBody = parsedBody; kdDebug(0) << k_funcinfo << "Analyzing message: \"" << myParsedBody << "\"" << endl; if(ex.search(myParsedBody) == -1 || (previewCount >= config->readNumEntry("PreviewAmount", 2))) { kdDebug(0) << k_funcinfo << "No more URLs found in message." << endl; return myParsedBody; } QString foundURL = ex.cap(2); KURL url(foundURL); QString tmpFile; kdDebug(0) << k_funcinfo << "Found an URL: " << foundURL << endl; if(url.isValid()) { kdDebug(0) << k_funcinfo << "URL \"" << foundURL << "\" is valid." << endl; if(url.fileName(false) != QString::null && // no file no pic! KIO::NetAccess::mimetype(url, Kopete::UI::Global::mainWidget()).startsWith("image/")) { if(KIO::NetAccess::download(url, tmpFile, Kopete::UI::Global::mainWidget())) { if(config->readBoolEntry("Scaling", true)) { int width = config->readNumEntry("PreviewScaleWidth", 256); kdDebug(0) << k_funcinfo << "Try to scale the image to width: " << width << endl; if(m_pic->load(tmpFile)) { // resize but keep aspect ratio if(m_pic->width() > width) { if(!(m_pic->scaleWidth(width)).save(tmpFile, "PNG")) { kdWarning(0) << k_funcinfo << "Couldn't save scaled image (Format: " << QImage::imageFormat(tmpFile) << ") " << tmpFile << endl; } } } else { kdWarning(0) << k_funcinfo << "Couldn't load image " << tmpFile << endl; } } myParsedBody.replace(QRegExp(rex), QString("<a href=\"%1\" title=\"%2\">%3</a><br /><img align=\"center\" src=\"%4\" title=\"" + i18n("Preview of:") + " %5\" /><br />").arg(foundURL).arg(foundURL).arg(foundURL).arg(tmpFile).arg(foundURL)); if(config->readBoolEntry("PreviewRestriction", true)) { previewCount++; kdDebug(0) << k_funcinfo << "Updating previewCount: " << previewCount << endl; } kdDebug(0) << k_funcinfo << "Registering temporary file for deletion." << endl; m_tmpFileRegistry.append(tmpFile); return myParsedBody + prepareBody(ex.cap(6), previewCount); } } else { kdWarning(0) << k_funcinfo << foundURL << " is not an image file. Ignoring." << endl; } } else { kdWarning(0) << k_funcinfo << "URL \"" << foundURL << "\" is invalid. Ignoring." << endl; } return myParsedBody.replace(QRegExp(rex), ex.cap(1) + ex.cap(2) + ex.cap(3) + ex.cap(4) + ex.cap(5)) + prepareBody(ex.cap(6), previewCount); } #include "urlpicpreviewplugin.moc" <|endoftext|>
<commit_before>/** * Copyright (c) 2017, Chris Fogelklou * All rights reserved. */ #include "snake_c_api.h" #include "snake_c_utils.h" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 /* Windows XP. */ #endif #include <winsock2.h> #include <Ws2tcpip.h> #else /* Assume that any non-Windows platform uses POSIX-style sockets instead. */ #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> /* Needed for getaddrinfo() and freeaddrinfo() */ #include <unistd.h> /* Needed for close() */ typedef int SOCKET; #define INVALID_SOCKET (SOCKET)(~0) #define SOCKET_ERROR (-1) #endif #ifdef STANDALONE_JSON #include "nlohmann/src/json.hpp" #else #include <main/json.hpp> #endif #include <iostream> #include <sstream> #include <assert.h> static const int DEFAULT_BUFLEN = 65536; // //////////////////////////////////////////////////////////////////////////// class SnakeSng { public: // Singleton getter static SnakeSng &inst() { if (NULL == mpInst) { mpInst = new SnakeSng(); } return *mpInst; } // Constructor. Init sockets. SnakeSng() { #ifdef _WIN32 WSADATA wsa_data; WSAStartup(MAKEWORD(1, 1), &wsa_data); #endif } // Destructor, deinit sockets. ~SnakeSng() { #ifdef _WIN32 WSACleanup(); #endif } // Close a socket. int sockClose(const SOCKET sock) { int status = 0; #ifdef _WIN32 status = shutdown(sock, SD_BOTH); if (status == 0) { status = closesocket(sock); } #else status = shutdown(sock, SHUT_RDWR); if (status == 0) { status = close(sock); } #endif return status; } private: static SnakeSng *mpInst; }; // Singleton instance SnakeSng *SnakeSng::mpInst = NULL; // //////////////////////////////////////////////////////////////////////////// class SnakeMoveListener { public: SnakeMoveListener(const SnakeCallbacks * const pSnake, const char * const port, void * const pUserData); ~SnakeMoveListener(); std::string parseStart(const char * const cbuf); std::string parseMove(const char * const cbuf); std::string handleReceive(std::string &rxBuf, const int recvbuflen); bool nextMove(); private: SOCKET ListenSocket = INVALID_SOCKET; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; const SnakeCallbacks *mpSnake; void *mpUserData; }; // //////////////////////////////////////////////////////////////////////////// SnakeMoveListener::SnakeMoveListener(const SnakeCallbacks * const pSnake, const char * const port, void * const pUserData) : mpSnake(pSnake) , mpUserData(pUserData) { struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port struct addrinfo *result = NULL; int iResult = getaddrinfo(NULL, port, &hints, &result); if (iResult != 0) { std::cerr << "getaddrinfo failed with error: " << iResult << std::endl; return; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { std::cerr << "socket failed with error" << std::endl; freeaddrinfo(result); return; } // Setup the TCP listening socket iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { std::cerr << "listen failed with error" << std::endl; freeaddrinfo(result); SnakeSng::inst().sockClose(ListenSocket); return; } freeaddrinfo(result); iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { std::cerr << "listen failed with error" << std::endl; SnakeSng::inst().sockClose(ListenSocket); return; } } // //////////////////////////////////////////////////////////////////////////// SnakeMoveListener::~SnakeMoveListener() { // No longer need server socket SnakeSng::inst().sockClose(ListenSocket); } // //////////////////////////////////////////////////////////////////////////// std::string SnakeMoveListener::parseStart(const char * const cbuf) { StartOutputT out = { "red", "white", "Default McDefaultyFace", "Your mother smells of elderberries!", SH_FANG, ST_CURLED, }; try { nlohmann::json req = nlohmann::json::parse(cbuf); if ((mpSnake) && (mpSnake->Start)) { const std::string game_id = req["game_id"].get<std::string>(); auto width = req["width"].get<int>(); auto height = req["height"].get<int>(); mpSnake->Start(mpUserData, game_id.c_str(), width, height, &out); } } catch (std::exception& e) { std::cerr << "ERROR in /start: " << e.what() << std::endl; } catch (...) { std::cerr << "ERROR in /start: Unknown exception caught." << std::endl; } // Create return value nlohmann::json rval = nlohmann::json::object(); if (strlen(out.color) >= 2) { rval["color"] = out.color; } if (strlen(out.secondary_color) >= 2) { rval["secondary_color"] = out.secondary_color; } if (strlen(out.name) >= 1) { rval["name"] = out.name; } if (strlen(out.taunt) >= 1) { rval["taunt"] = out.taunt; } rval["head_type"] = SnakeHeadStr(out.head_type); rval["tail_type"] = SnakeTailStr(out.tail_type); return rval.dump(); } // //////////////////////////////////////////////////////////////////////////// // Convert a json coordinate to a Coords struct void from_json(const nlohmann::json& jcoord, Coords& p) { p.x = jcoord[0].get<int>(); p.y = jcoord[1].get<int>(); } // //////////////////////////////////////////////////////////////////////////// // Convert json coords to coords array static void jsonArrToCArr(const nlohmann::json &jarr, Coords * &pArr, int &numCoords) { numCoords = jarr.size(); if (numCoords > 0) { pArr = (Coords *)calloc(numCoords, sizeof(Coords)); int coordsIdx = 0; for (const nlohmann::json coord : jarr) { pArr[coordsIdx] = coord.get<Coords>(); coordsIdx++; } } } // //////////////////////////////////////////////////////////////////////////// void from_json(const nlohmann::json& jsnake, Snake& s) { if (jsnake["id"].size() > 0) { const std::string id = jsnake["id"].get<std::string>(); memcpy(s.id, id.c_str(), SNAKE_STRLEN); } if (jsnake["name"].size() > 0) { const std::string name = jsnake["name"].get<std::string>(); memcpy(s.name, name.c_str(), SNAKE_STRLEN); } if (jsnake["taunt"].size() > 0) { const std::string taunt = jsnake["taunt"].get<std::string>(); memcpy(s.taunt, taunt.c_str(), SNAKE_STRLEN); } if (jsnake["health_points"].size() > 0) { s.healthPercent = jsnake["health_points"].get<int>(); } if (jsnake["coords"].size() > 0) { jsonArrToCArr(jsnake["coords"], s.coordsArr, s.numCoords); } } // //////////////////////////////////////////////////////////////////////////// std::string SnakeMoveListener::parseMove(const char * const cbuf) { nlohmann::json rval = { { "move", "up" }, { "taunt", "ouch" } }; try { // If the move function is defined, call it. if ((mpSnake) && (mpSnake->Move)) { MoveInput moveInput = { 0 }; MoveOutput moveOutput = { DIR_UP }; const nlohmann::json req = nlohmann::json::parse(cbuf); if ((req["you"].size() <= 0) && (req["snakes"].size() <= 0)) { return rval.dump(); } const std::string game_id = req["game_id"].get<std::string>(); const std::string you_uuid = req["you"]; const nlohmann::json snakes = req["snakes"]; #ifdef _DEBUG std::cout << "snakes were " << snakes.dump() << std::endl; std::cout << std::endl; #endif moveInput.numSnakes = snakes.size(); moveInput.snakesArr = (Snake *)calloc(moveInput.numSnakes, sizeof(Snake)); // Convert from json to struct. int snakeIdx = 0; for (const nlohmann::json jsnake : snakes) { Snake &destSnake = moveInput.snakesArr[snakeIdx]; destSnake = jsnake.get<Snake>(); if (destSnake.id == you_uuid) { moveInput.yourSnakeIdx = snakeIdx; } snakeIdx++; } // Convert food to a C array. jsonArrToCArr(req["food"], moveInput.foodArr, moveInput.numFood); moveInput.width = req["width"].get<int>(); moveInput.height = req["height"].get<int>(); mpSnake->Move(mpUserData, game_id.c_str(), &moveInput, &moveOutput); // Handle output of the move call rval["move"] = SnakeDirStr(moveOutput.dir); if (strlen(moveOutput.taunt) >= 1) { rval["taunt"] = moveOutput.taunt; } // Free allocated food. if (moveInput.foodArr) { free(moveInput.foodArr); } // Free the snakes array. if (moveInput.snakesArr) { // Free allocated snake coordinates. for (int snakeIdx = 0; snakeIdx < moveInput.numSnakes; snakeIdx++) { Snake &snake = moveInput.snakesArr[snakeIdx]; if (snake.coordsArr) { free(snake.coordsArr); } } // Free snakes array. free(moveInput.snakesArr); } } } catch (std::exception& e) { std::cerr << "ERROR in /move: " << e.what() << std::endl; } catch (...) { std::cerr << "ERROR in /move: Unknown exception caught." << std::endl; } return rval.dump(); } // ////////////////////////////////////////////////////////////////////////// std::string SnakeMoveListener::handleReceive(std::string &rxBuf, const int recvbuflen) { const char *cbuf = rxBuf.c_str(); const int jsonIdx = rxBuf.find("json", 0); std::string rval = "{ \"move\":\"up\" }"; if (jsonIdx >= 0) { const int contentLengthIdx = rxBuf.find("Content-Length", jsonIdx); if (contentLengthIdx >= jsonIdx) { const int bracketIdx = rxBuf.find("{", contentLengthIdx); if (bracketIdx >= 0) { const int startIdx = rxBuf.find("/start"); const bool isStart = ((startIdx > 0) && (startIdx < jsonIdx)); if (isStart) { rval = parseStart(&cbuf[bracketIdx]); } else { rval = parseMove(&cbuf[bracketIdx]); } } } } return rval; } // ////////////////////////////////////////////////////////////////////////// bool SnakeMoveListener::nextMove() { int iResult = 0; bool rval = true; // Accept a client socket SOCKET clientSocket = accept(ListenSocket, NULL, NULL); if (clientSocket == INVALID_SOCKET) { std::cerr << "accept failed with error" << std::endl; return false; } // Receive until the peer shuts down the connection do { iResult = recv(clientSocket, recvbuf, recvbuflen - 1, 0); if (iResult > 0) { recvbuf[iResult] = 0; printf("Bytes received: %d\n", iResult); std::string rxBuf = recvbuf; std::string response = handleReceive(rxBuf, iResult); response.append("\r\n"); // Echo the buffer back to the sender std::stringstream sstream; sstream << "HTTP/1.1 200 OK\r\n" "Server: Apache/1.3.0 (Unix)\r\n" "Content-Type: application/json\r\n" "Content-Length: " << response.length() << "\r\n\r\n" << response; const std::string s = sstream.str(); int iSendResult = send(clientSocket, s.c_str(), s.length(), 0); if (iSendResult == SOCKET_ERROR) { std::cerr << "send failed with error" << std::endl; SnakeSng::inst().sockClose(clientSocket); } printf("Bytes sent: %d\n", iSendResult); } else if (iResult == 0) { // Do nothing, just exit... Sleep(10); } else { std::cerr << "recv failed with error" << std::endl; SnakeSng::inst().sockClose(clientSocket); } } while (iResult >= 0); // shutdown the connection since we're done iResult = SnakeSng::inst().sockClose(clientSocket); if (iResult == SOCKET_ERROR) { std::cerr << "shutdown failed with error" << std::endl; SnakeSng::inst().sockClose(clientSocket); } // cleanup SnakeSng::inst().sockClose(clientSocket); return rval; } extern "C" { // //////////////////////////////////////////////////////////////////////////// void SnakeStart( const SnakeCallbacks * const pSnake, const char * const port, void * const pUserData) { (void)SnakeSng::inst(); assert(pSnake); assert(port); SnakeMoveListener snake(pSnake, port, pUserData); while (snake.nextMove()) { ; } } } // extern "C" { <commit_msg>Multi threads fix the shits.<commit_after>/** * Copyright (c) 2017, Chris Fogelklou * All rights reserved. */ #include "snake_c_api.h" #include "snake_c_utils.h" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 /* Windows XP. */ #endif #include <winsock2.h> #include <Ws2tcpip.h> #else /* Assume that any non-Windows platform uses POSIX-style sockets instead. */ #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> /* Needed for getaddrinfo() and freeaddrinfo() */ #include <unistd.h> /* Needed for close() */ typedef int SOCKET; #define INVALID_SOCKET (SOCKET)(~0) #define SOCKET_ERROR (-1) #endif #ifdef STANDALONE_JSON #include "nlohmann/src/json.hpp" #else #include <main/json.hpp> #endif #include <iostream> #include <sstream> #include <assert.h> static const int DEFAULT_BUFLEN = 65536; // //////////////////////////////////////////////////////////////////////////// class SnakeSng { public: // Singleton getter static SnakeSng &inst() { if (NULL == mpInst) { mpInst = new SnakeSng(); } return *mpInst; } // Constructor. Init sockets. SnakeSng() { #ifdef _WIN32 WSADATA wsa_data; WSAStartup(MAKEWORD(1, 1), &wsa_data); #endif } // Destructor, deinit sockets. ~SnakeSng() { #ifdef _WIN32 WSACleanup(); #endif } // Close a socket. int sockClose(const SOCKET sock) { int status = 0; #ifdef _WIN32 status = shutdown(sock, SD_BOTH); if (status == 0) { status = closesocket(sock); } #else status = shutdown(sock, SHUT_RDWR); if (status == 0) { status = close(sock); } #endif return status; } private: static SnakeSng *mpInst; }; // Singleton instance SnakeSng *SnakeSng::mpInst = NULL; // //////////////////////////////////////////////////////////////////////////// class SnakeMoveListener { public: SnakeMoveListener(const SnakeCallbacks * const pSnake, const char * const port, void * const pUserData); ~SnakeMoveListener(); std::string parseStart(const char * const cbuf); std::string parseMove(const char * const cbuf); std::string handleReceive(std::string &rxBuf, const int recvbuflen); bool nextMove(); static void ThreadCb(void *pUserData); void Moving(SOCKET clientSocket); private: SOCKET ListenSocket = INVALID_SOCKET; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; const SnakeCallbacks *mpSnake; void *mpUserData; }; // //////////////////////////////////////////////////////////////////////////// SnakeMoveListener::SnakeMoveListener(const SnakeCallbacks * const pSnake, const char * const port, void * const pUserData) : mpSnake(pSnake) , mpUserData(pUserData) { struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port struct addrinfo *result = NULL; int iResult = getaddrinfo(NULL, port, &hints, &result); if (iResult != 0) { std::cerr << "getaddrinfo failed with error: " << iResult << std::endl; return; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { std::cerr << "socket failed with error" << std::endl; freeaddrinfo(result); return; } // Setup the TCP listening socket iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { std::cerr << "listen failed with error" << std::endl; freeaddrinfo(result); SnakeSng::inst().sockClose(ListenSocket); return; } freeaddrinfo(result); iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { std::cerr << "listen failed with error" << std::endl; SnakeSng::inst().sockClose(ListenSocket); return; } } // //////////////////////////////////////////////////////////////////////////// SnakeMoveListener::~SnakeMoveListener() { // No longer need server socket SnakeSng::inst().sockClose(ListenSocket); } // //////////////////////////////////////////////////////////////////////////// std::string SnakeMoveListener::parseStart(const char * const cbuf) { StartOutputT out = { "red", "white", "Default McDefaultyFace", "Your mother smells of elderberries!", SH_FANG, ST_CURLED, }; try { nlohmann::json req = nlohmann::json::parse(cbuf); if ((mpSnake) && (mpSnake->Start)) { const std::string game_id = req["game_id"].get<std::string>(); auto width = req["width"].get<int>(); auto height = req["height"].get<int>(); mpSnake->Start(mpUserData, game_id.c_str(), width, height, &out); } } catch (std::exception& e) { std::cerr << "ERROR in /start: " << e.what() << std::endl; } catch (...) { std::cerr << "ERROR in /start: Unknown exception caught." << std::endl; } // Create return value nlohmann::json rval = nlohmann::json::object(); if (strlen(out.color) >= 2) { rval["color"] = out.color; } if (strlen(out.secondary_color) >= 2) { rval["secondary_color"] = out.secondary_color; } if (strlen(out.name) >= 1) { rval["name"] = out.name; } if (strlen(out.taunt) >= 1) { rval["taunt"] = out.taunt; } rval["head_type"] = SnakeHeadStr(out.head_type); rval["tail_type"] = SnakeTailStr(out.tail_type); return rval.dump(); } // //////////////////////////////////////////////////////////////////////////// // Convert a json coordinate to a Coords struct void from_json(const nlohmann::json& jcoord, Coords& p) { p.x = jcoord[0].get<int>(); p.y = jcoord[1].get<int>(); } // //////////////////////////////////////////////////////////////////////////// // Convert json coords to coords array static void jsonArrToCArr(const nlohmann::json &jarr, Coords * &pArr, int &numCoords) { numCoords = jarr.size(); if (numCoords > 0) { pArr = (Coords *)calloc(numCoords, sizeof(Coords)); int coordsIdx = 0; for (const nlohmann::json coord : jarr) { pArr[coordsIdx] = coord.get<Coords>(); coordsIdx++; } } } // //////////////////////////////////////////////////////////////////////////// void from_json(const nlohmann::json& jsnake, Snake& s) { if (jsnake["id"].size() > 0) { const std::string id = jsnake["id"].get<std::string>(); memcpy(s.id, id.c_str(), SNAKE_STRLEN); } if (jsnake["name"].size() > 0) { const std::string name = jsnake["name"].get<std::string>(); memcpy(s.name, name.c_str(), SNAKE_STRLEN); } if (jsnake["taunt"].size() > 0) { const std::string taunt = jsnake["taunt"].get<std::string>(); memcpy(s.taunt, taunt.c_str(), SNAKE_STRLEN); } if (jsnake["health_points"].size() > 0) { s.healthPercent = jsnake["health_points"].get<int>(); } if (jsnake["coords"].size() > 0) { jsonArrToCArr(jsnake["coords"], s.coordsArr, s.numCoords); } } // //////////////////////////////////////////////////////////////////////////// std::string SnakeMoveListener::parseMove(const char * const cbuf) { nlohmann::json rval = { { "move", "up" }, { "taunt", "ouch" } }; try { // If the move function is defined, call it. if ((mpSnake) && (mpSnake->Move)) { MoveInput moveInput = { 0 }; MoveOutput moveOutput = { DIR_UP }; const nlohmann::json req = nlohmann::json::parse(cbuf); if ((req["you"].size() <= 0) && (req["snakes"].size() <= 0)) { return rval.dump(); } const std::string game_id = req["game_id"].get<std::string>(); const std::string you_uuid = req["you"]; const nlohmann::json snakes = req["snakes"]; #ifdef _DEBUG std::cout << "snakes were " << snakes.dump() << std::endl; std::cout << std::endl; #endif moveInput.numSnakes = snakes.size(); moveInput.snakesArr = (Snake *)calloc(moveInput.numSnakes, sizeof(Snake)); // Convert from json to struct. int snakeIdx = 0; for (const nlohmann::json jsnake : snakes) { Snake &destSnake = moveInput.snakesArr[snakeIdx]; destSnake = jsnake.get<Snake>(); if (destSnake.id == you_uuid) { moveInput.yourSnakeIdx = snakeIdx; } snakeIdx++; } // Convert food to a C array. jsonArrToCArr(req["food"], moveInput.foodArr, moveInput.numFood); moveInput.width = req["width"].get<int>(); moveInput.height = req["height"].get<int>(); mpSnake->Move(mpUserData, game_id.c_str(), &moveInput, &moveOutput); // Handle output of the move call rval["move"] = SnakeDirStr(moveOutput.dir); if (strlen(moveOutput.taunt) >= 1) { rval["taunt"] = moveOutput.taunt; } // Free allocated food. if (moveInput.foodArr) { free(moveInput.foodArr); } // Free the snakes array. if (moveInput.snakesArr) { // Free allocated snake coordinates. for (int snakeIdx = 0; snakeIdx < moveInput.numSnakes; snakeIdx++) { Snake &snake = moveInput.snakesArr[snakeIdx]; if (snake.coordsArr) { free(snake.coordsArr); } } // Free snakes array. free(moveInput.snakesArr); } } } catch (std::exception& e) { std::cerr << "ERROR in /move: " << e.what() << std::endl; } catch (...) { std::cerr << "ERROR in /move: Unknown exception caught." << std::endl; } return rval.dump(); } // ////////////////////////////////////////////////////////////////////////// std::string SnakeMoveListener::handleReceive(std::string &rxBuf, const int recvbuflen) { const char *cbuf = rxBuf.c_str(); const int jsonIdx = rxBuf.find("json", 0); std::string rval = "{ \"move\":\"up\" }"; if (jsonIdx >= 0) { const int contentLengthIdx = rxBuf.find("Content-Length", jsonIdx); if (contentLengthIdx >= jsonIdx) { const int bracketIdx = rxBuf.find("{", contentLengthIdx); if (bracketIdx >= 0) { const int startIdx = rxBuf.find("/start"); const bool isStart = ((startIdx > 0) && (startIdx < jsonIdx)); if (isStart) { rval = parseStart(&cbuf[bracketIdx]); } else { rval = parseMove(&cbuf[bracketIdx]); } } } } return rval; } #include "osal.h" typedef struct { SnakeMoveListener *pThis; SOCKET clientSocket; } MoveListenerThreadData; // ////////////////////////////////////////////////////////////////////////// void SnakeMoveListener::ThreadCb(void *pUserData) { MoveListenerThreadData *p = (MoveListenerThreadData *)pUserData; p->pThis->Moving(p->clientSocket); free(p); } // ////////////////////////////////////////////////////////////////////////// void SnakeMoveListener::Moving(SOCKET clientSocket) { // Receive until the peer shuts down the connection int iResult = 1; do { iResult = recv(clientSocket, recvbuf, recvbuflen - 1, 0); if (iResult > 0) { recvbuf[iResult] = 0; printf("Bytes received: %d\n", iResult); std::string rxBuf = recvbuf; std::string response = handleReceive(rxBuf, iResult); response.append("\r\n"); // Echo the buffer back to the sender std::stringstream sstream; sstream << "HTTP/1.1 200 OK\r\n" "Server: Apache/1.3.0 (Unix)\r\n" "Content-Type: application/json\r\n" "Content-Length: " << response.length() << "\r\n\r\n" << response; const std::string s = sstream.str(); int iSendResult = send(clientSocket, s.c_str(), s.length(), 0); if (iSendResult == SOCKET_ERROR) { std::cerr << "send failed with error" << std::endl; SnakeSng::inst().sockClose(clientSocket); } printf("Bytes sent: %d\n", iSendResult); } else if (iResult == 0) { // Do nothing, just exit... } else { std::cerr << "recv failed with error" << std::endl; SnakeSng::inst().sockClose(clientSocket); } } while (iResult > 0); // shutdown the connection since we're done iResult = SnakeSng::inst().sockClose(clientSocket); if (iResult == SOCKET_ERROR) { std::cerr << "shutdown failed with error" << std::endl; SnakeSng::inst().sockClose(clientSocket); } // cleanup SnakeSng::inst().sockClose(clientSocket); } // ////////////////////////////////////////////////////////////////////////// bool SnakeMoveListener::nextMove() { int iResult = 0; bool rval = true; // Accept a client socket SOCKET clientSocket = accept(ListenSocket, NULL, NULL); if (clientSocket == INVALID_SOCKET) { std::cerr << "accept failed with error" << std::endl; return false; } MoveListenerThreadData *pThreadData = (MoveListenerThreadData *)malloc(sizeof(MoveListenerThreadData)); pThreadData->clientSocket = clientSocket; pThreadData->pThis = this; OSALStartThread(ThreadCb, pThreadData); return rval; } extern "C" { // //////////////////////////////////////////////////////////////////////////// void SnakeStart( const SnakeCallbacks * const pSnake, const char * const port, void * const pUserData) { (void)SnakeSng::inst(); assert(pSnake); assert(port); SnakeMoveListener snake(pSnake, port, pUserData); while (snake.nextMove()) { ; } } } // extern "C" { <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ //Poco headers #include "Poco/Path.h" //mitk headers #include "mitkNavigationToolWriter.h" #include "mitkCommon.h" #include "mitkTestingMacros.h" #include "mitkStandardFileLocations.h" #include "mitkNavigationTool.h" #include "mitkSTLFileReader.h" #include "mitkBaseData.h" #include "mitkDataNode.h" #include "mitkSurface.h" #include "mitkStandaloneDataStorage.h" #include "mitkDataStorage.h" #include "mitkNavigationToolReader.h" #include <sstream> #include <fstream> class mitkNavigationToolReaderAndWriterTestClass { private: static mitk::Surface::Pointer testSurface; public: static void TestInstantiation() { // let's create an object of our class mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); MITK_TEST_CONDITION_REQUIRED(myWriter.IsNotNull(),"Testing instantiation") } static void TestWrite() { //testcase with first test tool: a claron tool //create a NavigationTool which we can write on the harddisc std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration of claron tool file exists"); mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); myNavigationTool->SetCalibrationFile(toolFileName); mitk::DataNode::Pointer myNode = mitk::DataNode::New(); myNode->SetName("ClaronTool"); //load an stl File mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool.stl", "Testing/Data/").c_str() ); stlReader->Update(); } catch (...) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } if ( stlReader->GetOutput() == NULL ) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } else { testSurface = stlReader->GetOutput(); myNode->SetData(testSurface); } myNavigationTool->SetDataNode(myNode); myNavigationTool->SetIdentifier("ClaronTool#1"); myNavigationTool->SetSerialNumber("0815"); myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron); myNavigationTool->SetType(mitk::NavigationTool::Fiducial); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"; MITK_TEST_OUTPUT(<<"---- Testing navigation tool writer with first test tool (claron tool) ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(test,"OK"); } static void TestRead() { mitk::DataStorage::Pointer testStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"); MITK_TEST_OUTPUT(<<"---- Testing navigation tool reader with first test tool (claron tool) ----"); //Test if there was created a new tool MITK_TEST_CONDITION_REQUIRED(readTool->GetDataNode() == testStorage->GetNamedNode(readTool->GetDataNode()->GetName()),"Test if tool was added to storage..."); //Test if the surfaces do have the same number of vertexes (it would be better to test for real equality of the surfaces!) MITK_TEST_CONDITION_REQUIRED(dynamic_cast<mitk::Surface*>(readTool->GetDataNode()->GetData())->GetSizeOfPolyDataSeries()==testSurface->GetSizeOfPolyDataSeries(),"Test if surface was restored correctly ..."); MITK_TEST_CONDITION_REQUIRED(readTool->GetType()==mitk::NavigationTool::Fiducial,"Testing Tool Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetTrackingDeviceType()==mitk::ClaronMicron,"Testing Tracking Device Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetSerialNumber()=="0815","Testing Serial Number"); std::ifstream TestFile(readTool->GetCalibrationFile().c_str()); MITK_TEST_CONDITION_REQUIRED(TestFile,"Testing If Calibration File Exists"); } static void TestWrite2() { //testcase with second test tool: an aurora tool //create a NavigationTool which we can write on the harddisc mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); mitk::DataNode::Pointer myNode = mitk::DataNode::New(); myNode->SetName("AuroraTool"); //load an stl File mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("EMTool.stl", "Testing/Data/").c_str() ); stlReader->Update(); } catch (...) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } if ( stlReader->GetOutput() == NULL ) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } else { testSurface = stlReader->GetOutput(); myNode->SetData(testSurface); } myNavigationTool->SetDataNode(myNode); myNavigationTool->SetIdentifier("AuroraTool#1"); myNavigationTool->SetSerialNumber("0816"); myNavigationTool->SetTrackingDeviceType(mitk::NDIAurora); myNavigationTool->SetType(mitk::NavigationTool::Instrument); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool2.tool"; MITK_TEST_OUTPUT(<<"---- Testing navigation tool writer with second tool (aurora tool) ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(test,"OK"); } static void TestRead2() { mitk::DataStorage::Pointer testStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool2.tool"); MITK_TEST_OUTPUT(<<"---- Testing navigation tool reader with second tool (aurora tool) ----"); //Test if there was created a new tool MITK_TEST_CONDITION_REQUIRED(readTool->GetDataNode() == testStorage->GetNamedNode(readTool->GetDataNode()->GetName()),"Test if tool was added to storage..."); //Test if the surfaces do have the same number of vertexes (it would be better to test for real equality of the surfaces!) MITK_TEST_CONDITION_REQUIRED(dynamic_cast<mitk::Surface*>(readTool->GetDataNode()->GetData())->GetSizeOfPolyDataSeries()==testSurface->GetSizeOfPolyDataSeries(),"Test if surface was restored correctly ..."); //Test if the tool type is the same MITK_TEST_CONDITION_REQUIRED(readTool->GetType()==mitk::NavigationTool::Instrument,"Testing Tool Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetTrackingDeviceType()==mitk::NDIAurora,"Testing Tracking Device Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetSerialNumber()=="0816","Testing Serial Number"); MITK_TEST_CONDITION_REQUIRED(readTool->GetCalibrationFile()=="none","Testing Calibration File"); } static void CleanUp() { std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool").c_str()); std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool2.tool").c_str()); } }; mitk::Surface::Pointer mitkNavigationToolReaderAndWriterTestClass::testSurface = NULL; /** This function is testing the TrackingVolume class. */ int mitkNavigationToolReaderAndWriterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationToolWriter") mitkNavigationToolReaderAndWriterTestClass::TestInstantiation(); mitkNavigationToolReaderAndWriterTestClass::TestWrite(); mitkNavigationToolReaderAndWriterTestClass::TestRead(); mitkNavigationToolReaderAndWriterTestClass::TestWrite2(); mitkNavigationToolReaderAndWriterTestClass::TestRead2(); mitkNavigationToolReaderAndWriterTestClass::CleanUp(); MITK_TEST_END() } <commit_msg>further improvement of test<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ //Poco headers #include "Poco/Path.h" //mitk headers #include "mitkNavigationToolWriter.h" #include "mitkCommon.h" #include "mitkTestingMacros.h" #include "mitkStandardFileLocations.h" #include "mitkNavigationTool.h" #include "mitkSTLFileReader.h" #include "mitkBaseData.h" #include "mitkDataNode.h" #include "mitkSurface.h" #include "mitkStandaloneDataStorage.h" #include "mitkDataStorage.h" #include "mitkNavigationToolReader.h" #include <sstream> #include <fstream> class mitkNavigationToolReaderAndWriterTestClass { private: static mitk::Surface::Pointer testSurface; public: static void TestInstantiation() { // let's create an object of our class mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); MITK_TEST_CONDITION_REQUIRED(myWriter.IsNotNull(),"Testing instantiation") } static void TestWrite() { //testcase with first test tool: a claron tool //create a NavigationTool which we can write on the harddisc std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data"); MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration of claron tool file exists"); mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); myNavigationTool->SetCalibrationFile(toolFileName); mitk::DataNode::Pointer myNode = mitk::DataNode::New(); myNode->SetName("ClaronTool"); //load an stl File mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool.stl", "Testing/Data/").c_str() ); stlReader->Update(); } catch (...) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } if ( stlReader->GetOutput() == NULL ) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } else { testSurface = stlReader->GetOutput(); myNode->SetData(testSurface); } myNavigationTool->SetDataNode(myNode); myNavigationTool->SetIdentifier("ClaronTool#1"); myNavigationTool->SetSerialNumber("0815"); myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron); myNavigationTool->SetType(mitk::NavigationTool::Fiducial); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"; MITK_TEST_OUTPUT(<<"---- Testing navigation tool writer with first test tool (claron tool) ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(test,"OK"); } static void TestRead() { mitk::DataStorage::Pointer testStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool"); MITK_TEST_OUTPUT(<<"---- Testing navigation tool reader with first test tool (claron tool) ----"); //Test if there was created a new tool MITK_TEST_CONDITION_REQUIRED(readTool->GetDataNode() == testStorage->GetNamedNode(readTool->GetDataNode()->GetName()),"Test if tool was added to storage..."); //Test if the surfaces do have the same number of vertexes (it would be better to test for real equality of the surfaces!) MITK_TEST_CONDITION_REQUIRED(dynamic_cast<mitk::Surface*>(readTool->GetDataNode()->GetData())->GetSizeOfPolyDataSeries()==testSurface->GetSizeOfPolyDataSeries(),"Test if surface was restored correctly ..."); MITK_TEST_CONDITION_REQUIRED(readTool->GetType()==mitk::NavigationTool::Fiducial,"Testing Tool Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetTrackingDeviceType()==mitk::ClaronMicron,"Testing Tracking Device Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetSerialNumber()=="0815","Testing Serial Number"); std::ifstream TestFile(readTool->GetCalibrationFile().c_str()); MITK_TEST_CONDITION_REQUIRED(TestFile,"Testing If Calibration File Exists"); } static void TestWrite2() { //testcase with second test tool: an aurora tool //create a NavigationTool which we can write on the harddisc mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); mitk::DataNode::Pointer myNode = mitk::DataNode::New(); myNode->SetName("AuroraTool"); //load an stl File mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New(); try { stlReader->SetFileName( mitk::StandardFileLocations::GetInstance()->FindFile("EMTool.stl", "Testing/Data/").c_str() ); stlReader->Update(); } catch (...) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } if ( stlReader->GetOutput() == NULL ) { MITK_TEST_FAILED_MSG(<<"Cannot read stl file."); } else { testSurface = stlReader->GetOutput(); myNode->SetData(testSurface); } myNavigationTool->SetDataNode(myNode); myNavigationTool->SetIdentifier("AuroraTool#1"); myNavigationTool->SetSerialNumber("0816"); myNavigationTool->SetTrackingDeviceType(mitk::NDIAurora); myNavigationTool->SetType(mitk::NavigationTool::Instrument); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool2.tool"; MITK_TEST_OUTPUT(<<"---- Testing navigation tool writer with second tool (aurora tool) ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(test,"OK"); } static void TestRead2() { mitk::DataStorage::Pointer testStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead(mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool2.tool"); MITK_TEST_OUTPUT(<<"---- Testing navigation tool reader with second tool (aurora tool) ----"); //Test if there was created a new tool MITK_TEST_CONDITION_REQUIRED(readTool->GetDataNode() == testStorage->GetNamedNode(readTool->GetDataNode()->GetName()),"Test if tool was added to storage..."); //Test if the surfaces do have the same number of vertexes (it would be better to test for real equality of the surfaces!) MITK_TEST_CONDITION_REQUIRED(dynamic_cast<mitk::Surface*>(readTool->GetDataNode()->GetData())->GetSizeOfPolyDataSeries()==testSurface->GetSizeOfPolyDataSeries(),"Test if surface was restored correctly ..."); //Test if the tool type is the same MITK_TEST_CONDITION_REQUIRED(readTool->GetType()==mitk::NavigationTool::Instrument,"Testing Tool Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetTrackingDeviceType()==mitk::NDIAurora,"Testing Tracking Device Type"); MITK_TEST_CONDITION_REQUIRED(readTool->GetSerialNumber()=="0816","Testing Serial Number"); MITK_TEST_CONDITION_REQUIRED(readTool->GetCalibrationFile()=="none","Testing Calibration File"); } static void CleanUp() { std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool.tool").c_str()); std::remove((mitk::StandardFileLocations::GetInstance()->GetOptionDirectory()+Poco::Path::separator()+".."+Poco::Path::separator()+"TestTool2.tool").c_str()); } static void mitkNavigationToolReaderAndWriterTestClass::TestReadInvalidData() { mitk::DataStorage::Pointer testStorage = dynamic_cast<mitk::DataStorage*>(mitk::StandaloneDataStorage::New().GetPointer()); mitk::NavigationToolReader::Pointer myReader = mitk::NavigationToolReader::New(testStorage); mitk::NavigationTool::Pointer readTool = myReader->DoRead("invalidTool"); MITK_TEST_CONDITION_REQUIRED(readTool.IsNull(), "Testing return value if filename is invalid"); MITK_TEST_CONDITION_REQUIRED(myReader->GetErrorMessage() == "Cannot open 'invalidTool' for reading", "Testing error message in this case"); } static void mitkNavigationToolReaderAndWriterTestClass::TestWriteInvalidData() { mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New(); myNavigationTool->SetIdentifier("ClaronTool#1"); myNavigationTool->SetSerialNumber("0815"); myNavigationTool->SetTrackingDeviceType(mitk::ClaronMicron); myNavigationTool->SetType(mitk::NavigationTool::Fiducial); //now create a writer and write it to the harddisc mitk::NavigationToolWriter::Pointer myWriter = mitk::NavigationToolWriter::New(); std::string filename = "NH:/sfdsfsdsf.&%%%"; MITK_TEST_OUTPUT(<<"---- Testing write invalid file ----"); bool test = myWriter->DoWrite(filename,myNavigationTool); MITK_TEST_CONDITION_REQUIRED(!test,"testing write"); MITK_TEST_CONDITION_REQUIRED(myWriter->GetErrorMessage() == "Could not open a zip file for writing: 'NH:/sfdsfsdsf.&%%%'","testing error message"); } }; mitk::Surface::Pointer mitkNavigationToolReaderAndWriterTestClass::testSurface = NULL; /** This function is testing the TrackingVolume class. */ int mitkNavigationToolReaderAndWriterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("NavigationToolWriter") mitkNavigationToolReaderAndWriterTestClass::TestInstantiation(); mitkNavigationToolReaderAndWriterTestClass::TestWrite(); mitkNavigationToolReaderAndWriterTestClass::TestRead(); mitkNavigationToolReaderAndWriterTestClass::TestWrite2(); mitkNavigationToolReaderAndWriterTestClass::TestRead2(); mitkNavigationToolReaderAndWriterTestClass::TestReadInvalidData(); mitkNavigationToolReaderAndWriterTestClass::TestWriteInvalidData(); mitkNavigationToolReaderAndWriterTestClass::CleanUp(); MITK_TEST_END() } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <threadhelp/transactionmanager.hxx> #include <threadhelp/resetableguard.hxx> #include <macros/debug.hxx> #include <macros/generic.hxx> #include <fwidllapi.h> #include <com/sun/star/lang/DisposedException.hpp> namespace framework{ /*-************************************************************************************************************//** @short standard ctor @descr Initialize instance with right start values for correct working. @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ TransactionManager::TransactionManager() : m_eWorkingMode ( E_INIT ) , m_nTransactionCount ( 0 ) { m_aBarrier.open(); } /*-************************************************************************************************************//** @short standard dtor @descr - @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ TransactionManager::~TransactionManager() { } /*-****************************************************************************************************//** @interface ITransactionManager @short set new working mode @descr These implementation knows for states of working: E_INIT, E_WORK, E_CLOSING, E_CLOSE You can step during this ones only from the left to the right side and start at left side again! (This is neccessary e.g. for refcounted objects!) This call will block till all current existing transactions was finished. Follow results occure: E_INIT : All requests on this implementation are refused. It's your decision to react in a right way. E_WORK : The object can work now. The full functionality is available. E_BEFORECLOSE : The object start the closing mechanism ... but sometimes e.g. the dispose() method need to call some private methods. These some special methods should use E_SOFTEXCEPTIONS or ignore E_INCLOSE as returned reason for E_NOEXCEPTIONS to detect this special case! E_CLOSE : Object is already dead! All further requests will be refused. It's your decision to react in a right way. @seealso - @param "eMode", is the new mode - but we don't accept setting mode in wrong order! @return - @onerror We do nothing. *//*-*****************************************************************************************************/ void TransactionManager::setWorkingMode( EWorkingMode eMode ) { // Safe member access. ::osl::ClearableMutexGuard aAccessGuard( m_aAccessLock ); sal_Bool bWaitFor = sal_False ; // Change working mode first! if ( ( m_eWorkingMode == E_INIT && eMode == E_WORK ) || ( m_eWorkingMode == E_WORK && eMode == E_BEFORECLOSE ) || ( m_eWorkingMode == E_BEFORECLOSE && eMode == E_CLOSE ) || ( m_eWorkingMode == E_CLOSE && eMode == E_INIT ) ) { m_eWorkingMode = eMode; if( m_eWorkingMode == E_BEFORECLOSE || m_eWorkingMode == E_CLOSE ) { bWaitFor = sal_True; } } // Wait for current existing transactions then! // (Only necessary for changing to E_BEFORECLOSE or E_CLOSE! ... // otherwise; if you wait at setting E_WORK another thrad could finish a acquire-call during our unlock() and wait() call // ... and we will wait forever here!!!) // Don't forget to release access mutex before. aAccessGuard.clear(); if( bWaitFor == sal_True ) { m_aBarrier.wait(); } } /*-****************************************************************************************************//** @interface ITransactionManager @short get current working mode @descr If you stand in your close() or init() method ... but don't know if you called more then ones(!) ... you can use this function to get right information. e.g: You have a method init() which is used to change working mode from E_INIT to E_WORK and should be used to initialize some member too ... What should you do: void init( sal_Int32 nValue ) { // Reject this call if our transaction manager say: "Object already initialized!" // Otherwise initialize your member. if( m_aTransactionManager.getWorkingMode() == E_INIT ) { // Object is uninitialized ... // Make member access threadsafe! ResetableGuard aGuard( m_aMutex ); // Check working mode again .. because anozᅵther instance could be faster. // (It's possible to set this guard at first of this method too!) if( m_aTransactionManager.getWorkingMode() == E_INIT ) { m_aMember = nValue; // Object is initialized now ... set working mode to E_WORK! m_aTransactionManager.setWorkingMode( E_WORK ); } } } @seealso method setWorkingMode() @param - @return Current set mode. @onerror No error should occure. *//*-*****************************************************************************************************/ EWorkingMode TransactionManager::getWorkingMode() const { // Synchronize access to internal member! ::osl::MutexGuard aAccessLock( m_aAccessLock ); return m_eWorkingMode; } /*-****************************************************************************************************//** @interface ITransactionManager @short start new transaction @descr A guard should use this method to start a new transaction. He should looks for rejected calls to by using parameter eMode and eReason. If call was not rejected your transaction will be non breakable during releasing your transaction guard! BUT ... your code isn't threadsafe then! It's a transaction manager only .... @seealso method unregisterTransaction() @param "eMode" ,used to enable/disable throwing exceptions automaticly for rejected calls @param "eReason" ,reason for rejected calls if eMode=E_NOEXCEPTIONS @return - @onerror - *//*-*****************************************************************************************************/ void TransactionManager::registerTransaction( EExceptionMode eMode, ERejectReason& eReason ) throw( css::uno::RuntimeException, css::lang::DisposedException ) { // Look for rejected calls first. // If call was refused we throw some exceptions or do nothing! // It depends from given parameter eMode. if( isCallRejected( eReason ) == sal_True ) { impl_throwExceptions( eMode, eReason ); } // BUT if no exception was thrown ... (may be eMode = E_SOFTEXCEPTIONS!) // we must register this transaction too! // Don't use "else" or a new scope here!!! // Safe access to internal member. ::osl::MutexGuard aAccessGuard( m_aAccessLock ); // Register this new transaction. // If it is the first one .. close gate to disable changing of working mode. ++m_nTransactionCount; if( m_nTransactionCount == 1 ) { m_aBarrier.close(); } } /*-****************************************************************************************************//** @interface ITransactionManager @short finish transaction @descr A guard should call this method to release current transaction. @seealso method registerTransaction() @param - @return - @onerror - *//*-*****************************************************************************************************/ void TransactionManager::unregisterTransaction() throw( css::uno::RuntimeException, css::lang::DisposedException ) { // This call could not rejected! // Safe access to internal member. ::osl::MutexGuard aAccessGuard( m_aAccessLock ); // Deregister this transaction. // If it was the last one ... open gate to enable changing of working mode! // (see setWorkingMode()) --m_nTransactionCount; if( m_nTransactionCount == 0 ) { m_aBarrier.open(); } } /*-****************************************************************************************************//** @interface ITransactionManager @short look for rejected calls @descr Sometimes user need a possibility to get information about rejected calls without starting a transaction! @seealso - @param "eReason" returns reason of a rejected call @return true if call was rejected, false otherwise @onerror We return false. *//*-*****************************************************************************************************/ sal_Bool TransactionManager::isCallRejected( ERejectReason& eReason ) const { // This call must safe access to internal member only. // Set "possible reason" for return and check reject-state then! // User should look for return value first - reason then ... ::osl::MutexGuard aAccessGuard( m_aAccessLock ); switch( m_eWorkingMode ) { case E_INIT : eReason = E_UNINITIALIZED ; break; case E_WORK : eReason = E_NOREASON ; break; case E_BEFORECLOSE : eReason = E_INCLOSE ; break; case E_CLOSE : eReason = E_CLOSED ; break; } return( eReason!=E_NOREASON ); } /*-****************************************************************************************************//** @short throw any exceptions for rejected calls @descr If user whish to use our automaticly exception mode we use this impl-method. We check all combinations of eReason and eExceptionMode and throw right exception with some descriptions for recipient of it. @seealso method registerTransaction() @seealso enum ERejectReason @seealso enum EExceptionMode @param "eReason" , reason for rejected call @param "eMode" , exception mode - set by user @return - @onerror - *//*-*****************************************************************************************************/ void TransactionManager::impl_throwExceptions( EExceptionMode eMode, ERejectReason eReason ) const throw( css::uno::RuntimeException, css::lang::DisposedException ) { if( eMode != E_NOEXCEPTIONS ) { switch( eReason ) { case E_UNINITIALIZED : if( eMode == E_HARDEXCEPTIONS ) { // Help programmer to find out, why this exception is thrown! LOG_ERROR( "TransactionManager...", "Owner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!" ) //ATTENTION: temp. disabled - till all bad code positions are detected and changed! */ // throw css::uno::RuntimeException( DECLARE_ASCII("TransactionManager...\nOwner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!\n" ), css::uno::Reference< css::uno::XInterface >() ); } break; case E_INCLOSE : if( eMode == E_HARDEXCEPTIONS ) { // Help programmer to find out, why this exception is thrown! LOG_ERROR( "TransactionManager...", "Owner instance stand in close method. Call was rejected!" ) throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance stand in close method. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() ); } break; case E_CLOSED : { // Help programmer to find out, why this exception is thrown! LOG_ERROR( "TransactionManager...", "Owner instance already closed. Call was rejected!" ) throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance already closed. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() ); } case E_NOREASON : { // Help programmer to find out LOG_ERROR( "TransactionManager...", "Impossible case E_NOREASON!" ) } break; default: break; // nothing to do } } } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>improve comments<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <threadhelp/transactionmanager.hxx> #include <threadhelp/resetableguard.hxx> #include <macros/debug.hxx> #include <macros/generic.hxx> #include <fwidllapi.h> #include <com/sun/star/lang/DisposedException.hpp> namespace framework{ /*-************************************************************************************************************//** @short standard ctor @descr Initialize instance with right start values for correct working. @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ TransactionManager::TransactionManager() : m_eWorkingMode ( E_INIT ) , m_nTransactionCount ( 0 ) { m_aBarrier.open(); } /*-************************************************************************************************************//** @short standard dtor @descr - @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ TransactionManager::~TransactionManager() { } /*-****************************************************************************************************//** @interface ITransactionManager @short set new working mode @descr These implementation knows for states of working: E_INIT, E_WORK, E_CLOSING, E_CLOSE You can step during this ones only from the left to the right side and start at left side again! (This is neccessary e.g. for refcounted objects!) This call will block till all current existing transactions was finished. Follow results occure: E_INIT : All requests on this implementation are refused. It's your decision to react in a right way. E_WORK : The object can work now. The full functionality is available. E_BEFORECLOSE : The object start the closing mechanism ... but sometimes e.g. the dispose() method need to call some private methods. These some special methods should use E_SOFTEXCEPTIONS or ignore E_INCLOSE as returned reason for E_NOEXCEPTIONS to detect this special case! E_CLOSE : Object is already dead! All further requests will be refused. It's your decision to react in a right way. @seealso - @param "eMode", is the new mode - but we don't accept setting mode in wrong order! @return - @onerror We do nothing. *//*-*****************************************************************************************************/ void TransactionManager::setWorkingMode( EWorkingMode eMode ) { // Safe member access. ::osl::ClearableMutexGuard aAccessGuard( m_aAccessLock ); sal_Bool bWaitFor = sal_False ; // Change working mode first! if ( ( m_eWorkingMode == E_INIT && eMode == E_WORK ) || ( m_eWorkingMode == E_WORK && eMode == E_BEFORECLOSE ) || ( m_eWorkingMode == E_BEFORECLOSE && eMode == E_CLOSE ) || ( m_eWorkingMode == E_CLOSE && eMode == E_INIT ) ) { m_eWorkingMode = eMode; if( m_eWorkingMode == E_BEFORECLOSE || m_eWorkingMode == E_CLOSE ) { bWaitFor = sal_True; } } // Wait for current existing transactions then! // (Only necessary for changing to E_BEFORECLOSE or E_CLOSE! ... // otherwise; if you wait at setting E_WORK another thrad could finish a acquire-call during our unlock() and wait() call // ... and we will wait forever here!!!) // Don't forget to release access mutex before. aAccessGuard.clear(); if( bWaitFor == sal_True ) { m_aBarrier.wait(); } } /*-****************************************************************************************************//** @interface ITransactionManager @short get current working mode @descr If you stand in your close() or init() method ... but don't know if you called more then ones(!) ... you can use this function to get right information. e.g: You have a method init() which is used to change working mode from E_INIT to E_WORK and should be used to initialize some member too ... What should you do: void init( sal_Int32 nValue ) { // Reject this call if our transaction manager say: "Object already initialized!" // Otherwise initialize your member. if( m_aTransactionManager.getWorkingMode() == E_INIT ) { // Object is uninitialized ... // Make member access threadsafe! ResetableGuard aGuard( m_aMutex ); // Check working mode again .. because anozᅵther instance could be faster. // (It's possible to set this guard at first of this method too!) if( m_aTransactionManager.getWorkingMode() == E_INIT ) { m_aMember = nValue; // Object is initialized now ... set working mode to E_WORK! m_aTransactionManager.setWorkingMode( E_WORK ); } } } @seealso method setWorkingMode() @param - @return Current set mode. @onerror No error should occure. *//*-*****************************************************************************************************/ EWorkingMode TransactionManager::getWorkingMode() const { // Synchronize access to internal member! ::osl::MutexGuard aAccessLock( m_aAccessLock ); return m_eWorkingMode; } /*-****************************************************************************************************//** @interface ITransactionManager @short start new transaction @descr A guard should use this method to start a new transaction. He should looks for rejected calls to by using parameter eMode and eReason. If call was not rejected your transaction will be non breakable during releasing your transaction guard! BUT ... your code isn't threadsafe then! It's a transaction manager only .... @seealso method unregisterTransaction() @param "eMode" ,used to enable/disable throwing exceptions automatically for rejected calls @param "eReason" ,reason for rejected calls if eMode=E_NOEXCEPTIONS @return - @onerror - *//*-*****************************************************************************************************/ void TransactionManager::registerTransaction( EExceptionMode eMode, ERejectReason& eReason ) throw( css::uno::RuntimeException, css::lang::DisposedException ) { // Look for rejected calls first. // If call was refused we throw some exceptions or do nothing! // It depends from given parameter eMode. if( isCallRejected( eReason ) == sal_True ) { impl_throwExceptions( eMode, eReason ); } // BUT if no exception was thrown ... (may be eMode = E_SOFTEXCEPTIONS!) // we must register this transaction too! // Don't use "else" or a new scope here!!! // Safe access to internal member. ::osl::MutexGuard aAccessGuard( m_aAccessLock ); // Register this new transaction. // If it is the first one .. close gate to disable changing of working mode. ++m_nTransactionCount; if( m_nTransactionCount == 1 ) { m_aBarrier.close(); } } /*-****************************************************************************************************//** @interface ITransactionManager @short finish transaction @descr A guard should call this method to release current transaction. @seealso method registerTransaction() @param - @return - @onerror - *//*-*****************************************************************************************************/ void TransactionManager::unregisterTransaction() throw( css::uno::RuntimeException, css::lang::DisposedException ) { // This call could not rejected! // Safe access to internal member. ::osl::MutexGuard aAccessGuard( m_aAccessLock ); // Deregister this transaction. // If it was the last one ... open gate to enable changing of working mode! // (see setWorkingMode()) --m_nTransactionCount; if( m_nTransactionCount == 0 ) { m_aBarrier.open(); } } /*-****************************************************************************************************//** @interface ITransactionManager @short look for rejected calls @descr Sometimes user need a possibility to get information about rejected calls without starting a transaction! @seealso - @param "eReason" returns reason of a rejected call @return true if call was rejected, false otherwise @onerror We return false. *//*-*****************************************************************************************************/ sal_Bool TransactionManager::isCallRejected( ERejectReason& eReason ) const { // This call must safe access to internal member only. // Set "possible reason" for return and check reject-state then! // User should look for return value first - reason then ... ::osl::MutexGuard aAccessGuard( m_aAccessLock ); switch( m_eWorkingMode ) { case E_INIT : eReason = E_UNINITIALIZED ; break; case E_WORK : eReason = E_NOREASON ; break; case E_BEFORECLOSE : eReason = E_INCLOSE ; break; case E_CLOSE : eReason = E_CLOSED ; break; } return( eReason!=E_NOREASON ); } /*-****************************************************************************************************//** @short throw any exceptions for rejected calls @descr If a user wishes to use our automatic exception mode we use this impl-method. We check all combinations of eReason and eExceptionMode and throw correct exception with some descriptions for the recipient. @seealso method registerTransaction() @seealso enum ERejectReason @seealso enum EExceptionMode @param "eReason" , reason for rejected call @param "eMode" , exception mode - set by user @return - @onerror - *//*-*****************************************************************************************************/ void TransactionManager::impl_throwExceptions( EExceptionMode eMode, ERejectReason eReason ) const throw( css::uno::RuntimeException, css::lang::DisposedException ) { if( eMode != E_NOEXCEPTIONS ) { switch( eReason ) { case E_UNINITIALIZED : if( eMode == E_HARDEXCEPTIONS ) { // Help programmer to find out, why this exception is thrown! LOG_ERROR( "TransactionManager...", "Owner instance not correctly initialized yet. Call was rejected! Normally it's an algorithm error ... wrong use of class!" ) //ATTENTION: temp. disabled - till all bad code positions are detected and changed! */ // throw css::uno::RuntimeException( DECLARE_ASCII("TransactionManager...\nOwner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!\n" ), css::uno::Reference< css::uno::XInterface >() ); } break; case E_INCLOSE : if( eMode == E_HARDEXCEPTIONS ) { // Help programmer to find out, why this exception is thrown! LOG_ERROR( "TransactionManager...", "Owner instance stand in close method. Call was rejected!" ) throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance stand in close method. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() ); } break; case E_CLOSED : { // Help programmer to find out, why this exception is thrown! LOG_ERROR( "TransactionManager...", "Owner instance already closed. Call was rejected!" ) throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance already closed. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() ); } case E_NOREASON : { // Help programmer to find out LOG_ERROR( "TransactionManager...", "Impossible case E_NOREASON!" ) } break; default: break; // nothing to do } } } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// hydraulic.C // // Copyright 1996-2001 Per Abrahamsen and Sren Hansen // Copyright 2000-2001 KVL. // // This file is part of Daisy. // // Daisy is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // Daisy 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 Public License for more details. // // You should have received a copy of the GNU Lesser Public License // along with Daisy; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "hydraulic.h" #include "plf.h" #include "log.h" #include "tmpstream.h" #include "check_range.h" void Hydraulic::set_porosity (double Theta) { daisy_assert (Theta > Theta_res); Theta_sat = Theta; } void Hydraulic::output (Log& log) const { log.output ("Theta_sat", Theta_sat); } void Hydraulic::K_to_M (PLF& plf, const int intervals) const { static const double h0 = -20000.0; const double Ksat = K (0.0); const double max_change = pow (Ksat / K (h0), 1.0 / intervals); double step = (0 - h0) / 4.0; double h = h0; double sum = 0.0; while (h < 0) { plf.add (h, sum); step *= 2; while (K (h + step) / K (h) > max_change) { if (step < 1e-15) { TmpStream tmp; tmp () << "Hydraulic conductivity changes too fast in " << name << "\n"; tmp () << "h = " << h << ", step = " << step << " and h + step = " << h + step << "\n"; tmp () << "K (h) = " << K (h) << ", K (h + step) = " << K (h + step) << " and K (0) = " << Ksat << "\n"; tmp () << "Change = " << K (h + step) / K (h) << " > Max = " << max_change; daisy_warning (tmp.str ()); break; } step /= 2; } sum += step * (K (h) + K (h + step)) / 2; h += step; } plf.add (h, sum); } bool Hydraulic::zero_Theta_res (const AttributeList& al, Treelog& err) { bool ok = true; if (al.number ("Theta_res") != 0.0) { err.error ("Theta_res should be zero for this model"); ok = false; } return ok; } static bool check_alist (const AttributeList& al, Treelog& err) { bool ok = true; const double Theta_res = al.number ("Theta_res"); const double Theta_sat = al.number ("Theta_sat"); if (Theta_res >= Theta_sat) { err.error ("Theta_sat should be above Theta_res"); ok = false; } return ok; } void Hydraulic::load_syntax (Syntax& syntax, AttributeList& alist) { syntax.add_check (check_alist); static RangeEI K_sat_range (0.0, 0.9); syntax.add ("Theta_sat", "cm^3 H2O/cm^3", K_sat_range, Syntax::State, "Saturation point."); syntax.add ("Theta_res", "cm^3 H2O/cm^3", Check::fraction (), Syntax::Const, "Soil residual water."); alist.add ("Theta_res", 0.0); } void Hydraulic::initialize (double /* clay */, double /* silt */, double /* sand */, double /* humus */, double /* rho_b */, bool /* top_soil */, Treelog&) { } Hydraulic::Hydraulic (const AttributeList& al) : name (al.name ("type")), Theta_sat (al.number ("Theta_sat")), Theta_res (al.number ("Theta_res")) { } Hydraulic::~Hydraulic () { } EMPTY_TEMPLATE Librarian<Hydraulic>::Content* Librarian<Hydraulic>::content = NULL; const char *const Hydraulic::description = "\ This component is responsible for specifying the soils hydraulic\n\ properties."; <commit_msg>bcc warning<commit_after>// hydraulic.C // // Copyright 1996-2001 Per Abrahamsen and Sren Hansen // Copyright 2000-2001 KVL. // // This file is part of Daisy. // // Daisy is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // Daisy 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 Public License for more details. // // You should have received a copy of the GNU Lesser Public License // along with Daisy; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "hydraulic.h" #include "plf.h" #include "log.h" #include "tmpstream.h" #include "check_range.h" void Hydraulic::set_porosity (double Theta) { daisy_assert (Theta > Theta_res); Theta_sat = Theta; } void Hydraulic::output (Log& log) const { log.output ("Theta_sat", Theta_sat); } void Hydraulic::K_to_M (PLF& plf, const int intervals) const { static const double h0 = -20000.0; const double Ksat = K (0.0); const double max_change = pow (Ksat / K (h0), 1.0 / intervals); double step = (0 - h0) / 4.0; double h = h0; double sum = 0.0; while (h < 0) { plf.add (h, sum); step *= 2; while (K (h + step) / K (h) > max_change) { if (step < 1e-15) { TmpStream tmp; tmp () << "Hydraulic conductivity changes too fast in " << name << "\n"; tmp () << "h = " << h << ", step = " << step << " and h + step = " << (h + step) << "\n"; tmp () << "K (h) = " << K (h) << ", K (h + step) = " << K (h + step) << " and K (0) = " << Ksat << "\n"; tmp () << "Change = " << K (h + step) / K (h) << " > Max = " << max_change; daisy_warning (tmp.str ()); break; } step /= 2; } sum += step * (K (h) + K (h + step)) / 2; h += step; } plf.add (h, sum); } bool Hydraulic::zero_Theta_res (const AttributeList& al, Treelog& err) { bool ok = true; if (al.number ("Theta_res") != 0.0) { err.error ("Theta_res should be zero for this model"); ok = false; } return ok; } static bool check_alist (const AttributeList& al, Treelog& err) { bool ok = true; const double Theta_res = al.number ("Theta_res"); const double Theta_sat = al.number ("Theta_sat"); if (Theta_res >= Theta_sat) { err.error ("Theta_sat should be above Theta_res"); ok = false; } return ok; } void Hydraulic::load_syntax (Syntax& syntax, AttributeList& alist) { syntax.add_check (check_alist); static RangeEI K_sat_range (0.0, 0.9); syntax.add ("Theta_sat", "cm^3 H2O/cm^3", K_sat_range, Syntax::State, "Saturation point."); syntax.add ("Theta_res", "cm^3 H2O/cm^3", Check::fraction (), Syntax::Const, "Soil residual water."); alist.add ("Theta_res", 0.0); } void Hydraulic::initialize (double /* clay */, double /* silt */, double /* sand */, double /* humus */, double /* rho_b */, bool /* top_soil */, Treelog&) { } Hydraulic::Hydraulic (const AttributeList& al) : name (al.name ("type")), Theta_sat (al.number ("Theta_sat")), Theta_res (al.number ("Theta_res")) { } Hydraulic::~Hydraulic () { } EMPTY_TEMPLATE Librarian<Hydraulic>::Content* Librarian<Hydraulic>::content = NULL; const char *const Hydraulic::description = "\ This component is responsible for specifying the soils hydraulic\n\ properties."; <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include <mapnik/map.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/agg_renderer.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/image_util.hpp> #include <mapnik/config_error.hpp> #if defined(HAVE_CAIRO) // cairo #include <mapnik/cairo_renderer.hpp> #include <cairomm/surface.h> #endif #include <iostream> int main ( int argc , char** argv) { if (argc != 2) { std::cout << "usage: ./rundemo <mapnik_install_dir>\nUsually /usr/local/lib/mapnik\n"; std::cout << "Warning: ./rundemo looks for data in ../data/,\nTherefore must be run from within the demo/c++ folder.\n"; return EXIT_SUCCESS; } using namespace mapnik; try { std::cout << " running demo ... \n"; std::string mapnik_dir(argv[1]); std::cout << " looking for 'shape.input' plugin in... " << mapnik_dir << "/input/" << "\n"; datasource_cache::instance()->register_datasources(mapnik_dir + "/input/"); std::cout << " looking for DejaVuSans font in... " << mapnik_dir << "/fonts/DejaVuSans.ttf" << "\n"; freetype_engine::register_font(mapnik_dir + "/fonts/DejaVuSans.ttf"); Map m(800,600); m.set_background(color_factory::from_string("white")); // create styles // Provinces (polygon) feature_type_style provpoly_style; rule provpoly_rule_on; provpoly_rule_on.set_filter(parse_expression("[NAME_EN] = 'Ontario'")); provpoly_rule_on.append(polygon_symbolizer(color(250, 190, 183))); provpoly_style.add_rule(provpoly_rule_on); rule provpoly_rule_qc; provpoly_rule_qc.set_filter(parse_expression("[NOM_FR] = 'Qubec'")); provpoly_rule_qc.append(polygon_symbolizer(color(217, 235, 203))); provpoly_style.add_rule(provpoly_rule_qc); m.insert_style("provinces",provpoly_style); // Provinces (polyline) feature_type_style provlines_style; stroke provlines_stk (color(0,0,0),1.0); provlines_stk.add_dash(8, 4); provlines_stk.add_dash(2, 2); provlines_stk.add_dash(2, 2); rule provlines_rule; provlines_rule.append(line_symbolizer(provlines_stk)); provlines_style.add_rule(provlines_rule); m.insert_style("provlines",provlines_style); // Drainage feature_type_style qcdrain_style; rule qcdrain_rule; qcdrain_rule.set_filter(parse_expression("[HYC] = 8")); qcdrain_rule.append(polygon_symbolizer(color(153, 204, 255))); qcdrain_style.add_rule(qcdrain_rule); m.insert_style("drainage",qcdrain_style); // Roads 3 and 4 (The "grey" roads) feature_type_style roads34_style; rule roads34_rule; roads34_rule.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4")); stroke roads34_rule_stk(color(171,158,137),2.0); roads34_rule_stk.set_line_cap(ROUND_CAP); roads34_rule_stk.set_line_join(ROUND_JOIN); roads34_rule.append(line_symbolizer(roads34_rule_stk)); roads34_style.add_rule(roads34_rule); m.insert_style("smallroads",roads34_style); // Roads 2 (The thin yellow ones) feature_type_style roads2_style_1; rule roads2_rule_1; roads2_rule_1.set_filter(parse_expression("[CLASS] = 2")); stroke roads2_rule_stk_1(color(171,158,137),4.0); roads2_rule_stk_1.set_line_cap(ROUND_CAP); roads2_rule_stk_1.set_line_join(ROUND_JOIN); roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1)); roads2_style_1.add_rule(roads2_rule_1); m.insert_style("road-border", roads2_style_1); feature_type_style roads2_style_2; rule roads2_rule_2; roads2_rule_2.set_filter(parse_expression("[CLASS] = 2")); stroke roads2_rule_stk_2(color(255,250,115),2.0); roads2_rule_stk_2.set_line_cap(ROUND_CAP); roads2_rule_stk_2.set_line_join(ROUND_JOIN); roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2)); roads2_style_2.add_rule(roads2_rule_2); m.insert_style("road-fill", roads2_style_2); // Roads 1 (The big orange ones, the highways) feature_type_style roads1_style_1; rule roads1_rule_1; roads1_rule_1.set_filter(parse_expression("[CLASS] = 1")); stroke roads1_rule_stk_1(color(188,149,28),7.0); roads1_rule_stk_1.set_line_cap(ROUND_CAP); roads1_rule_stk_1.set_line_join(ROUND_JOIN); roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1)); roads1_style_1.add_rule(roads1_rule_1); m.insert_style("highway-border", roads1_style_1); feature_type_style roads1_style_2; rule roads1_rule_2; roads1_rule_2.set_filter(parse_expression("[CLASS] = 1")); stroke roads1_rule_stk_2(color(242,191,36),5.0); roads1_rule_stk_2.set_line_cap(ROUND_CAP); roads1_rule_stk_2.set_line_join(ROUND_JOIN); roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2)); roads1_style_2.add_rule(roads1_rule_2); m.insert_style("highway-fill", roads1_style_2); // Populated Places feature_type_style popplaces_style; rule popplaces_rule; text_symbolizer popplaces_text_symbolizer(parse_expression("[GEONAME]"),"DejaVu Sans Book",10,color(0,0,0)); popplaces_text_symbolizer.set_halo_fill(color(255,255,200)); popplaces_text_symbolizer.set_halo_radius(1); popplaces_rule.append(popplaces_text_symbolizer); popplaces_style.add_rule(popplaces_rule); m.insert_style("popplaces",popplaces_style ); // layers // Provincial polygons { parameters p; p["type"]="shape"; p["file"]="../data/boundaries"; layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provinces"); m.addLayer(lyr); } // Drainage { parameters p; p["type"]="shape"; p["file"]="../data/qcdrainage"; layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } { parameters p; p["type"]="shape"; p["file"]="../data/ontdrainage"; layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } // Provincial boundaries { parameters p; p["type"]="shape"; p["file"]="../data/boundaries_l"; layer lyr("Provincial borders"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provlines"); m.addLayer(lyr); } // Roads { parameters p; p["type"]="shape"; p["file"]="../data/roads"; layer lyr("Roads"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("smallroads"); lyr.add_style("road-border"); lyr.add_style("road-fill"); lyr.add_style("highway-border"); lyr.add_style("highway-fill"); m.addLayer(lyr); } // popplaces { parameters p; p["type"]="shape"; p["file"]="../data/popplaces"; p["encoding"] = "latin1"; layer lyr("Populated Places"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("popplaces"); m.addLayer(lyr); } m.zoom_to_box(box2d<double>(1405120.04127408,-247003.813399447, 1706357.31328276,-25098.593149577)); image_32 buf(m.width(),m.height()); agg_renderer<image_32> ren(m,buf); ren.apply(); save_to_file<image_data_32>(buf.data(),"demo.jpg","jpeg"); save_to_file<image_data_32>(buf.data(),"demo.png","png"); save_to_file<image_data_32>(buf.data(),"demo256.png","png256"); save_to_file<image_data_32>(buf.data(),"demo.tif","tiff"); std::cout << "Three maps have been rendered using AGG in the current directory:\n" "- demo.jpg\n" "- demo.png\n" "- demo256.png\n" "- demo.tif\n" "Have a look!\n"; #if defined(HAVE_CAIRO) Cairo::RefPtr<Cairo::ImageSurface> image_surface; image_surface = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, m.width(),m.height()); cairo_renderer<Cairo::Surface> png_render(m, image_surface); png_render.apply(); image_surface->write_to_png("cairo-demo.png"); image_32 im(image_surface); save_to_file(im, "cairo-demo256.png","png256"); Cairo::RefPtr<Cairo::Surface> surface; surface = Cairo::PdfSurface::create("cairo-demo.pdf", m.width(),m.height()); cairo_renderer<Cairo::Surface> pdf_render(m, surface); pdf_render.apply(); surface = Cairo::SvgSurface::create("cairo-demo.svg", m.width(),m.height()); cairo_renderer<Cairo::Surface> svg_render(m, surface); svg_render.apply(); std::cout << "Three maps have been rendered using Cairo in the current directory:\n" "- cairo-demo.png\n" "- cairo-demo256.png\n" "- cairo-demo.pdf\n" "- cairo-demo.svg\n" "Have a look!\n"; #endif } catch ( const mapnik::config_error & ex ) { std::cerr << "### Configuration error: " << ex.what() << std::endl; return EXIT_FAILURE; } catch ( const std::exception & ex ) { std::cerr << "### std::exception: " << ex.what() << std::endl; return EXIT_FAILURE; } catch ( ... ) { std::cerr << "### Unknown exception." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>whitespace fixes<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include <mapnik/map.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/agg_renderer.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/image_util.hpp> #include <mapnik/config_error.hpp> #if defined(HAVE_CAIRO) // cairo #include <mapnik/cairo_renderer.hpp> #include <cairomm/surface.h> #endif #include <iostream> int main ( int argc , char** argv) { if (argc != 2) { std::cout << "usage: ./rundemo <mapnik_install_dir>\nUsually /usr/local/lib/mapnik\n"; std::cout << "Warning: ./rundemo looks for data in ../data/,\nTherefore must be run from within the demo/c++ folder.\n"; return EXIT_SUCCESS; } using namespace mapnik; try { std::cout << " running demo ... \n"; std::string mapnik_dir(argv[1]); std::cout << " looking for 'shape.input' plugin in... " << mapnik_dir << "/input/" << "\n"; datasource_cache::instance()->register_datasources(mapnik_dir + "/input/"); std::cout << " looking for DejaVuSans font in... " << mapnik_dir << "/fonts/DejaVuSans.ttf" << "\n"; freetype_engine::register_font(mapnik_dir + "/fonts/DejaVuSans.ttf"); Map m(800,600); m.set_background(color_factory::from_string("white")); // create styles // Provinces (polygon) feature_type_style provpoly_style; rule provpoly_rule_on; provpoly_rule_on.set_filter(parse_expression("[NAME_EN] = 'Ontario'")); provpoly_rule_on.append(polygon_symbolizer(color(250, 190, 183))); provpoly_style.add_rule(provpoly_rule_on); rule provpoly_rule_qc; provpoly_rule_qc.set_filter(parse_expression("[NOM_FR] = 'Qubec'")); provpoly_rule_qc.append(polygon_symbolizer(color(217, 235, 203))); provpoly_style.add_rule(provpoly_rule_qc); m.insert_style("provinces",provpoly_style); // Provinces (polyline) feature_type_style provlines_style; stroke provlines_stk (color(0,0,0),1.0); provlines_stk.add_dash(8, 4); provlines_stk.add_dash(2, 2); provlines_stk.add_dash(2, 2); rule provlines_rule; provlines_rule.append(line_symbolizer(provlines_stk)); provlines_style.add_rule(provlines_rule); m.insert_style("provlines",provlines_style); // Drainage feature_type_style qcdrain_style; rule qcdrain_rule; qcdrain_rule.set_filter(parse_expression("[HYC] = 8")); qcdrain_rule.append(polygon_symbolizer(color(153, 204, 255))); qcdrain_style.add_rule(qcdrain_rule); m.insert_style("drainage",qcdrain_style); // Roads 3 and 4 (The "grey" roads) feature_type_style roads34_style; rule roads34_rule; roads34_rule.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4")); stroke roads34_rule_stk(color(171,158,137),2.0); roads34_rule_stk.set_line_cap(ROUND_CAP); roads34_rule_stk.set_line_join(ROUND_JOIN); roads34_rule.append(line_symbolizer(roads34_rule_stk)); roads34_style.add_rule(roads34_rule); m.insert_style("smallroads",roads34_style); // Roads 2 (The thin yellow ones) feature_type_style roads2_style_1; rule roads2_rule_1; roads2_rule_1.set_filter(parse_expression("[CLASS] = 2")); stroke roads2_rule_stk_1(color(171,158,137),4.0); roads2_rule_stk_1.set_line_cap(ROUND_CAP); roads2_rule_stk_1.set_line_join(ROUND_JOIN); roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1)); roads2_style_1.add_rule(roads2_rule_1); m.insert_style("road-border", roads2_style_1); feature_type_style roads2_style_2; rule roads2_rule_2; roads2_rule_2.set_filter(parse_expression("[CLASS] = 2")); stroke roads2_rule_stk_2(color(255,250,115),2.0); roads2_rule_stk_2.set_line_cap(ROUND_CAP); roads2_rule_stk_2.set_line_join(ROUND_JOIN); roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2)); roads2_style_2.add_rule(roads2_rule_2); m.insert_style("road-fill", roads2_style_2); // Roads 1 (The big orange ones, the highways) feature_type_style roads1_style_1; rule roads1_rule_1; roads1_rule_1.set_filter(parse_expression("[CLASS] = 1")); stroke roads1_rule_stk_1(color(188,149,28),7.0); roads1_rule_stk_1.set_line_cap(ROUND_CAP); roads1_rule_stk_1.set_line_join(ROUND_JOIN); roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1)); roads1_style_1.add_rule(roads1_rule_1); m.insert_style("highway-border", roads1_style_1); feature_type_style roads1_style_2; rule roads1_rule_2; roads1_rule_2.set_filter(parse_expression("[CLASS] = 1")); stroke roads1_rule_stk_2(color(242,191,36),5.0); roads1_rule_stk_2.set_line_cap(ROUND_CAP); roads1_rule_stk_2.set_line_join(ROUND_JOIN); roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2)); roads1_style_2.add_rule(roads1_rule_2); m.insert_style("highway-fill", roads1_style_2); // Populated Places feature_type_style popplaces_style; rule popplaces_rule; text_symbolizer popplaces_text_symbolizer(parse_expression("[GEONAME]"),"DejaVu Sans Book",10,color(0,0,0)); popplaces_text_symbolizer.set_halo_fill(color(255,255,200)); popplaces_text_symbolizer.set_halo_radius(1); popplaces_rule.append(popplaces_text_symbolizer); popplaces_style.add_rule(popplaces_rule); m.insert_style("popplaces",popplaces_style ); // layers // Provincial polygons { parameters p; p["type"]="shape"; p["file"]="../data/boundaries"; layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provinces"); m.addLayer(lyr); } // Drainage { parameters p; p["type"]="shape"; p["file"]="../data/qcdrainage"; layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } { parameters p; p["type"]="shape"; p["file"]="../data/ontdrainage"; layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } // Provincial boundaries { parameters p; p["type"]="shape"; p["file"]="../data/boundaries_l"; layer lyr("Provincial borders"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provlines"); m.addLayer(lyr); } // Roads { parameters p; p["type"]="shape"; p["file"]="../data/roads"; layer lyr("Roads"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("smallroads"); lyr.add_style("road-border"); lyr.add_style("road-fill"); lyr.add_style("highway-border"); lyr.add_style("highway-fill"); m.addLayer(lyr); } // popplaces { parameters p; p["type"]="shape"; p["file"]="../data/popplaces"; p["encoding"] = "latin1"; layer lyr("Populated Places"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("popplaces"); m.addLayer(lyr); } m.zoom_to_box(box2d<double>(1405120.04127408,-247003.813399447, 1706357.31328276,-25098.593149577)); image_32 buf(m.width(),m.height()); agg_renderer<image_32> ren(m,buf); ren.apply(); save_to_file<image_data_32>(buf.data(),"demo.jpg","jpeg"); save_to_file<image_data_32>(buf.data(),"demo.png","png"); save_to_file<image_data_32>(buf.data(),"demo256.png","png256"); save_to_file<image_data_32>(buf.data(),"demo.tif","tiff"); std::cout << "Three maps have been rendered using AGG in the current directory:\n" "- demo.jpg\n" "- demo.png\n" "- demo256.png\n" "- demo.tif\n" "Have a look!\n"; #if defined(HAVE_CAIRO) Cairo::RefPtr<Cairo::ImageSurface> image_surface; image_surface = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, m.width(),m.height()); cairo_renderer<Cairo::Surface> png_render(m, image_surface); png_render.apply(); image_surface->write_to_png("cairo-demo.png"); image_32 im(image_surface); save_to_file(im, "cairo-demo256.png","png256"); Cairo::RefPtr<Cairo::Surface> surface; surface = Cairo::PdfSurface::create("cairo-demo.pdf", m.width(),m.height()); cairo_renderer<Cairo::Surface> pdf_render(m, surface); pdf_render.apply(); surface = Cairo::SvgSurface::create("cairo-demo.svg", m.width(),m.height()); cairo_renderer<Cairo::Surface> svg_render(m, surface); svg_render.apply(); std::cout << "Three maps have been rendered using Cairo in the current directory:\n" "- cairo-demo.png\n" "- cairo-demo256.png\n" "- cairo-demo.pdf\n" "- cairo-demo.svg\n" "Have a look!\n"; #endif } catch ( const mapnik::config_error & ex ) { std::cerr << "### Configuration error: " << ex.what() << std::endl; return EXIT_FAILURE; } catch ( const std::exception & ex ) { std::cerr << "### std::exception: " << ex.what() << std::endl; return EXIT_FAILURE; } catch ( ... ) { std::cerr << "### Unknown exception." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <BlobExtractor.h> #include <BlobParams.h> #include <OptionalStream.h> #include <cvUtils.h> // Library/third-party includes #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // Standard includes #include <cmath> #include <iostream> #define OSVR_DEBUG_CONTOUR_CONDITIONS namespace osvr { namespace vbtracker { void showImage(std::string const &title, cv::Mat const &img) { cv::namedWindow(title); cv::imshow(title, img); } void handleImage(std::string const &fn, bool pause) { BlobParams p; p.filterByCircularity = true; p.minCircularity = 0.75; /// Initial image loading std::cout << "Handling image " << fn << std::endl; cv::Mat color = cv::imread(fn, cv::IMREAD_COLOR); if (!color.data) { std::cerr << "Could not load image!" << std::endl; return; } cv::Mat gray; cv::cvtColor(color, gray, cv::COLOR_BGR2GRAY); if (!gray.data) { std::cerr << "Conversion to gray failed?" << std::endl; return; } // showImage("Original", gray); /// Basic thresholding to reduce background noise auto thresholdInfo = ImageThresholdInfo(ImageRangeInfo(gray), p); cv::Mat thresholded; cv::threshold(gray, thresholded, p.absoluteMinThreshold, 255, cv::THRESH_TOZERO); showImage("Cleaned", thresholded); cv::imwrite(fn + ".thresh.png", thresholded); /// Edge detection cv::Mat edge; cv::Laplacian(thresholded, edge, CV_8U, 5); cv::imwrite(fn + ".edge.png", edge); showImage("Edges", edge); /// Extract beacons from the edge detection image std::vector<ContourType> contours; LedMeasurementVec measurements; // turn the edge detection into a binary image. cv::Mat edgeTemp = edge > 0; // The lambda ("continuation") is called with each "hole" in the edge // detection image, it's up to us what to do with the contour we're // given. We examine it for suitability as an LED, and if it passes our // checks, add a derived measurement to our measurement vector and the // contour itself to our list of contours for debugging display. consumeHolesOfConnectedComponents(edgeTemp, [&](ContourType &&contour) { auto data = getBlobDataFromContour(contour); auto debugStream = [] { #ifdef OSVR_DEBUG_CONTOUR_CONDITIONS return outputIf(std::cout, true); #else return outputIf(std::cout, false); #endif }; debugStream() << "\nContour centered at " << data.center; debugStream() << " - diameter: " << data.diameter; debugStream() << " - area: " << data.area; debugStream() << " - circularity: " << data.circularity; debugStream() << " - bounding box size: " << data.bounds.size(); if (data.area < p.minArea) { debugStream() << "Reject based on area: " << data.area << " < " << p.minArea << "\n"; return; } { /// Check to see if we accidentally picked up a non-LED /// stuck between a few bright ones. cv::Mat patch; cv::getRectSubPix(gray, cv::Size(1, 1), cv::Point2f(data.center), patch); auto centerPointValue = patch.at<unsigned char>(0, 0); if (centerPointValue < p.absoluteMinThreshold) { debugStream() << "Reject based on center point value: " << int(centerPointValue) << " < " << p.absoluteMinThreshold << "\n"; return; } } if (p.filterByCircularity) { if (data.circularity < p.minCircularity) { debugStream() << "Reject based on circularity: " << data.circularity << " < " << p.minCircularity << "\n"; return; } } if (p.filterByConvexity) { auto convexity = getConvexity(contour, data.area); debugStream() << " - convexity: " << convexity; if (convexity < p.minConvexity) { debugStream() << "Reject based on convexity: " << convexity << " < " << p.minConvexity << "\n"; return; } } debugStream() << "Accepted!\n"; { auto newMeas = LedMeasurement( cv::Point2f(data.center), static_cast<float>(data.diameter), gray.size(), static_cast<float>(data.area)); newMeas.circularity = static_cast<float>(data.circularity); newMeas.setBoundingBox(data.bounds); measurements.emplace_back(std::move(newMeas)); } contours.emplace_back(std::move(contour)); }); /// Produce a colored debug image where each accepted contour is /// encircled with a different color. cv::Mat highlightedContours = drawColoredContours(gray, contours); showImage("Selected contours", highlightedContours); cv::imwrite(fn + ".contours.png", highlightedContours); if (pause) { cv::waitKey(); } } } // namespace vbtracker } // namespace osvr int main(int argc, char *argv[]) { /// Don't stop before exiting if we've got multiple to process. bool pause = (argc < 3); for (int arg = 1; arg < argc; ++arg) { osvr::vbtracker::handleImage(argv[arg], true); } return 0; } <commit_msg>Remove the duplicate implementation now of the new blob detector.<commit_after>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <BlobExtractor.h> #include <BlobParams.h> #include <EdgeHoleBasedLedExtractor.h> #include <OptionalStream.h> #include <cvUtils.h> // Library/third-party includes #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // Standard includes #include <cmath> #include <iostream> namespace osvr { namespace vbtracker { void showImage(std::string const &title, cv::Mat const &img) { cv::namedWindow(title); cv::imshow(title, img); } void handleImage(std::string const &fn, bool pause) { BlobParams p; p.filterByCircularity = true; p.minCircularity = 0.75; /// Initial image loading std::cout << "Handling image " << fn << std::endl; cv::Mat color = cv::imread(fn, cv::IMREAD_COLOR); if (!color.data) { std::cerr << "Could not load image!" << std::endl; return; } cv::Mat gray; cv::cvtColor(color, gray, cv::COLOR_BGR2GRAY); if (!gray.data) { std::cerr << "Conversion to gray failed?" << std::endl; return; } // showImage("Original", gray); EdgeHoleBasedLedExtractor extractor; extractor(gray, p, true); /// Basic thresholding to reduce background noise showImage("Cleaned", extractor.getThresholdedImage()); cv::imwrite(fn + ".thresh.png", extractor.getThresholdedImage()); /// Edge detection showImage("Edges", extractor.getEdgeDetectedImage()); cv::imwrite(fn + ".edge.png", extractor.getEdgeDetectedImage()); /// Extract beacons from the edge detection image /// Produce a colored debug image where each accepted contour is /// encircled with a different color. cv::Mat highlightedContours = drawColoredContours(gray, extractor.getContours()); showImage("Selected contours", highlightedContours); cv::imwrite(fn + ".contours.png", highlightedContours); if (pause) { cv::waitKey(); } } } // namespace vbtracker } // namespace osvr int main(int argc, char *argv[]) { /// Don't stop before exiting if we've got multiple to process. bool pause = (argc < 3); for (int arg = 1; arg < argc; ++arg) { osvr::vbtracker::handleImage(argv[arg], true); } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/test/unit_test.hpp> #include "kaa/ClientStatus.hpp" #include "kaa/KaaDefaults.hpp" #include <map> #include <cstdlib> #include <fstream> #include <sstream> #include <utility> #ifdef RESOURCE_DIR const char * const filename = RESOURCE_DIR"/kaa_status.file"; #else const char * const filename = "kaa_status.file"; #endif void cleanfile() { std::remove(filename); } namespace kaa { BOOST_AUTO_TEST_SUITE(ClientStatusSuite); BOOST_AUTO_TEST_CASE(checkDefaults) { ClientStatus cs(filename); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().configurationSequenceNumber, 0); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().notificationSequenceNumber, 0); BOOST_CHECK_EQUAL(cs.isRegistered(), false); BOOST_CHECK_EQUAL(cs.getProfileHash().second, 0); BOOST_CHECK_EQUAL(cs.getTopicStates().size(), 0); BOOST_CHECK_EQUAL(cs.getAttachedEndpoints().size(), 0); BOOST_CHECK_EQUAL(cs.getEndpointAccessToken().empty(), true); BOOST_CHECK_EQUAL(cs.getEndpointAttachStatus(), false); cleanfile(); } BOOST_AUTO_TEST_CASE(checkSetAndSaveParameters) { ClientStatus cs(filename); cs.setAppSeqNumber({1,2,3}); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().configurationSequenceNumber, 1); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().notificationSequenceNumber, 2); cs.setRegistered(true); BOOST_CHECK_EQUAL(cs.isRegistered(), true); SharedDataBuffer sdb; sdb.first.reset(new std::uint8_t[5]); std::uint8_t *temp = sdb.first.get(); temp[0] = 1; temp[1] = 2; temp[2] = 2; temp[3] = 3; temp[4] = 4; sdb.second = 5; cs.setProfileHash(sdb); BOOST_CHECK_EQUAL(cs.getProfileHash().second, 5); BOOST_CHECK_EQUAL_COLLECTIONS(cs.getProfileHash().first.get(), cs.getProfileHash().first.get() + 5, temp, temp + 5); DetailedTopicStates empty_ts = cs.getTopicStates(); BOOST_CHECK_EQUAL(empty_ts.size(), 0); DetailedTopicStates ts; DetailedTopicState ts1; ts1.topicId = "topic1"; ts1.sequenceNumber = 100; ts1.topicName = "topicName1"; ts1.subscriptionType = SubscriptionType::MANDATORY; DetailedTopicState ts2; ts2.topicId = "topic2"; ts2.sequenceNumber = 200; ts2.topicName = "topicName2"; ts2.subscriptionType = SubscriptionType::OPTIONAL; ts.insert(std::make_pair(ts1.topicId, ts1)); ts.insert(std::make_pair(ts2.topicId, ts2)); cs.setTopicStates(ts); DetailedTopicStates act_ts = cs.getTopicStates(); BOOST_CHECK_EQUAL(act_ts.size(), 2); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].topicId, ts1.topicId); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].sequenceNumber, ts1.sequenceNumber); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].topicName, ts1.topicName); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].subscriptionType, ts1.subscriptionType); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].topicId, ts2.topicId); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].sequenceNumber, ts2.sequenceNumber); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].topicName, ts2.topicName); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].subscriptionType, ts2.subscriptionType); AttachedEndpoints attachedEndpoints; std::string token1("Token1"), hash1("hash1"); std::string token2("Token2"), hash2("hash2"); attachedEndpoints.insert(std::make_pair(token1, hash1)); attachedEndpoints.insert(std::make_pair(token2, hash2)); cs.setAttachedEndpoints(attachedEndpoints); std::string endpointAccessToken; bool isAttached = true; cs.setEndpointAttachStatus(isAttached); std::string endpointKeyHash = "thisEndpointKeyHash"; cs.setEndpointKeyHash(endpointKeyHash); cs.save(); ClientStatus cs_restored(filename); DetailedTopicStates act_ts1 = cs_restored.getTopicStates(); BOOST_CHECK_EQUAL(act_ts1.size(), 2); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].topicId, ts1.topicId); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].sequenceNumber, ts1.sequenceNumber); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].topicName, ts1.topicName); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].subscriptionType, ts1.subscriptionType); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].topicId, ts2.topicId); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].sequenceNumber, ts2.sequenceNumber); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].topicName, ts2.topicName); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].subscriptionType, ts2.subscriptionType); AttachedEndpoints restoredAttachedEndpoints = cs.getAttachedEndpoints(); BOOST_CHECK_EQUAL(restoredAttachedEndpoints[token1], hash1); BOOST_CHECK_EQUAL(restoredAttachedEndpoints[token2], hash2); BOOST_CHECK_EQUAL(cs_restored.getEndpointAccessToken(), endpointAccessToken); BOOST_CHECK_EQUAL(cs_restored.getEndpointAttachStatus(), isAttached); BOOST_CHECK_EQUAL(cs_restored.getEndpointKeyHash(), endpointKeyHash); cleanfile(); } BOOST_AUTO_TEST_CASE(checkConfigVersionUpdates) { const std::string filename(RESOURCE_DIR + std::string("/test_kaa_status.file")); ClientStatus cs(filename); BOOST_CHECK_MESSAGE(cs.isConfigurationVersionUpdated(), "Expect: configuration version is updated"); } } // namespace kaa BOOST_AUTO_TEST_SUITE_END() <commit_msg>Minor fix for the Cpp client status unit test<commit_after>/* * Copyright 2014 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/test/unit_test.hpp> #include "kaa/ClientStatus.hpp" #include "kaa/KaaDefaults.hpp" #include <map> #include <cstdlib> #include <fstream> #include <sstream> #include <utility> #ifdef RESOURCE_DIR const char * const filename = RESOURCE_DIR"/kaa_status.file"; #else const char * const filename = "kaa_status.file"; #endif void cleanfile() { std::remove(filename); } namespace kaa { BOOST_AUTO_TEST_SUITE(ClientStatusSuite); BOOST_AUTO_TEST_CASE(checkDefaults) { cleanfile(); ClientStatus cs(filename); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().configurationSequenceNumber, 0); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().notificationSequenceNumber, 0); BOOST_CHECK_EQUAL(cs.isRegistered(), false); BOOST_CHECK_EQUAL(cs.getProfileHash().second, 0); BOOST_CHECK_EQUAL(cs.getTopicStates().size(), 0); BOOST_CHECK_EQUAL(cs.getAttachedEndpoints().size(), 0); BOOST_CHECK_EQUAL(cs.getEndpointAccessToken().empty(), true); BOOST_CHECK_EQUAL(cs.getEndpointAttachStatus(), false); cleanfile(); } BOOST_AUTO_TEST_CASE(checkSetAndSaveParameters) { ClientStatus cs(filename); cs.setAppSeqNumber({1,2,3}); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().configurationSequenceNumber, 1); BOOST_CHECK_EQUAL(cs.getAppSeqNumber().notificationSequenceNumber, 2); cs.setRegistered(true); BOOST_CHECK_EQUAL(cs.isRegistered(), true); SharedDataBuffer sdb; sdb.first.reset(new std::uint8_t[5]); std::uint8_t *temp = sdb.first.get(); temp[0] = 1; temp[1] = 2; temp[2] = 2; temp[3] = 3; temp[4] = 4; sdb.second = 5; cs.setProfileHash(sdb); BOOST_CHECK_EQUAL(cs.getProfileHash().second, 5); BOOST_CHECK_EQUAL_COLLECTIONS(cs.getProfileHash().first.get(), cs.getProfileHash().first.get() + 5, temp, temp + 5); DetailedTopicStates empty_ts = cs.getTopicStates(); BOOST_CHECK_EQUAL(empty_ts.size(), 0); DetailedTopicStates ts; DetailedTopicState ts1; ts1.topicId = "topic1"; ts1.sequenceNumber = 100; ts1.topicName = "topicName1"; ts1.subscriptionType = SubscriptionType::MANDATORY; DetailedTopicState ts2; ts2.topicId = "topic2"; ts2.sequenceNumber = 200; ts2.topicName = "topicName2"; ts2.subscriptionType = SubscriptionType::OPTIONAL; ts.insert(std::make_pair(ts1.topicId, ts1)); ts.insert(std::make_pair(ts2.topicId, ts2)); cs.setTopicStates(ts); DetailedTopicStates act_ts = cs.getTopicStates(); BOOST_CHECK_EQUAL(act_ts.size(), 2); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].topicId, ts1.topicId); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].sequenceNumber, ts1.sequenceNumber); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].topicName, ts1.topicName); BOOST_CHECK_EQUAL(act_ts[ts1.topicId].subscriptionType, ts1.subscriptionType); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].topicId, ts2.topicId); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].sequenceNumber, ts2.sequenceNumber); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].topicName, ts2.topicName); BOOST_CHECK_EQUAL(act_ts[ts2.topicId].subscriptionType, ts2.subscriptionType); AttachedEndpoints attachedEndpoints; std::string token1("Token1"), hash1("hash1"); std::string token2("Token2"), hash2("hash2"); attachedEndpoints.insert(std::make_pair(token1, hash1)); attachedEndpoints.insert(std::make_pair(token2, hash2)); cs.setAttachedEndpoints(attachedEndpoints); std::string endpointAccessToken; bool isAttached = true; cs.setEndpointAttachStatus(isAttached); std::string endpointKeyHash = "thisEndpointKeyHash"; cs.setEndpointKeyHash(endpointKeyHash); cs.save(); ClientStatus cs_restored(filename); DetailedTopicStates act_ts1 = cs_restored.getTopicStates(); BOOST_CHECK_EQUAL(act_ts1.size(), 2); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].topicId, ts1.topicId); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].sequenceNumber, ts1.sequenceNumber); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].topicName, ts1.topicName); BOOST_CHECK_EQUAL(act_ts1[ts1.topicId].subscriptionType, ts1.subscriptionType); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].topicId, ts2.topicId); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].sequenceNumber, ts2.sequenceNumber); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].topicName, ts2.topicName); BOOST_CHECK_EQUAL(act_ts1[ts2.topicId].subscriptionType, ts2.subscriptionType); AttachedEndpoints restoredAttachedEndpoints = cs.getAttachedEndpoints(); BOOST_CHECK_EQUAL(restoredAttachedEndpoints[token1], hash1); BOOST_CHECK_EQUAL(restoredAttachedEndpoints[token2], hash2); BOOST_CHECK_EQUAL(cs_restored.getEndpointAccessToken(), endpointAccessToken); BOOST_CHECK_EQUAL(cs_restored.getEndpointAttachStatus(), isAttached); BOOST_CHECK_EQUAL(cs_restored.getEndpointKeyHash(), endpointKeyHash); cleanfile(); } BOOST_AUTO_TEST_CASE(checkConfigVersionUpdates) { const std::string filename(RESOURCE_DIR + std::string("/test_kaa_status.file")); ClientStatus cs(filename); BOOST_CHECK_MESSAGE(cs.isConfigurationVersionUpdated(), "Expect: configuration version is updated"); } } // namespace kaa BOOST_AUTO_TEST_SUITE_END() <|endoftext|>