text
string
size
int64
token_count
int64
// Copyright 2018 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/android/explore_sites/explore_sites_fetcher.h" #include <string> #include <utility> #include "base/bind.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_functions.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "base/version.h" #include "chrome/browser/android/explore_sites/catalog.pb.h" #include "chrome/browser/android/explore_sites/explore_sites_bridge.h" #include "chrome/browser/android/explore_sites/explore_sites_feature.h" #include "chrome/browser/android/explore_sites/explore_sites_types.h" #include "chrome/browser/android/explore_sites/url_util.h" #include "chrome/browser/flags/android/chrome_feature_list.h" #include "chrome/common/channel_info.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h" #include "google_apis/google_api_keys.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_request_headers.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "url/gurl.h" namespace explore_sites { namespace { // Content type needed in order to communicate with the server in binary // proto format. const char kRequestContentType[] = "application/x-protobuf"; const char kRequestMethod[] = "GET"; constexpr net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("explore_sites", R"( semantics { sender: "Explore Sites" description: "Downloads a catalog of categories and sites for the purposes of " "exploring the Web." trigger: "Periodically scheduled for update in the background and also " "triggered by New Tab Page UI." data: "Proto data comprising interesting site and category information." " No user information is sent." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO policy_exception_justification: "TODO(crbug.com/1231780): Add this field." })"); } // namespace const net::BackoffEntry::Policy ExploreSitesFetcher::kImmediateFetchBackoffPolicy = { 0, // Number of initial errors to ignore without backoff. 1 * 1000, // Initial delay for backoff in ms: 1 second. 2, // Factor to multiply for exponential backoff. 0, // Fuzzing percentage. 4 * 1000, // Maximum time to delay requests in ms: 4 seconds. -1, // Don't discard entry even if unused. false // Don't use initial delay unless the last was an error. }; const int ExploreSitesFetcher::kMaxFailureCountForImmediateFetch = 3; const net::BackoffEntry::Policy ExploreSitesFetcher::kBackgroundFetchBackoffPolicy = { 0, // Number of initial errors to ignore without backoff. 5 * 1000, // Initial delay for backoff in ms: 5 seconds. 2, // Factor to multiply for exponential backoff. 0, // Fuzzing percentage. 320 * 1000, // Maximum time to delay requests in ms: 320 seconds. -1, // Don't discard entry even if unused. false // Don't use initial delay unless the last was an error. }; const int ExploreSitesFetcher::kMaxFailureCountForBackgroundFetch = 2; // static std::unique_ptr<ExploreSitesFetcher> ExploreSitesFetcher::CreateForGetCatalog( bool is_immediate_fetch, const std::string& catalog_version, const std::string& accept_languages, const std::string& country_code, scoped_refptr<network::SharedURLLoaderFactory> loader_factory, Callback callback) { GURL url = GetCatalogURL(); return base::WrapUnique(new ExploreSitesFetcher( is_immediate_fetch, url, catalog_version, accept_languages, country_code, loader_factory, std::move(callback))); } ExploreSitesFetcher::ExploreSitesFetcher( bool is_immediate_fetch, const GURL& url, const std::string& catalog_version, const std::string& accept_languages, const std::string& country_code, scoped_refptr<network::SharedURLLoaderFactory> loader_factory, Callback callback) : is_immediate_fetch_(is_immediate_fetch), accept_languages_(accept_languages), country_code_(country_code), catalog_version_(catalog_version), url_(url), device_delegate_(std::make_unique<DeviceDelegate>()), callback_(std::move(callback)), url_loader_factory_(loader_factory) { base::Version version = version_info::GetVersion(); std::string channel_name = chrome::GetChannelName(chrome::WithExtendedStable(true)); client_version_ = base::StringPrintf("%d.%d.%d.%s.chrome", version.components()[0], // Major version.components()[2], // Build version.components()[3], // Patch channel_name.c_str()); UpdateBackoffEntry(); } ExploreSitesFetcher::~ExploreSitesFetcher() {} void ExploreSitesFetcher::Start() { auto resource_request = std::make_unique<network::ResourceRequest>(); GURL request_url = net::AppendOrReplaceQueryParameter(url_, "country_code", country_code_); request_url = net::AppendOrReplaceQueryParameter(request_url, "version_token", catalog_version_); resource_request->url = request_url; resource_request->method = kRequestMethod; bool is_stable_channel = chrome::GetChannel() == version_info::Channel::STABLE; std::string api_key = is_stable_channel ? google_apis::GetAPIKey() : google_apis::GetNonStableAPIKey(); resource_request->headers.SetHeader("x-goog-api-key", api_key); resource_request->headers.SetHeader("X-Client-Version", client_version_); resource_request->headers.SetHeader(net::HttpRequestHeaders::kContentType, kRequestContentType); std::string scale_factor = std::to_string(device_delegate_->GetScaleFactorFromDevice()); resource_request->headers.SetHeader("X-Device-Scale-Factor", scale_factor); if (!accept_languages_.empty()) { resource_request->headers.SetHeader( net::HttpRequestHeaders::kAcceptLanguage, accept_languages_); } // Get field trial value, if any. std::string tag = base::GetFieldTrialParamValueByFeature( chrome::android::kExploreSites, chrome::android::explore_sites:: kExploreSitesHeadersExperimentParameterName); if (!tag.empty()) { resource_request->headers.SetHeader("X-Goog-Chrome-Experiment-Tag", tag); } url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_.get(), base::BindOnce(&ExploreSitesFetcher::OnSimpleLoaderComplete, weak_factory_.GetWeakPtr())); } float ExploreSitesFetcher::DeviceDelegate::GetScaleFactorFromDevice() { return ExploreSitesBridge::GetScaleFactorFromDevice(); } void ExploreSitesFetcher::SetDeviceDelegateForTest( std::unique_ptr<ExploreSitesFetcher::DeviceDelegate> device_delegate) { device_delegate_ = std::move(device_delegate); } void ExploreSitesFetcher::RestartAsImmediateFetchIfNotYet() { if (is_immediate_fetch_) return; is_immediate_fetch_ = true; UpdateBackoffEntry(); url_loader_.reset(); Start(); } void ExploreSitesFetcher::OnSimpleLoaderComplete( std::unique_ptr<std::string> response_body) { ExploreSitesRequestStatus status = HandleResponseCode(); if (response_body && response_body->empty()) { DVLOG(1) << "Failed to get response or empty response"; status = ExploreSitesRequestStatus::kFailure; } if (status == ExploreSitesRequestStatus::kFailure && !disable_retry_for_testing_) { RetryWithBackoff(); return; } std::move(callback_).Run(status, std::move(response_body)); } ExploreSitesRequestStatus ExploreSitesFetcher::HandleResponseCode() { int response_code = -1; int net_error = url_loader_->NetError(); base::UmaHistogramSparse("ExploreSites.FetcherNetErrorCode", -net_error); if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers) response_code = url_loader_->ResponseInfo()->headers->response_code(); if (response_code == -1) { DVLOG(1) << "Net error: " << net_error; return (net_error == net::ERR_BLOCKED_BY_ADMINISTRATOR) ? ExploreSitesRequestStatus::kShouldSuspendBlockedByAdministrator : ExploreSitesRequestStatus::kFailure; } base::UmaHistogramSparse("ExploreSites.FetcherHttpResponseCode", response_code); if (response_code < 200 || response_code > 299) { DVLOG(1) << "HTTP status: " << response_code; switch (response_code) { case net::HTTP_BAD_REQUEST: return ExploreSitesRequestStatus::kShouldSuspendBadRequest; default: return ExploreSitesRequestStatus::kFailure; } } return ExploreSitesRequestStatus::kSuccess; } void ExploreSitesFetcher::RetryWithBackoff() { backoff_entry_->InformOfRequest(false); if (backoff_entry_->failure_count() >= max_failure_count_) { std::move(callback_).Run(ExploreSitesRequestStatus::kFailure, std::unique_ptr<std::string>()); return; } base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&ExploreSitesFetcher::Start, weak_factory_.GetWeakPtr()), backoff_entry_->GetTimeUntilRelease()); } void ExploreSitesFetcher::UpdateBackoffEntry() { backoff_entry_ = std::make_unique<net::BackoffEntry>( is_immediate_fetch_ ? &kImmediateFetchBackoffPolicy : &kBackgroundFetchBackoffPolicy); max_failure_count_ = is_immediate_fetch_ ? kMaxFailureCountForImmediateFetch : kMaxFailureCountForBackgroundFetch; } } // namespace explore_sites
10,698
3,264
#include "SectorFeature.hpp" #include "CoordUtils.hpp" using namespace std; bool SectorFeature::generate(MapPtr map, const Coordinate& start_coord, const Coordinate& end_coord) { bool generated = false; if (map && CoordUtils::is_in_range(map->size(), start_coord, end_coord)) { generated = generate_feature(map, start_coord, end_coord); } return generated; }
395
139
#include "lexer.hpp" void skip_spaces(std::string const& in, int& pos) { while(pos < (int)in.size() && in[pos] == ' ') ++pos; } void skip_spaces(std::vector<std::string> const& in, int& x) { while(x < (int)in[0].size()) { bool all_space = true; for(int y = 0; y < (int)in.size(); ++y) { all_space &= in[y][x] == '0'; } if(!all_space) break; ++x; } } auto trim_input(std::vector<std::string> const& in) { int x = 0; std::vector<std::vector<std::string>> res; while(true) { skip_spaces(in, x); if(x == (int)in[0].size()) break; std::vector<std::string> tmp(in.size()); // scanning while(x < (int)in[0].size()) { bool exists_one = false; for(int y = 0; y < (int)in.size(); ++y) { exists_one |= in[y][x] == '1'; } if(!exists_one) break; for(int y = 0; y < (int)in.size(); ++y) { tmp[y].push_back(in[y][x]); } ++x; } // trim top/bottom tmp.erase(std::remove_if(tmp.begin(), tmp.end(), [] (auto const& s) { return s.find_first_of('1') == std::string::npos; }), tmp.end()); res.push_back(std::move(tmp)); } return res; } Token dict_operator(const ll id) { if(id == 0) return app; if(id == 1) return {TokenType::I, 0}; if(id == 2) return {TokenType::True, 0}; if(id == 5) return comb_b; if(id == 6) return comb_c; if(id == 7) return {TokenType::S, 0}; if(id == 8) return {TokenType::False, 0}; if(id == 10) return {TokenType::Negate, 0}; if(id == 12) return {TokenType::Equality, 0}; if(id == 14) return nil; if(id == 15) return {TokenType::IsNil, 0}; if(id == 40) return {TokenType::Division, 0}; if(id == 146) return {TokenType::Product, 0}; if(id == 170) return {TokenType::Modulate, 0}; if(id == 174) return {TokenType::Send, 0}; if(id == 341) return {TokenType::Demod, 0}; if(id == 365) return sum; if(id == 401) return {TokenType::Pred, 0}; if(id == 416) return {TokenType::Lt, 0}; if(id == 417) return {TokenType::Succ, 0}; if(id == 448) return {TokenType::Eq, 0}; if(id == 64170) return cons; if(id == 64171) return {TokenType::Cdr, 0}; if(id == 64174) return {TokenType::Car, 0}; if(id == 17043521) return cons; throw std::runtime_error("dict_operator: not supported " + std::to_string(id)); } ll calc_number_part(std::vector<std::string> const& symbol) { const int n = std::min(symbol.size(), symbol[0].size()) - 1; ll res = 0; for(int y = 0; y < n; ++y) { for(int x = 0; x < n; ++x) { if(symbol[y + 1][x + 1] == '1') { res += 1LL << (y * n + x); } } } return res; } ll calc_var_number_part(std::vector<std::string> const& symbol) { assert(symbol.size() == symbol[0].size()); const int n = symbol.size(); ll res = 0; for(int y = 0; y < n - 3; ++y) { for(int x = 0; x < n - 3; ++x) { if(symbol[y + 2][x + 2] == '0') { res += 1LL << (y * (n - 3) + x); } } } return res; } bool is_lparen(std::vector<std::string> const& symbol) { if(symbol.size() != 5u || symbol[0].size() != 3u) return false; bool res = true; for(int x = 0; x < 3; ++x) { for(int y = 2 - x; y <= 2 + x; ++y) { res &= symbol[y][x] == '1'; } } return res; } bool is_rparen(std::vector<std::string> const& symbol) { if(symbol.size() != 5u || symbol[0].size() != 3u) return false; bool res = true; for(int x = 0; x < 3; ++x) { for(int y = x; y <= 4 - x; ++y) { res &= symbol[y][x] == '1'; } } return res; } bool is_list_sep(std::vector<std::string> const& symbol) { if(symbol.size() != 5u || symbol[0].size() != 2u) return false; bool res = true; for(auto const& s : symbol) { for(auto const c : s) { res &= c == '1'; } } return res; } bool is_variable(std::vector<std::string> const& symbol) { if(symbol.size() != symbol[0].size()) return false; if(symbol.size() < 4u) return false; if(symbol[1][1] == '0') return false; const int n = symbol.size(); for(int i = 2; i < n - 1; ++i) { if(symbol[1][i] == '1' || symbol[i][1] == '1') return false; } bool res = true; for(int i = 0; i < n; ++i) { res &= symbol[0][i] == '1' && symbol[i][0] == '1' && symbol[n - 1][i] == '1' && symbol[i][n - 1] == '1'; } return res; } Token tokenize_one(std::vector<std::string> const& symbol) { if(is_lparen(symbol)) { throw std::runtime_error("tokenize_one: not implemented lparen"); } else if(is_rparen(symbol)) { throw std::runtime_error("tokenize_one: not implemented rparen"); } else if(is_list_sep(symbol)) { throw std::runtime_error("tokenize_one: not implemented list_sep"); } else if(is_variable(symbol)) { const ll id = calc_var_number_part(symbol); std::cout << ("x" + std::to_string(id)) << std::endl; //throw std::runtime_error("not supported"); } else if(symbol[0][0] == '0') { // number const ll num = calc_number_part(symbol); if(symbol.size() == symbol[0].size()) { // positive return number(num); } else { return number(-num); } } else if(symbol[0][0] == '1') { // operator return dict_operator(calc_number_part(symbol)); } throw std::runtime_error("tokenize_one: not implmented"); } std::vector<Token> tokenize(std::vector<std::string> const& input) { std::vector<Token> res; for(auto&& v : trim_input(input)) { res.push_back(tokenize_one(std::move(v))); } return res; } bool is_number(std::string const& s) { bool res = true; for(int i = s[0] == '-'; i < (int)s.size(); ++i) { res &= (bool)isdigit(s[i]); } return res; } // require: all tokens are separated by spaces std::vector<Token> tokenize(std::string const& input) { std::vector<Token> res; std::string cur; int pos = 0; while(true) { skip_spaces(input, pos); if(pos >= (int)input.size()) return res; while(pos < (int)input.size() && input[pos] != ' ') cur += input[pos++]; if(cur == "ap") res.push_back(app); else if(cur[0] == ':') res.push_back({TokenType::Variable, std::stoll(cur.substr(1))}); // todo else if(is_number(cur)) res.push_back(number(std::stoll(cur))); else if(cur == "inc") res.push_back({TokenType::Succ, 0}); else if(cur == "dec") res.push_back({TokenType::Pred, 0}); else if(cur == "add") res.push_back(sum); else if(cur == "=") res.push_back({TokenType::Equality, 0}); else if(cur[0] == 'x') res.push_back({TokenType::Variable, std::stoll(cur.substr(1))}); else if(cur == "mul") res.push_back({TokenType::Product, 0}); else if(cur == "div") res.push_back({TokenType::Division, 0}); else if(cur == "eq") res.push_back({TokenType::Eq, 0}); else if(cur == "lt") res.push_back({TokenType::Lt, 0}); else if(cur == "mod") res.push_back({TokenType::Modulate, 0}); else if(cur == "dem") res.push_back({TokenType::Demod, 0}); else if(cur == "send") res.push_back({TokenType::Send, 0}); else if(cur == "neg") res.push_back({TokenType::Negate, 0}); else if(cur == "s") res.push_back({TokenType::S, 0}); else if(cur == "c") res.push_back({TokenType::C, 0}); else if(cur == "b") res.push_back({TokenType::B, 0}); else if(cur == "t") res.push_back({TokenType::True, 0}); else if(cur == "f") res.push_back({TokenType::False, 0}); else if(cur == "i") res.push_back({TokenType::I, 0}); else if(cur == "pwr2") res.push_back({TokenType::Pwr2, 0}); // ??? else if(cur == "cons") res.push_back(cons); else if(cur == "car") res.push_back({TokenType::Car, 0}); else if(cur == "cdr") res.push_back({TokenType::Cdr, 0}); else if(cur == "nil") res.push_back(nil); else if(cur == "isnil") res.push_back({TokenType::IsNil, 0}); else if(cur == "(") throw std::runtime_error("not implemented"); else if(cur == ",") throw std::runtime_error("not implemented"); else if(cur == ")") throw std::runtime_error("not implemented"); else if(cur == "vec") res.push_back(cons); else if(cur == "draw") throw std::runtime_error("not implemented draw"); else if(cur == "interact") throw std::runtime_error("not implemented: interact"); else throw std::runtime_error("error lexing: " + cur); cur.clear(); } }
9,281
3,430
/* $Id$ * EOSERV is released under the zlib license. * See LICENSE.txt for more info. */ #ifndef FWD_SLN_HPP_INCLUDED #define FWD_SLN_HPP_INCLUDED class SLN; #endif // FWD_SLN_HPP_INCLUDED
196
99
// Copyright (c) 2011 Andrew Green. MIT License. http://www.zoolib.org #include "zoolib/ValPred/Expr_Bool_ValPred.h" namespace ZooLib { // ================================================================================================= #pragma mark - Expr_Bool_ValPred Expr_Bool_ValPred::Expr_Bool_ValPred(const ValPred& iValPred) : fValPred(iValPred) {} Expr_Bool_ValPred::~Expr_Bool_ValPred() {} void Expr_Bool_ValPred::Accept(const Visitor& iVisitor) { if (Visitor_Expr_Bool_ValPred* theVisitor = sDynNonConst<Visitor_Expr_Bool_ValPred>(&iVisitor)) this->Accept_Expr_Bool_ValPred(*theVisitor); else inherited::Accept(iVisitor); } void Expr_Bool_ValPred::Accept_Expr_Op0(Visitor_Expr_Op0_T<Expr_Bool>& iVisitor) { if (Visitor_Expr_Bool_ValPred* theVisitor = sDynNonConst<Visitor_Expr_Bool_ValPred>(&iVisitor)) this->Accept_Expr_Bool_ValPred(*theVisitor); else inherited::Accept_Expr_Op0(iVisitor); } int Expr_Bool_ValPred::Compare(const ZP<Expr>& iOther) { if (ZP<Expr_Bool_ValPred> other = iOther.DynamicCast<Expr_Bool_ValPred>()) return sCompare_T(this->GetValPred(), other->GetValPred()); return Expr::Compare(iOther); } ZP<Expr_Bool> Expr_Bool_ValPred::Self() { return this; } ZP<Expr_Bool> Expr_Bool_ValPred::Clone() { return this; } void Expr_Bool_ValPred::Accept_Expr_Bool_ValPred(Visitor_Expr_Bool_ValPred& iVisitor) { iVisitor.Visit_Expr_Bool_ValPred(this); } const ValPred& Expr_Bool_ValPred::GetValPred() const { return fValPred; } // ================================================================================================= #pragma mark - Visitor_Expr_Bool_ValPred void Visitor_Expr_Bool_ValPred::Visit_Expr_Bool_ValPred(const ZP<Expr_Bool_ValPred >& iExpr) { this->Visit_Expr_Op0(iExpr); } // ================================================================================================= #pragma mark - Operators ZP<Expr_Bool> sExpr_Bool(const ValPred& iValPred) { return new Expr_Bool_ValPred(iValPred); } ZP<Expr_Bool> operator~(const ValPred& iValPred) { return new Expr_Bool_Not(sExpr_Bool(iValPred)); } ZP<Expr_Bool> operator&(bool iBool, const ValPred& iValPred) { if (iBool) return sExpr_Bool(iValPred); return sFalse(); } ZP<Expr_Bool> operator&(const ValPred& iValPred, bool iBool) { if (iBool) return sExpr_Bool(iValPred); return sFalse(); } ZP<Expr_Bool> operator|(bool iBool, const ValPred& iValPred) { if (iBool) return sTrue(); return sExpr_Bool(iValPred); } ZP<Expr_Bool> operator|(const ValPred& iValPred, bool iBool) { if (iBool) return sTrue(); return sExpr_Bool(iValPred); } ZP<Expr_Bool> operator&(const ValPred& iLHS, const ValPred& iRHS) { return new Expr_Bool_And(sExpr_Bool(iLHS), sExpr_Bool(iRHS)); } ZP<Expr_Bool> operator&(const ValPred& iLHS, const ZP<Expr_Bool>& iRHS) { return new Expr_Bool_And(sExpr_Bool(iLHS), iRHS); } ZP<Expr_Bool> operator&(const ZP<Expr_Bool>& iLHS, const ValPred& iRHS) { return new Expr_Bool_And(iLHS, sExpr_Bool(iRHS)); } ZP<Expr_Bool>& operator&=(ZP<Expr_Bool>& ioLHS, const ValPred& iRHS) { return ioLHS = ioLHS & iRHS; } ZP<Expr_Bool> operator|(const ValPred& iLHS, const ValPred& iRHS) { return new Expr_Bool_Or(sExpr_Bool(iLHS), sExpr_Bool(iRHS)); } ZP<Expr_Bool> operator|(const ValPred& iLHS, const ZP<Expr_Bool>& iRHS) { return new Expr_Bool_Or(sExpr_Bool(iLHS), iRHS); } ZP<Expr_Bool> operator|(const ZP<Expr_Bool>& iLHS, const ValPred& iRHS) { return new Expr_Bool_Or(iLHS, sExpr_Bool(iRHS)); } ZP<Expr_Bool>& operator|=(ZP<Expr_Bool>& ioLHS, const ValPred& iRHS) { return ioLHS = ioLHS | iRHS; } } // namespace ZooLib
3,606
1,448
/* Tariq ahmed khan - Daffodil */ #include <bits/stdc++.h> #define _ ios_base::sync_with_stdio(0);cin.tie(0); // I/O optimization #define pi 2*acos(0.0) #define scan(x) scanf("%d",&x) #define sf scanf #define pf printf #define pb push_back #define memoclr(n,x) memset(n,x,sizeof(n) ) #define INF 1 << 30 typedef long long LLI; typedef unsigned long long LLU; template<class T> T gcd(T x, T y){if (y==0) return x; return gcd(y,x%y);} template<class T> T lcm(T x, T y){return ((x/gcd(x,y))*y);} template<class T> T maxt(T x, T y){if (x > y) return x; else return y;} template<class T> T mint(T x, T y){if (x < y) return x; else return y;} template<class T> T power(T x, T y){T res=1,a = x; while(y){if(y&1){res*=a;}a*=a;y>>=1;}return res;} template<class T> T bigmod(T x,T y,T mod){T res=1,a=x; while(y){if(y&1){res=(res*a)%mod;}a=(a*a)%mod;y>>=1;}return res;} int dir[8][2]={{-1,0} ,{1,0} ,{0,-1} ,{0,1} ,{-1,-1} ,{-1,1} ,{1,-1} ,{1,1}}; using namespace std; struct node{ int st,ed,len; }; node edge[300]; bool comp(const node &a , const node &b){ if(a.len < b.len) return true; return false; } int up[300],dow[300]; int main() { #ifdef partho222 //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); #endif int test,kase=0; scan(test); while(test--) { int n,wk,x,y; scan(n); scan(wk); pf("Case %d:\n",++kase); for(int i=0 ; i<wk ; i++) { scanf("%d %d %d",&edge[i].st,&edge[i].ed,&edge[i].len); if(i < n-1) { pf("-1\n"); continue; } memoclr(up,-1); memoclr(dow,-1); sort(edge+0,edge+(i+1),comp); int res = 0,all=0; for(int j=0 ; j<= i && all != n-1 ; j++) { if( dow[ edge[j].ed ] == -1 || up[ edge[j].st ] == -1 ) { //cout << edge[j].st << " -> " << edge[j].ed << " = " << edge[j].len << endl; up[ edge[j].st ] = 0 ; dow[ edge[j].ed ] = 0; //up[ edge[j].ed ] = 0 ; dow[ edge[j].st ] = 0; res += edge[j].len; all++; } } //cout << res << endl; if( all == n-1) pf("%d\n",res); else pf("-1\n"); } } return 0; }
2,542
1,042
/* * Biquad_Filter.cpp * * Created on: 24. 6. 2017 * Author: michp */ #include <Biquad_Filter.h> namespace flyhero { Biquad_Filter::Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency) { double K = std::tan(this->PI * cut_frequency / sample_frequency); double Q = 1.0 / std::sqrt(2); // let Q be 1 / sqrt(2) for Butterworth double norm; switch (type) { case FILTER_LOW_PASS: norm = 1.0 / (1 + K / Q + K * K); this->a0 = K * K * norm; this->a1 = 2 * this->a0; this->a2 = this->a0; this->b1 = 2 * (K * K - 1) * norm; this->b2 = (1 - K / Q + K * K) * norm; break; case FILTER_NOTCH: norm = 1.0 / (1 + K / Q + K * K); this->a0 = (1 + K * K) * norm; this->a1 = 2 * (K * K - 1) * norm; this->a2 = this->a0; this->b1 = this->a1; this->b2 = (1 - K / Q + K * K) * norm; break; } this->z1 = 0; this->z2 = 0; } } /* namespace flyhero */
954
465
/** * ============================================================================ * MIT License * * Copyright (c) 2016 Eric Phillips * * 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. * ============================================================================ * * * This file implements a series of math functions for manipulating a * 2D vector. * * Created by Eric Phillips on October 15, 2016. */ #pragma once #define _USE_MATH_DEFINES #include <math.h> struct Vector2 { union { struct { double X; double Y; }; double data[2]; }; /** * Constructors. */ inline Vector2(); inline Vector2(double data[]); inline Vector2(double value); inline Vector2(double x, double y); /** * Constants for common vectors. */ static inline Vector2 Zero(); static inline Vector2 One(); static inline Vector2 Right(); static inline Vector2 Left(); static inline Vector2 Up(); static inline Vector2 Down(); /** * Returns the angle between two vectors in radians. * @param a: The first vector. * @param b: The second vector. * @return: A scalar value. */ static inline double Angle(Vector2 a, Vector2 b); /** * Returns a vector with its magnitude clamped to maxLength. * @param vector: The target vector. * @param maxLength: The maximum length of the return vector. * @return: A new vector. */ static inline Vector2 ClampMagnitude(Vector2 vector, double maxLength); /** * Returns the component of a in the direction of b (scalar projection). * @param a: The target vector. * @param b: The vector being compared against. * @return: A scalar value. */ static inline double Component(Vector2 a, Vector2 b); /** * Returns the distance between a and b. * @param a: The first point. * @param b: The second point. * @return: A scalar value. */ static inline double Distance(Vector2 a, Vector2 b); /** * Returns the dot product of two vectors. * @param lhs: The left side of the multiplication. * @param rhs: The right side of the multiplication. * @return: A scalar value. */ static inline double Dot(Vector2 lhs, Vector2 rhs); /** * Converts a polar representation of a vector into cartesian * coordinates. * @param rad: The magnitude of the vector. * @param theta: The angle from the X axis. * @return: A new vector. */ static inline Vector2 FromPolar(double rad, double theta); /** * Returns a vector linearly interpolated between a and b, moving along * a straight line. The vector is clamped to never go beyond the end points. * @param a: The starting point. * @param b: The ending point. * @param t: The interpolation value [0-1]. * @return: A new vector. */ static inline Vector2 Lerp(Vector2 a, Vector2 b, double t); /** * Returns a vector linearly interpolated between a and b, moving along * a straight line. * @param a: The starting point. * @param b: The ending point. * @param t: The interpolation value [0-1] (no actual bounds). * @return: A new vector. */ static inline Vector2 LerpUnclamped(Vector2 a, Vector2 b, double t); /** * Returns the magnitude of a vector. * @param v: The vector in question. * @return: A scalar value. */ static inline double Magnitude(Vector2 v); /** * Returns a vector made from the largest components of two other vectors. * @param a: The first vector. * @param b: The second vector. * @return: A new vector. */ static inline Vector2 Max(Vector2 a, Vector2 b); /** * Returns a vector made from the smallest components of two other vectors. * @param a: The first vector. * @param b: The second vector. * @return: A new vector. */ static inline Vector2 Min(Vector2 a, Vector2 b); /** * Returns a vector "maxDistanceDelta" units closer to the target. This * interpolation is in a straight line, and will not overshoot. * @param current: The current position. * @param target: The destination position. * @param maxDistanceDelta: The maximum distance to move. * @return: A new vector. */ static inline Vector2 MoveTowards(Vector2 current, Vector2 target, double maxDistanceDelta); /** * Returns a new vector with magnitude of one. * @param v: The vector in question. * @return: A new vector. */ static inline Vector2 Normalized(Vector2 v); /** * Creates a new coordinate system out of the two vectors. * Normalizes "normal" and normalizes "tangent" and makes it orthogonal to * "normal".. * @param normal: A reference to the first axis vector. * @param tangent: A reference to the second axis vector. */ static inline void OrthoNormalize(Vector2 &normal, Vector2 &tangent); /** * Returns the vector projection of a onto b. * @param a: The target vector. * @param b: The vector being projected onto. * @return: A new vector. */ static inline Vector2 Project(Vector2 a, Vector2 b); /** * Returns a vector reflected about the provided line. * This behaves as if there is a plane with the line as its normal, and the * vector comes in and bounces off this plane. * @param vector: The vector traveling inward at the imaginary plane. * @param line: The line about which to reflect. * @return: A new vector pointing outward from the imaginary plane. */ static inline Vector2 Reflect(Vector2 vector, Vector2 line); /** * Returns the vector rejection of a on b. * @param a: The target vector. * @param b: The vector being projected onto. * @return: A new vector. */ static inline Vector2 Reject(Vector2 a, Vector2 b); /** * Rotates vector "current" towards vector "target" by "maxRadiansDelta". * This treats the vectors as directions and will linearly interpolate * between their magnitudes by "maxMagnitudeDelta". This function does not * overshoot. If a negative delta is supplied, it will rotate away from * "target" until it is pointing the opposite direction, but will not * overshoot that either. * @param current: The starting direction. * @param target: The destination direction. * @param maxRadiansDelta: The maximum number of radians to rotate. * @param maxMagnitudeDelta: The maximum delta for magnitude interpolation. * @return: A new vector. */ static inline Vector2 RotateTowards(Vector2 current, Vector2 target, double maxRadiansDelta, double maxMagnitudeDelta); /** * Multiplies two vectors component-wise. * @param a: The lhs of the multiplication. * @param b: The rhs of the multiplication. * @return: A new vector. */ static inline Vector2 Scale(Vector2 a, Vector2 b); /** * Returns a vector rotated towards b from a by the percent t. * Since interpolation is done spherically, the vector moves at a constant * angular velocity. This rotation is clamped to 0 <= t <= 1. * @param a: The starting direction. * @param b: The ending direction. * @param t: The interpolation value [0-1]. */ static inline Vector2 Slerp(Vector2 a, Vector2 b, double t); /** * Returns a vector rotated towards b from a by the percent t. * Since interpolation is done spherically, the vector moves at a constant * angular velocity. This rotation is unclamped. * @param a: The starting direction. * @param b: The ending direction. * @param t: The interpolation value [0-1]. */ static inline Vector2 SlerpUnclamped(Vector2 a, Vector2 b, double t); /** * Returns the squared magnitude of a vector. * This is useful when comparing relative lengths, where the exact length * is not important, and much time can be saved by not calculating the * square root. * @param v: The vector in question. * @return: A scalar value. */ static inline double SqrMagnitude(Vector2 v); /** * Calculates the polar coordinate space representation of a vector. * @param vector: The vector to convert. * @param rad: The magnitude of the vector. * @param theta: The angle from the X axis. */ static inline void ToPolar(Vector2 vector, double &rad, double &theta); /** * Operator overloading. */ inline struct Vector2& operator+=(const double rhs); inline struct Vector2& operator-=(const double rhs); inline struct Vector2& operator*=(const double rhs); inline struct Vector2& operator/=(const double rhs); inline struct Vector2& operator+=(const Vector2 rhs); inline struct Vector2& operator-=(const Vector2 rhs); }; inline Vector2 operator-(Vector2 rhs); inline Vector2 operator+(Vector2 lhs, const double rhs); inline Vector2 operator-(Vector2 lhs, const double rhs); inline Vector2 operator*(Vector2 lhs, const double rhs); inline Vector2 operator/(Vector2 lhs, const double rhs); inline Vector2 operator+(const double lhs, Vector2 rhs); inline Vector2 operator-(const double lhs, Vector2 rhs); inline Vector2 operator*(const double lhs, Vector2 rhs); inline Vector2 operator/(const double lhs, Vector2 rhs); inline Vector2 operator+(Vector2 lhs, const Vector2 rhs); inline Vector2 operator-(Vector2 lhs, const Vector2 rhs); inline bool operator==(const Vector2 lhs, const Vector2 rhs); inline bool operator!=(const Vector2 lhs, const Vector2 rhs); /******************************************************************************* * Implementation */ Vector2::Vector2() : X(0), Y(0) {} Vector2::Vector2(double data[]) : X(data[0]), Y(data[1]) {} Vector2::Vector2(double value) : X(value), Y(value) {} Vector2::Vector2(double x, double y) : X(x), Y(y) {} Vector2 Vector2::Zero() { return Vector2(0, 0); } Vector2 Vector2::One() { return Vector2(1, 1); } Vector2 Vector2::Right() { return Vector2(1, 0); } Vector2 Vector2::Left() { return Vector2(-1, 0); } Vector2 Vector2::Up() { return Vector2(0, 1); } Vector2 Vector2::Down() { return Vector2(0, -1); } double Vector2::Angle(Vector2 a, Vector2 b) { double v = Dot(a, b) / (Magnitude(a) * Magnitude(b)); v = fmax(v, -1.0); v = fmin(v, 1.0); return acos(v); } Vector2 Vector2::ClampMagnitude(Vector2 vector, double maxLength) { double length = Magnitude(vector); if (length > maxLength) vector *= maxLength / length; return vector; } double Vector2::Component(Vector2 a, Vector2 b) { return Dot(a, b) / Magnitude(b); } double Vector2::Distance(Vector2 a, Vector2 b) { return Vector2::Magnitude(a - b); } double Vector2::Dot(Vector2 lhs, Vector2 rhs) { return lhs.X * rhs.X + lhs.Y * rhs.Y; } Vector2 Vector2::FromPolar(double rad, double theta) { Vector2 v; v.X = rad * cos(theta); v.Y = rad * sin(theta); return v; } Vector2 Vector2::Lerp(Vector2 a, Vector2 b, double t) { if (t < 0) return a; else if (t > 1) return b; return LerpUnclamped(a, b, t); } Vector2 Vector2::LerpUnclamped(Vector2 a, Vector2 b, double t) { return (b - a) * t + a; } double Vector2::Magnitude(Vector2 v) { return sqrt(SqrMagnitude(v)); } Vector2 Vector2::Max(Vector2 a, Vector2 b) { double x = a.X > b.X ? a.X : b.X; double y = a.Y > b.Y ? a.Y : b.Y; return Vector2(x, y); } Vector2 Vector2::Min(Vector2 a, Vector2 b) { double x = a.X > b.X ? b.X : a.X; double y = a.Y > b.Y ? b.Y : a.Y; return Vector2(x, y); } Vector2 Vector2::MoveTowards(Vector2 current, Vector2 target, double maxDistanceDelta) { Vector2 d = target - current; double m = Magnitude(d); if (m < maxDistanceDelta || m == 0) return target; return current + (d * maxDistanceDelta / m); } Vector2 Vector2::Normalized(Vector2 v) { double mag = Magnitude(v); if (mag == 0) return Vector2::Zero(); return v / mag; } void Vector2::OrthoNormalize(Vector2 &normal, Vector2 &tangent) { normal = Normalized(normal); tangent = Reject(tangent, normal); tangent = Normalized(tangent); } Vector2 Vector2::Project(Vector2 a, Vector2 b) { double m = Magnitude(b); return Dot(a, b) / (m * m) * b; } Vector2 Vector2::Reflect(Vector2 vector, Vector2 planeNormal) { return vector - 2 * Project(vector, planeNormal); } Vector2 Vector2::Reject(Vector2 a, Vector2 b) { return a - Project(a, b); } Vector2 Vector2::RotateTowards(Vector2 current, Vector2 target, double maxRadiansDelta, double maxMagnitudeDelta) { double magCur = Magnitude(current); double magTar = Magnitude(target); double newMag = magCur + maxMagnitudeDelta * ((magTar > magCur) - (magCur > magTar)); newMag = fmin(newMag, fmax(magCur, magTar)); newMag = fmax(newMag, fmin(magCur, magTar)); double totalAngle = Angle(current, target) - maxRadiansDelta; if (totalAngle <= 0) return Normalized(target) * newMag; else if (totalAngle >= M_PI) return Normalized(-target) * newMag; double axis = current.X * target.Y - current.Y * target.X; axis = axis / fabs(axis); if (!(1 - fabs(axis) < 0.00001)) axis = 1; current = Normalized(current); Vector2 newVector = current * cos(maxRadiansDelta) + Vector2(-current.Y, current.X) * sin(maxRadiansDelta) * axis; return newVector * newMag; } Vector2 Vector2::Scale(Vector2 a, Vector2 b) { return Vector2(a.X * b.X, a.Y * b.Y); } Vector2 Vector2::Slerp(Vector2 a, Vector2 b, double t) { if (t < 0) return a; else if (t > 1) return b; return SlerpUnclamped(a, b, t); } Vector2 Vector2::SlerpUnclamped(Vector2 a, Vector2 b, double t) { double magA = Magnitude(a); double magB = Magnitude(b); a /= magA; b /= magB; double dot = Dot(a, b); dot = fmax(dot, -1.0); dot = fmin(dot, 1.0); double theta = acos(dot) * t; Vector2 relativeVec = Normalized(b - a * dot); Vector2 newVec = a * cos(theta) + relativeVec * sin(theta); return newVec * (magA + (magB - magA) * t); } double Vector2::SqrMagnitude(Vector2 v) { return v.X * v.X + v.Y * v.Y; } void Vector2::ToPolar(Vector2 vector, double &rad, double &theta) { rad = Magnitude(vector); theta = atan2(vector.Y, vector.X); } struct Vector2& Vector2::operator+=(const double rhs) { X += rhs; Y += rhs; return *this; } struct Vector2& Vector2::operator-=(const double rhs) { X -= rhs; Y -= rhs; return *this; } struct Vector2& Vector2::operator*=(const double rhs) { X *= rhs; Y *= rhs; return *this; } struct Vector2& Vector2::operator/=(const double rhs) { X /= rhs; Y /= rhs; return *this; } struct Vector2& Vector2::operator+=(const Vector2 rhs) { X += rhs.X; Y += rhs.Y; return *this; } struct Vector2& Vector2::operator-=(const Vector2 rhs) { X -= rhs.X; Y -= rhs.Y; return *this; } Vector2 operator-(Vector2 rhs) { return rhs * -1; } Vector2 operator+(Vector2 lhs, const double rhs) { return lhs += rhs; } Vector2 operator-(Vector2 lhs, const double rhs) { return lhs -= rhs; } Vector2 operator*(Vector2 lhs, const double rhs) { return lhs *= rhs; } Vector2 operator/(Vector2 lhs, const double rhs) { return lhs /= rhs; } Vector2 operator+(const double lhs, Vector2 rhs) { return rhs += lhs; } Vector2 operator-(const double lhs, Vector2 rhs) { return rhs -= lhs; } Vector2 operator*(const double lhs, Vector2 rhs) { return rhs *= lhs; } Vector2 operator/(const double lhs, Vector2 rhs) { return rhs /= lhs; } Vector2 operator+(Vector2 lhs, const Vector2 rhs) { return lhs += rhs; } Vector2 operator-(Vector2 lhs, const Vector2 rhs) { return lhs -= rhs; } bool operator==(const Vector2 lhs, const Vector2 rhs) { return lhs.X == rhs.X && lhs.Y == rhs.Y; } bool operator!=(const Vector2 lhs, const Vector2 rhs) { return !(lhs == rhs); }
17,331
5,452
#include <gtest/gtest.h> #include <memory> #include <string> #include <logger.h> #include "Pick.h" #include "PickList.h" #include "Site.h" #include "SiteList.h" #define SITEJSON "{\"Type\":\"StationInfo\",\"Elevation\":2326.000000,\"Latitude\":45.822170,\"Longitude\":-112.451000,\"Site\":{\"Station\":\"LRM\",\"Channel\":\"EHZ\",\"Network\":\"MB\",\"Location\":\"\"},\"Enable\":true,\"Quality\":1.0,\"UseForTeleseismic\":true}" // NOLINT #define SITE2JSON "{\"Type\":\"StationInfo\",\"Elevation\":1342.000000,\"Latitude\":46.711330,\"Longitude\":-111.831200,\"Site\":{\"Station\":\"HRY\",\"Channel\":\"EHZ\",\"Network\":\"MB\",\"Location\":\"\"},\"Enable\":true,\"Quality\":1.0,\"UseForTeleseismic\":true}" // NOLINT #define SITE3JSON "{\"Type\":\"StationInfo\",\"Elevation\":1589.000000,\"Latitude\":45.596970,\"Longitude\":-111.629670,\"Site\":{\"Station\":\"BOZ\",\"Channel\":\"BHZ\",\"Network\":\"US\",\"Location\":\"00\"},\"Enable\":true,\"Quality\":1.0,\"UseForTeleseismic\":true}" // NOLINT #define PICKJSON "{\"ID\":\"20682831\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"LRM\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:01:43.599Z\",\"Type\":\"Pick\"}" // NOLINT #define PICK2JSON "{\"ID\":\"20682832\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"HRY\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:02:43.599Z\",\"Type\":\"Pick\"}" // NOLINT #define PICK3JSON "{\"ID\":\"20682833\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"BHZ\",\"Location\":\"00\",\"Network\":\"US\",\"Station\":\"BOZ\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:03:43.599Z\",\"Type\":\"Pick\"}" // NOLINT #define PICK4JSON "{\"ID\":\"20682834\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"LRM\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:04:43.599Z\",\"Type\":\"Pick\"}" // NOLINT #define PICK5JSON "{\"ID\":\"20682835\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"EHZ\",\"Location\":\"\",\"Network\":\"MB\",\"Station\":\"HRY\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:05:43.599Z\",\"Type\":\"Pick\"}" // NOLINT #define PICK6JSON "{\"ID\":\"20682836\",\"Phase\":\"P\",\"Polarity\":\"up\",\"Site\":{\"Channel\":\"BHZ\",\"Location\":\"00\",\"Network\":\"US\",\"Station\":\"BOZ\"},\"Source\":{\"AgencyID\":\"228041013\",\"Author\":\"228041013\"},\"Time\":\"2014-12-23T00:00:43.599Z\",\"Type\":\"Pick\"}" // NOLINT #define SCNL "LRM.EHZ.MB" #define SCNL2 "BOZ.BHZ.US.00" #define TPICK 3628281643.59000 #define TPICK2 3628281943.590000 #define TPICK3 3628281763.590000 #define MAXNPICK 5 // NOTE: Need to consider testing scavenge, and rouges functions, // but that would need a much more involved set of real nodes and data, // not this simple setup. // Maybe consider performing this test at a higher level? // test to see if the picklist can be constructed TEST(PickListTest, Construction) { glass3::util::Logger::disable(); // construct a picklist glasscore::CPickList * testPickList = new glasscore::CPickList(); // assert default values ASSERT_EQ(0, testPickList->getCountOfTotalPicksProcessed())<< "nPickTotal is 0"; // lists ASSERT_EQ(0, testPickList->length())<< "getVPickSize() is 0"; // pointers ASSERT_EQ(NULL, testPickList->getSiteList())<< "pSiteList null"; } // test various pick operations TEST(PickListTest, PickOperations) { glass3::util::Logger::disable(); // create json objects from the strings std::shared_ptr<json::Object> siteJSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(SITEJSON)))); std::shared_ptr<json::Object> site2JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(SITE2JSON)))); std::shared_ptr<json::Object> site3JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(SITE3JSON)))); std::shared_ptr<json::Object> pickJSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(PICKJSON)))); std::shared_ptr<json::Object> pick2JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(PICK2JSON)))); std::shared_ptr<json::Object> pick3JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(PICK3JSON)))); std::shared_ptr<json::Object> pick4JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(PICK4JSON)))); std::shared_ptr<json::Object> pick5JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(PICK5JSON)))); std::shared_ptr<json::Object> pick6JSON = std::make_shared<json::Object>( json::Object(json::Deserialize(std::string(PICK6JSON)))); // construct a sitelist glasscore::CSiteList * testSiteList = new glasscore::CSiteList(); // add sites to site list testSiteList->addSiteFromJSON(siteJSON); testSiteList->addSiteFromJSON(site2JSON); testSiteList->addSiteFromJSON(site3JSON); // construct a picklist glasscore::CPickList * testPickList = new glasscore::CPickList(); testPickList->setSiteList(testSiteList); glasscore::CGlass::setMaxNumPicks(-1); testPickList->setMaxAllowablePickCount(MAXNPICK); // test adding picks by addPick and dispatch testPickList->addPick(pickJSON); testPickList->receiveExternalMessage(pick3JSON); // give time for work std::this_thread::sleep_for(std::chrono::seconds(1)); int expectedSize = 2; ASSERT_EQ(expectedSize, testPickList->getCountOfTotalPicksProcessed())<< "Added Picks"; // add more picks testPickList->addPick(pick2JSON); testPickList->addPick(pick4JSON); testPickList->addPick(pick5JSON); testPickList->addPick(pick6JSON); // give time for work std::this_thread::sleep_for(std::chrono::seconds(1)); // check to make sure the size isn't any larger than our max expectedSize = MAXNPICK; ASSERT_EQ(expectedSize, testPickList->length())<< "testPickList not larger than max"; // test clearing picks testPickList->clear(); expectedSize = 0; ASSERT_EQ(expectedSize, testPickList->getCountOfTotalPicksProcessed())<< "Cleared Picks"; }
6,419
2,653
///////////////////////////////////////////////////////////////////////////// // Name: doc.cpp // Purpose: Implements document functionality // Author: Julian Smart // Modified by: // Created: 12/07/98 // RCS-ID: $Id: doc.cpp,v 1.2 2001/10/30 13:28:45 GT Exp $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifdef __GNUG__ // #pragma implementation #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/wxexpr.h> #include "studio.h" #include "doc.h" #include "view.h" #include <wx/ogl/basicp.h> IMPLEMENT_DYNAMIC_CLASS(csDiagramDocument, wxDocument) #ifdef _MSC_VER #pragma warning(disable:4355) #endif csDiagramDocument::csDiagramDocument():m_diagram(this) { } #ifdef _MSC_VER #pragma warning(default:4355) #endif csDiagramDocument::~csDiagramDocument() { } bool csDiagramDocument::OnCloseDocument() { m_diagram.DeleteAllShapes(); return TRUE; } bool csDiagramDocument::OnSaveDocument(const wxString& file) { if (file == "") return FALSE; if (!m_diagram.SaveFile(file)) { wxString msgTitle; if (wxTheApp->GetAppName() != "") msgTitle = wxTheApp->GetAppName(); else msgTitle = wxString("File error"); (void)wxMessageBox("Sorry, could not open this file for saving.", msgTitle, wxOK | wxICON_EXCLAMATION, GetDocumentWindow()); return FALSE; } Modify(FALSE); SetFilename(file); return TRUE; } bool csDiagramDocument::OnOpenDocument(const wxString& file) { if (!OnSaveModified()) return FALSE; wxString msgTitle; if (wxTheApp->GetAppName() != "") msgTitle = wxTheApp->GetAppName(); else msgTitle = wxString("File error"); m_diagram.DeleteAllShapes(); if (!m_diagram.LoadFile(file)) { (void)wxMessageBox("Sorry, could not open this file.", msgTitle, wxOK|wxICON_EXCLAMATION, GetDocumentWindow()); return FALSE; } SetFilename(file, TRUE); Modify(FALSE); UpdateAllViews(); return TRUE; } /* * Implementation of drawing command */ csDiagramCommand::csDiagramCommand(const wxString& name, csDiagramDocument *doc, csCommandState* onlyState): wxCommand(TRUE, name) { m_doc = doc; if (onlyState) { AddState(onlyState); } } csDiagramCommand::~csDiagramCommand() { wxNode* node = m_states.First(); while (node) { csCommandState* state = (csCommandState*) node->Data(); delete state; node = node->Next(); } } void csDiagramCommand::AddState(csCommandState* state) { state->m_doc = m_doc; // state->m_cmd = m_cmd; m_states.Append(state); } // Insert a state at the beginning of the list void csDiagramCommand::InsertState(csCommandState* state) { state->m_doc = m_doc; // state->m_cmd = m_cmd; m_states.Insert(state); } // Schedule all lines connected to the states to be cut. void csDiagramCommand::RemoveLines() { wxNode* node = m_states.First(); while (node) { csCommandState* state = (csCommandState*) node->Data(); wxShape* shape = state->GetShapeOnCanvas(); wxASSERT( (shape != NULL) ); wxNode *node1 = shape->GetLines().First(); while (node1) { wxLineShape *line = (wxLineShape *)node1->Data(); if (!FindStateByShape(line)) { csCommandState* newState = new csCommandState(ID_CS_CUT, NULL, line); InsertState(newState); } node1 = node1->Next(); } node = node->Next(); } } csCommandState* csDiagramCommand::FindStateByShape(wxShape* shape) { wxNode* node = m_states.First(); while (node) { csCommandState* state = (csCommandState*) node->Data(); if (shape == state->GetShapeOnCanvas() || shape == state->GetSavedState()) return state; node = node->Next(); } return NULL; } bool csDiagramCommand::Do() { wxNode* node = m_states.First(); while (node) { csCommandState* state = (csCommandState*) node->Data(); if (!state->Do()) return FALSE; node = node->Next(); } return TRUE; } bool csDiagramCommand::Undo() { // Undo in reverse order, so e.g. shapes get added // back before the lines do. wxNode* node = m_states.Last(); while (node) { csCommandState* state = (csCommandState*) node->Data(); if (!state->Undo()) return FALSE; node = node->Previous(); } return TRUE; } csCommandState::csCommandState(int cmd, wxShape* savedState, wxShape* shapeOnCanvas) { m_cmd = cmd; m_doc = NULL; m_savedState = savedState; m_shapeOnCanvas = shapeOnCanvas; m_linePositionFrom = 0; m_linePositionTo = 0; } csCommandState::~csCommandState() { if (m_savedState) { m_savedState->SetCanvas(NULL); delete m_savedState; } } bool csCommandState::Do() { switch (m_cmd) { case ID_CS_CUT: { // New state is 'nothing' - maybe pass shape ID to state so we know what // we're talking about. // Then save old shape in m_savedState (actually swap pointers) wxASSERT( (m_shapeOnCanvas != NULL) ); wxASSERT( (m_savedState == NULL) ); // new state will be 'nothing' wxASSERT( (m_doc != NULL) ); wxShapeCanvas* canvas = m_shapeOnCanvas->GetCanvas(); // In case this is a line wxShape* lineFrom = NULL; wxShape* lineTo = NULL; int attachmentFrom = 0, attachmentTo = 0; if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape))) { // Store the from/to info to save in the line shape wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas; lineFrom = lineShape->GetFrom(); lineTo = lineShape->GetTo(); attachmentFrom = lineShape->GetAttachmentFrom(); attachmentTo = lineShape->GetAttachmentTo(); m_linePositionFrom = lineFrom->GetLinePosition(lineShape); m_linePositionTo = lineTo->GetLinePosition(lineShape); } m_shapeOnCanvas->Select(FALSE); ((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, FALSE); m_shapeOnCanvas->Unlink(); m_doc->GetDiagram()->RemoveShape(m_shapeOnCanvas); m_savedState = m_shapeOnCanvas; if (m_savedState->IsKindOf(CLASSINFO(wxLineShape))) { // Restore the from/to info for future reference wxLineShape* lineShape = (wxLineShape*) m_savedState; lineShape->SetFrom(lineFrom); lineShape->SetTo(lineTo); lineShape->SetAttachments(attachmentFrom, attachmentTo); wxClientDC dc(canvas); canvas->PrepareDC(dc); lineFrom->MoveLinks(dc); lineTo->MoveLinks(dc); } m_doc->Modify(TRUE); m_doc->UpdateAllViews(); break; } case ID_CS_ADD_SHAPE: case ID_CS_ADD_SHAPE_SELECT: { // The app has given the command state a new m_savedState // shape, which is the new shape to add to the canvas (but // not actually added until this point). // The new 'saved state' is therefore 'nothing' since there // was nothing there before. wxASSERT( (m_shapeOnCanvas == NULL) ); wxASSERT( (m_savedState != NULL) ); wxASSERT( (m_doc != NULL) ); m_shapeOnCanvas = m_savedState; m_savedState = NULL; m_doc->GetDiagram()->AddShape(m_shapeOnCanvas); m_shapeOnCanvas->Show(TRUE); wxClientDC dc(m_shapeOnCanvas->GetCanvas()); m_shapeOnCanvas->GetCanvas()->PrepareDC(dc); csEvtHandler *handler = (csEvtHandler *)m_shapeOnCanvas->GetEventHandler(); m_shapeOnCanvas->FormatText(dc, handler->m_label); m_shapeOnCanvas->Move(dc, m_shapeOnCanvas->GetX(), m_shapeOnCanvas->GetY()); if (m_cmd == ID_CS_ADD_SHAPE_SELECT) { m_shapeOnCanvas->Select(TRUE, &dc); ((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, TRUE); } m_doc->Modify(TRUE); m_doc->UpdateAllViews(); break; } case ID_CS_ADD_LINE: case ID_CS_ADD_LINE_SELECT: { wxASSERT( (m_shapeOnCanvas == NULL) ); wxASSERT( (m_savedState != NULL) ); wxASSERT( (m_doc != NULL) ); wxLineShape *lineShape = (wxLineShape *)m_savedState; wxASSERT( (lineShape->GetFrom() != NULL) ); wxASSERT( (lineShape->GetTo() != NULL) ); m_shapeOnCanvas = m_savedState; m_savedState = NULL; m_doc->GetDiagram()->AddShape(lineShape); lineShape->GetFrom()->AddLine(lineShape, lineShape->GetTo(), lineShape->GetAttachmentFrom(), lineShape->GetAttachmentTo()); lineShape->Show(TRUE); wxClientDC dc(lineShape->GetCanvas()); lineShape->GetCanvas()->PrepareDC(dc); // It won't get drawn properly unless you move both // connected images lineShape->GetFrom()->Move(dc, lineShape->GetFrom()->GetX(), lineShape->GetFrom()->GetY()); lineShape->GetTo()->Move(dc, lineShape->GetTo()->GetX(), lineShape->GetTo()->GetY()); if (m_cmd == ID_CS_ADD_LINE_SELECT) { lineShape->Select(TRUE, &dc); ((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, TRUE); } m_doc->Modify(TRUE); m_doc->UpdateAllViews(); break; } case ID_CS_CHANGE_BACKGROUND_COLOUR: case ID_CS_MOVE: case ID_CS_SIZE: case ID_CS_EDIT_PROPERTIES: case ID_CS_FONT_CHANGE: case ID_CS_ARROW_CHANGE: case ID_CS_ROTATE_CLOCKWISE: case ID_CS_ROTATE_ANTICLOCKWISE: case ID_CS_CHANGE_LINE_ORDERING: case ID_CS_CHANGE_LINE_ATTACHMENT: case ID_CS_ALIGN: case ID_CS_NEW_POINT: case ID_CS_CUT_POINT: case ID_CS_MOVE_LINE_POINT: case ID_CS_STRAIGHTEN: case ID_CS_MOVE_LABEL: { // At this point we have been given a new shape // just like the old one but with a changed colour. // It's now time to apply that change to the // shape on the canvas, saving the old state. // NOTE: this is general enough to work with MOST attribute // changes! wxASSERT( (m_shapeOnCanvas != NULL) ); wxASSERT( (m_savedState != NULL) ); // This is the new shape with changed colour wxASSERT( (m_doc != NULL) ); wxClientDC dc(m_shapeOnCanvas->GetCanvas()); m_shapeOnCanvas->GetCanvas()->PrepareDC(dc); bool isSelected = m_shapeOnCanvas->Selected(); if (isSelected) m_shapeOnCanvas->Select(FALSE, & dc); if (m_cmd == ID_CS_SIZE || m_cmd == ID_CS_ROTATE_CLOCKWISE || m_cmd == ID_CS_ROTATE_ANTICLOCKWISE || m_cmd == ID_CS_CHANGE_LINE_ORDERING || m_cmd == ID_CS_CHANGE_LINE_ATTACHMENT) { m_shapeOnCanvas->Erase(dc); } // TODO: make sure the ID is the same. Or, when applying the new state, // don't change the original ID. wxShape* tempShape = m_shapeOnCanvas->CreateNewCopy(); // Apply the saved state to the shape on the canvas, by copying. m_savedState->CopyWithHandler(*m_shapeOnCanvas); // Delete this state now it's been used (m_shapeOnCanvas currently holds this state) delete m_savedState; // Remember the previous state m_savedState = tempShape; // Redraw the shape if (m_cmd == ID_CS_MOVE || m_cmd == ID_CS_ROTATE_CLOCKWISE || m_cmd == ID_CS_ROTATE_ANTICLOCKWISE || m_cmd == ID_CS_ALIGN) { m_shapeOnCanvas->Move(dc, m_shapeOnCanvas->GetX(), m_shapeOnCanvas->GetY()); csEvtHandler *handler = (csEvtHandler *)m_shapeOnCanvas->GetEventHandler(); m_shapeOnCanvas->FormatText(dc, handler->m_label); m_shapeOnCanvas->Draw(dc); } else if (m_cmd == ID_CS_CHANGE_LINE_ORDERING) { m_shapeOnCanvas->MoveLinks(dc); } else if (m_cmd == ID_CS_CHANGE_LINE_ATTACHMENT) { wxLineShape *lineShape = (wxLineShape *)m_shapeOnCanvas; // Have to move both sets of links since we don't know which links // have been affected (unless we compared before and after states). lineShape->GetFrom()->MoveLinks(dc); lineShape->GetTo()->MoveLinks(dc); } else if (m_cmd == ID_CS_SIZE) { double width, height; m_shapeOnCanvas->GetBoundingBoxMax(&width, &height); m_shapeOnCanvas->SetSize(width, height); m_shapeOnCanvas->Move(dc, m_shapeOnCanvas->GetX(), m_shapeOnCanvas->GetY()); m_shapeOnCanvas->Show(TRUE); // Recursively redraw links if we have a composite. if (m_shapeOnCanvas->GetChildren().Number() > 0) m_shapeOnCanvas->DrawLinks(dc, -1, TRUE); m_shapeOnCanvas->GetEventHandler()->OnEndSize(width, height); } else if (m_cmd == ID_CS_EDIT_PROPERTIES || m_cmd == ID_CS_FONT_CHANGE) { csEvtHandler *handler = (csEvtHandler *)m_shapeOnCanvas->GetEventHandler(); m_shapeOnCanvas->FormatText(dc, handler->m_label); m_shapeOnCanvas->Draw(dc); } else { m_shapeOnCanvas->Draw(dc); } if (isSelected) m_shapeOnCanvas->Select(TRUE, & dc); m_doc->Modify(TRUE); m_doc->UpdateAllViews(); break; } } return TRUE; } bool csCommandState::Undo() { switch (m_cmd) { case ID_CS_CUT: { wxASSERT( (m_savedState != NULL) ); wxASSERT( (m_doc != NULL) ); m_doc->GetDiagram()->AddShape(m_savedState); m_shapeOnCanvas = m_savedState; m_savedState = NULL; if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape))) { wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas; lineShape->GetFrom()->AddLine(lineShape, lineShape->GetTo(), lineShape->GetAttachmentFrom(), lineShape->GetAttachmentTo(), m_linePositionFrom, m_linePositionTo); wxShapeCanvas* canvas = lineShape->GetFrom()->GetCanvas(); wxClientDC dc(canvas); canvas->PrepareDC(dc); lineShape->GetFrom()->MoveLinks(dc); lineShape->GetTo()->MoveLinks(dc); } m_shapeOnCanvas->Show(TRUE); m_doc->Modify(TRUE); m_doc->UpdateAllViews(); break; } case ID_CS_ADD_SHAPE: case ID_CS_ADD_LINE: case ID_CS_ADD_SHAPE_SELECT: case ID_CS_ADD_LINE_SELECT: { wxASSERT( (m_shapeOnCanvas != NULL) ); wxASSERT( (m_savedState == NULL) ); wxASSERT( (m_doc != NULL) ); // In case this is a line wxShape* lineFrom = NULL; wxShape* lineTo = NULL; int attachmentFrom = 0, attachmentTo = 0; if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape))) { // Store the from/to info to save in the line shape wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas; lineFrom = lineShape->GetFrom(); lineTo = lineShape->GetTo(); attachmentFrom = lineShape->GetAttachmentFrom(); attachmentTo = lineShape->GetAttachmentTo(); } wxClientDC dc(m_shapeOnCanvas->GetCanvas()); m_shapeOnCanvas->GetCanvas()->PrepareDC(dc); m_shapeOnCanvas->Select(FALSE, &dc); ((csDiagramView*) m_doc->GetFirstView())->SelectShape(m_shapeOnCanvas, FALSE); m_doc->GetDiagram()->RemoveShape(m_shapeOnCanvas); m_shapeOnCanvas->Unlink(); // Unlinks the line, if it is a line if (m_shapeOnCanvas->IsKindOf(CLASSINFO(wxLineShape))) { // Restore the from/to info for future reference wxLineShape* lineShape = (wxLineShape*) m_shapeOnCanvas; lineShape->SetFrom(lineFrom); lineShape->SetTo(lineTo); lineShape->SetAttachments(attachmentFrom, attachmentTo); } m_savedState = m_shapeOnCanvas; m_shapeOnCanvas = NULL; m_doc->Modify(TRUE); m_doc->UpdateAllViews(); break; } case ID_CS_CHANGE_BACKGROUND_COLOUR: case ID_CS_MOVE: case ID_CS_SIZE: case ID_CS_EDIT_PROPERTIES: case ID_CS_FONT_CHANGE: case ID_CS_ARROW_CHANGE: case ID_CS_ROTATE_CLOCKWISE: case ID_CS_ROTATE_ANTICLOCKWISE: case ID_CS_CHANGE_LINE_ORDERING: case ID_CS_CHANGE_LINE_ATTACHMENT: case ID_CS_ALIGN: case ID_CS_NEW_POINT: case ID_CS_CUT_POINT: case ID_CS_MOVE_LINE_POINT: case ID_CS_STRAIGHTEN: case ID_CS_MOVE_LABEL: { // Exactly like the Do case; we're just swapping states. Do(); break; } } return TRUE; }
17,177
5,632
#include "IndexTaskService.h" #include <common/JobScheduler.h> #include <aggregator-manager/IndexWorker.h> #include <node-manager/NodeManagerBase.h> #include <node-manager/MasterManagerBase.h> #include <node-manager/sharding/ScdSharder.h> #include <node-manager/sharding/ScdDispatcher.h> #include <node-manager/DistributeRequestHooker.h> #include <node-manager/DistributeFileSyncMgr.h> #include <node-manager/DistributeFileSys.h> #include <util/driver/Request.h> #include <common/Utilities.h> #include <glog/logging.h> #include <boost/filesystem.hpp> namespace bfs = boost::filesystem; using namespace izenelib::driver; namespace sf1r { static const char* SCD_BACKUP_DIR = "backup"; const static std::string DISPATCH_TEMP_DIR = "dispatch-temp-dir/"; IndexTaskService::IndexTaskService(IndexBundleConfiguration* bundleConfig) : bundleConfig_(bundleConfig) { service_ = Sf1rTopology::getServiceName(Sf1rTopology::SearchService); //ShardingConfig::RangeListT ranges; //ranges.push_back(100); //ranges.push_back(1000); //shard_cfg_.addRangeShardKey("UnchangableRangeProperty", ranges); //ShardingConfig::AttrListT strranges; //strranges.push_back("abc"); //shard_cfg_.addAttributeShardKey("UnchangableAttributeProperty", strranges); if (DistributeFileSys::get()->isEnabled() && !bundleConfig_->indexShardKeys_.empty()) { const std::string& coll = bundleConfig_->collectionName_; sharding_map_dir_ = DistributeFileSys::get()->getFixedCopyPath("/sharding_map/"); sharding_map_dir_ = DistributeFileSys::get()->getDFSPathForLocal(sharding_map_dir_); if (!bfs::exists(sharding_map_dir_)) { bfs::create_directories(sharding_map_dir_); } sharding_strategy_.reset(new MapShardingStrategy(sharding_map_dir_ + coll)); sharding_strategy_->shard_cfg_.shardidList_ = bundleConfig_->col_shard_info_.shardList_; if (sharding_strategy_->shard_cfg_.shardidList_.empty()) throw "sharding config is error!"; sharding_strategy_->shard_cfg_.setUniqueShardKey(bundleConfig_->indexShardKeys_[0]); sharding_strategy_->init(); } } IndexTaskService::~IndexTaskService() { } std::string IndexTaskService::getShardingMapDir() { return sharding_map_dir_; } bool IndexTaskService::SendRequestToSharding(uint32_t shardid) { Request::kCallType hooktype = (Request::kCallType)DistributeRequestHooker::get()->getHookType(); if (hooktype == Request::FromAPI) { return true; } const std::string& reqdata = DistributeRequestHooker::get()->getAdditionData(); bool ret = false; if (hooktype == Request::FromDistribute) { indexAggregator_->singleRequest(bundleConfig_->collectionName_, 0, "HookDistributeRequestForIndex", (int)hooktype, reqdata, ret, shardid); } else { ret = true; } if (!ret) { LOG(WARNING) << "Send Request to shard node failed."; } return ret; } bool IndexTaskService::HookDistributeRequestForIndex() { Request::kCallType hooktype = (Request::kCallType)DistributeRequestHooker::get()->getHookType(); if (hooktype == Request::FromAPI) { // from api do not need hook, just process as usually. return true; } const std::string& reqdata = DistributeRequestHooker::get()->getAdditionData(); bool ret = false; if (hooktype == Request::FromDistribute) { indexAggregator_->distributeRequestWithoutLocal(bundleConfig_->collectionName_, 0, "HookDistributeRequestForIndex", (int)hooktype, reqdata, ret); } else { // local hook has been moved to the request controller. ret = true; } if (!ret) { LOG(WARNING) << "Request failed, HookDistributeRequestForIndex failed."; } return ret; } bool IndexTaskService::index(unsigned int numdoc, std::string scd_path, int disable_sharding_type) { bool result = true; // disable_sharding_type , 0 no disable, 1 disable sending request to sharding node, // 2 disable sending to sharding node and disable sharding SCD on local. (This means // local node will index all of the docs in the given SCD files.) bool disable_sharding = (disable_sharding_type != (int)DefaultShard); indexWorker_->disableSharding(disable_sharding_type == (int)LocalOnly); if (DistributeFileSys::get()->isEnabled()) { if (scd_path.empty()) { LOG(ERROR) << "scd path should be specified while dfs is enabled."; return false; } scd_path = DistributeFileSys::get()->getDFSPathForLocal(scd_path); } else { scd_path = bundleConfig_->indexSCDPath(); } if (bundleConfig_->isMasterAggregator() && indexAggregator_->isNeedDistribute() && DistributeRequestHooker::get()->isRunningPrimary()) { if (DistributeRequestHooker::get()->isHooked()) { if (DistributeRequestHooker::get()->getHookType() == Request::FromDistribute && !disable_sharding) { result = distributedIndex_(numdoc, scd_path); } else { if (disable_sharding) LOG(INFO) << "==== The sharding is disabled! ====="; //if (DistributeFileSys::get()->isEnabled()) //{ // // while dfs enabled, the master will shard the scd file under the main scd_path // // to sub-directory directly on dfs. // // and the shard worker only index the sub-directory belong to it. // // // std::string myshard; // myshard = boost::lexical_cast<std::string>(MasterManagerBase::get()->getMyShardId()); // scd_path = (bfs::path(scd_path)/bfs::path(DISPATCH_TEMP_DIR + myshard)).string(); //} if (!isNeedDoLocal()) return false; indexWorker_->index(scd_path, numdoc, result); } } else { task_type task = boost::bind(&IndexTaskService::distributedIndex_, this, numdoc, scd_path); JobScheduler::get()->addTask(task, bundleConfig_->collectionName_); } } else { if (bundleConfig_->isMasterAggregator() && DistributeRequestHooker::get()->isRunningPrimary() && !DistributeFileSys::get()->isEnabled()) { LOG(INFO) << "only local worker available, copy master scd files and indexing local."; // search the directory for files static const bfs::directory_iterator kItrEnd; std::string masterScdPath = bundleConfig_->masterIndexSCDPath(); ScdParser parser(bundleConfig_->encoding_); bfs::path bkDir = bfs::path(masterScdPath) / SCD_BACKUP_DIR; LOG(INFO) << "creating directory : " << bkDir; bfs::create_directories(bkDir); for (bfs::directory_iterator itr(masterScdPath); itr != kItrEnd; ++itr) { if (bfs::is_regular_file(itr->status())) { std::string fileName = itr->path().filename().string(); if (parser.checkSCDFormat(fileName)) { try { bfs::copy_file(itr->path().string(), bundleConfig_->indexSCDPath() + "/" + fileName); LOG(INFO) << "SCD File copy to local index path:" << fileName; LOG(INFO) << "moving SCD files to directory " << bkDir; bfs::rename(itr->path().string(), bkDir / itr->path().filename()); } catch(const std::exception& e) { LOG(WARNING) << "failed to move file: " << std::endl << fileName << std::endl << e.what(); } } else { LOG(WARNING) << "SCD File not valid " << fileName; } } } } if (!isNeedDoLocal()) return false; indexWorker_->index(scd_path, numdoc, result); } return result; } bool IndexTaskService::isNeedSharding() { if (bundleConfig_->isMasterAggregator() && indexAggregator_->isNeedDistribute() && DistributeRequestHooker::get()->isRunningPrimary()) { return DistributeRequestHooker::get()->getHookType() == Request::FromDistribute; } return false; } bool IndexTaskService::isNeedDoLocal() { if (NodeManagerBase::get()->isDistributed() && !bundleConfig_->isWorkerNode()) { LOG(INFO) << "local worker is disabled, no need do local work."; return false; } return true; } bool IndexTaskService::reindex_from_scd(const std::vector<std::string>& scd_list, int64_t timestamp) { if (!isNeedDoLocal()) return false; indexWorker_->disableSharding(false); return indexWorker_->buildCollection(0, scd_list, timestamp); } bool IndexTaskService::index(boost::shared_ptr<DocumentManager>& documentManager, int64_t timestamp) { if (!isNeedDoLocal()) return false; return indexWorker_->reindex(documentManager, timestamp); } bool IndexTaskService::optimizeIndex() { if (!isNeedDoLocal()) return false; return indexWorker_->optimizeIndex(); } bool IndexTaskService::createDocument(const Value& documentValue) { if (isNeedSharding()) { if (!scdSharder_) createScdSharder(scdSharder_); SCDDoc scddoc; IndexWorker::value2SCDDoc(documentValue, scddoc); shardid_t shardid = scdSharder_->sharding(scddoc); if (shardid != MasterManagerBase::get()->getMyShardId()) { // need send to the shard. return SendRequestToSharding(shardid); } } return indexWorker_->createDocument(documentValue); } bool IndexTaskService::updateDocument(const Value& documentValue) { if (isNeedSharding()) { if (!scdSharder_) createScdSharder(scdSharder_); SCDDoc scddoc; IndexWorker::value2SCDDoc(documentValue, scddoc); shardid_t shardid = scdSharder_->sharding(scddoc); if (shardid != MasterManagerBase::get()->getMyShardId()) { // need send to the shard. return SendRequestToSharding(shardid); } } return indexWorker_->updateDocument(documentValue); } bool IndexTaskService::updateDocumentInplace(const Value& request) { if (isNeedSharding()) { if (!scdSharder_) createScdSharder(scdSharder_); SCDDoc scddoc; IndexWorker::value2SCDDoc(request, scddoc); shardid_t shardid = scdSharder_->sharding(scddoc); if (shardid != MasterManagerBase::get()->getMyShardId()) { // need send to the shard. return SendRequestToSharding(shardid); } } return indexWorker_->updateDocumentInplace(request); } bool IndexTaskService::destroyDocument(const Value& documentValue) { if (isNeedSharding()) { if (!scdSharder_) createScdSharder(scdSharder_); SCDDoc scddoc; IndexWorker::value2SCDDoc(documentValue, scddoc); shardid_t shardid = scdSharder_->sharding(scddoc); if (shardid != MasterManagerBase::get()->getMyShardId()) { // need send to the shard. return SendRequestToSharding(shardid); } } return indexWorker_->destroyDocument(documentValue); } void IndexTaskService::flush() { indexWorker_->flush(true); } bool IndexTaskService::getIndexStatus(Status& status) { return indexWorker_->getIndexStatus(status); } bool IndexTaskService::isAutoRebuild() { return bundleConfig_->isAutoRebuild_; } std::string IndexTaskService::getScdDir(bool rebuild) const { if (rebuild) return bundleConfig_->rebuildIndexSCDPath(); if( bundleConfig_->isMasterAggregator() ) return bundleConfig_->masterIndexSCDPath(); return bundleConfig_->indexSCDPath(); } CollectionPath& IndexTaskService::getCollectionPath() const { return bundleConfig_->collPath_; } boost::shared_ptr<DocumentManager> IndexTaskService::getDocumentManager() const { return indexWorker_->getDocumentManager(); } bool IndexTaskService::distributedIndex_(unsigned int numdoc, std::string scd_dir) { // notify that current master is indexing for the specified collection, // we may need to check that whether other Master it's indexing this collection in some cases, // or it's depends on Nginx router strategy. MasterManagerBase::get()->registerIndexStatus(bundleConfig_->collectionName_, true); if (!DistributeFileSys::get()->isEnabled()) { scd_dir = bundleConfig_->masterIndexSCDPath(); } bool ret = distributedIndexImpl_( numdoc, bundleConfig_->collectionName_, scd_dir); MasterManagerBase::get()->registerIndexStatus(bundleConfig_->collectionName_, false); return ret; } bool IndexTaskService::distributedIndexImpl_( unsigned int numdoc, const std::string& collectionName, const std::string& masterScdPath) { if (!scdSharder_) { if (!createScdSharder(scdSharder_)) { LOG(ERROR) << "create scd sharder failed."; return false; } if (!scdSharder_) { LOG(INFO) << "no scd sharder!"; return false; } } if (!MasterManagerBase::get()->isAllShardNodeOK(bundleConfig_->col_shard_info_.shardList_)) { LOG(ERROR) << "some of sharding node is not ready for index."; return false; } std::string scd_dir = masterScdPath; std::vector<std::string> outScdFileList; // // 1. dispatching scd to multiple nodes if (!DistributeFileSys::get()->isEnabled()) { boost::shared_ptr<ScdDispatcher> scdDispatcher(new BatchScdDispatcher(scdSharder_, collectionName, DistributeFileSys::get()->isEnabled())); if(!scdDispatcher->dispatch(outScdFileList, masterScdPath, bundleConfig_->indexSCDPath(), numdoc)) return false; } // 2. send index request to multiple nodes LOG(INFO) << "start distributed indexing"; HookDistributeRequestForIndex(); if (!DistributeFileSys::get()->isEnabled()) scd_dir = bundleConfig_->indexSCDPath(); bool ret = true; if (isNeedDoLocal()) { // starting local index. indexWorker_->index(scd_dir, numdoc, ret); } if (ret && !DistributeFileSys::get()->isEnabled()) { bfs::path bkDir = bfs::path(masterScdPath) / SCD_BACKUP_DIR; bfs::create_directories(bkDir); LOG(INFO) << "moving " << outScdFileList.size() << " SCD files to directory " << bkDir; for (size_t i = 0; i < outScdFileList.size(); i++) { try { bfs::rename(outScdFileList[i], bkDir / bfs::path(outScdFileList[i]).filename()); } catch(const std::exception& e) { LOG(WARNING) << "failed to move file: " << std::endl << outScdFileList[i] << std::endl << e.what(); } } } if (!isNeedDoLocal()) return false; return ret; } bool IndexTaskService::createScdSharder( boost::shared_ptr<ScdSharder>& scdSharder) { return indexWorker_->createScdSharder(scdSharder); } izenelib::util::UString::EncodingType IndexTaskService::getEncode() const { return bundleConfig_->encoding_; } const std::vector<shardid_t>& IndexTaskService::getShardidListForSearch() { return bundleConfig_->col_shard_info_.shardList_; } typedef std::map<shardid_t, std::vector<vnodeid_t> > ShardingTopologyT; static void printSharding(const ShardingTopologyT& sharding_topology) { for(ShardingTopologyT::const_iterator cit = sharding_topology.begin(); cit != sharding_topology.end(); ++cit) { std::cout << "sharding : " << (uint32_t)cit->first << " is holding : "; for (size_t i = 0; i < cit->second.size(); ++i) { std::cout << cit->second[i] << ", "; } std::cout << std::endl; } } static bool removeSharding(const std::vector<shardid_t>& remove_sharding_nodes, std::vector<shardid_t>& left_sharding_nodes, size_t new_vnode_for_sharding, ShardingTopologyT& current_sharding_topology, std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >& migrate_data_list, std::vector<shardid_t>& sharding_map) { ShardingTopologyT remove_sharding_topo; for (size_t i = 0; i < remove_sharding_nodes.size(); ++i) { remove_sharding_topo[remove_sharding_nodes[i]] = current_sharding_topology[remove_sharding_nodes[i]]; current_sharding_topology.erase(remove_sharding_nodes[i]); } if (current_sharding_topology.empty() || remove_sharding_topo.size() != remove_sharding_nodes.size()) { return false; } ShardingTopologyT::iterator migrate_to_it = current_sharding_topology.begin(); for(ShardingTopologyT::iterator remove_it = remove_sharding_topo.begin(); remove_it != remove_sharding_topo.end(); ++remove_it) { size_t vnode_index = 0; for (; vnode_index < remove_it->second.size(); ++vnode_index) { vnodeid_t vid = remove_it->second[vnode_index]; migrate_data_list[vid] = std::pair<shardid_t, shardid_t>(remove_it->first, migrate_to_it->first); LOG(INFO) << "vnode : " << vid << " will be moved from " << (uint32_t)remove_it->first << " to " << (uint32_t)migrate_to_it->first; sharding_map[vid] = migrate_to_it->first; migrate_to_it->second.push_back(vid); if (migrate_to_it->second.size() > new_vnode_for_sharding) { // the new sharding node got enough data. move to next. left_sharding_nodes.push_back(migrate_to_it->first); ++migrate_to_it; if (migrate_to_it == current_sharding_topology.end()) { ShardingTopologyT::iterator tmpit = remove_it; if (vnode_index != (remove_it->second.size() - 1) || ++tmpit != remove_sharding_topo.end() ) { LOG(INFO) << "the remove sharding vnode can not totally migrate to others."; return false; } break; } } } remove_it->second.clear(); } while(migrate_to_it != current_sharding_topology.end()) { left_sharding_nodes.push_back(migrate_to_it->first); ++migrate_to_it; } return true; } static void migrateSharding(const std::vector<shardid_t>& new_sharding_nodes, size_t new_vnode_for_sharding, ShardingTopologyT& current_sharding_topology, ShardingTopologyT& new_sharding_topology, std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >& migrate_data_list, std::vector<shardid_t>& sharding_map) { // move the vnode from src sharding node to dest sharding node. size_t migrate_to = 0; for(ShardingTopologyT::iterator it = current_sharding_topology.begin(); it != current_sharding_topology.end(); ++it) { size_t migrate_start = it->second.size() - 1; while (migrate_to < new_sharding_nodes.size()) { // this old sharding has not enough data so do not migrate from this node. if (it->second.size() <= new_vnode_for_sharding) break; size_t old_start = migrate_start; for (size_t vnode_index = old_start; vnode_index > new_vnode_for_sharding; --vnode_index) { vnodeid_t vid = it->second[vnode_index]; migrate_data_list[vid] = std::pair<shardid_t, shardid_t>(it->first, new_sharding_nodes[migrate_to]); LOG(INFO) << "vnode : " << vid << " will be moved from " << (uint32_t)it->first << " to " << (uint32_t)new_sharding_nodes[migrate_to]; sharding_map[vid] = new_sharding_nodes[migrate_to]; new_sharding_topology[new_sharding_nodes[migrate_to]].push_back(vid); --migrate_start; if (new_sharding_topology[new_sharding_nodes[migrate_to]].size() >= new_vnode_for_sharding) { // the new sharding node got enough data. move to next. ++migrate_to; if (migrate_to >= new_sharding_nodes.size()) break; } } it->second.erase(it->second.begin() + migrate_start, it->second.end()); } if (migrate_to >= new_sharding_nodes.size()) break; } } bool IndexTaskService::doMigrateWork(bool removing, const std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >& migrate_data_list, const std::vector<shardid_t>& migrate_nodes, const std::string& map_file, const std::vector<shardid_t>& current_sharding_map) { std::map<std::string, std::map<shardid_t, std::vector<vnodeid_t> > > migrate_from_to_list; for(std::map<vnodeid_t, std::pair<shardid_t, shardid_t> >::const_iterator cit = migrate_data_list.begin(); cit != migrate_data_list.end(); ++cit) { std::string shardip = MasterManagerBase::get()->getShardNodeIP(cit->second.first); if (shardip.empty()) { LOG(ERROR) << "get source shard node ip error. " << cit->second.first; return false; } migrate_from_to_list[shardip][cit->second.second].push_back(cit->first); } std::map<shardid_t, std::vector<std::string> > generated_insert_scds; // the scds used for remove on the src node. std::map<shardid_t, std::vector<std::string> > generated_del_scds; bool ret = true; ret = DistributeFileSyncMgr::get()->generateMigrateScds(bundleConfig_->collectionName_, migrate_from_to_list, generated_insert_scds, generated_del_scds); if (!ret) { LOG(ERROR) << "generate the migrate SCD files failed."; return false; } // wait for all sharding nodes to finish their write queue. if(!MasterManagerBase::get()->waitForMigrateReady(getShardidListForSearch())) { LOG(INFO) << " wait for migrate get ready failed."; return false; } if (!removing) { // wait new sharding nodes to started. if (!MasterManagerBase::get()->waitForNewShardingNodes(migrate_nodes)) { LOG(INFO) << "wait for new sharding nodes to startup failed."; return false; } } if (!indexShardingNodes(generated_insert_scds)) { return false; } if (!removing) { // wait for the new sharding nodes to finish indexing. MasterManagerBase::get()->waitForMigrateIndexing(migrate_nodes); } indexShardingNodes(generated_del_scds); MasterManagerBase::get()->waitForMigrateIndexing(getShardidListForSearch()); MapShardingStrategy::saveShardingMapToFile(map_file, current_sharding_map); // update config will cause the collection to restart, so // the IndexTaskService will be destructed. updateShardingConfig(migrate_nodes, removing); return true; } bool IndexTaskService::addNewShardingNodes(const std::vector<shardid_t>& new_sharding_nodes) { if (!bundleConfig_->isMasterAggregator()) { LOG(INFO) << "change sharding node must be send to the master node."; return false; } if (!sharding_strategy_ || sharding_strategy_->shard_cfg_.shardidList_.size() == 0) { LOG(ERROR) << "no sharding config."; return false; } if (new_sharding_nodes.empty()) { LOG(INFO) << "empty new sharding nodes."; return false; } for (size_t i = 0; i < new_sharding_nodes.size(); ++i) { if (std::find(bundleConfig_->col_shard_info_.shardList_.begin(), bundleConfig_->col_shard_info_.shardList_.end(), new_sharding_nodes[i]) != bundleConfig_->col_shard_info_.shardList_.end()) { LOG(ERROR) << "new sharding nodes exists in the old sharding config."; return false; } } size_t current_sharding_num = sharding_strategy_->shard_cfg_.shardidList_.size(); // reading current sharding config(include the load on these nodes), // and determine which nodes need // migrate which part of their data. std::vector<shardid_t> current_sharding_map; std::string map_file = sharding_map_dir_ + bundleConfig_->collectionName_; MapShardingStrategy::readShardingMapFile(map_file, current_sharding_map); if (bundleConfig_->col_shard_info_.shardList_.size() == 1) { if (current_sharding_map.empty()) { current_sharding_map.resize(MapShardingStrategy::MAX_MAP_SIZE, bundleConfig_->col_shard_info_.shardList_[0]); } } if (current_sharding_map.empty()) { LOG(ERROR) << "sharding map is empty!"; return false; } if (current_sharding_map.size() < current_sharding_num + new_sharding_nodes.size()) { LOG(ERROR) << "the actual sharding num is larger than virtual nodes." << current_sharding_map.size(); return false; } size_t current_vnode_for_sharding = current_sharding_map.size()/current_sharding_num; size_t new_vnode_for_sharding = current_sharding_map.size()/(current_sharding_num + new_sharding_nodes.size()); ShardingTopologyT current_sharding_topology; for (size_t i = 0; i < current_sharding_map.size(); ++i) { current_sharding_topology[current_sharding_map[i]].push_back(i); } LOG(INFO) << "Before migrate, the average vnodes for each sharding is: " << current_vnode_for_sharding << " and sharding topology is : "; printSharding(current_sharding_topology); // move the vnode from src sharding node to dest sharding node. std::map<vnodeid_t, std::pair<shardid_t, shardid_t> > migrate_data_list; ShardingTopologyT new_sharding_topology; migrateSharding(new_sharding_nodes, new_vnode_for_sharding, current_sharding_topology, new_sharding_topology, migrate_data_list, current_sharding_map); LOG(INFO) << "After migrate, the average vnodes for each sharding will be: " << new_vnode_for_sharding << " and sharding topology will be : "; printSharding(current_sharding_topology); printSharding(new_sharding_topology); // this will disallow any new write. This may fail if other migrate // running or not all sharding nodes alive. if(!MasterManagerBase::get()->notifyAllShardingBeginMigrate(getShardidListForSearch())) { return false; } bool ret = doMigrateWork(false, migrate_data_list, new_sharding_nodes, map_file, current_sharding_map); // allow new write running. MasterManagerBase::get()->notifyAllShardingEndMigrate(); return ret; } bool IndexTaskService::indexShardingNodes(const std::map<shardid_t, std::vector<std::string> >& generated_migrate_scds) { std::string tmp_migrate_scd_dir = DistributeFileSys::get()->getFixedCopyPath("/migrate_scds/" + bundleConfig_->collectionName_ + "/" + boost::lexical_cast<std::string>(Utilities::createTimeStamp())); bfs::create_directories(DistributeFileSys::get()->getDFSPathForLocal(tmp_migrate_scd_dir)); std::map<shardid_t, std::vector<std::string> >::const_iterator cit = generated_migrate_scds.begin(); for (; cit != generated_migrate_scds.end(); ++cit) { LOG(INFO) << "prepare scd files for sharding node : " << (uint32_t)cit->first; std::string shard_scd_dir = tmp_migrate_scd_dir + "/shard" + getShardidStr(cit->first) + "/"; bfs::create_directories(DistributeFileSys::get()->getDFSPathForLocal(shard_scd_dir)); for (size_t i = 0; i < cit->second.size(); ++i) { LOG(INFO) << "add migrate scd : " << cit->second[i]; bfs::rename(DistributeFileSys::get()->getDFSPathForLocal(cit->second[i]), bfs::path(DistributeFileSys::get()->getDFSPathForLocal(shard_scd_dir))/(bfs::path(cit->second[i]).filename())); } // send index command. std::string json_req = "{\"collection\":\"" + bundleConfig_->collectionName_ + "\",\"index_scd_path\":\"" + shard_scd_dir + "\",\"disable_sharding\":2" + ",\"header\":{\"action\":\"index\",\"controller\":\"commands\"},\"uri\":\"commands/index\"}"; LOG(INFO) << "send request : " << json_req; std::vector<shardid_t> shardid; shardid.push_back(cit->first); if (!MasterManagerBase::get()->pushWriteReqToShard(json_req, shardid, true, true)) { LOG(WARNING) << "push write failed."; return false; } } return true; } void IndexTaskService::updateShardingConfig(const std::vector<shardid_t>& new_sharding_nodes, bool removing) { std::string sharding_cfg; std::vector<shardid_t> curr_shard_nodes = getShardidListForSearch(); if (!removing) { for (size_t i = 0; i < curr_shard_nodes.size(); ++i) { if (sharding_cfg.empty()) sharding_cfg = getShardidStr(curr_shard_nodes[i]); else sharding_cfg += "," + getShardidStr(curr_shard_nodes[i]); } } for (size_t i = 0; i < new_sharding_nodes.size(); ++i) { if (sharding_cfg.empty()) sharding_cfg = getShardidStr(new_sharding_nodes[i]); else sharding_cfg += "," + getShardidStr(new_sharding_nodes[i]); } LOG(INFO) << "new sharding cfg is : " << sharding_cfg; // // send index command. std::string json_req = "{\"collection\":\"" + bundleConfig_->collectionName_ + "\",\"new_sharding_cfg\":\"" + sharding_cfg + "\",\"header\":{\"action\":\"update_sharding_conf\",\"controller\":\"collection\"},\"uri\":\"collection/update_sharding_conf\"}"; LOG(INFO) << "send request : " << json_req; if (!removing) MasterManagerBase::get()->pushWriteReqToShard(json_req, new_sharding_nodes, true, true); if (bundleConfig_->isMasterAggregator() && !bundleConfig_->isWorkerNode()) { curr_shard_nodes.push_back(MasterManagerBase::get()->getMyShardId()); } MasterManagerBase::get()->pushWriteReqToShard(json_req, curr_shard_nodes, true, true); } bool IndexTaskService::generateMigrateSCD(const std::map<shardid_t, std::vector<vnodeid_t> >& vnode_list, std::map<shardid_t, std::string>& generated_insert_scds, std::map<shardid_t, std::string>& generated_del_scds) { return indexWorker_->generateMigrateSCD(vnode_list, generated_insert_scds, generated_del_scds); } bool IndexTaskService::removeShardingNodes(const std::vector<shardid_t>& remove_sharding_nodes) { if (!bundleConfig_->isMasterAggregator()) { LOG(INFO) << "change sharding node must be send to the master node."; return false; } if (!sharding_strategy_ || sharding_strategy_->shard_cfg_.shardidList_.size() == 0) { LOG(ERROR) << "no sharding config."; return false; } if (remove_sharding_nodes.empty()) { LOG(INFO) << "empty sharding nodes."; return false; } size_t current_sharding_num = sharding_strategy_->shard_cfg_.shardidList_.size(); if (current_sharding_num == 1) { LOG(INFO) << "The last one sharding node can not be removed."; return false; } if (remove_sharding_nodes.size() >= current_sharding_num) { LOG(INFO) << "You can not remove all sharding nodes."; return false; } for (size_t i = 0; i < remove_sharding_nodes.size(); ++i) { if (std::find(bundleConfig_->col_shard_info_.shardList_.begin(), bundleConfig_->col_shard_info_.shardList_.end(), remove_sharding_nodes[i]) == bundleConfig_->col_shard_info_.shardList_.end()) { LOG(ERROR) << "removing sharding node does not exist in the old sharding config."; return false; } } std::vector<shardid_t> current_sharding_map; std::string map_file = sharding_map_dir_ + bundleConfig_->collectionName_; MapShardingStrategy::readShardingMapFile(map_file, current_sharding_map); if (current_sharding_map.empty()) { LOG(ERROR) << "sharding map is empty!"; return false; } size_t current_vnode_for_sharding = current_sharding_map.size()/current_sharding_num; size_t new_vnode_for_sharding = current_sharding_map.size()/(current_sharding_num - remove_sharding_nodes.size()); ShardingTopologyT current_sharding_topology; for (size_t i = 0; i < current_sharding_map.size(); ++i) { current_sharding_topology[current_sharding_map[i]].push_back(i); } LOG(INFO) << "Before migrate, the average vnodes for each sharding is: " << current_vnode_for_sharding << " and sharding topology is : "; printSharding(current_sharding_topology); std::map<vnodeid_t, std::pair<shardid_t, shardid_t> > migrate_data_list; ShardingTopologyT new_sharding_topology; std::vector<shardid_t> left_sharding_nodes; bool ret = removeSharding(remove_sharding_nodes, left_sharding_nodes, new_vnode_for_sharding, current_sharding_topology, migrate_data_list, current_sharding_map); if (!ret || left_sharding_nodes.empty()) { LOG(INFO) << "removing nodes are wrong."; return false; } LOG(INFO) << "After migrate, the average vnodes for each sharding will be: " << new_vnode_for_sharding << " and sharding topology will be : "; printSharding(current_sharding_topology); if(!MasterManagerBase::get()->notifyAllShardingBeginMigrate(getShardidListForSearch())) { return false; } ret = doMigrateWork(true, migrate_data_list, left_sharding_nodes, map_file, current_sharding_map); // allow new write running. MasterManagerBase::get()->notifyAllShardingEndMigrate(); return ret; } }
35,486
11,277
// ************************************************************* // File: memory_manager.cc // Author: Novoselov Anton @ 2018 // URL: https://github.com/ans-hub/gdm_framework // ************************************************************* #include "memory_manager.h" #include <memory/memory_tracker.h> #include <memory/defines.h> #include <math/general.h> #include <system/assert_utils.h> #if defined (_WIN32) #include <malloc.h> #else #include <cstdlib> #endif // --public void* gdm::MemoryManager::Allocate(size_t bytes, MemoryTagValue tag) { return AllocateAligned(bytes, GetDefaultAlignment(), tag); } void* gdm::MemoryManager::AllocateAligned(size_t bytes, size_t align, MemoryTagValue tag) { align = math::Max(align, GetDefaultAlignment()); ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align); #if defined (_WIN32) void* ptr = _aligned_malloc(bytes, align); #else void* ptr = std::aligned_alloc(size, align); #endif MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(ptr, align)); return ptr; } void* gdm::MemoryManager::Reallocate(void* ptr, size_t new_bytes, MemoryTagValue tag) { return ReallocateAligned(ptr, new_bytes, GetDefaultAlignment(), tag); } void* gdm::MemoryManager::ReallocateAligned(void* ptr, size_t new_bytes, size_t align, MemoryTagValue tag) { align = math::Max(align, GetDefaultAlignment()); ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align); #if defined (_WIN32) MemoryTracker::GetInstance().SubUsage(tag, GetPointerSize(ptr, align)); void* new_ptr = _aligned_realloc(ptr, new_bytes, align); MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(new_ptr, align)); #else void* new_ptr = Allocate(new_bytes, align); memcpy(new_mem, ptr, GetPointerSize(ptr, align)); Deallocate(ptr, align); #endif MemoryTracker::GetInstance().AddUsage(tag, GetPointerSize(new_ptr, align)); return new_ptr; } void gdm::MemoryManager::Deallocate(void* ptr, MemoryTagValue tag) { DeallocateAligned(ptr, GetDefaultAlignment(), tag); } void gdm::MemoryManager::DeallocateAligned(void* ptr, size_t align, MemoryTagValue tag) { MemoryTracker::GetInstance().SubUsage(tag, GetPointerSize(ptr, align)); #if defined (_WIN32) _aligned_free(ptr); #else std::free(mem); #endif } size_t gdm::MemoryManager::GetPointerSize(void* ptr, size_t align) { if (!ptr) return 0; align = math::Max(align, GetDefaultAlignment()); ASSERTF(math::IsPowerOfTwo(align), "Alignment %zu is not power of 2", align); #if defined(_WIN32) return _aligned_msize(ptr, align, 0); #else return malloc_usabe_size(ptr); #endif } auto gdm::MemoryManager::GetTagUsage(MemoryTagValue tag) -> size_t { return MemoryTracker::GetInstance().GetTagUsage(tag); } auto gdm::MemoryManager::GetTagName(MemoryTagValue tag) -> const char* { return MemoryTracker::GetInstance().GetTagName(tag); }
2,903
999
/*************************************************************************** * * (C) Copyright 2010 The Board of Trustees of the * University of Illinois * All Rights Reserved * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "scanLargeArray.h" #include "OpenCL_common.h" #define UINT32_MAX 4294967295 #define BITS 4 #define LNB 4 #define SORT_BS 256 void sort (int numElems, unsigned int max_value, cl_mem* &dkeysPtr, cl_mem* &dvaluesPtr, cl_mem* &dkeys_oPtr, cl_mem* &dvalues_oPtr, cl_context *clContextPtr, cl_command_queue clCommandQueue, const cl_device_id clDevice, size_t *workItemSizes){ size_t block[1] = { SORT_BS }; size_t grid[1] = { ((numElems+4*SORT_BS-1)/(4*SORT_BS)) * block[0] }; unsigned int iterations = 0; while(max_value > 0){ max_value >>= BITS; iterations++; } cl_int ciErrNum; cl_context clContext = *clContextPtr; cl_program sort_program; cl_kernel splitSort; cl_kernel splitRearrange; cl_mem dhisto; cl_mem* original = dkeysPtr; unsigned int *zeroData; zeroData = (unsigned int *) calloc( (1<<BITS)*grid[0], sizeof(unsigned int) ); if (zeroData == NULL) { fprintf(stderr, "Could not allocate host memory! (%s: %d)\n", __FILE__, __LINE__); exit(1); } dhisto = clCreateBuffer(clContext, CL_MEM_COPY_HOST_PTR, (1<<BITS)*((numElems+4*SORT_BS-1)/(4*SORT_BS))*sizeof(unsigned int), zeroData, &ciErrNum); OCL_ERRCK_VAR(ciErrNum); free(zeroData); //char compileOptions[256]; // -cl-nv-verbose // Provides register info for NVIDIA devices // Set all Macros referenced by kernels /* sprintf(compileOptions, "\ -D CUTOFF2_VAL=%f -D CUTOFF_VAL=%f\ -D GRIDSIZE_VAL1=%d -D GRIDSIZE_VAL2=%d -D GRIDSIZE_VAL3=%d\ -D SIZE_XY_VAL=%d -D ONE_OVER_CUTOFF2_VAL=%f", cutoff2, cutoff, params.gridSize[0], params.gridSize[1], params.gridSize[2], size_xy, _1overCutoff2 );*/ size_t program_length; const char *source_path = "src/opencl_base/sort.cl"; char *source; // Dynamically allocate buffer for source source = oclLoadProgSource(source_path, "", &program_length); if(!source) { fprintf(stderr, "Could not load program source (%s)\n", __FILE__); exit(1); } sort_program = clCreateProgramWithSource(clContext, 1, (const char **)&source, &program_length, &ciErrNum); OCL_ERRCK_VAR(ciErrNum); free(source); OCL_ERRCK_RETVAL ( clBuildProgram(sort_program, 1, &clDevice, NULL /*compileOptions*/, NULL, NULL) ); // Uncomment to get build log from compiler for debugging char *build_log; size_t ret_val_size; ciErrNum = clGetProgramBuildInfo(sort_program, clDevice, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size); OCL_ERRCK_VAR(ciErrNum); build_log = (char *)malloc(ret_val_size+1); ciErrNum = clGetProgramBuildInfo(sort_program, clDevice, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL); OCL_ERRCK_VAR(ciErrNum); // to be carefully, terminate with \0 // there's no information in the reference whether the string is 0 terminated or not build_log[ret_val_size] = '\0'; fprintf(stderr, "%s\n", build_log ); splitSort = clCreateKernel(sort_program, "splitSort", &ciErrNum); OCL_ERRCK_VAR(ciErrNum); splitRearrange = clCreateKernel(sort_program, "splitRearrange", &ciErrNum); OCL_ERRCK_VAR(ciErrNum); OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 0, sizeof(int), &numElems) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 2, sizeof(cl_mem), (void *)dkeysPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 3, sizeof(cl_mem), (void *)dvaluesPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 4, sizeof(cl_mem), (void *)&dhisto) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 0, sizeof(int), &numElems) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 2, sizeof(cl_mem), (void *)dkeysPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 3, sizeof(cl_mem), (void *)dkeys_oPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 4, sizeof(cl_mem), (void *)dvaluesPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 5, sizeof(cl_mem), (void *)dvalues_oPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 6, sizeof(cl_mem), (void *)&dhisto) ); for (int i=0; i<iterations; i++){ OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 1, sizeof(int), &i) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 2, sizeof(cl_mem), (void *)dkeysPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitSort, 3, sizeof(cl_mem), (void *)dvaluesPtr) ); OCL_ERRCK_RETVAL ( clEnqueueNDRangeKernel(clCommandQueue, splitSort, 1, 0, grid, block, 0, 0, 0) ); scanLargeArray(((numElems+4*SORT_BS-1)/(4*SORT_BS))*(1<<BITS), dhisto, clContext, clCommandQueue, clDevice, workItemSizes); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 1, sizeof(int), &i ) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 2, sizeof(cl_mem), (void *)dkeysPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 3, sizeof(cl_mem), (void *)dkeys_oPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 4, sizeof(cl_mem), (void *)dvaluesPtr) ); OCL_ERRCK_RETVAL( clSetKernelArg(splitRearrange, 5, sizeof(cl_mem), (void *)dvalues_oPtr) ); OCL_ERRCK_RETVAL ( clEnqueueNDRangeKernel(clCommandQueue, splitRearrange, 1, 0, grid, block, 0, 0, 0) ); cl_mem* temp = dkeysPtr; dkeysPtr = dkeys_oPtr; dkeys_oPtr = temp; temp = dvaluesPtr; dvaluesPtr = dvalues_oPtr; dvalues_oPtr = temp; } OCL_ERRCK_RETVAL ( clReleaseKernel(splitSort) ); OCL_ERRCK_RETVAL ( clReleaseKernel(splitRearrange) ); OCL_ERRCK_RETVAL ( clReleaseMemObject(*dkeys_oPtr) ); OCL_ERRCK_RETVAL ( clReleaseMemObject(*dvalues_oPtr) ); OCL_ERRCK_RETVAL ( clReleaseMemObject(dhisto) ); OCL_ERRCK_RETVAL ( clReleaseProgram(sort_program) ); }
6,134
2,400
#ifndef __KF_DEPLOY_SERVER_MODULE_H__ #define __KF_DEPLOY_SERVER_MODULE_H__ /************************************************************************ // @Module : 部署Server // @Author : __凌_痕__ // @QQ : 7969936 // @Mail : lori227@qq.com // @Date : 2018-7-2 ************************************************************************/ #include "KFProtocol/KFProtocol.h" #include "KFDeployServerInterface.h" #include "KFMySQL/KFMySQLInterface.h" #include "KFMessage/KFMessageInterface.h" #include "KFDelayed/KFDelayedInterface.h" #include "KFTcpServer/KFTcpServerInterface.h" #include "KFHttpServer/KFHttpServerInterface.h" #include "KFHttpClient/KFHttpClientInterface.h" namespace KFrame { class KFAgentData { public: KFAgentData() { _port = 0; status = 0; } public: // 服务器id std::string _agent_id; // 局域网地址 std::string _local_ip; // 名字 std::string _name; // 类型 std::string _type; // 服务 std::string _service; // 端口 uint32 _port; // 状态 uint32 status; }; class KFDeployServerModule : public KFDeployServerInterface { public: KFDeployServerModule() = default; ~KFDeployServerModule() = default; // 逻辑 virtual void BeforeRun(); virtual void PrepareRun(); // 关闭 virtual void ShutDown(); protected: // 连接丢失 __KF_NET_EVENT_FUNCTION__( OnServerLostClient ); // 启动服务器 __KF_HTTP_FUNCTION__( HandleDeployCommand ); // 部署命令 __KF_DELAYED_FUNCTION__( OnHttpDeployCommandToAgent ); __KF_DELAYED_FUNCTION__( OnTcpDeployCommandToAgent ); protected: // 注册Agent __KF_MESSAGE_FUNCTION__( HandleRegisterAgentToServerReq ); // 执行sql语句 __KF_MESSAGE_FUNCTION__( HandleExecuteMySQLReq ); // 查询sql语句 __KF_MESSAGE_FUNCTION__( HandleQueryMySQLReq ); // 查询sql语句 __KF_MESSAGE_FUNCTION__( HandleDeleteMySQLReq ); // 部署命令 __KF_MESSAGE_FUNCTION__( HandleDeployToolCommandReq ); // 日志 __KF_MESSAGE_FUNCTION__( HandleDeployLogToServerReq ); // 查询toolid __KF_MESSAGE_FUNCTION__( HandleDeployQueryToolIdReq ); protected: // 更新Agnet状态 void UpdateAgentToDatabase( KFAgentData* kfagent, uint32 status ); // 回发日志消息 template<typename... P> void LogDeploy( uint64 agentid, const char* myfmt, P&& ... args ) { auto msg = __FORMAT__( myfmt, std::forward<P>( args )... ); return SendLogMessage( agentid, msg ); } void SendLogMessage( uint64 agentid, const std::string& msg ); private: KFMySQLDriver* _mysql_driver{ nullptr }; // Agent列表 KFHashMap< std::string, const std::string&, KFAgentData > _agent_list; // 定时任务id uint64 _delayed_id = 0u; // web列表 std::string _web_deploy_url; }; } #endif
3,118
1,139
#include "processor.h" stat_vars Processor::assign_values(stat_vars &in) { std::vector<std::string> vals = LinuxParser::CpuUtilization(); in.idle = std::stof(vals[LinuxParser::CPUStates::kIdle_]); in.iowait = std::stof(vals[LinuxParser::CPUStates::kIOwait_]); in.user = std::stof(vals[LinuxParser::CPUStates::kUser_]); in.nice = std::stof(vals[LinuxParser::CPUStates::kNice_]); in.system = std::stof(vals[LinuxParser::CPUStates::kSystem_]); in.irq = std::stof(vals[LinuxParser::CPUStates::kIRQ_]); in.softirq = std::stof(vals[LinuxParser::CPUStates::kSoftIRQ_]); in.steal = std::stof(vals[LinuxParser::CPUStates::kSteal_]); return in; } float Processor::calculate_sum(float idle, float iowait){ return ( idle + iowait); } float Processor::calculate_sum(float user, float nice, float system, float irq, float softirq, float steal){ return (user+nice+system+irq+softirq+steal); } float Processor::Utilization() { float PrevIdle = calculate_sum(prev.idle,prev.iowait); float PrevNonIdle = calculate_sum(prev.user , prev.nice, prev.system, prev.irq,prev.softirq,prev.steal); float PrevTotal = PrevIdle + PrevNonIdle; std::this_thread::sleep_for(std::chrono::milliseconds(100)); curr = assign_values(curr); float Idle = calculate_sum(curr.idle,curr.iowait); float NonIdle = calculate_sum(curr.user , curr.nice, curr.system, curr.irq,curr.softirq,curr.steal); float Total = Idle + NonIdle; float totald = Total - PrevTotal; float idled = Idle - PrevIdle; float CPU_percent = (totald - idled)/totald; prev = curr; return CPU_percent; }
1,655
637
// Copyright 2015, Christopher J. Foster and the other displaz contributors. // Use of this code is governed by the BSD-style license found in LICENSE.txt #include "ply_io.h" #include <cstdint> #include "QtLogger.h" //------------------------------------------------------------------------------ // Utilities for interfacing with rply /// Callback handler for reading ply data into a point field using rply class PlyFieldLoader { public: PlyFieldLoader(GeomField& field) : m_field(&field), m_pointIndex(0), m_componentReadCount(0), m_isPositionField(field.name == "position") { } /// rply callback to accept a single element of a point field static int rplyCallback(p_ply_argument argument) { void* pinfo = 0; long idata = 0; ply_get_argument_user_data(argument, &pinfo, &idata); double value = ply_get_argument_value(argument); return pinfo ? ((PlyFieldLoader*)pinfo)->writeValue(idata, value) : 0; } /// Accept a single element of a point field from the ply file int writeValue(int componentIndex, double value) { if (m_isPositionField) { // Remove fixed offset using first value read. if (m_pointIndex == 0) m_offset[componentIndex] = value; value -= m_offset[componentIndex]; } // Set data value depending on type size_t idx = m_pointIndex*m_field->spec.count + componentIndex; switch(m_field->spec.type) { case TypeSpec::Int: switch(m_field->spec.elsize) { case 1: m_field->as<int8_t>()[idx] = (int8_t)value; break; case 2: m_field->as<int16_t>()[idx] = (int16_t)value; break; case 4: m_field->as<int32_t>()[idx] = (int32_t)value; break; } break; case TypeSpec::Uint: switch(m_field->spec.elsize) { case 1: m_field->as<uint8_t>()[idx] = (uint8_t)value; break; case 2: m_field->as<uint16_t>()[idx] = (uint16_t)value; break; case 4: m_field->as<uint32_t>()[idx] = (uint32_t)value; break; } break; case TypeSpec::Float: switch(m_field->spec.elsize) { case 4: m_field->as<float>()[idx] = (float)value; break; case 8: m_field->as<double>()[idx] = (double)value; break; } break; default: assert(0 && "Unknown type encountered"); } // Keep track of which point we're on ++m_componentReadCount; if (m_componentReadCount == m_field->spec.count) { ++m_pointIndex; m_componentReadCount = 0; } return 1; } V3d offset() const { return V3d(m_offset[0], m_offset[1], m_offset[2]); } private: GeomField* m_field; size_t m_pointIndex; int m_componentReadCount; bool m_isPositionField; double m_offset[3]; }; /// Get TypeSpec type info from associated rply type void plyTypeToPointFieldType(e_ply_type& plyType, TypeSpec::Type& type, int& elsize) { switch(plyType) { case PLY_INT8: case PLY_CHAR: type = TypeSpec::Int; elsize = 1; break; case PLY_INT16: case PLY_SHORT: type = TypeSpec::Int; elsize = 2; break; case PLY_INT32: case PLY_INT: type = TypeSpec::Int; elsize = 4; break; case PLY_UINT8: case PLY_UCHAR: type = TypeSpec::Uint; elsize = 1; break; case PLY_UINT16: case PLY_USHORT: type = TypeSpec::Uint; elsize = 2; break; case PLY_UIN32: case PLY_UINT: type = TypeSpec::Uint; elsize = 4; break; case PLY_FLOAT32: case PLY_FLOAT: type = TypeSpec::Float; elsize = 4; break; case PLY_FLOAT64: case PLY_DOUBLE: type = TypeSpec::Float; elsize = 8; break; default: assert(0 && "Unknown ply type"); } } //------------------------------------------------------------------------------ // Utilities for loading point fields from the "vertex" element /// Find "vertex" element in ply file p_ply_element findVertexElement(p_ply ply, size_t& npoints) { for (p_ply_element elem = ply_get_next_element(ply, NULL); elem != NULL; elem = ply_get_next_element(ply, elem)) { const char* name = 0; long ninstances = 0; if (!ply_get_element_info(elem, &name, &ninstances)) continue; //tfm::printf("element %s, ninstances = %d\n", name, ninstances); if (strcmp(name, "vertex") == 0) { npoints = ninstances; return elem; } } return NULL; } /// Mapping from ply field names to internal (name,index) struct PlyPointField { std::string displazName; int componentIndex; TypeSpec::Semantics semantics; std::string plyName; e_ply_type plyType; }; /// Parse ply point properties, and recognize standard names static std::vector<PlyPointField> parsePlyPointFields(p_ply_element vertexElement) { // List of some fields which might be found in a .ply file and mappings to // displaz field groups. Note that there's no standard! PlyPointField standardFields[] = { {"position", 0, TypeSpec::Vector, "x", PLY_FLOAT}, {"position", 1, TypeSpec::Vector, "y", PLY_FLOAT}, {"position", 2, TypeSpec::Vector, "z", PLY_FLOAT}, {"color", 0, TypeSpec::Color , "red", PLY_UINT8}, {"color", 1, TypeSpec::Color , "green", PLY_UINT8}, {"color", 2, TypeSpec::Color , "blue", PLY_UINT8}, {"color", 0, TypeSpec::Color , "r", PLY_UINT8}, {"color", 1, TypeSpec::Color , "g", PLY_UINT8}, {"color", 2, TypeSpec::Color , "b", PLY_UINT8}, {"normal", 0, TypeSpec::Vector, "nx", PLY_FLOAT}, {"normal", 1, TypeSpec::Vector, "ny", PLY_FLOAT}, {"normal", 2, TypeSpec::Vector, "nz", PLY_FLOAT}, }; QRegExp vec3ComponentPattern("(.*)_?([xyz])"); QRegExp arrayComponentPattern("(.*)\\[([0-9]+)\\]"); size_t numStandardFields = sizeof(standardFields)/sizeof(standardFields[0]); std::vector<PlyPointField> fieldInfo; for (p_ply_property prop = ply_get_next_property(vertexElement, NULL); prop != NULL; prop = ply_get_next_property(vertexElement, prop)) { const char* propName = 0; e_ply_type propType; if (!ply_get_property_info(prop, &propName, &propType, NULL, NULL)) continue; if (propType == PLY_LIST) { g_logger.warning("Ignoring list property %s in ply file", propName); continue; } bool isStandardField = false; for (size_t i = 0; i < numStandardFields; ++i) { if (iequals(standardFields[i].plyName, propName)) { fieldInfo.push_back(standardFields[i]); fieldInfo.back().plyType = propType; fieldInfo.back().plyName = propName; // ensure correct string case isStandardField = true; break; } } if (!isStandardField) { // Try to guess whether this is one of several components - if so, // it will be turned into an array type (such as a vector) std::string displazName = propName; int index = 0; TypeSpec::Semantics semantics = TypeSpec::Array; if (vec3ComponentPattern.exactMatch(propName)) { displazName = vec3ComponentPattern.cap(1).toStdString(); index = vec3ComponentPattern.cap(2)[0].toLatin1() - 'x'; semantics = TypeSpec::Vector; } else if(arrayComponentPattern.exactMatch(propName)) { displazName = arrayComponentPattern.cap(1).toStdString(); index = arrayComponentPattern.cap(2).toInt(); } PlyPointField field = {displazName, index, semantics, propName, propType}; fieldInfo.push_back(field); } } return fieldInfo; } /// Order PlyPointField by displaz field name and component index bool displazFieldComparison(const PlyPointField& a, const PlyPointField& b) { if (a.displazName != b.displazName) return a.displazName < b.displazName; if (a.componentIndex != b.componentIndex) return a.componentIndex < b.componentIndex; return a.semantics < b.semantics; } bool loadPlyVertexProperties(QString fileName, p_ply ply, p_ply_element vertexElement, std::vector<GeomField>& fields, V3d& offset, size_t npoints) { // Create displaz GeomField for each property of the "vertex" element std::vector<PlyPointField> fieldInfo = parsePlyPointFields(vertexElement); std::sort(fieldInfo.begin(), fieldInfo.end(), &displazFieldComparison); std::vector<PlyFieldLoader> fieldLoaders; // Hack: use reserve to avoid iterator invalidation in push_back() fields.reserve(fieldInfo.size()); fieldLoaders.reserve(fieldInfo.size()); // Always add position field fields.push_back(GeomField(TypeSpec::vec3float32(), "position", npoints)); fieldLoaders.push_back(PlyFieldLoader(fields[0])); bool hasPosition = false; // Add all other fields, and connect fields to rply callbacks for (size_t i = 0; i < fieldInfo.size(); ) { const std::string& fieldName = fieldInfo[i].displazName; TypeSpec::Semantics semantics = fieldInfo[i].semantics; TypeSpec::Type baseType = TypeSpec::Unknown; int elsize = 0; plyTypeToPointFieldType(fieldInfo[i].plyType, baseType, elsize); size_t eltBegin = i; int maxComponentIndex = 0; while (i < fieldInfo.size() && fieldInfo[i].displazName == fieldName && fieldInfo[i].semantics == semantics) { maxComponentIndex = std::max(maxComponentIndex, fieldInfo[i].componentIndex); ++i; } size_t eltEnd = i; PlyFieldLoader* loader = 0; if (fieldName == "position") { hasPosition = true; loader = &fieldLoaders[0]; } else { TypeSpec type(baseType, elsize, maxComponentIndex+1, semantics); //tfm::printf("%s: type %s\n", fieldName, type); fields.push_back(GeomField(type, fieldName, npoints)); fieldLoaders.push_back(PlyFieldLoader(fields.back())); loader = &fieldLoaders.back(); } for (size_t j = eltBegin; j < eltEnd; ++j) { ply_set_read_cb(ply, "vertex", fieldInfo[j].plyName.c_str(), &PlyFieldLoader::rplyCallback, loader, fieldInfo[j].componentIndex); } } if (!hasPosition) { g_logger.error("No position property found in file %s", fileName); return false; } // All setup is done; read ply file using the callbacks if (!ply_read(ply)) return false; offset = fieldLoaders[0].offset(); return true; } //------------------------------------------------------------------------------ // Utilities for loading ply in "displaz-native" format /// Find all elements with name "vertex_*" /// /// The position element will always be in vertexElements[0] if present. bool findVertexElements(std::vector<p_ply_element>& vertexElements, p_ply ply, size_t& npoints) { int64_t np = -1; int positionIndex = -1; for (p_ply_element elem = ply_get_next_element(ply, NULL); elem != NULL; elem = ply_get_next_element(ply, elem)) { const char* name = 0; long ninstances = 0; if (!ply_get_element_info(elem, &name, &ninstances)) continue; if (strncmp(name, "vertex_", 7) == 0) { if (np == -1) np = ninstances; if (np != ninstances) { g_logger.error("Inconsistent number of points in \"vertex_*\" fields"); return false; } vertexElements.push_back(elem); if (strcmp(name, "vertex_position") == 0) positionIndex = (int)vertexElements.size()-1; } else { g_logger.warning("Ignoring unrecogized ply element: %s", name); } } if (positionIndex == -1) { g_logger.error("%s", "No vertex position found in ply file"); return false; } if (positionIndex != 0) std::swap(vertexElements[0], vertexElements[positionIndex]); npoints = np; return true; } bool loadDisplazNativePly(QString fileName, p_ply ply, std::vector<GeomField>& fields, V3d& offset, size_t& npoints) { std::vector<p_ply_element> vertexElements; if (!findVertexElements(vertexElements, ply, npoints)) return false; // Map each vertex element to the associated displaz type std::vector<PlyFieldLoader> fieldLoaders; // Reserve to avoid reallocs which invalidate pointers to elements. fields.reserve(vertexElements.size()); fieldLoaders.reserve(vertexElements.size()); for (auto elem = vertexElements.begin(); elem != vertexElements.end(); ++elem) { const char* elemName = 0; ply_get_element_info(*elem, &elemName, 0); assert(elemName); // Figure out type of current element. All properties of the element // should have the same type. TypeSpec::Type baseType = TypeSpec::Unknown; int elsize = 0; p_ply_property firstProp = ply_get_next_property(*elem, NULL); e_ply_type firstPropType = PLY_LIST; const char* firstPropName = 0; ply_get_property_info(firstProp, &firstPropName, &firstPropType, NULL, NULL); plyTypeToPointFieldType(firstPropType, baseType, elsize); // Determine semantics from first property. Displaz-native storage // doesn't care about the rest of the property names (or perhaps it // should be super strict?) TypeSpec::Semantics semantics; if (strcmp(firstPropName, "x") == 0) semantics = TypeSpec::Vector; else if (strcmp(firstPropName, "r") == 0) semantics = TypeSpec::Color; else if (strcmp(firstPropName, "0") == 0) semantics = TypeSpec::Array; else { g_logger.error("Could not determine vector semantics for property %s.%s: expected property name x, r or 0", elemName, firstPropName); return false; } // Count properties int numProps = 0; for (p_ply_property prop = ply_get_next_property(*elem, NULL); prop != NULL; prop = ply_get_next_property(*elem, prop)) { numProps += 1; } std::string fieldName = elemName + 7; // Strip off "vertex_" prefix if (fieldName == "position") { if (numProps != 3) { g_logger.error("position field must have three elements, found %d", numProps); return false; } // Force "vector float[3]" for position semantics = TypeSpec::Vector; elsize = 4; baseType = TypeSpec::Float; } // Create loader callback object TypeSpec type(baseType, elsize, numProps, semantics); fields.push_back(GeomField(type, fieldName, npoints)); fieldLoaders.push_back(PlyFieldLoader(fields.back())); // Connect callbacks for each property int propIdx = 0; for (p_ply_property prop = ply_get_next_property(*elem, NULL); prop != NULL; prop = ply_get_next_property(*elem, prop)) { e_ply_type propType; const char* propName = 0; ply_get_property_info(prop, &propName, &propType, NULL, NULL); ply_set_read_cb(ply, elemName, propName, &PlyFieldLoader::rplyCallback, &fieldLoaders.back(), propIdx); propIdx += 1; } g_logger.info("%s: %s %s", fileName, type, fieldName); } // All setup is done; read ply file using the callbacks if (!ply_read(ply)) { g_logger.error("Error in ply_read()"); return false; } offset = fieldLoaders[0].offset(); return true; } void logRplyError(p_ply ply, const char* message) { g_logger.error("rply: %s", message); }
17,113
5,170
/************************************************************************** * Contributors are not mentioned at all. * * * * 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. * **************************************************************************/ // //----------------------------------------------------------------- // AliAnalysisTaskLNNntuple class //----------------------------------------------------------------- class TTree; class TParticle; class TVector3; #include "AliAnalysisManager.h" #include <AliMCEventHandler.h> #include <AliMCEvent.h> #include <AliStack.h> class AliESDVertex; class AliESDv0; #include <iostream> #include "AliAnalysisTaskSE.h" #include "TList.h" #include "TH1.h" #include "TH2.h" #include "TH3.h" #include "TNtuple.h" #include "TNtupleD.h" #include "TCutG.h" #include "TF1.h" #include "TVector3.h" #include "TCanvas.h" #include "TMath.h" #include "TChain.h" #include "Riostream.h" #include "AliLog.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliExternalTrackParam.h" #include "AliInputEventHandler.h" #include "AliAnalysisTaskLNNntuple.h" #include "AliCentrality.h" #include "AliTRDPIDResponse.h" #include "TString.h" #include <TDatime.h> #include <TRandom3.h> #include <TLorentzVector.h> //#include <AliVTrack.h> ClassImp (AliAnalysisTaskLNNntuple) //________________________________________________________________________ AliAnalysisTaskLNNntuple::AliAnalysisTaskLNNntuple (): AliAnalysisTaskSE (), fMaxPtPion(0.55), fMinPtTriton(0.75), fYear(2015), fMC(kTRUE), fEventCuts(), fListHist (0), fHistEventMultiplicity (0), fHistTrackMultiplicity (0), fhBB (0), fhTOF (0), fhMassTOF (0), fhBBPions (0), fhBBH3 (0), fhBBH3TofSel (0), fhTestNsigma (0), fTPCclusPID(0), fhTestQ(0), fNt (0), fPIDResponse(0) { // Dummy Constructor //Printf(" ****************** Default ctor \n"); } //________________________________________________________________________ AliAnalysisTaskLNNntuple::AliAnalysisTaskLNNntuple (const char *name, Bool_t mc): AliAnalysisTaskSE (name), fMaxPtPion(0.55), fMinPtTriton(0.75), fYear(2015), fMC(mc), fEventCuts(), fListHist (0), fHistEventMultiplicity (0), fHistTrackMultiplicity (0), fhBB (0), fhTOF (0), fhMassTOF (0), fhBBPions (0), fhBBH3 (0), fhBBH3TofSel (0), fhTestNsigma (0), fTPCclusPID(0), fhTestQ(0), fNt (0), fPIDResponse(0) { // Define input and output slots here // Input slot #0 works with a TChain //DefineInput(0, TChain::Class()); // Output slot #0 writes into a TList container () DefineInput (0, TChain::Class ()); DefineOutput (1, TList::Class ()); //DefineOutput(2, TTree::Class()); //DefineOutput(3, TTree::Class()); //Printf(" ****************** Right ctor \n"); } //_______________________________________________________ AliAnalysisTaskLNNntuple::~AliAnalysisTaskLNNntuple () { // Destructor if (fListHist) { delete fListHist; fListHist = 0; } } //==================DEFINITION OF OUTPUT OBJECTS============================== void AliAnalysisTaskLNNntuple::UserCreateOutputObjects () { fListHist = new TList (); fListHist->SetOwner (); // IMPORTANT! if(fYear==2015) fEventCuts.SetupLHC15o(); if(fYear==2011) fEventCuts.SetupRun1PbPb(); if (!fHistEventMultiplicity) { fHistEventMultiplicity = new TH1F ("fHistEventMultiplicity", "Nb of Events", 13, -0.5, 12.5); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (1, "All Events"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (2, "Events w/PV"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (3, "Events w/|Vz|<10cm"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (4, "Central Events"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (5, "SemiCentral Events"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (6, "MB Events"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (7, "Central Events w/|Vz|<10cm"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (8, "SemiCentral Events w/|Vz|<10cm"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (9, "MB Events w/|Vz|<10cm"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (10,"Any Events"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (11,"Any Events w/|Vz|<10cm"); fHistEventMultiplicity->GetXaxis ()->SetBinLabel (12,"other"); fListHist->Add (fHistEventMultiplicity); } if (!fHistTrackMultiplicity) { fHistTrackMultiplicity = new TH2F ("fHistTrackMultiplicity", "Nb of Tracks", 2500, 0, 25000, 210, -1, 104); fHistTrackMultiplicity->GetXaxis ()->SetTitle ("Number of tracks"); fHistTrackMultiplicity->GetYaxis ()->SetTitle ("Percentile"); fListHist->Add (fHistTrackMultiplicity); } Double_t pMax = 8; Double_t binWidth = 0.1; Int_t nBinBB = (Int_t) (2 * pMax / binWidth); if (!fhBB) { fhBB = new TH2F ("fhBB", "BetheBlochTPC", nBinBB, -pMax, pMax, 400, 0, 800); fhBB->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})"); fhBB->GetYaxis ()->SetTitle ("TPC Signal"); fListHist->Add (fhBB); } if (!fhTOF) { fhTOF = new TH2F ("fhTOF", "Scatter Plot TOF", nBinBB, -pMax, pMax, 100, 0,1.2); fhTOF->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})"); fhTOF->GetYaxis ()->SetTitle ("#beta"); fListHist->Add (fhTOF); } if (!fhMassTOF) { fhMassTOF = new TH2F ("fhMassTOF", "Particle Mass - TOF", nBinBB, 0, pMax, 400, 0,5); fhMassTOF->GetYaxis ()->SetTitle ("Mass (GeV/#it{c}^{2})"); fhMassTOF->GetXaxis ()->SetTitle ("P (GeV/#it{c})"); fListHist->Add (fhMassTOF); } if (!fhBBPions) { fhBBPions = new TH2F ("fhBBPions", "Bethe-Bloch TPC Pions", nBinBB, -pMax, pMax, 400, 0, 800); fhBBPions->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})"); fhBBPions->GetYaxis ()->SetTitle ("TPC Signal"); fListHist->Add (fhBBPions); } if (!fhBBH3) { fhBBH3 = new TH2F ("fhBBH3", "Bethe-Bloch TPC ^3H", nBinBB, -pMax, pMax, 400, 0, 800); fhBBH3->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})"); fhBBH3->GetYaxis ()->SetTitle ("TPC Signal"); fListHist->Add (fhBBH3); } if (!fhBBH3TofSel) { fhBBH3TofSel = new TH2F ("fhBBH3TofSel","Bethe-Bloch TPC #^{3}H after TOF 3#sigma cut", nBinBB,-pMax, pMax, 400, 0, 800); fhBBH3TofSel->GetXaxis ()->SetTitle ("p/z (GeV/#it{c})"); fhBBH3TofSel->GetYaxis ()->SetTitle ("TPC Signal"); fListHist->Add (fhBBH3TofSel); } if (!fhTestNsigma) { fhTestNsigma = new TH2F ("hNsigmaTri", "n #sigma distribution", 300, 0, 15, 100, -10, 10); fListHist->Add (fhTestNsigma); } if(!fTPCclusPID){ fTPCclusPID = new TH2F("fTPCclusPID","triton track : clusters vs PID clusters",200,0,200,200,0,200); fListHist->Add (fTPCclusPID); } if(!fhTestQ){ fhTestQ = new TH2F("htestQ","candidate charge as from TPC",16,-2,2,16,-2,2); fhTestQ->SetXTitle("#pi Id charge"); fhTestQ->SetYTitle("3H Id charge"); fListHist->Add(fhTestQ); } if (!fNt) { if(!fMC){ fNt = new TNtupleD ("nt", "V0 ntuple","piPx:piPy:piPz:triPx:triPy:triPz:nSpi:nStri:triTOFmass:piTPCsig:triTPCsig:v0P:ptArm:alphaArm:triDcaXY:triDcaZ:v0DcaD:decayL:decayLxy:v0Dca:CosP:v0VtxErrSum:sign:dcaPi:is3Hele:nSPiFromPiTof:nSPrTof:nSPiTof:nITSclus:triTRDsig"); fListHist->Add (fNt); } else { fNt = new TNtupleD ("nt", "V0 ntuple","piPx:piPy:piPz:triPx:triPy:triPz:nSpi:nStri:triTOFmass:piTPCsig:triTPCsig:v0P:ptArm:alphaArm:triDcaXY:triDCAZ:v0DcaD:decayL:decayLxy:v0Dca:CosP:v0VtxErrSum:sign:dcaPi:is3Hele:nSPiFromPiTof:nSPrTof:nSPiTof:nITSclus:piPdgCode:triPdgCode:piMumPdgCode:triMumPdgCode:triTRDsig"); fListHist->Add (fNt); } } PostData (1, fListHist); } // end UserCreateOutputObjects //====================== USER EXEC ======================== void AliAnalysisTaskLNNntuple::UserExec (Option_t *) { //------------------------------------------ // Main loop AliVEvent *event = InputEvent (); if (!event) { Printf ("ERROR: Could not retrieve event"); return; } if(fMC) Info ("AliAnalysisTaskLNNntuple for MC", "Starting UserExec"); else Info ("AliAnalysisTaskLNNntuple for Data", "Starting UserExec"); // Load MC if required AliStack *stack = 0; Int_t nbMcTracks=0; if(fMC){ AliMCEvent *mcEvent = MCEvent(); if (!mcEvent) { Printf("ERROR: Could not retrieve MC event"); return; } stack = mcEvent->Stack(); nbMcTracks = stack->GetNtrack();; if(!stack) { Printf( "Stack not available, Exiting... \n"); return; } } // Load ESD event AliESDEvent *lESDevent = dynamic_cast < AliESDEvent * >(event); if (!lESDevent) { AliError ("Cannot get the ESD event"); return; } fHistEventMultiplicity->Fill (0); Double_t lMagneticField = lESDevent->GetMagneticField (); Int_t TrackNumber = -1; AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager (); AliInputEventHandler *inputHandler = (AliInputEventHandler *) (man->GetInputEventHandler ()); TrackNumber = lESDevent->GetNumberOfTracks (); if (TrackNumber < 3) return; if(!fEventCuts.AcceptEvent(lESDevent)) return; Float_t centrality=fEventCuts.GetCentrality(0); // 0 = V0M fHistTrackMultiplicity->Fill(TrackNumber,centrality); Int_t selCentrality = SelectCentrality(centrality); fHistEventMultiplicity->Fill (selCentrality); //*******// // PID // //*******// fPIDResponse = inputHandler->GetPIDResponse (); if(!fPIDResponse) { AliError("!!! Please check the PID task, it is not loaded!!\n"); return; } fPIDResponse->SetCachePID (kTRUE); //=========================================== // Primary vertex cut const AliESDVertex *vtx = lESDevent->GetPrimaryVertexTracks (); if (vtx->GetNContributors () < 1) { // SPD vertex cut vtx = lESDevent->GetPrimaryVertexSPD (); if (vtx->GetNContributors () < 1) { Info ("AliAnalysisTaskLNNntuple","No good vertex, skip event"); return; // NO GOOD VERTEX, SKIP EVENT } } fHistEventMultiplicity->Fill (1); // analyzed events with PV if (TMath::Abs (vtx->GetX()) > 10) return; selCentrality = SelectCentrality(centrality,kTRUE); fHistEventMultiplicity->Fill (selCentrality); fHistEventMultiplicity->Fill (2); // track quality monitor plots for (Int_t j=0; j<TrackNumber; j++) { //loop on tracks AliESDtrack *esdtrack=lESDevent->GetTrack(j); if(!esdtrack) { AliError(Form("ERROR: Could not retrieve esdtrack %d",j)); continue; } // ************** Track cuts **************** if (!PassTrackCuts(esdtrack)) continue; fhBB->Fill(esdtrack->P()/esdtrack->GetSign(),esdtrack->GetTPCsignal()); fhTestNsigma->Fill(esdtrack->P(),fPIDResponse->NumberOfSigmasTPC(esdtrack,(AliPID::EParticleType)6)); Double_t tofmass = -1; tofmass = GetTOFmass(esdtrack); if(tofmass>0) { fhMassTOF->Fill(esdtrack->P(),tofmass); } } // *************** Loop over V0s *************** for(Int_t iv=0; iv<lESDevent->GetNumberOfV0s(); iv++){ AliESDv0 * v0s = lESDevent->GetV0(iv); if(!v0s) continue; TVector3 globVtx(vtx->GetX(),vtx->GetY(),vtx->GetZ()); TVector3 v0Vtx(v0s->Xv(),v0s->Yv(),v0s->Zv()); TVector3 decayL = globVtx-v0Vtx; Double_t path = decayL.Mag(); if(!Passv0Cuts(v0s,path)) continue; AliESDtrack* trackPos = lESDevent->GetTrack(v0s->GetPindex()); AliESDtrack* trackNeg = lESDevent->GetTrack(v0s->GetNindex()); if(!PassTrackCuts(trackPos)) continue; if(!PassTrackCuts(trackNeg)) continue; AliESDtrack *pion =0x0; AliESDtrack *triton=0x0; Double_t momPi[3], momTri[3]; if(IsPionCandidate(trackPos) && IsTritonCandidate(trackNeg)) { pion = trackPos; triton = trackNeg; v0s->GetPPxPyPz(momPi[0],momPi[1],momPi[2]); v0s->GetNPxPyPz(momTri[0],momTri[1],momTri[2]); } else if(IsPionCandidate(trackNeg)&&IsTritonCandidate(trackPos)){ pion = trackNeg; triton = trackPos; v0s->GetNPxPyPz(momPi[0],momPi[1],momPi[2]); v0s->GetPPxPyPz(momTri[0],momTri[1],momTri[2]); } else continue; // monitor dE/dx of tracks in selected V0s fhBBPions->Fill(pion->P()*pion->GetSign(),pion->GetTPCsignal()); fhBBH3->Fill(triton->P()*triton->GetSign(),triton->GetTPCsignal()); Double_t tofMass = GetTOFmass(triton); if(tofMass>2.5 && tofMass <3.5) fhBBH3TofSel->Fill(triton->P()*triton->GetSign(),triton->GetTPCsignal()); Double_t nSPi = fPIDResponse->NumberOfSigmasTPC (pion,(AliPID::EParticleType) 2); Double_t nSTri = fPIDResponse->NumberOfSigmasTPC (triton,(AliPID::EParticleType) 6); Double_t decayLXY = TMath::Sqrt(decayL.Mag2 () - decayL.Z () * decayL.Z ()); Double_t ptArm = v0s->PtArmV0 (); Double_t alphaArm = v0s->AlphaV0 (); Float_t dcaTri[2] = { -100, -100 }; Double_t Vtxpos[3] ={ globVtx.X (), globVtx.Y (), globVtx.Z () }; triton->GetDZ (Vtxpos[0], Vtxpos[1], Vtxpos[2], lESDevent->GetMagneticField (), dcaTri); //dca to primary vertex Float_t dcaPi= pion->GetD(Vtxpos[0],Vtxpos[1],lESDevent->GetMagneticField()); //Float_t dcaTriTot = triton->GetD(Vtxpos[0],Vtxpos[1],lESDevent->GetMagneticField()); -> same as dcaTri[1] Double_t nSPiFromPiTof = fPIDResponse->NumberOfSigmasTOF (pion,(AliPID::EParticleType) 2); Double_t nSPrTof = fPIDResponse->NumberOfSigmasTOF (triton,(AliPID::EParticleType) 4); //check if 3H is identified as proton in TOF PID Double_t nSPiTof = fPIDResponse->NumberOfSigmasTOF (triton,(AliPID::EParticleType) 2); // check if 3H is identified as pion TOF PID AliESDVertex vtxV0 = v0s->GetVertex (); Double_t sigmaVtxV0[2] = { pion->GetD(vtxV0.GetX (), vtxV0.GetY (),lMagneticField), triton->GetD (vtxV0.GetX (), vtxV0.GetY (), lMagneticField) }; Double_t err = TMath::Sqrt (sigmaVtxV0[0] * sigmaVtxV0[0] + sigmaVtxV0[1] * sigmaVtxV0[1]); fhTestQ->Fill(pion->Charge(),triton->Charge()); Float_t isHele=0; Int_t nTrackletsPID=0; Float_t eleEff[3] = {0.85,0.9,0.95}; AliPIDResponse::EDetPidStatus pidStatus = fPIDResponse->CheckPIDStatus(AliPIDResponse::kTRD,triton); if(pidStatus!=AliPIDResponse::kDetPidOk) isHele = -1; else { for(Int_t iEff=0; iEff<3; iEff++) { Bool_t isEle = fPIDResponse->IdentifiedAsElectronTRD(triton,nTrackletsPID,eleEff[iEff],centrality,AliTRDPIDResponse::kLQ2D); if(isEle && nTrackletsPID>3) isHele += (iEff+1)*TMath::Power(10,iEff); } } if(fMC){ Double_t pdgPion=-1, pdgTriton=-1, pdgPionMum=-1, pdgTritonMum=-1; if(TMath::Abs(pion->GetLabel()<nbMcTracks)) { TParticle *piMC = stack->Particle(TMath::Abs(pion->GetLabel())); pdgPion = piMC->GetPdgCode(); Int_t mum = piMC->GetFirstMother(); if(mum>0 && mum<nbMcTracks){ pdgPionMum = stack->Particle(mum)->GetPdgCode(); } } if(TMath::Abs(triton->GetLabel()<nbMcTracks)) { TParticle *tritonMC = stack->Particle(TMath::Abs(triton->GetLabel())); pdgTriton = tritonMC->GetPdgCode(); Int_t mum = tritonMC->GetFirstMother(); if(mum>0 && mum<nbMcTracks){ pdgTritonMum = stack->Particle(mum)->GetPdgCode(); } } Double_t ntuple[34] = { momPi[0], momPi[1], momPi[2], momTri[0], momTri[1],momTri[2], nSPi, nSTri, tofMass,pion->GetTPCsignal (), triton->GetTPCsignal (), v0s->P(), ptArm, alphaArm, dcaTri[0], dcaTri[1],v0s->GetDcaV0Daughters (), decayL.Mag(), decayLXY, v0s->GetD (vtx->GetX (), vtx->GetY (), vtx->GetZ ()),v0s->GetV0CosineOfPointingAngle (), err, pion->GetSign () + triton->GetSign ()*10, dcaPi,isHele,nSPiFromPiTof,nSPrTof,nSPiTof,pion->GetNumberOfITSClusters()+100.*triton->GetNumberOfITSClusters(), pdgPion,pdgTriton,pdgPionMum,pdgTritonMum,triton->GetTRDsignal()}; fNt->Fill (ntuple); } else { Double_t ntuple[30] = { momPi[0], momPi[1], momPi[2], momTri[0], momTri[1],momTri[2], nSPi, nSTri, tofMass,pion->GetTPCsignal (), triton->GetTPCsignal (), v0s->P(), ptArm, alphaArm, dcaTri[0], dcaTri[1], v0s->GetDcaV0Daughters (), decayL.Mag(), decayLXY, v0s->GetD (vtx->GetX (), vtx->GetY (), vtx->GetZ ()),v0s->GetV0CosineOfPointingAngle (), err, pion->GetSign () + triton->GetSign ()*10, dcaPi,isHele,nSPiFromPiTof,nSPrTof,nSPiTof,pion->GetNumberOfITSClusters()+100.*triton->GetNumberOfITSClusters(),triton->GetTRDsignal()}; fNt->Fill (ntuple); } } // loop over V0s PostData (1, fListHist); } //end userexec //________________________________________________________________________ void AliAnalysisTaskLNNntuple::Terminate (Option_t *) { // Draw result to the screen // Called once at the end of the query } //________________________________________________________________________ Bool_t AliAnalysisTaskLNNntuple::PassTrackCuts (AliESDtrack * tr) { if(tr->GetTPCNcls() < 60 ) return kFALSE; if (!(tr->GetStatus () & AliESDtrack::kTPCrefit)) return kFALSE; if (Chi2perNDF (tr) > 5) return kFALSE; if (tr->GetKinkIndex (0) != 0) return kFALSE; if (TMath::Abs (tr->Eta ()) > 0.9) return kFALSE; if (tr->P () < 0.15) return kFALSE; if (tr->P () > 10) return kFALSE; return true; } //________________________________________________________________________ Bool_t AliAnalysisTaskLNNntuple::Passv0Cuts (AliESDv0 * v0, Double_t decayLength) { if(v0->GetOnFlyStatus()==kTRUE) return false; if (v0->P () < 0.7) return kFALSE; if (v0->P () > 10) return kFALSE; if (v0->GetDcaV0Daughters () > 0.8) return kFALSE; if (v0->GetV0CosineOfPointingAngle () < 0.9995) return kFALSE; if (decayLength < 0.5) return false; // loose cut to reduce bkg of V0s coming from primary vertex( weak decay and the coice of 1 cm comes from MC study ) return true; } //________________________________________________________________ Bool_t AliAnalysisTaskLNNntuple::IsPionCandidate (AliESDtrack * tr) { if(tr->Pt()> fMaxPtPion) return kFALSE; AliPIDResponse::EDetPidStatus statusTPC; Double_t nSigmaTPC = -999; statusTPC = fPIDResponse->NumberOfSigmas (AliPIDResponse::kTPC, tr, AliPID::kPion,nSigmaTPC); Bool_t z = kFALSE; if (statusTPC == AliPIDResponse::kDetPidOk && TMath::Abs (nSigmaTPC) <= 3.5) z = kTRUE; return z; } //________________________________________________________________________ Bool_t AliAnalysisTaskLNNntuple::IsTritonCandidate(AliESDtrack * tr) { if(tr->Pt()<fMinPtTriton) return kFALSE; AliPIDResponse::EDetPidStatus statusTPC; Double_t nSigmaTPC = -999; statusTPC = fPIDResponse->NumberOfSigmas (AliPIDResponse::kTPC, tr, AliPID::kTriton, nSigmaTPC); Bool_t z = kFALSE; if (statusTPC == AliPIDResponse::kDetPidOk && TMath::Abs (nSigmaTPC) <= 3.5) z = kTRUE; if(z) { fTPCclusPID->Fill(tr->GetTPCNcls(),tr->GetTPCsignalN()); if(tr->GetTPCsignalN()<40) z = kFALSE; } return z; } //________________________________________________________________________ Double_t AliAnalysisTaskLNNntuple::GetTOFmass(AliESDtrack * tr) { // get TOF mass Double_t m = -999; //mass Double_t b = -999; //beta Double_t trackLeng = 0; if ((tr->GetStatus () & AliESDtrack::kTOFout) == AliESDtrack::kTOFout) { trackLeng = tr->GetIntegratedLength (); //Double_t p = tr->P (); Double_t p = tr->GetTPCmomentum(); Double_t speedOfLight = TMath::C () * 1E2 * 1E-12; // cm/ps Double_t timeTOF = tr->GetTOFsignal () - fPIDResponse->GetTOFResponse ().GetStartTime (p); // ps b = trackLeng / (timeTOF * speedOfLight); if (b >= 1 || b == 0) return m; m = p * TMath::Sqrt (1 / (b * b) - 1); } return m; } //________________________________________________________________________ Double_t AliAnalysisTaskLNNntuple::Chi2perNDF (AliESDtrack * track) { // Calculate chi2 per ndf for track Int_t nClustersTPC = track->GetTPCNcls (); if (nClustersTPC > 5) return (track->GetTPCchi2 () / Float_t (nClustersTPC - 5)); else return (-1.); } //________________________________________________________________________ Int_t AliAnalysisTaskLNNntuple::SelectCentrality(Float_t perc, Bool_t isPrimVtx){ // enum {kCentral=3, kSemiCentral=4, kPeripheral=5, kOther=9, kCentralPV=6,kSemiCentralPV=7, kPeripheralPV=8, kOtherPV=10 }; Int_t result=-1; if(!isPrimVtx){ if(perc<=10) result=3; else if(perc>10 && perc <=40) result=4; else if(perc>40 && perc <=90) result=5; else result=9; } else { if(perc<=10) result=6; else if(perc>10 && perc <=40) result=7; else if(perc>40 && perc <=90) result=8; else result=10; } return result; }
21,230
8,907
#include <bits/stdc++.h> #define ll long long #define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) using namespace std; set<ll> usinversal; ll ans = 0; ll aa = 0; int main() { fast; ll n; cin >> n; ll sum1 = 0, sum2= 0; vector<ll> a1, a2; bool l; while (n--) { ll x; cin >>x; if (x >= 0) { sum1 += x; a1.push_back(x); l = true; } else { sum2 += -1 *x; a2.push_back(-1 * x); l = false; } } if (sum1 >sum2) { cout << "first" << "\n"; } else if (sum2 > sum1) { cout << "second" << "\n"; } else { if (a1 > a2) { cout << "first" << "\n"; } else if (a1 < a2) { cout <<"second" << "\n"; } else if (l) { cout << "first" << "\n"; } else { cout << "second" << "\n"; } } return 0; }
1,081
415
// // Created by Bradley Austin Davis on 2016/07/01 // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "KtxTests.h" #include <mutex> #include <QtTest/QtTest> #include <ktx/KTX.h> #include <gpu/Texture.h> #include <image/Image.h> QTEST_GUILESS_MAIN(KtxTests) QString getRootPath() { static std::once_flag once; static QString result; std::call_once(once, [&] { QFileInfo file(__FILE__); QDir parent = file.absolutePath(); result = QDir::cleanPath(parent.currentPath() + "/../../.."); }); return result; } void KtxTests::initTestCase() { } void KtxTests::cleanupTestCase() { } void KtxTests::testKhronosCompressionFunctions() { using namespace khronos::gl::texture; QCOMPARE(evalAlignedCompressedBlockCount<4>(0), (uint32_t)0x0); QCOMPARE(evalAlignedCompressedBlockCount<4>(1), (uint32_t)0x1); QCOMPARE(evalAlignedCompressedBlockCount<4>(4), (uint32_t)0x1); QCOMPARE(evalAlignedCompressedBlockCount<4>(5), (uint32_t)0x2); QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x00), (uint32_t)0x00); QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x01), (uint32_t)0x01); QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x04), (uint32_t)0x01); QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x05), (uint32_t)0x02); QCOMPARE(evalCompressedBlockCount(InternalFormat::COMPRESSED_SRGB_S3TC_DXT1_EXT, 0x1000), (uint32_t)0x400); QVERIFY_EXCEPTION_THROWN(evalCompressedBlockCount(InternalFormat::RGBA8, 0x00), std::runtime_error); } void KtxTests::testKtxEvalFunctions() { QCOMPARE(sizeof(ktx::Header), (size_t)64); QCOMPARE(ktx::evalPadding(0x0), (uint8_t)0); QCOMPARE(ktx::evalPadding(0x1), (uint8_t)3); QCOMPARE(ktx::evalPadding(0x2), (uint8_t)2); QCOMPARE(ktx::evalPadding(0x3), (uint8_t)1); QCOMPARE(ktx::evalPadding(0x4), (uint8_t)0); QCOMPARE(ktx::evalPadding(0x400), (uint8_t)0); QCOMPARE(ktx::evalPadding(0x401), (uint8_t)3); QCOMPARE(ktx::evalPaddedSize(0x0), 0x0); QCOMPARE(ktx::evalPaddedSize(0x1), 0x4); QCOMPARE(ktx::evalPaddedSize(0x2), 0x4); QCOMPARE(ktx::evalPaddedSize(0x3), 0x4); QCOMPARE(ktx::evalPaddedSize(0x4), 0x4); QCOMPARE(ktx::evalPaddedSize(0x400), 0x400); QCOMPARE(ktx::evalPaddedSize(0x401), 0x404); QCOMPARE(ktx::evalAlignedCount((uint32_t)0x0), (uint32_t)0x0); QCOMPARE(ktx::evalAlignedCount((uint32_t)0x1), (uint32_t)0x1); QCOMPARE(ktx::evalAlignedCount((uint32_t)0x4), (uint32_t)0x1); QCOMPARE(ktx::evalAlignedCount((uint32_t)0x5), (uint32_t)0x2); } void KtxTests::testKtxSerialization() { const QString TEST_IMAGE = getRootPath() + "/scripts/developer/tests/cube_texture.png"; QImage image(TEST_IMAGE); std::atomic<bool> abortSignal; gpu::TexturePointer testTexture = image::TextureUsage::process2DTextureColorFromImage(std::move(image), TEST_IMAGE.toStdString(), true, abortSignal); auto ktxMemory = gpu::Texture::serialize(*testTexture); QVERIFY(ktxMemory.get()); // Serialize the image to a file QTemporaryFile TEST_IMAGE_KTX; { const auto& ktxStorage = ktxMemory->getStorage(); QVERIFY(ktx::KTX::validate(ktxStorage)); QVERIFY(ktxMemory->isValid()); auto& outFile = TEST_IMAGE_KTX; if (!outFile.open()) { QFAIL("Unable to open file"); } auto ktxSize = ktxStorage->size(); outFile.resize(ktxSize); auto dest = outFile.map(0, ktxSize); memcpy(dest, ktxStorage->data(), ktxSize); outFile.unmap(dest); outFile.close(); } { auto ktxStorage = std::make_shared<storage::FileStorage>(TEST_IMAGE_KTX.fileName()); QVERIFY(ktx::KTX::validate(ktxStorage)); auto ktxFile = ktx::KTX::create(ktxStorage); QVERIFY(ktxFile.get()); QVERIFY(ktxFile->isValid()); { const auto& memStorage = ktxMemory->getStorage(); const auto& fileStorage = ktxFile->getStorage(); QVERIFY(memStorage->size() == fileStorage->size()); QVERIFY(memStorage->data() != fileStorage->data()); QVERIFY(0 == memcmp(memStorage->data(), fileStorage->data(), memStorage->size())); QVERIFY(ktxFile->_images.size() == ktxMemory->_images.size()); auto imageCount = ktxFile->_images.size(); auto startMemory = ktxMemory->_storage->data(); auto startFile = ktxFile->_storage->data(); for (size_t i = 0; i < imageCount; ++i) { auto memImages = ktxMemory->_images[i]; auto fileImages = ktxFile->_images[i]; QVERIFY(memImages._padding == fileImages._padding); QVERIFY(memImages._numFaces == fileImages._numFaces); QVERIFY(memImages._imageSize == fileImages._imageSize); QVERIFY(memImages._faceSize == fileImages._faceSize); QVERIFY(memImages._faceBytes.size() == memImages._numFaces); QVERIFY(fileImages._faceBytes.size() == fileImages._numFaces); auto faceCount = fileImages._numFaces; for (uint32_t face = 0; face < faceCount; ++face) { auto memFace = memImages._faceBytes[face]; auto memOffset = memFace - startMemory; auto fileFace = fileImages._faceBytes[face]; auto fileOffset = fileFace - startFile; QVERIFY(memOffset % 4 == 0); QVERIFY(memOffset == fileOffset); } } } } testTexture->setKtxBacking(TEST_IMAGE_KTX.fileName().toStdString()); } #if 0 static const QString TEST_FOLDER { "H:/ktx_cacheold" }; //static const QString TEST_FOLDER { "C:/Users/bdavis/Git/KTX/testimages" }; //static const QString EXTENSIONS { "4bbdf8f786470e4ab3e672d44b8e8df2.ktx" }; static const QString EXTENSIONS { "*.ktx" }; int mainTemp(int, char**) { setupHifiApplication("KTX Tests"); auto fileInfoList = QDir { TEST_FOLDER }.entryInfoList(QStringList { EXTENSIONS }); for (auto fileInfo : fileInfoList) { qDebug() << fileInfo.filePath(); std::shared_ptr<storage::Storage> storage { new storage::FileStorage { fileInfo.filePath() } }; if (!ktx::KTX::validate(storage)) { qDebug() << "KTX invalid"; } auto ktxFile = ktx::KTX::create(storage); ktx::KTXDescriptor ktxDescriptor = ktxFile->toDescriptor(); qDebug() << "Contains " << ktxDescriptor.keyValues.size() << " key value pairs"; for (const auto& kv : ktxDescriptor.keyValues) { qDebug() << "\t" << kv._key.c_str(); } auto offsetToMinMipKV = ktxDescriptor.getValueOffsetForKey(ktx::HIFI_MIN_POPULATED_MIP_KEY); if (offsetToMinMipKV) { auto data = storage->data() + ktx::KTX_HEADER_SIZE + offsetToMinMipKV; auto minMipLevelAvailable = *data; qDebug() << "\tMin mip available " << minMipLevelAvailable; assert(minMipLevelAvailable < ktxDescriptor.header.numberOfMipmapLevels); } auto storageSize = storage->size(); for (const auto& faceImageDesc : ktxDescriptor.images) { //assert(0 == (faceImageDesc._faceSize % 4)); for (const auto& faceOffset : faceImageDesc._faceOffsets) { assert(0 == (faceOffset % 4)); auto faceEndOffset = faceOffset + faceImageDesc._faceSize; assert(faceEndOffset <= storageSize); } } for (const auto& faceImage : ktxFile->_images) { for (const ktx::Byte* faceBytes : faceImage._faceBytes) { assert(0 == (reinterpret_cast<size_t>(faceBytes) % 4)); } } } return 0; } #endif
8,081
2,935
#include <stdio.h> #include <component468/lib1.h> int component468_8 () { printf("Hello world!\n"); return 0; }
118
52
// // HMACAuth.cpp // libraries/networking/src // // Created by Simon Walton on 3/19/2018. // Copyright 2018 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "HMACAuth.h" #include <openssl/opensslv.h> #include <openssl/hmac.h> #include <QUuid> #include "NetworkLogging.h" #include <cassert> #if OPENSSL_VERSION_NUMBER >= 0x10100000 HMACAuth::HMACAuth(AuthMethod authMethod) : _hmacContext(HMAC_CTX_new()) , _authMethod(authMethod) { } HMACAuth::~HMACAuth() { HMAC_CTX_free(_hmacContext); } #else HMACAuth::HMACAuth(AuthMethod authMethod) : _hmacContext(new HMAC_CTX()) , _authMethod(authMethod) { HMAC_CTX_init(_hmacContext); } HMACAuth::~HMACAuth() { HMAC_CTX_cleanup(_hmacContext); delete _hmacContext; } #endif bool HMACAuth::setKey(const char* keyValue, int keyLen) { const EVP_MD* sslStruct = nullptr; switch (_authMethod) { case MD5: sslStruct = EVP_md5(); break; case SHA1: sslStruct = EVP_sha1(); break; case SHA224: sslStruct = EVP_sha224(); break; case SHA256: sslStruct = EVP_sha256(); break; case RIPEMD160: sslStruct = EVP_ripemd160(); break; default: return false; } QMutexLocker lock(&_lock); return (bool) HMAC_Init_ex(_hmacContext, keyValue, keyLen, sslStruct, nullptr); } bool HMACAuth::setKey(const QUuid& uidKey) { const QByteArray rfcBytes(uidKey.toRfc4122()); return setKey(rfcBytes.constData(), rfcBytes.length()); } bool HMACAuth::addData(const char* data, int dataLen) { QMutexLocker lock(&_lock); return (bool) HMAC_Update(_hmacContext, reinterpret_cast<const unsigned char*>(data), dataLen); } HMACAuth::HMACHash HMACAuth::result() { HMACHash hashValue(EVP_MAX_MD_SIZE); unsigned int hashLen; QMutexLocker lock(&_lock); auto hmacResult = HMAC_Final(_hmacContext, &hashValue[0], &hashLen); if (hmacResult) { hashValue.resize((size_t)hashLen); } else { // the HMAC_FINAL call failed - should not be possible to get into this state qCWarning(networking) << "Error occured calling HMAC_Final"; assert(hmacResult); } // Clear state for possible reuse. HMAC_Init_ex(_hmacContext, nullptr, 0, nullptr, nullptr); return hashValue; } bool HMACAuth::calculateHash(HMACHash& hashResult, const char* data, int dataLen) { QMutexLocker lock(&_lock); if (!addData(data, dataLen)) { qCWarning(networking) << "Error occured calling HMACAuth::addData()"; assert(false); return false; } hashResult = result(); return true; }
2,795
1,074
#include "stdafx.h" // GCStallError.cpp // ///////////////////////////////////////////////////// #include "GCStallError.h" BOOL GCStallError::Read( SocketInputStream& iStream ) { __ENTER_FUNCTION iStream.Read( (CHAR*)(&m_ID), sizeof(BYTE)); return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL GCStallError::Write( SocketOutputStream& oStream )const { __ENTER_FUNCTION oStream.Write( (CHAR*)(&m_ID), sizeof(BYTE)); return TRUE ; __LEAVE_FUNCTION return FALSE ; } UINT GCStallError::Execute( Player* pPlayer ) { __ENTER_FUNCTION return GCStallErrorHandler::Execute( this, pPlayer ) ; __LEAVE_FUNCTION return FALSE ; }
706
248
// // ae_pasteboard_types.cpp // #include "ae_pasteboard_types.h" #include <audio_editor_core/ae_pasteboard_constants.h> #include <audio_editor_core/ae_pasteboard_utils.h> using namespace yas; using namespace yas::ae; using namespace yas::ae::pasteboard_constants; std::string pasting_file_module::data() const { std::map<std::string, std::string> map{{file_module_key::kind, file_module_kind::value}, {file_module_key::file_frame, std::to_string(this->file_frame)}, {file_module_key::length, std::to_string(this->length)}}; return pasteboard_utils::to_data_string(map); } std::optional<pasting_file_module> pasting_file_module::make_value(std::string const &data) { auto const map = pasteboard_utils::to_data_map(data); if (map.contains(file_module_key::kind) && map.at(file_module_key::kind) == file_module_kind::value && map.contains(file_module_key::file_frame) && map.contains(file_module_key::length)) { auto const file_frame_string = map.at(file_module_key::file_frame); auto const length_string = map.at(file_module_key::length); return pasting_file_module{.file_frame = std::stoll(file_frame_string), .length = std::stoul(length_string)}; } return std::nullopt; } std::string yas::to_string(ae::pasting_file_module const &module) { return "{" + std::to_string(module.file_frame) + "," + std::to_string(module.length) + "}"; } std::ostream &operator<<(std::ostream &os, yas::ae::pasting_file_module const &value) { os << to_string(value); return os; }
1,624
548
// Fill out your copyright notice in the Description page of Project Settings. #include "StateRoot_EnemyE4.h" #include "StateMng_EnemyE4.h" UStateRoot_EnemyE4::UStateRoot_EnemyE4() { } UStateRoot_EnemyE4::~UStateRoot_EnemyE4() { } void UStateRoot_EnemyE4::Init(class UStateMng_GC* pMng) { Super::Init(pMng); m_pStateMng_Override = Cast<UStateMng_EnemyE4>(pMng); if (m_pStateMng_Override == nullptr) { ULOG(TEXT("m_pStateMng_Override is nullptr")); } } void UStateRoot_EnemyE4::Enter() { Super::Enter(); } void UStateRoot_EnemyE4::Exit() { Super::Exit(); } void UStateRoot_EnemyE4::Update(float fDeltaTime) { Super::Update(fDeltaTime); } void UStateRoot_EnemyE4::StateMessage(FString sMessage) { Super::StateMessage(sMessage); } AEnemyE4* UStateRoot_EnemyE4::GetRootChar() { if (m_pStateMng_Override == nullptr) { return nullptr; } return m_pStateMng_Override->GetRootCharacter_Override(); }
920
396
#pragma once #ifndef _WORLDLOADER_WORLDDATATAGS_HPP_ #define _WORLDLOADER_WORLDDATATAGS_HPP_ /* Define the tags which make up the entities in an xml world file. */ #define WORLD_TAG "World" #define ASSETS_TAG "Assets" #define ENTITIES_TAG "Entities" #define ENTITY_TAG "Entity" #define NAME_TAG "Name" #define COMPONENTS_TAG "Components" #define NODES_TAG "Nodes" /* <!-- An example of the structure of an xml world file --> <World> <Entity> <Name> "The entity's name" <Name/> <Components> <!-- A list of components stored in the entity. --> <Components/> <Nodes> <!-- A list of nodes stored in the entity. --> <Nodes/> <Entity/> <!-- More entities .... --> <World/> */ #endif
813
382
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; /* Laboratory 5 Ex 6 Write a program to generate two-dimentional array with random numbers and find maximum element in the whole array. Print array and maximum element. */ int main() { srand (time(NULL)); int array1[3][3]; int row = 3, column = 3; // Generating Random two-dimensional array for (int i = 0; i < column; i++) { for(int j = 0; j < row; j++) { array1[i][j] = rand() % 10; } } //Printing Array for (int i = 0; i < column; i++) { for(int j = 0; j < row; j++) { cout << array1[i][j] << " "; } cout << "\n"; } //Finding maximum element in the Array int maxElement; for (int i = 0; i < column; i++) { for (int j = 0; j < row; j++) { if (array1[i][j] > maxElement) { maxElement = array1[i][j]; } } } cout << "Maximum element is "<< maxElement << endl; return 0; }
966
419
/* Copyright (c) 2010, Matt Berger 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 University of Utah 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. */ #include "tri_integrator.h" TriIntegrator::TriIntegrator(Vector3RB _point, Vector3RB _v1, Vector3RB _v2, Vector3RB _v3, double _eps, double _lambda) { v1 = _v1; v2 = _v2; v3 = _v3; point = _point; eps = _eps; normal = (v2-v1).cross(v3-v1); area = 0.5*normal.length(); normal.normalize(); verify = false; // setup integration, determine if approximation is ok this->tri_integrals(); double approx_lambda = _lambda; double shortest_length = point.length(closest_point); double d1 = v1.length(point), d2 = v2.length(point), d3 = v3.length(point); double inv_shortest_length = 1.0 / shortest_length; use_approximation = (inv_shortest_length*d1) < approx_lambda && (inv_shortest_length*d2) < approx_lambda && (inv_shortest_length*d3) < approx_lambda; } TriIntegrator::TriIntegrator(Vector3RB _point, Vector3RB _v1, Vector3RB _v2, Vector3RB _v3, double _eps) { v1 = _v1; v2 = _v2; v3 = _v3; point = _point; eps = _eps; normal = (v2-v1).cross(v3-v1); area = 0.5*normal.length(); normal.normalize(); verify = false; use_approximation = false; this->tri_integrals(); } // assumption: ONLY LINE INTEGRALS! TriIntegrator::TriIntegrator(Vector3RB _pt, double _eps) { point = _pt; eps = _eps; } TriIntegrator::~TriIntegrator() { } double TriIntegrator::weight_eval(Vector3RB _p1, Vector3RB _p2) { return 1.0 / (_p1.sqdDist(_p2) + (eps*eps)); } double TriIntegrator::weight_eval_sqd(Vector3RB _p1, Vector3RB _p2) { double main_weight = _p1.sqdDist(_p2) + (eps*eps); return 1.0 / (main_weight*main_weight); } double TriIntegrator::weight_eval_cbd(Vector3RB _p1, Vector3RB _p2) { double main_weight = _p1.sqdDist(_p2) + (eps*eps); return 1.0 / (main_weight*main_weight*main_weight); } double TriIntegrator::constant_integration() { if(use_approximation) { Vector3RB bary = (v1+v2+v3)*(1.0/3.0); double w = this->weight_eval_sqd(bary, point); return area*w; } // else return this->numerical_constant_integration(); } double TriIntegrator::numerical_constant_integration() { double full_integral = 0, full_area = 0; double* inner_integration = new double[num_steps]; for(int t = 0; t < num_subtris; t++) { SubTri sub_tri = subdivided_tris[t]; Vector3RB weighty_pt, lesser_pt; if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) { weighty_pt = sub_tri.v2; lesser_pt = sub_tri.v3; } else { weighty_pt = sub_tri.v3; lesser_pt = sub_tri.v2; } Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal); edge_perp.normalize(); Vector3RB edge_dir = weighty_pt-sub_tri.o; edge_dir.normalize(); Vector3RB integral_dir = edge_dir.cross(normal); // inner analytical integration: solve at each step point for(unsigned i = 0; i < num_steps; i++) { double alpha = nonuniform_steps[i]; Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha; Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir); if(e1 == e2) cout << "positions equal?? " << alpha << endl; double analytical_integral = this->constant_line_integration(e1, e2); //double analytical_integral = this->weight_eval_sqd((e1+e2)*0.5, point); inner_integration[i] = analytical_integral; } // outer numerical integration: trapezoidal rule double sub_integral = 0; for(unsigned i = 1; i < num_steps; i++) { double alpha_0 = nonuniform_steps[i-1]; Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0; double alpha_1 = nonuniform_steps[i]; Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1; Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir); double step_size = e1_0.length(proj_pt); sub_integral += 0.5*(inner_integration[i-1]+inner_integration[i])*step_size; } full_integral += sub_integral; } delete [] inner_integration; // VERIFICATION: monte-carlo integration if(verify) { int num_samples = 900000; double mc_integral = 0; for(int i = 0; i < num_samples; i++) { double u = (double)rand() / (double)RAND_MAX; double v = (double)rand() / (double)RAND_MAX; double tmp = sqrt(u); double b1 = 1.0-tmp; double b2 = v*tmp; double b3 = (1.0-b1-b2); Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3; mc_integral += this->weight_eval_sqd(rand_pt, point); } mc_integral *= (area / (double)num_samples); cout << "constant quadrature integral: " << full_integral << " ; mc integral: " << mc_integral << endl; } return full_integral; } double TriIntegrator::linear_integration(TriFunction _f) { if(use_approximation) { Vector3RB bary = (v1+v2+v3)*(1.0/3.0); double w = this->weight_eval_sqd(bary, point); double bary_f = (_f.f1+_f.f2+_f.f3)/3.0; return bary_f*area*w; } // else return this->numerical_linear_integration(_f); } double TriIntegrator::numerical_linear_integration(TriFunction _f) { double full_integral = 0, full_area = 0; double* inner_integration = new double[num_steps]; for(int t = 0; t < num_subtris; t++) { SubTri sub_tri = subdivided_tris[t]; Vector3RB weighty_pt, lesser_pt; if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) { weighty_pt = sub_tri.v2; lesser_pt = sub_tri.v3; } else { weighty_pt = sub_tri.v3; lesser_pt = sub_tri.v2; } Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal); edge_perp.normalize(); Vector3RB edge_dir = weighty_pt-sub_tri.o; edge_dir.normalize(); Vector3RB integral_dir = edge_dir.cross(normal); double b0_1, b1_1, b2_1; double b0_2, b1_2, b2_2; // inner analytical integration: solve at each step point for(unsigned i = 0; i < num_steps; i++) { double alpha = nonuniform_steps[i]; Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha; this->barycentric_coordinate(e1, b0_1, b1_1, b2_1); Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir); this->barycentric_coordinate(e2, b0_2, b1_2, b2_2); double f1 = _f.f1*b0_1 + _f.f2*b1_1 + _f.f3*b2_1; double f2 = _f.f1*b0_2 + _f.f2*b1_2 + _f.f3*b2_2; double analytical_integral = this->linear_line_integration(e1, e2, f1, f2); inner_integration[i] = analytical_integral; } // outer numerical integration: trapezoidal rule double sub_integral = 0; for(unsigned i = 1; i < num_steps; i++) { double alpha_0 = nonuniform_steps[i-1]; Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0; double alpha_1 = nonuniform_steps[i]; Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1; Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir); double step_size = e1_0.length(proj_pt); sub_integral += 0.5*(inner_integration[i-1]+inner_integration[i])*step_size; } full_integral += sub_integral; } delete [] inner_integration; // VERIFICATION: monte-carlo integration if(verify) { int num_samples = 900000; double mc_integral = 0; for(int i = 0; i < num_samples; i++) { double u = (double)rand() / (double)RAND_MAX; double v = (double)rand() / (double)RAND_MAX; double tmp = sqrt(u); double b1 = 1.0-tmp; double b2 = v*tmp; double b3 = (1.0-b1-b2); Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3; double rand_f = _f.f1*b1 + _f.f2*b2 + _f.f3*b3; mc_integral += rand_f*this->weight_eval_sqd(rand_pt, point); } mc_integral *= (area / (double)num_samples); cout << "linear quadrature integral["<<num_subtris<<"] : " << full_integral << " ; mc integral: " << mc_integral << endl; } return full_integral; } double TriIntegrator::product_integration(TriFunction _f, TriFunction _g) { if(use_approximation) { Vector3RB bary = (v1+v2+v3)*(1.0/3.0); double w = this->weight_eval_sqd(bary, point); double bary_f = (_f.f1+_f.f2+_f.f3)/3.0; double bary_g = (_g.f1+_g.f2+_g.f3)/3.0; return bary_f*bary_g*area*w; } // else return this->numerical_product_integration(_f, _g); } double TriIntegrator::numerical_product_integration(TriFunction _f, TriFunction _g) { double full_integral = 0, full_area = 0; for(int t = 0; t < num_subtris; t++) { SubTri sub_tri = subdivided_tris[t]; Vector3RB weighty_pt, lesser_pt; if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) { weighty_pt = sub_tri.v2; lesser_pt = sub_tri.v3; } else { weighty_pt = sub_tri.v3; lesser_pt = sub_tri.v2; } Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal); edge_perp.normalize(); Vector3RB edge_dir = weighty_pt-sub_tri.o; edge_dir.normalize(); Vector3RB integral_dir = edge_dir.cross(normal); double b0_1, b1_1, b2_1; double b0_2, b1_2, b2_2; // inner analytical integration: solve at each step point vector<double> inner_integration; for(unsigned i = 0; i < num_steps; i++) { double alpha = nonuniform_steps[i]; Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha; this->barycentric_coordinate(e1, b0_1, b1_1, b2_1); Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir); this->barycentric_coordinate(e2, b0_2, b1_2, b2_2); double f1 = _f.f1*b0_1 + _f.f2*b1_1 + _f.f3*b2_1; double g1 = _g.f1*b0_1 + _g.f2*b1_1 + _g.f3*b2_1; double f2 = _f.f1*b0_2 + _f.f2*b1_2 + _f.f3*b2_2; double g2 = _g.f1*b0_2 + _g.f2*b1_2 + _g.f3*b2_2; double analytical_integral = this->quadratic_line_integration(e1, e2, f1, f2, g1, g2); inner_integration.push_back(analytical_integral); } // outer numerical integration: trapezoidal rule double sub_integral = 0; for(unsigned i = 1; i < num_steps; i++) { double alpha_0 = nonuniform_steps[i-1]; Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0; double alpha_1 = nonuniform_steps[i]; Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1; Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir); double step_size = e1_0.length(proj_pt); sub_integral += 0.5*(inner_integration[i-1]+inner_integration[i])*step_size; } full_integral += sub_integral; } // VERIFICATION: monte-carlo integration if(verify) { int num_samples = 900000; double mc_integral = 0; for(int i = 0; i < num_samples; i++) { double u = (double)rand() / (double)RAND_MAX; double v = (double)rand() / (double)RAND_MAX; double tmp = sqrt(u); double b1 = 1.0-tmp; double b2 = v*tmp; double b3 = (1.0-b1-b2); Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3; double rand_f = _f.f1*b1 + _f.f2*b2 + _f.f3*b3; double rand_g = _g.f1*b1 + _g.f2*b2 + _g.f3*b3; mc_integral += rand_f*rand_g*this->weight_eval_sqd(rand_pt, point); } mc_integral *= (area / (double)num_samples); cout << "quadratic quadrature integral: " << full_integral << " ; mc integral: " << mc_integral << endl; } return full_integral; } Vector3RB TriIntegrator::gradient_integration() { if(use_approximation) { Vector3RB bary = (v1+v2+v3)*(1.0/3.0); double w = this->weight_eval_cbd(bary, point); return (bary-point)*4.0*area*w; } // else return this->numerical_gradient_integration(); } Vector3RB TriIntegrator::numerical_gradient_integration() { Vector3RB full_integral(0,0,0); Vector3RB* inner_integration = new Vector3RB[num_steps]; for(int t = 0; t < num_subtris; t++) { SubTri sub_tri = subdivided_tris[t]; Vector3RB weighty_pt, lesser_pt; if(this->weight_eval(sub_tri.v2, point) > this->weight_eval(sub_tri.v3, point)) { weighty_pt = sub_tri.v2; lesser_pt = sub_tri.v3; } else { weighty_pt = sub_tri.v3; lesser_pt = sub_tri.v2; } Vector3RB edge_perp = (lesser_pt-weighty_pt).cross(normal); edge_perp.normalize(); Vector3RB edge_dir = weighty_pt-sub_tri.o; edge_dir.normalize(); Vector3RB integral_dir = edge_dir.cross(normal); // inner analytical integration: solve at each step point for(unsigned i = 0; i < num_steps; i++) { double alpha = nonuniform_steps[i]; Vector3RB e1 = sub_tri.o*(1.0-alpha) + lesser_pt*alpha; Vector3RB e2 = ray_plane_intersection(weighty_pt, edge_perp, e1, edge_dir); inner_integration[i] = this->gradient_line_integration(e1, e2); } // outer numerical integration: trapezoidal rule Vector3RB sub_integral(0,0,0); for(unsigned i = 1; i < num_steps; i++) { double alpha_0 = nonuniform_steps[i-1]; Vector3RB e1_0 = sub_tri.o*(1.0-alpha_0) + lesser_pt*alpha_0; double alpha_1 = nonuniform_steps[i]; Vector3RB e1_1 = sub_tri.o*(1.0-alpha_1) + lesser_pt*alpha_1; Vector3RB proj_pt = orthogonal_projection(e1_0, e1_1, integral_dir); double step_size = e1_0.length(proj_pt); sub_integral = sub_integral + (inner_integration[i-1]+inner_integration[i])*0.5*step_size; } full_integral = full_integral + sub_integral; } delete [] inner_integration; // VERIFICATION: monte-carlo integration if(verify) { int num_samples = 900000; Vector3RB mc_integral(0,0,0); for(int i = 0; i < num_samples; i++) { double u = (double)rand() / (double)RAND_MAX; double v = (double)rand() / (double)RAND_MAX; double tmp = sqrt(u); double b1 = 1.0-tmp; double b2 = v*tmp; double b3 = (1.0-b1-b2); Vector3RB rand_pt = v1*b1 + v2*b2 + v3*b3; mc_integral = mc_integral + (rand_pt-point)*4.0*this->weight_eval_cbd(rand_pt,point); } mc_integral = mc_integral*(area / (double)num_samples); cout << "gradient quadrature integral: " << full_integral << " ; mc integral: " << mc_integral << endl; } return full_integral; } double TriIntegrator::inv_quadratic_integral(double _a, double _b, double _c) { double c1 = sqrt(4.0*_a*_c-_b*_b); return (2.0/c1)*(atan( (2.0*_a+_b)/(c1) ) - atan( (_b)/(c1) )); //return 2.0/c1; } double TriIntegrator::inv_sqd_quadratic_integral(double _a, double _b, double _c) { double c1_sqd = 4.0*_a*_c-_b*_b; double factor1 = ( ((2.0*_a+_b) / (_a+_b+_c)) - (_b/_c) ) / c1_sqd; double factor2 = (2.0*_a) / c1_sqd; return factor1 + factor2*this->inv_quadratic_integral(_a,_b,_c); } double TriIntegrator::inv_cubic_integral(double _a, double _b, double _c) { double descr = 4.0*_a*_c-_b*_b; double sqd_sum = (_a+_b+_c)*(_a+_b+_c); double factor1 = ( ((2.0*_a+_b)/sqd_sum) - (_b/(_c*_c)) ) / (2.0*descr); double factor2 = (3.0*_a) / descr; return factor1 + factor2*this->inv_sqd_quadratic_integral(_a,_b,_c); } double TriIntegrator::inv_linear_sqd_quadratic_integral(double _a, double _b, double _c) { double c1_sqd = 4.0*_a*_c-_b*_b; double factor1 = -( ((_b+2.0*_c) / (_a+_b+_c)) - 2.0 ) / c1_sqd; double factor2 = -_b / c1_sqd; return factor1 + factor2*this->inv_quadratic_integral(_a,_b,_c); } double TriIntegrator::inv_linear_cubic_integral(double _a, double _b, double _c) { double descr = 4.0*_a*_c-_b*_b; double sqd_sum = (_a+_b+_c)*(_a+_b+_c); double factor1 = -( ((_b+2.0*_c)/sqd_sum) - (2.0/_c) ) / (2.0*descr); double factor2 = -(3.0*_b)/(2.0*descr); return factor1 + factor2*this->inv_sqd_quadratic_integral(_a,_b,_c); } double TriIntegrator::constant_line_integration(Vector3RB _p1, Vector3RB _p2) { Vector3RB v1 = point-_p1, v2 = _p1-_p2; double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps; double descr = 4.0*a*c-b*b; if(descr == 0) { cout << "line " << _p1 << " " << _p2 << " : " << point << endl; } double line_length = _p1.length(_p2); double full_integral = line_length*this->inv_sqd_quadratic_integral(a,b,c); return full_integral; } double TriIntegrator::linear_line_integration(Vector3RB _p1, Vector3RB _p2, double _f1, double _f2) { Vector3RB v1 = point-_p1, v2 = _p1-_p2; double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps; double line_length = _p1.length(_p2); double full_integral = line_length*(_f1*this->inv_sqd_quadratic_integral(a,b,c) + (_f2-_f1)*this->inv_linear_sqd_quadratic_integral(a,b,c)); return full_integral; } double TriIntegrator::quadratic_line_integration(Vector3RB _p1, Vector3RB _p2, double _f1, double _f2, double _g1, double _g2) { Vector3RB v1 = point-_p1, v2 = _p1-_p2; double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps; double line_length = _p1.length(_p2); double alpha_1 = (_f2-_f1)*(_g2-_g1); double alpha_2 = (_f2-_f1)*_g1 + (_g2-_g1)*_f1; double alpha_3 = _f1*_g1; double simple_factor = (alpha_1/a)*this->inv_quadratic_integral(a,b,c); double const_factor = (alpha_3 - (alpha_1*c)/a)*this->inv_sqd_quadratic_integral(a,b,c); double linear_factor = (alpha_2 - (alpha_1*b)/a)*this->inv_linear_sqd_quadratic_integral(a,b,c); double full_integral = line_length*(simple_factor+const_factor+linear_factor); return full_integral; } Vector3RB TriIntegrator::gradient_line_integration(Vector3RB _p1, Vector3RB _p2) { Vector3RB v1 = point-_p1, v2 = _p1-_p2; double a = v2.dotProduct(v2), b = 2.0*v1.dotProduct(v2), c = v1.dotProduct(v1) + eps*eps; double line_length = _p1.length(_p2); Vector3RB factor1 = point; Vector3RB factor2_1 = _p1, factor2_2 = _p2-_p1; double integral1 = line_length*this->inv_cubic_integral(a,b,c); double integral2 = line_length*this->inv_linear_cubic_integral(a,b,c); return ((factor2_1*integral1 + factor2_2*integral2) - factor1*integral1)*4.0; } void TriIntegrator::tri_integrals() { if(point == v1) { num_subtris = 1; subdivided_tris[0] = SubTri(v1, v2, v3); closest_point = v1; return; } else if(point == v2) { num_subtris = 1; subdivided_tris[0] = SubTri(v2, v3, v1); closest_point = v2; return; } else if(point == v3) { num_subtris = 1; subdivided_tris[0] = SubTri(v3, v1, v2); closest_point = v3; return; } // --- first step: project point onto plane, and subdivide triangle based on projected point --- // Vector3RB orthog_pt = point + normal*(v1-point).dotProduct(normal); Vector3RB area_normal1 = (v2-orthog_pt).cross(v3-orthog_pt); Vector3RB area_normal2 = (v3-orthog_pt).cross(v1-orthog_pt); Vector3RB area_normal3 = (v1-orthog_pt).cross(v2-orthog_pt); bool is_area1_positive = area_normal1.dotProduct(normal) > 0; bool is_area2_positive = area_normal2.dotProduct(normal) > 0; bool is_area3_positive = area_normal3.dotProduct(normal) > 0; // is our projection in the triangle? if(is_area1_positive && is_area2_positive && is_area3_positive) { num_subtris = 3; subdivided_tris[0] = SubTri(orthog_pt, v1, v2); subdivided_tris[1] = SubTri(orthog_pt, v2, v3); subdivided_tris[2] = SubTri(orthog_pt, v3, v1); closest_point = orthog_pt; return; } // otherwise, find the point on the border of the triangle closest to orthog_pt Vector3RB tri_verts[3]; tri_verts[0] = v1; tri_verts[1] = v2; tri_verts[2] = v3; // first try the edges ... bool is_contained = false; for(int i = 0; i < 3; i++) { Vector3RB q1 = tri_verts[i], q2 = tri_verts[(i+1)%3], q3 = tri_verts[(i+2)%3]; Vector3RB e1 = q2-q1, e2 = q1-q2; Vector3RB edge_perp = e2.cross(normal); is_contained = signed_dist(orthog_pt, q1, edge_perp) > 0 && signed_dist(orthog_pt, q1, e1) > 0 && signed_dist(orthog_pt, q2, e2) > 0; if(is_contained) { Vector3RB edge_point = this->edge_projection(q1, q2, normal, orthog_pt); num_subtris = 2; subdivided_tris[0] = SubTri(edge_point, q2, q3); subdivided_tris[1] = SubTri(edge_point, q3, q1); closest_point = edge_point; return; } } // ... and last, find closest vertex int min_ind = 2; double sqd_dist1 = v1.sqdDist(orthog_pt), sqd_dist2 = v2.sqdDist(orthog_pt), sqd_dist3 = v3.sqdDist(orthog_pt); if(sqd_dist1 < sqd_dist2 && sqd_dist1 < sqd_dist3) min_ind = 0; else if(sqd_dist2 < sqd_dist3) min_ind = 1; Vector3RB q1 = tri_verts[min_ind], q2 = tri_verts[(min_ind+1)%3], q3 = tri_verts[(min_ind+2)%3]; num_subtris = 1; subdivided_tris[0] = SubTri(q1,q2,q3); closest_point = q1; } Vector3RB TriIntegrator::ray_plane_intersection(Vector3RB _p, Vector3RB _n, Vector3RB _m, Vector3RB _d) { double t = (_p-_m).dotProduct(_n) / _d.dotProduct(_n); return _m + _d*t; } Vector3RB TriIntegrator::orthogonal_projection(Vector3RB _p, Vector3RB _x, Vector3RB _normal) { return _p + _normal*((_p-_x).dotProduct(_normal)/_normal.dotProduct(_normal)); } double TriIntegrator::signed_dist(Vector3RB _p, Vector3RB _x, Vector3RB _normal) { return ((_p-_x).dotProduct(_normal)) / _normal.dotProduct(_normal); } Vector3RB TriIntegrator::edge_projection(Vector3RB _v1, Vector3RB _v2, Vector3RB _normal, Vector3RB _point) { // get normal of edge -> just cross of edge with normal Vector3RB edge_normal = (_v2-_v1).cross(_normal); edge_normal.normalize(); // projection of _point onto plane spanned by edge normal return _point + edge_normal*(_v1-_point).dotProduct(edge_normal); } void TriIntegrator::barycentric_coordinate(Vector3RB _point, double& b1, double& b2, double& b3) { double area1 = 0.5*((_point-v2).cross(_point-v3)).length(); double area2 = 0.5*((_point-v3).cross(_point-v1)).length(); double area3 = 0.5*((_point-v1).cross(_point-v2)).length(); double inv_area = 1.0 / area; b1 = area1*inv_area; b2 = area2*inv_area; b3 = area3*inv_area; }
22,383
10,240
// Copyright (c) 2018, the Newspeak project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" // NOLINT #if defined(OS_ANDROID) || defined(OS_LINUX) #include "vm/message_loop.h" #include <errno.h> #include <fcntl.h> #include <signal.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <unistd.h> #include "vm/lockers.h" #include "vm/os.h" namespace psoup { static bool SetBlockingHelper(intptr_t fd, bool blocking) { intptr_t status; status = fcntl(fd, F_GETFL); if (status < 0) { perror("fcntl(F_GETFL) failed"); return false; } status = blocking ? (status & ~O_NONBLOCK) : (status | O_NONBLOCK); if (fcntl(fd, F_SETFL, status) < 0) { perror("fcntl(F_SETFL, O_NONBLOCK) failed"); return false; } return true; } EPollMessageLoop::EPollMessageLoop(Isolate* isolate) : MessageLoop(isolate), mutex_(), head_(NULL), tail_(NULL), wakeup_(0) { int result = pipe(interrupt_fds_); if (result != 0) { FATAL("Failed to create pipe"); } if (!SetBlockingHelper(interrupt_fds_[0], false)) { FATAL("Failed to set pipe fd non-blocking\n"); } timer_fd_ = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC); if (timer_fd_ == -1) { FATAL("Failed to creater timer_fd"); } epoll_fd_ = epoll_create(64); if (epoll_fd_ == -1) { FATAL("Failed to create epoll"); } struct epoll_event event; event.events = EPOLLIN; event.data.fd = interrupt_fds_[0]; int status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupt_fds_[0], &event); if (status == -1) { FATAL("Failed to add pipe to epoll"); } event.events = EPOLLIN; event.data.fd = timer_fd_; status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &event); if (status == -1) { FATAL("Failed to add timer_fd to epoll"); } } EPollMessageLoop::~EPollMessageLoop() { close(epoll_fd_); close(timer_fd_); close(interrupt_fds_[0]); close(interrupt_fds_[1]); } intptr_t EPollMessageLoop::AwaitSignal(intptr_t fd, intptr_t signals) { struct epoll_event event; event.events = EPOLLRDHUP | EPOLLET; if (signals & (1 << kReadEvent)) { event.events |= EPOLLIN; } if (signals & (1 << kWriteEvent)) { event.events |= EPOLLOUT; } event.data.fd = fd; int status = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event); if (status == -1) { FATAL("Failed to add to epoll"); } return fd; } void EPollMessageLoop::CancelSignalWait(intptr_t wait_id) { UNIMPLEMENTED(); } void EPollMessageLoop::MessageEpilogue(int64_t new_wakeup) { wakeup_ = new_wakeup; struct itimerspec it; memset(&it, 0, sizeof(it)); if (new_wakeup != 0) { it.it_value.tv_sec = new_wakeup / kNanosecondsPerSecond; it.it_value.tv_nsec = new_wakeup % kNanosecondsPerSecond; } timerfd_settime(timer_fd_, TFD_TIMER_ABSTIME, &it, NULL); if ((open_ports_ == 0) && (wakeup_ == 0)) { Exit(0); } } void EPollMessageLoop::Exit(intptr_t exit_code) { exit_code_ = exit_code; isolate_ = NULL; } void EPollMessageLoop::PostMessage(IsolateMessage* message) { MutexLocker locker(&mutex_); if (head_ == NULL) { head_ = tail_ = message; Notify(); } else { tail_->next_ = message; tail_ = message; } } void EPollMessageLoop::Notify() { uword message = 0; ssize_t written = write(interrupt_fds_[1], &message, sizeof(message)); if (written != sizeof(message)) { FATAL("Failed to atomically write notify message"); } } IsolateMessage* EPollMessageLoop::TakeMessages() { MutexLocker locker(&mutex_); IsolateMessage* message = head_; head_ = tail_ = NULL; return message; } intptr_t EPollMessageLoop::Run() { while (isolate_ != NULL) { static const intptr_t kMaxEvents = 16; struct epoll_event events[kMaxEvents]; int result = epoll_wait(epoll_fd_, events, kMaxEvents, -1); if (result <= 0) { if ((errno != EWOULDBLOCK) && (errno != EINTR)) { FATAL("epoll_wait failed"); } } else { for (int i = 0; i < result; i++) { if (events[i].data.fd == interrupt_fds_[0]) { // Interrupt fd. uword message = 0; ssize_t red = read(interrupt_fds_[0], &message, sizeof(message)); if (red != sizeof(message)) { FATAL("Failed to atomically write notify message"); } } else if (events[i].data.fd == timer_fd_) { int64_t value; ssize_t ignore = read(timer_fd_, &value, sizeof(value)); (void)ignore; DispatchWakeup(); } else { intptr_t fd = events[i].data.fd; intptr_t pending = 0; if (events[i].events & EPOLLERR) { pending |= 1 << kErrorEvent; } if (events[i].events & EPOLLIN) { pending |= 1 << kReadEvent; } if (events[i].events & EPOLLOUT) { pending |= 1 << kWriteEvent; } if (events[i].events & EPOLLHUP) { pending |= 1 << kCloseEvent; } if (events[i].events & EPOLLRDHUP) { pending |= 1 << kCloseEvent; } DispatchSignal(fd, 0, pending, 0); } } } IsolateMessage* message = TakeMessages(); while (message != NULL) { IsolateMessage* next = message->next_; DispatchMessage(message); message = next; } } if (open_ports_ > 0) { PortMap::CloseAllPorts(this); } while (head_ != NULL) { IsolateMessage* message = head_; head_ = message->next_; delete message; } return exit_code_; } void EPollMessageLoop::Interrupt() { Exit(SIGINT); Notify(); } } // namespace psoup #endif // defined(OS_ANDROID) || defined(OS_LINUX)
5,813
2,251
#include "Frame.h" #include "mbed.h" Frame::Frame(char * data) { this->data = data; memset(id, 0x00, 32); } Frame::~Frame(void) { } void Frame::decode(void) { len = data[2]; idd = data[3]; tmp = (data[4] << 8) + data[5];; pwm = data[6]; tun = data[7]; for(int i = 8; i < (strlen(data) - 3); i++) { id[i-8] = data[i]; } crc = data[strlen(data)-4]; } void Frame::checkCRC(void) { } void Frame::calculateCRC(void) { } void Frame::generate(char * data) { memset(data, 0x00, 256); data[0] = FRAME_SOF_1; data[1] = FRAME_SOF_2; data[2] = len; data[3] = idd; data[4] = 1; data[5] = 203; // data[4] = tmp >> 8; // data[5] = tmp & 0xFF; data[6] = pwm; data[7] = tun; // for(int i = 0; i < (strlen(id)); i++) { // data[7 + i] = id[i]; // } data[8] = 108; data[9] = crc; data[10] = FRAME_EOF_1; data[11] = FRAME_EOF_2; // data[6 + strlen(id) + 1] = 109; // data[6 + strlen(id) + 2] = crc; // data[6 + strlen(id) + 3] = FRAME_EOF_1; // data[6 + strlen(id) + 4] = FRAME_EOF_2; for(int i = 0; i < (strlen(data)); i++) { printf("Data[%i]: %i\n\r", i, data[i]); } }
1,232
628
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkLandmarkBasedTransformInitializer.h" #include "itkImage.h" #include "itkObject.h" #include "itkTestingMacros.h" #include <iostream> template <unsigned int Dimension> typename itk::Image<unsigned char, Dimension>::Pointer CreateTestImage() { using FixedImageType = itk::Image<unsigned char, Dimension>; typename FixedImageType::Pointer image = FixedImageType::New(); typename FixedImageType::RegionType fRegion; typename FixedImageType::SizeType fSize; typename FixedImageType::IndexType fIndex; fSize.Fill(30); // size 30 x 30 x 30 fIndex.Fill(0); fRegion.SetSize(fSize); fRegion.SetIndex(fIndex); image->SetLargestPossibleRegion(fRegion); image->SetBufferedRegion(fRegion); image->SetRequestedRegion(fRegion); image->Allocate(); return image; } // Moving Landmarks = Fixed Landmarks rotated by 'angle' degrees and then // translated by the 'translation'. Offset can be used to move the fixed // landmarks around. template <typename TTransformInitializer> void Init3DPoints(typename TTransformInitializer::LandmarkPointContainer & fixedLandmarks, typename TTransformInitializer::LandmarkPointContainer & movingLandmarks) { const double nPI = 4.0 * std::atan(1.0); typename TTransformInitializer::LandmarkPointType point; typename TTransformInitializer::LandmarkPointType tmp; double angle = 10 * nPI / 180.0; typename TTransformInitializer::LandmarkPointType translation; translation[0] = 6; translation[1] = 10; translation[2] = 7; typename TTransformInitializer::LandmarkPointType offset; offset[0] = 10; offset[1] = 1; offset[2] = 5; point[0] = 2 + offset[0]; point[1] = 2 + offset[1]; point[2] = 0 + offset[2]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; point[2] = point[2] + translation[2]; movingLandmarks.push_back(point); point[0] = 2 + offset[0]; point[1] = -2 + offset[1]; point[2] = 0 + offset[2]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; point[2] = point[2] + translation[2]; movingLandmarks.push_back(point); point[0] = -2 + offset[0]; point[1] = 2 + offset[1]; point[2] = 0 + offset[2]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; point[2] = point[2] + translation[2]; movingLandmarks.push_back(point); point[0] = -2 + offset[0]; point[1] = -2 + offset[1]; point[2] = 0 + offset[2]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; point[2] = point[2] + translation[2]; movingLandmarks.push_back(point); } template <typename TransformInitializerType> bool ExecuteAndExamine(typename TransformInitializerType::Pointer initializer, typename TransformInitializerType::LandmarkPointContainer fixedLandmarks, typename TransformInitializerType::LandmarkPointContainer movingLandmarks, unsigned failLimit = 0) { typename TransformInitializerType::TransformType::Pointer transform = TransformInitializerType::TransformType::New(); initializer->SetTransform(transform); initializer->InitializeTransform(); // Transform the landmarks now. For the given set of landmarks, since we computed the // moving landmarks explicitly from the rotation and translation specified, we should // get a transform that does not give any mismatch. In other words, if the fixed // landmarks are transformed by the transform computed by the // LandmarkBasedTransformInitializer, they should coincide exactly with the moving // landmarks. Note that we specified 4 landmarks, although three non-collinear // landmarks is sufficient to guarantee a solution. typename TransformInitializerType::PointsContainerConstIterator fitr = fixedLandmarks.begin(); typename TransformInitializerType::PointsContainerConstIterator mitr = movingLandmarks.begin(); using OutputVectorType = typename TransformInitializerType::OutputVectorType; OutputVectorType error; typename OutputVectorType::RealValueType tolerance = 0.1; unsigned int failed = 0; while (mitr != movingLandmarks.end()) { typename TransformInitializerType::LandmarkPointType transformedPoint = transform->TransformPoint(*fitr); std::cout << " Fixed Landmark: " << *fitr << " Moving landmark " << *mitr << " Transformed fixed Landmark : " << transformedPoint; error = *mitr - transformedPoint; std::cout << " error = " << error.GetNorm() << std::endl; if (error.GetNorm() > tolerance) { failed++; } ++mitr; ++fitr; } if (failed > failLimit) { std::cout << " Fixed landmarks transformed by the transform did not match closely " << "enough with the moving landmarks. The transform computed was: "; transform->Print(std::cout); std::cout << "[FAILED]" << std::endl; return false; } else { std::cout << " Landmark alignment using " << transform->GetNameOfClass() << " [PASSED]" << std::endl; } return true; } // Test LandmarkBasedTransformInitializer for given transform type // Returns false if test failed, true if it succeeded template <typename TransformType> bool test1() { typename TransformType::Pointer transform = TransformType::New(); std::cout << "Testing Landmark alignment with " << transform->GetNameOfClass() << std::endl; using PixelType = unsigned char; constexpr unsigned int Dimension = 3; using FixedImageType = itk::Image<PixelType, Dimension>; using MovingImageType = itk::Image<PixelType, Dimension>; using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType, FixedImageType, MovingImageType>; typename TransformInitializerType::Pointer initializer = TransformInitializerType::New(); typename TransformInitializerType::LandmarkPointContainer fixedLandmarks; typename TransformInitializerType::LandmarkPointContainer movingLandmarks; Init3DPoints<TransformInitializerType>(fixedLandmarks, movingLandmarks); // No landmarks are set, it should throw ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); initializer->SetMovingLandmarks(movingLandmarks); ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); // Fixed landmarks missing initializer->SetFixedLandmarks(fixedLandmarks); return ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks); } // The test specifies a bunch of fixed and moving landmarks and tests if the // fixed landmarks after transform by the computed transform coincides // with the moving landmarks. int itkLandmarkBasedTransformInitializerTest(int, char *[]) { bool success = true; success &= test1<itk::VersorRigid3DTransform<double>>(); // Rigid3DTransform isn't supported by the landmark based initializer // success &= test1<itk::Rigid3DTransform< double > >(); using PixelType = unsigned char; { // Test landmark alignment using Rigid 2D transform in 2 dimensions std::cout << "Testing Landmark alignment with Rigid2DTransform" << std::endl; constexpr unsigned int Dimension = 2; using FixedImageType = itk::Image<PixelType, Dimension>; using MovingImageType = itk::Image<PixelType, Dimension>; FixedImageType::Pointer fixedImage = CreateTestImage<Dimension>(); MovingImageType::Pointer movingImage = CreateTestImage<Dimension>(); // Set the transform type using TransformType = itk::Rigid2DTransform<double>; using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType, FixedImageType, MovingImageType>; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object); initializer->DebugOn(); // Set fixed and moving landmarks TransformInitializerType::LandmarkPointContainer fixedLandmarks; TransformInitializerType::LandmarkPointContainer movingLandmarks; TransformInitializerType::LandmarkPointType point; TransformInitializerType::LandmarkPointType tmp; // Moving Landmarks = Fixed Landmarks rotated by 'angle' degrees and then // translated by the 'translation'. Offset can be used to move the fixed // landmarks around. const double nPI = 4.0 * std::atan(1.0); double angle = 10 * nPI / 180.0; TransformInitializerType::LandmarkPointType translation; translation[0] = 6; translation[1] = 10; TransformInitializerType::LandmarkPointType offset; offset[0] = 10; offset[1] = 1; point[0] = 2 + offset[0]; point[1] = 2 + offset[1]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; movingLandmarks.push_back(point); point[0] = 2 + offset[0]; point[1] = -2 + offset[1]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; movingLandmarks.push_back(point); point[0] = -2 + offset[0]; point[1] = 2 + offset[1]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; movingLandmarks.push_back(point); point[0] = -2 + offset[0]; point[1] = -2 + offset[1]; fixedLandmarks.push_back(point); tmp = point; point[0] = std::cos(angle) * point[0] - std::sin(angle) * point[1] + translation[0]; point[1] = std::sin(angle) * tmp[0] + std::cos(angle) * point[1] + translation[1]; movingLandmarks.push_back(point); // No landmarks are set, it should throw ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); initializer->SetFixedLandmarks(fixedLandmarks); ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); // Moving landmarks missing initializer->SetMovingLandmarks(movingLandmarks); success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks); } { constexpr unsigned int Dimension = 3; using ImageType = itk::Image<PixelType, Dimension>; ImageType::Pointer fixedImage = CreateTestImage<Dimension>(); ImageType::Pointer movingImage = CreateTestImage<Dimension>(); using TransformType = itk::AffineTransform<double, Dimension>; TransformType::Pointer transform = TransformType::New(); using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType, ImageType, ImageType>; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object); initializer->SetTransform(transform); // Test that an exception is thrown if there aren't enough points ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); const unsigned int numLandmarks(8); double fixedLandMarkInit[numLandmarks][3] = { { -1.33671, -279.739, 176.001 }, { 28.0989, -346.692, 183.367 }, { -1.36713, -257.43, 155.36 }, { -33.0851, -347.026, 180.865 }, { -0.16083, -268.529, 148.96 }, { -0.103873, -251.31, 122.973 }, { 200, 200, 200 }, // dummy { -300, 100, 1000 } // dummy }; double movingLandmarkInit[numLandmarks][3] = { { -1.65605 + 0.011, -30.0661, 20.1656 }, { 28.1409, -93.1172 + 0.015, -5.34366 }, { -1.55885, -0.499696 - 0.04, 12.7584 }, { -33.0151 + 0.001, -92.0973, -8.66965 }, { -0.189769, -7.3485, 1.74263 + 0.008 }, { 0.1021, 20.2155, -12.8526 - 0.006 }, { 200, 200, 200 }, // dummy { -300, 100, 1000 } // dummy }; double weights[numLandmarks] = { 10, 1, 10, 1, 1, 1, 0.001, 0.001 }; { // First Test with working Landmarks // These landmark should match properly constexpr unsigned int numWorkingLandmark = 6; TransformInitializerType::LandmarkPointContainer fixedLandmarks; TransformInitializerType::LandmarkPointContainer movingLandmarks; TransformInitializerType::LandmarkWeightType landmarkWeights; for (unsigned i = 0; i < numWorkingLandmark; ++i) { TransformInitializerType::LandmarkPointType fixedPoint, movingPoint; for (unsigned j = 0; j < 3; ++j) { fixedPoint[j] = fixedLandMarkInit[i][j]; movingPoint[j] = movingLandmarkInit[i][j]; } fixedLandmarks.push_back(fixedPoint); movingLandmarks.push_back(movingPoint); landmarkWeights.push_back(weights[i]); } initializer->SetFixedLandmarks(fixedLandmarks); initializer->SetMovingLandmarks(movingLandmarks); initializer->SetLandmarkWeight(landmarkWeights); std::cerr << "Transform " << transform << std::endl; success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks); } { // Test with dummy points // dummy points should not matched based on given weights constexpr unsigned int numDummyLandmark = 8; TransformInitializerType::LandmarkPointContainer fixedLandmarks; TransformInitializerType::LandmarkPointContainer movingLandmarks; TransformInitializerType::LandmarkWeightType landmarkWeights; for (unsigned i = 0; i < numDummyLandmark; ++i) { TransformInitializerType::LandmarkPointType fixedPoint, movingPoint; for (unsigned j = 0; j < 3; ++j) { fixedPoint[j] = fixedLandMarkInit[i][j]; movingPoint[j] = movingLandmarkInit[i][j]; } fixedLandmarks.push_back(fixedPoint); movingLandmarks.push_back(movingPoint); landmarkWeights.push_back(weights[i]); } initializer->SetFixedLandmarks(fixedLandmarks); initializer->SetMovingLandmarks(movingLandmarks); initializer->SetLandmarkWeight(landmarkWeights); std::cerr << "Transform " << transform << std::endl; success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks, 2); } // Second test with dummy } { std::cout << "\nTesting Landmark alignment with BSplineTransform..." << std::endl; constexpr unsigned int Dimension = 3; using FixedImageType = itk::Image<PixelType, Dimension>; using MovingImageType = itk::Image<PixelType, Dimension>; FixedImageType::Pointer fixedImage = CreateTestImage<Dimension>(); MovingImageType::Pointer movingImage = CreateTestImage<Dimension>(); FixedImageType::PointType origin; origin[0] = -5; origin[1] = -5; origin[2] = -5; fixedImage->SetOrigin(origin); // Set the transform type constexpr unsigned int SplineOrder = 3; using TransformType = itk::BSplineTransform<double, FixedImageType::ImageDimension, SplineOrder>; TransformType::Pointer transform = TransformType::New(); using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType, FixedImageType, MovingImageType>; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object); TransformInitializerType::LandmarkPointContainer fixedLandmarks; TransformInitializerType::LandmarkPointContainer movingLandmarks; Init3DPoints<TransformInitializerType>(fixedLandmarks, movingLandmarks); constexpr unsigned int numLandmarks = 4; double weights[numLandmarks] = { 1, 3, 0.01, 0.5 }; TransformInitializerType::LandmarkWeightType landmarkWeights; for (double weight : weights) { landmarkWeights.push_back(weight); } initializer->SetFixedLandmarks(fixedLandmarks); initializer->SetMovingLandmarks(movingLandmarks); initializer->SetLandmarkWeight(landmarkWeights); initializer->SetTransform(transform); initializer->SetBSplineNumberOfControlPoints(8); // Test that an exception is thrown if the reference image isn't set ITK_TRY_EXPECT_EXCEPTION(initializer->InitializeTransform()); // Now set the reference image and initialization should work initializer->SetReferenceImage(fixedImage); success &= ExecuteAndExamine<TransformInitializerType>(initializer, fixedLandmarks, movingLandmarks); } { using TransformType = itk::Transform<float, 3, 3>; using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType>; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(initializer, LandmarkBasedTransformInitializer, Object); } if (!success) { return EXIT_FAILURE; } std::cout << "Test PASSED!" << std::endl; return EXIT_SUCCESS; }
18,567
6,006
#include "Arduino.h" #include<Wire.h> #include<math.h> // Description /* By Binh B. 07/23/2018 first commit */ #define ToRad(x) ((x)*0.01745329252) // *pi/180 #define ToDeg(x) ((x)*57.2957795131) // *180/pi #define PI 3.1415926 #define twoPI 6.2831853 #define PItwo 1.570796 // LSM303DLHC ACC and MAG Addresses const int LSM303_ACC_ADDR = 0b0011001; const int LSM303_MAG_ADDR = 0b0011110; // MAG Register LSM303DLHC const int CRA_REG_M = 0x00; const int CRB_REG_M = 0x01; const int MR_REG_M = 0x02; const int OUT_X_H_M = 0x03; // starting read register for mag // tbd on usage struct sensorParams { float xSF; float ySF; float zSF; } lsm303Mag; // ACC Register LSM303DLHC const int CTRL_REG4_A = 0x23; const int CTRL_REG1_A = 0x20; const int OUT_X_L_A = 0x28; // starting read register for acc // L3GD20 Address const int L3GD20_GYRO_ADDR = 0b1101011; // GYRO Register L3GD20 const int CTRL_REG1_G = 0x20; const int CTRL_REG4_G = 0x23; const int OUT_X_L_G = 0x28; const float r2d = 57.29577951308232; /////////// // GLOBAL PARAMS int mRaw[3] = {0, 0, 0}; int aRaw[3] = {0, 0, 0}; int gRaw[3]= {0,0,0}; // gRaw corrected for offset int gyroDigiCorr[3] = {0,0,0}; float mGauss[3] = {0.0, 0.0, 0.0}; float aGrav[3] = {0.0, 0.0, 0.0}; float gRad[3] = {0.0, 0.0, 0.0}; float aNorm[3] = {0.0, 0.0, 0.0}; int mMin[3] = { -665, -749, -577}; int mMax[3] = {505, 404, 442}; int mOffset[3] = {0, 0, 0}; // gyro bias int gyroRawBias[3] = {-333,61,-237}; // accel bias int accelRawBias[3] = {-1113,-42,-1620}; // accel external g protection bound (10% of 16384 digi) is error of 1638 int oneGDigit = 16384; // 2g full scale at 16 bit int extForceBoundDigi = 0.1*oneGDigit; int aMagDigi = 0; // mag external protection bound ~0.47 gauss nominal, +/- 10% float nomGaussMag = 0.47; float nomGaussBound = 0.15*nomGaussMag; bool isMagNomValid = true; float RefRpy[3] = {0.0, 0.0, 0.0}; float SolRpy[3] = {0.0,0.0,0.0}; // fused solution float magGauss = 0.0; float headingDeg = 0.0; //gyro rate in rad float gyroRateRad[3] = {0.0, 0.0, 0.0}; // rad/sec // QUATERNION STATES float quatRatePrev[4] = {0.0, 0.0, 0.0, 0.0}; float quatPrev[4] = {1.0, 0.0, 0.0, 0.0}; float quatSol[4] = {1.0, 0.0, 0.0, 0.0}; // rpy filtering float Krpy[3]= {0.05, 0.05, 0.01}; // proportional gains // execution dt float stepSize = 0.02; unsigned long stepSizeMicroSec = stepSize*1000000; // timer unsigned long t0; unsigned long t1; unsigned long t2; unsigned long t3; void printDataToSerial(byte opt); void printVec(int (&vec)[3]); void setupLsm(); void setupL3G(); void readRawLsm(bool applyAccelOffset, int (&mRawData)[3],int (&aBiasData)[3], int (&aRawData)[3]); void readRawL3G(bool applyOffset, int (&gBiasData)[3],int (&gRawData)[3]); void getGdigiMagnitude(int (&aRawData)[3], int& aMag ); void rawGyroToRad(int (&gRawData)[3], float (&rpyAngle)[3]); void calGyroBias(int (&gRawData)[3], int (&gBiasData)[3]); void accelBiasCal(int (&aRawData)[3], int (&aBiasData)[3]); void calGyroAndAccel(int (&aRawData)[3], int (&aBiasData)[3],int (&gRawData)[3], int (&gBiasData)[3]); void getRefRPY(int (&mRawData)[3], float (&mGaussData)[3], int (&mOffsetData)[3],bool& isMagValid, int (&aRawData)[3], float (&aNormData)[3], float (&refRpyData)[3]); void vectorCopy(int (&vecA)[3], float (&vecB)[3]); void writeToReg(int addr, int reg, int value); void calMag(int (&mMinData)[3], int (&mMaxData)[3], int (&offsetData)[3]); void setupMagOffset(int (&mMinData)[3], int (&mMaxData)[3], int (&offsetData)[3]); void magCalAux(int& minMax, int rawVal, int (&states)[3]); void integrateAndFilterSoln(float dt, int aMag, bool isMagValid, float (&gyroRate)[3],float (&refRpyData)[3], float (&qRatePrev)[4], float (&qPrev)[4],float (&qSol)[4]); void quatRateFromBodyRate(float (&gyroRate)[3], float (&q)[4],float (&qDot)[4] ); void quatNorm(float (&q)[4]); void quat2Euler(float (&q)[4], float (&gyroRpyData)[3]); void euler2Quat(float (&rpy)[3], float (&q)[4]); void integrateQuat(float dt, float (&qRate)[4], float (&qRatePrev)[4], float (&qPrev)[4],float (&qOut)[4]); void rpyFiltering(bool isMagValid, float (&refRpyData)[3],float (&q)[4] ); void wrapAngles(float &angle, int opt); void printEulerAngles(float (&gyroRpyData)[3]); void printQuat( float (&q)[4]); void MatrixVectorMul(float (&matA)[3][3],float (&vecB)[3],float (&vecOut)[3]); void VectorDotProduct(float (&vecA)[3],float (&vecB)[3],float& dotSol); void VectorCross(float (&vecA)[3], float (&vecB)[3], float (&vecC)[3]); void VectorMag(float (&vecA)[3], float& magOut); void VectorNorm(float (&vecA)[3]); void setup() { // put your setup code here, to run once: Serial.begin(115200); // Open serial port Wire.begin(); // I2C Setup // default is 100 kHz, with 400 kHz you get 4x the speed*/ Wire.setClock(400000); // set I2C SCL to High Speed Mode of 400kHz setupLsm(); setupL3G(); /* // not used yet but for future implementation, also cant be initialized outside of setup. lsm303Mag.xSF = 1100.0; lsm303Mag.ySF = 1100.0; lsm303Mag.zSF = 980.0; */ // optional mag cal //calMag(mMin, mMax, mOffset); setupMagOffset(mMin, mMax, mOffset); /* Serial.print("Offset"); printVec(mOffset); */ //calGyroBias(gRaw,gyroRawBias); //accelBiasCal(aRaw,accelRawBias); calGyroAndAccel(aRaw,accelRawBias,gRaw,gyroRawBias); readRawLsm(true,mRaw, accelRawBias, aRaw); getRefRPY(mRaw, mGauss, mOffset, isMagNomValid, aRaw, aNorm, RefRpy); // initialize SolRpy to the refer rpy for (int i = 0; i<3; i++) { SolRpy[i] = RefRpy[i]; } euler2Quat(SolRpy,quatSol); euler2Quat(SolRpy,quatPrev); Serial.println("Setup Complete"); } void loop() { // total from t0 to t2 ~ 5.2 ms t0 = micros(); readRawLsm(true,mRaw, accelRawBias, aRaw); getRefRPY(mRaw, mGauss, mOffset, isMagNomValid, aRaw, aNorm, RefRpy); /* if (isMagNomValid == false) { Serial.println("mag Nom Value Exceeded"); } */ readRawL3G(true,gyroRawBias,gRaw); rawGyroToRad(gRaw,gyroRateRad); getGdigiMagnitude(aRaw,aMagDigi); integrateAndFilterSoln(stepSize,aMagDigi,isMagNomValid, gyroRateRad,RefRpy,quatRatePrev, quatPrev,quatSol); quat2Euler(quatSol, SolRpy); t2 = micros(); //printEulerAngles(SolRpy); printDataToSerial(0b00010000); //Serial.print((t2-t0)/1000.0,5); //Serial.println(" ms"); while((micros()-t0)<=stepSizeMicroSec) { t1 = micros(); }; } void printDataToSerial(byte opt) { if ((opt & 0b00000001) > 0) { Serial.print("rawMag,"); printVec(mRaw); } if ((opt & 0b00000010) > 0) { Serial.print("rawAcc,"); printVec(aRaw); } if ((opt & 0b00000100) > 0) { Serial.print("gyroRaw,"); printVec(gRaw); } if ((opt & 0b00001000) > 0) { Serial.print("roll: "); Serial.print(ToDeg(RefRpy[0])); Serial.print(" "); Serial.print("pitch: "); Serial.print(ToDeg(RefRpy[1])); Serial.print(" "); Serial.print("yaw: "); Serial.println(ToDeg(RefRpy[2])); } if ((opt & 0b00010000) > 0) { Serial.print("!ANG:,"); Serial.print(ToDeg(SolRpy[0])); Serial.print(","); Serial.print(ToDeg(SolRpy[1])); Serial.print(","); Serial.print(ToDeg(SolRpy[2])); Serial.println(); } } void printVec(int (&vec)[3]) { Serial.print(vec[0]); Serial.print(","); Serial.print(vec[1]); Serial.print(","); Serial.println(vec[2]); } void setupLsm() { // MAG SETUP // 0x10 = 0b00010000 // DO = 100 (15 Hz ODR) writeToReg(LSM303_MAG_ADDR, CRA_REG_M, 0x10); // 0x20 = 0b00100000 // GN = 001 (+/- 1.3 gauss full scale) writeToReg(LSM303_MAG_ADDR, CRB_REG_M, 0x20); // 0x00 = 0b00000000 // MD = 00 (continuous-conversion mode) writeToReg(LSM303_MAG_ADDR, MR_REG_M, 0x00); // ACC Setup // 0x08 = 0b00001000 // FS = 00 (+/- 2 g full scale); HR = 1 (high resolution enable) // FS +/- 2g (16 bit) // (2^15-1)/2 = 16384 digits/g or 1/16384 = 0.000061035 mg/digit writeToReg(LSM303_ACC_ADDR, CTRL_REG4_A, 0x08); // 0x57 = 0b01010111 // ODR = 0101 (100 Hz); Zen = Yen = Xen = 1 (all axes enabled) writeToReg(LSM303_ACC_ADDR, CTRL_REG1_A, 0x57); } void setupL3G() { // GYRO SETUP //0x77 0b01111111 // DR = 01 (190Hz), BW = 11 (70Hz),PD = 1 (normal mode), Zen=Xen=Yen=1 writeToReg(L3GD20_GYRO_ADDR,CTRL_REG1_G,0x7F); //writeToReg(L3GD20_GYRO_ADDR,CTRL_REG1_G,0x6F); // 0x01 = 0b00010000 // FS = 500 dps writeToReg(L3GD20_GYRO_ADDR,CTRL_REG4_G,0x10); } void readRawLsm(bool applyAccelOffset, int (&mRawData)[3],int (&aBiasData)[3], int (&aRawData)[3]) { Wire.beginTransmission(LSM303_ACC_ADDR); // need to add a 1 bit to the MSB (SUPER STUPID) Wire.write(OUT_X_L_A | (1 << 7)); // Wire.endTransmission(); Wire.requestFrom(LSM303_ACC_ADDR, 6); while (Wire.available() < 6); // wait to get bytes // see page 22/42 of LSM303DLHC aRawData[0] = Wire.read() | Wire.read() << 8; aRawData[1] = Wire.read() | Wire.read() << 8; aRawData[2] = Wire.read() | Wire.read() << 8; Wire.beginTransmission(LSM303_MAG_ADDR); Wire.write(OUT_X_H_M); // Trigger outputs starting with register 3B or 59 Wire.endTransmission(); Wire.requestFrom(LSM303_MAG_ADDR, 6); while (Wire.available() < 6); // wait to get bytes // see page 23/42 of LSM303DLHC mRawData[0] = Wire.read() << 8 | Wire.read(); mRawData[2] = Wire.read() << 8 | Wire.read(); mRawData[1] = Wire.read() << 8 | Wire.read(); if (applyAccelOffset == true) { for (int i = 0; i<3; i++) { aRawData[i] -= aBiasData[i]; } } } void readRawL3G(bool applyOffset, int (&gBiasData)[3],int (&gRawData)[3]) { Wire.beginTransmission(L3GD20_GYRO_ADDR); // need to add a 1 bit to the MSB (SUPER STUPID) Wire.write(OUT_X_L_G | (1 << 7)); // Wire.endTransmission(); Wire.requestFrom(L3GD20_GYRO_ADDR, 6); while (Wire.available() < 6); // wait to get bytes // see page 22/42 of LSM303DLHC gRawData[0] = Wire.read() | Wire.read() << 8; gRawData[1] = Wire.read() | Wire.read() << 8; gRawData[2] = Wire.read() | Wire.read() << 8; if (applyOffset == true) { for (int i = 0; i<3; i++) { gRawData[i] -= gBiasData[i]; } } } void getGdigiMagnitude(int (&aRawData)[3], int& aMag ) { aMag = sqrt((unsigned long)aRawData[0]*aRawData[0]+(unsigned long)aRawData[1]*aRawData[1]+(unsigned long)aRawData[2]*aRawData[2]); } void rawGyroToRad(int (&gRawData)[3], float (&rpyAngle)[3]) { // FS = 500 dps // (2^15-1)/500 = 65.534 digit/(deg/sec) or 1/65.534 = 15.26 (mdeg/sec)/digit for (int i = 0; i<3; i++) { rpyAngle[i] = ToRad(0.01525925*gRawData[i]); } } void calGyroBias(int (&gRawData)[3], int (&gBiasData)[3]) { long biasTemp[3] = {0,0,0}; // initialize bias to zero for (int i = 0; i<3; i++) { gBiasData[i] = 0; } // add data points to perform averaging int n = 100; // number of points to average for (int i = 1; i<=n; i++) { // read gyro data readRawL3G(false,gBiasData,gRawData); for (int j = 0; j <3; j++) { biasTemp[j]+=gRawData[j]; } } // average for (int i = 0; i<3; i++) { biasTemp[i] /= n; gBiasData[i] = biasTemp[i]; } printVec(gBiasData); } void accelBiasCal(int (&aRawData)[3], int (&aBiasData)[3]) { long biasTemp[3] = {0,0,0}; int dummy[3] = {0,0,0}; // initialize bias to zero for (int i = 0; i<3; i++) { aBiasData[i] = 0; } // add data points to perform averaging int n = 100; // number of points to average for (int i = 1; i<=n; i++) { // read accelData readRawLsm(false, dummy,dummy,aRawData); for (int j = 0; j <3; j++) { biasTemp[j]+=aRawData[j]; } } // average for (int i = 0; i<3; i++) { biasTemp[i] /= n; } aBiasData[0] = biasTemp[0]; aBiasData[1] = biasTemp[1]; aBiasData[2] = biasTemp[2] + oneGDigit; printVec(aBiasData); } void calGyroAndAccel(int (&aRawData)[3], int (&aBiasData)[3],int (&gRawData)[3], int (&gBiasData)[3]) { long biasTempGyro[3] = {0,0,0}; long biasTempAccel[3] = {0,0,0}; int dummy[3] = {0,0,0}; // add data points to perform averaging int n = 100; // number of points to average for (int i = 1; i<=n; i++) { // get data readRawLsm(false, dummy,dummy,aRawData); readRawL3G(false,dummy,gRawData); for (int j = 0; j <3; j++) { biasTempAccel[j]+=aRawData[j]; biasTempGyro[j]+=gRawData[j]; } } // average for (int i = 0; i<3; i++) { biasTempAccel[i] /= n; biasTempGyro[i] /= n; gBiasData[i] = biasTempGyro[i]; } aBiasData[0] = biasTempAccel[0]; aBiasData[1] = biasTempAccel[1]; aBiasData[2] = biasTempAccel[2] + oneGDigit; Serial.println("bias accel"); printVec(aBiasData); Serial.println("bias gyro"); printVec(gBiasData); } void getRefRPY(int (&mRawData)[3], float (&mGaussData)[3], int (&mOffsetData)[3],bool& isMagValid, int (&aRawData)[3], float (&aNormData)[3], float (&refRpyData)[3]) { float mGaussMag; float magErr; // see page 37/42 of LSM303DLHC // Need to this to scale values of each axis correctly! mGaussData[0] = (mRawData[0] - mOffsetData[0]) / 1100.0; //X mGaussData[1] = (mRawData[1] - mOffsetData[1]) / 1100.0; //Y mGaussData[2] = (mRawData[2] - mOffsetData[2]) / 980.0; //Z ///////////////// CHECK FOR EXTERNAL MAG INTEREFERENCE VectorMag(mGaussData,mGaussMag); magErr = abs(mGaussMag - nomGaussMag); if ( magErr >= nomGaussBound ) { isMagValid = false; } else { isMagValid = true; } ////////////// // right now no need to actually convert gravity raw data //normalize gvector (must do this or else incorrect and img values for pitch and roll) vectorCopy(aRawData, aNormData); VectorNorm(aNormData); // pitch refRpyData[1] = asin(aNormData[0]); // roll refRpyData[0] = atan2(-aNormData[1], -aNormData[2]); // yaw/heading float mvecX_NED = cos(refRpyData[1])*mGaussData[0] + sin(refRpyData[0])*sin(refRpyData[1])*mGaussData[1]+cos(refRpyData[0])*sin(refRpyData[1])*mGaussData[2]; float mvecY_NED = cos(refRpyData[0])*mGaussData[1]-sin(refRpyData[0])*mGaussData[2]; refRpyData[2] = -atan2(mvecY_NED,mvecX_NED); } void vectorCopy(int (&vecA)[3], float (&vecB)[3]) { // set vec B == vec A vecB[0] = (float)vecA[0]; vecB[1] = (float)vecA[1]; vecB[2] = (float)vecA[2]; } void writeToReg(int addr, int reg, int value) { Wire.beginTransmission(addr); Wire.write(reg); Wire.write(value); Wire.endTransmission(); } void calMag(int (&mMinData)[3], int (&mMaxData)[3], int (&offsetData)[3]) { // NOTE DUE TO THE USAGE OR ARDUINO LIBRARY, THIS CANNOT BE MADE A LIBRARY int numSamples = 300; // ~ 30 secs int xMinState[3] = {0, 0, 0}; int yMinState[3] = {0, 0, 0}; int zMinState[3] = {0, 0, 0}; int xMaxState[3] = {0, 0, 0}; int yMaxState[3] = {0, 0, 0}; int zMaxState[3] = {0, 0, 0}; int mRawData[3] = {0, 0, 0}; int dummy[3] = {0, 0, 0}; // initialize using global min max for (int i = 0; i < 3; i++) { xMinState[i] = mMinData[0]; yMinState[i] = mMinData[1]; zMinState[i] = mMinData[2]; xMaxState[i] = mMaxData[0]; yMaxState[i] = mMaxData[1]; zMaxState[i] = mMaxData[2]; } // cal mx for (int i = 0; i < numSamples; i++) { readRawLsm(false,mRawData,dummy, dummy); if (mRawData[0] > mMaxData[0]) { magCalAux(mMaxData[0], mRawData[0], xMaxState); } if (mRawData[1] > mMaxData[1]) { magCalAux(mMaxData[1], mRawData[1], yMaxState); } if (mRawData[2] > mMaxData[2]) { magCalAux(mMaxData[2], mRawData[2], zMaxState); } if (mRawData[0] < mMinData[0]) { magCalAux(mMinData[0], mRawData[0], xMinState); } if (mRawData[1] < mMinData[1]) { magCalAux(mMinData[1], mRawData[1], yMinState); } if (mRawData[2] < mMinData[2]) { magCalAux(mMinData[2], mRawData[2], zMinState); } // cant have this in the partition code Serial.println(""); Serial.print("Min: "); printVec(mMinData); Serial.print("Max: "); Serial.println(""); Serial.print("Min: "); delay(100); } setupMagOffset(mMinData, mMaxData, mOffset); } void setupMagOffset(int (&mMinData)[3], int (&mMaxData)[3], int (&offsetData)[3]) { offsetData[0] = (mMinData[0] + mMaxData[0]) / 2; offsetData[1] = (mMinData[1] + mMaxData[1]) / 2; offsetData[2] = (mMinData[2] + mMaxData[2]) / 2; } void magCalAux(int& minMax, int rawVal, int (&states)[3]) { minMax = (rawVal + states[0] + states[1] + states[2]) / 4.0; // floor states[2] = states[1]; states[1] = states[0]; states[0] = rawVal; } void integrateAndFilterSoln(float dt, int aMag, bool isMagValid, float (&gyroRate)[3],float (&refRpyData)[3], float (&qRatePrev)[4], float (&qPrev)[4],float (&qSol)[4]) { // Step 1 compute quat rate float qRate[4] = {0.0, 0.0, 0.0, 0.0}; quatRateFromBodyRate(gyroRate,qSol,qRate); // Step 2 integrate quat rate integrateQuat(dt, qRate, qRatePrev,qPrev,qSol); // Step 3 normalize integrate quat quatNorm(qSol); // Step 4 fuse data if (abs(aMag - oneGDigit) <= extForceBoundDigi) { rpyFiltering(isMagValid,refRpyData,qSol); } // set state for (int i=0; i<4; i++) { qPrev[i] = qSol[i]; qRatePrev[i] = qRate[i]; } } void quatRateFromBodyRate(float (&gyroRate)[3], float (&q)[4],float (&qDot)[4] ) { // gyroRate, xyz at the body level in rad/sec // q is quaternion vecor where the first element is magnitude, and the next 3 elem defines the vector qDot[0] = 0.5*(-q[1]*gyroRate[0] - q[2]*gyroRate[1] - q[3]*gyroRate[2]); qDot[1] = 0.5*(q[0]*gyroRate[0] + q[2]*gyroRate[2] - q[3]*gyroRate[1]); qDot[2] = 0.5*(q[0]*gyroRate[1] - q[1]*gyroRate[2] + q[3]*gyroRate[0]); qDot[3] = 0.5*(q[0]*gyroRate[2] + q[1]*gyroRate[1] - q[2]*gyroRate[0]); } void quatNorm(float (&q)[4]) { float normVal = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]); q[0] /= normVal; q[1] /= normVal; q[2] /= normVal; q[3] /= normVal; } void quat2Euler(float (&q)[4], float (&gyroRpyData)[3]) { float test = q[0]*q[2]-q[3]*q[1]; if (test > 0.5) { gyroRpyData[0] = 0.0; gyroRpyData[1] = 1.570796326794897; gyroRpyData[2] = -2*atan2(q[1],q[0]); } else if (test < -0.5) { gyroRpyData[0] = 0.0; gyroRpyData[1] = -1.570796326794897; gyroRpyData[2] = 2*atan2(q[1],q[0]); } else { gyroRpyData[0] = atan2(2*(q[0]*q[1]+q[2]*q[3]),1-2*(q[1]*q[1]+q[2]*q[2])); gyroRpyData[1] = asin(2*(q[0]*q[2]-q[3]*q[1])); gyroRpyData[2] = atan2(2*(q[0]*q[3]+q[1]*q[2]),1-2*(q[2]*q[2]+q[3]*q[3])); } } void euler2Quat(float (&rpy)[3], float (&q)[4]) { float cosPhi2 = cos(rpy[0]/2.0); float cosTheta2 = cos(rpy[1]/2.0); float cosPsi2 = cos(rpy[2]/2.0); float sinPhi2 = sin(rpy[0]/2.0); float sinTheta2 = sin(rpy[1]/2.0); float sinPsi2 = sin(rpy[2]/2.0); q[0] = cosPhi2*cosTheta2*cosPsi2 + sinPhi2*sinTheta2*sinPsi2; q[1] = sinPhi2*cosTheta2*cosPsi2 - cosPhi2*sinTheta2*sinPsi2; q[2] = cosPhi2*sinTheta2*cosPsi2 + sinPhi2*cosTheta2*sinPsi2; q[3] = cosPhi2*cosTheta2*sinPsi2 - sinPhi2*sinTheta2*cosPsi2; } void integrateQuat(float dt, float (&qRate)[4], float (&qRatePrev)[4], float (&qPrev)[4],float (&qOut)[4]) { for (int i=0; i<4; i++) { qOut[i] = qPrev[i] + 0.5*(qRate[i] + qRatePrev[i])*dt; } } void rpyFiltering(bool isMagValid, float (&refRpyData)[3],float (&q)[4] ) { float rpy[3] = {0,0,0}; float rpyErr[3] = {0,0,0}; // convert to Euler angles quat2Euler(q, rpy); // compute errors for (int i = 0; i<3; i++) { rpyErr[i] = refRpyData[i] - rpy[i]; } // add angle wrapping to prevent angle overflow wrapAngles(rpyErr[0],1); // +/- pi wrapAngles(rpyErr[1],2); // +/- pi/2 wrapAngles(rpyErr[2],1); // +/- pi // apply Gains to get new estimated rpy // note Krpy is a global param rpy[0] = rpy[0] + Krpy[0]*rpyErr[0]; rpy[1] = rpy[1] + Krpy[1]*rpyErr[1]; if (isMagValid == true) { rpy[2] = rpy[2] + Krpy[2]*rpyErr[2]; } // convert rpy to quat euler2Quat(rpy, q); } void wrapAngles(float &angle, int opt) { if (opt == 1) { // +/- pi while ( angle > PI ) { angle = angle - twoPI; } //+/- 2pi while ( angle < -PI ) { angle = angle + twoPI; } } else { while ( angle > PItwo ) { angle = angle - PI; } while ( angle < -PItwo ) { angle = angle + PI; } } } void printEulerAngles(float (&gyroRpyData)[3]) { Serial.print("roll: "); Serial.print(ToDeg(gyroRpyData[0]),5); Serial.print(" "); Serial.print("pitch: "); Serial.print(ToDeg(gyroRpyData[1]),5); Serial.print(" "); Serial.print("yaw: "); Serial.println(ToDeg(gyroRpyData[2]),5); } void printQuat( float (&q)[4]) { Serial.print("q: "); for (int i = 0; i < 4; i++) { Serial.print(q[i],5); Serial.print(", "); } Serial.println(" "); } void MatrixVectorMul(float (&matA)[3][3],float (&vecB)[3],float (&vecOut)[3]) { vecOut[0] = vecB[0]*matA[0][0]+vecB[1]*matA[0][1]+vecB[2]*matA[0][2]; vecOut[1] = vecB[0]*matA[1][0]+vecB[1]*matA[1][1]+vecB[2]*matA[1][2]; vecOut[2] = vecB[0]*matA[2][0]+vecB[1]*matA[2][1]+vecB[2]*matA[2][2]; } void VectorDotProduct(float (&vecA)[3],float (&vecB)[3],float& dotSol) { dotSol= vecA[0]*vecB[0]+vecA[1]*vecB[1]+vecA[2]*vecB[2]; } void VectorCross(float (&vecA)[3], float (&vecB)[3], float (&vecC)[3]) { vecC[0] = vecA[1]*vecB[2]-vecB[1]*vecA[2]; vecC[1] = -vecA[0]*vecB[2]+vecB[0]*vecA[2]; vecC[2] = vecA[0]*vecB[1]-vecB[0]*vecA[1]; } void VectorMag(float (&vecA)[3], float& magOut) { VectorDotProduct(vecA,vecA,magOut); magOut = sqrt(magOut); } void VectorNorm(float (&vecA)[3]) { float mag(0.0); VectorMag(vecA,mag); vecA[0] /= mag; vecA[1] /= mag; vecA[2] /= mag; }
23,122
10,632
// && operator: if the left operand is flase, there is no need to compute the right operand // || operator: if the left operand is true, there is no need to compute the right operand // == operator: there is no order
217
57
#include<iostream> #include<algorithm> #include<cmath> #include<vector> #include<map> #include<queue> #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep1(i, n) for (int i = 1; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; const int INF = 1001001001; const int mod = 1000000007; struct mint { ll x; mint(ll x=0):x((x%mod+mod)%mod){} mint operator-() const { return mint(-x);} mint& operator+=(const mint a) { if ((x += a.x) >= mod) x -= mod; return *this; } mint& operator-=(const mint a) { if ((x += mod-a.x) >= mod) x -= mod; return *this; } mint& operator*=(const mint a) { (x *= a.x) %= mod; return *this; } mint operator+(const mint a) const { mint res(*this); return res+=a; } mint operator-(const mint a) const { mint res(*this); return res-=a; } mint operator*(const mint a) const { mint res(*this); return res*=a; } mint pow(ll t) const { if (!t) return 1; mint a = pow(t>>1); a *= a; if (t&1) a *= *this; return a; } // for prime mod mint inv() const { return pow(mod-2); } mint& operator/=(const mint a) { return (*this) *= a.inv(); } mint operator/(const mint a) const { mint res(*this); return res/=a; } }; int main() { int N; cin >> N; ll A[N]; rep(i,N) cin >> A[i]; mint ans = 0; rep(k,60) { mint n1 = 0; rep(i,N) { if((A[i] >> k) & 1) n1+=1; } ans += n1*(mint(N)-n1)*mint(2).pow(k); } cout << ans.x << endl; return 0; }
1,560
680
#ifdef _OPENMP #include <omp.h> #endif #ifdef _WIN32 #include <DxLib.h> #ifndef __DXLIB #define __DXLIB #endif #ifndef __WINDOWS__ #define __WINDOWS__ #endif #else #include <Siv3D.hpp> #endif #include <Sample/UseAsLib2/Sample1.hpp>
232
113
// Copyright (c) Team CharLS. // SPDX-License-Identifier: BSD-3-Clause #include "pch.h" #include "util.h" #include <charls/charls.h> #include "../src/jpeg_stream_writer.h" #include "../test/portable_anymap_file.h" using Microsoft::VisualStudio::CppUnitTestFramework::Assert; using std::ifstream; using std::vector; using namespace charls; using namespace charls_test; namespace { void triplet_to_planar(vector<uint8_t>& buffer, uint32_t width, uint32_t height) { vector<uint8_t> workBuffer(buffer.size()); const size_t byteCount = static_cast<size_t>(width) * height; for (size_t index = 0; index < byteCount; index++) { workBuffer[index] = buffer[index * 3 + 0]; workBuffer[index + 1 * byteCount] = buffer[index * 3 + 1]; workBuffer[index + 2 * byteCount] = buffer[index * 3 + 2]; } swap(buffer, workBuffer); } } // namespace vector<uint8_t> read_file(const char* filename) { ifstream input; input.exceptions(input.eofbit | input.failbit | input.badbit); input.open(filename, input.in | input.binary); input.seekg(0, input.end); const auto byteCountFile = static_cast<int>(input.tellg()); input.seekg(0, input.beg); vector<uint8_t> buffer(byteCountFile); input.read(reinterpret_cast<char*>(buffer.data()), buffer.size()); return buffer; } portable_anymap_file read_anymap_reference_file(const char* filename, const interleave_mode interleave_mode, const frame_info& frame_info) { portable_anymap_file reference_file(filename); if (interleave_mode == interleave_mode::none && frame_info.component_count == 3) { triplet_to_planar(reference_file.image_data(), frame_info.width, frame_info.height); } return reference_file; } portable_anymap_file read_anymap_reference_file(const char* filename, const interleave_mode interleave_mode) { portable_anymap_file reference_file(filename); if (interleave_mode == interleave_mode::none && reference_file.component_count() == 3) { triplet_to_planar(reference_file.image_data(), reference_file.width(), reference_file.height()); } return reference_file; } vector<uint8_t> create_test_spiff_header(const uint8_t high_version, const uint8_t low_version, const bool end_of_directory) { vector<uint8_t> buffer; buffer.push_back(0xFF); buffer.push_back(0xD8); // SOI. buffer.push_back(0xFF); buffer.push_back(0xE8); // ApplicationData8 buffer.push_back(0); buffer.push_back(32); // SPIFF identifier string. buffer.push_back('S'); buffer.push_back('P'); buffer.push_back('I'); buffer.push_back('F'); buffer.push_back('F'); buffer.push_back(0); // Version buffer.push_back(high_version); buffer.push_back(low_version); buffer.push_back(0); // profile id buffer.push_back(3); // component count // Height buffer.push_back(0); buffer.push_back(0); buffer.push_back(0x3); buffer.push_back(0x20); // Width buffer.push_back(0); buffer.push_back(0); buffer.push_back(0x2); buffer.push_back(0x58); buffer.push_back(10); // color space buffer.push_back(8); // bits per sample buffer.push_back(6); // compression type, 6 = JPEG-LS buffer.push_back(1); // resolution units // vertical_resolution buffer.push_back(0); buffer.push_back(0); buffer.push_back(0); buffer.push_back(96); // header.horizontal_resolution = 1024; buffer.push_back(0); buffer.push_back(0); buffer.push_back(4); buffer.push_back(0); const size_t spiff_header_size = buffer.size(); buffer.resize(buffer.size() + 100); const ByteStreamInfo info = FromByteArray(buffer.data() + spiff_header_size, buffer.size() - spiff_header_size); JpegStreamWriter writer(info); if (end_of_directory) { writer.WriteSpiffEndOfDirectoryEntry(); } writer.WriteStartOfFrameSegment(100, 100, 8, 1); writer.WriteStartOfScanSegment(1, 0, interleave_mode::none); return buffer; } vector<uint8_t> create_noise_image_16bit(const size_t pixel_count, const int bit_count, const uint32_t seed) { srand(seed); vector<uint8_t> buffer(pixel_count * 2); const auto mask = static_cast<uint16_t>((1 << bit_count) - 1); for (size_t i = 0; i < pixel_count; i = i + 2) { const uint16_t value = static_cast<uint16_t>(rand()) & mask; buffer[i] = static_cast<uint8_t>(value); buffer[i] = static_cast<uint8_t>(value >> 8); } return buffer; } void test_round_trip_legacy(const vector<uint8_t>& source, const JlsParameters& params) { vector<uint8_t> encodedBuffer(params.height * params.width * params.components * params.bitsPerSample / 4); vector<uint8_t> decodedBuffer(static_cast<size_t>(params.height) * params.width * ((params.bitsPerSample + 7) / 8) * params.components); size_t compressedLength = 0; auto error = JpegLsEncode(encodedBuffer.data(), encodedBuffer.size(), &compressedLength, source.data(), source.size(), &params, nullptr); Assert::AreEqual(jpegls_errc::success, error); error = JpegLsDecode(decodedBuffer.data(), decodedBuffer.size(), encodedBuffer.data(), compressedLength, nullptr, nullptr); Assert::AreEqual(jpegls_errc::success, error); const uint8_t* byteOut = decodedBuffer.data(); for (size_t i = 0; i < decodedBuffer.size(); ++i) { if (source[i] != byteOut[i]) { Assert::IsTrue(false); break; } } }
5,554
1,993
/* ----------------------------------------------------------------------------- This source file is part of OGRE-Next (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" /* Although the code is original, many of the ideas for the profiler were borrowed from "Real-Time In-Game Profiling" by Steve Rabin which can be found in Game Programming Gems 1. This code can easily be adapted to your own non-Ogre project. The only code that is Ogre-dependent is in the visualization/logging routines and the use of the Timer class. Enjoy! */ #include "OgreProfiler.h" #include "OgreLogManager.h" #include "OgreRenderSystem.h" #include "OgreRoot.h" #include "OgreTimer.h" namespace Ogre { //----------------------------------------------------------------------- // PROFILE DEFINITIONS //----------------------------------------------------------------------- template <> Profiler *Singleton<Profiler>::msSingleton = 0; Profiler *Profiler::getSingletonPtr() { return msSingleton; } Profiler &Profiler::getSingleton() { assert( msSingleton ); return ( *msSingleton ); } //----------------------------------------------------------------------- Profile::Profile( const String &profileName, ProfileSampleFlags::ProfileSampleFlags flags, uint32 groupID ) : mName( profileName ), mGroupID( groupID ) { Ogre::Profiler::getSingleton().beginProfile( profileName, groupID, flags ); } //----------------------------------------------------------------------- Profile::~Profile() { Ogre::Profiler::getSingleton().endProfile( mName, mGroupID ); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- // PROFILER DEFINITIONS //----------------------------------------------------------------------- Profiler::Profiler() : mCurrent( &mRoot ), mLast( NULL ), mRoot(), mInitialized( false ), mUpdateDisplayFrequency( 10 ), mCurrentFrame( 0 ), mTimer( 0 ), mTotalFrameTime( 0 ), mEnabled( OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE ), mUseStableMarkers( false ), mNewEnableState( false ), mProfileMask( 0xFFFFFFFF ), mMaxTotalFrameTime( 0 ), mAverageFrameTime( 0 ), mResetExtents( false ) #if OGRE_PROFILING == OGRE_PROFILING_REMOTERY , mRemotery( 0 ) #endif { mRoot.hierarchicalLvl = std::numeric_limits<uint>::max(); } //----------------------------------------------------------------------- ProfileInstance::ProfileInstance() : parent( NULL ), frameNumber( 0 ), accum( 0 ), hierarchicalLvl( 0 ) { history.numCallsThisFrame = 0; history.totalTimePercent = 0; history.totalTimeMillisecs = 0; history.totalCalls = 0; history.maxTimePercent = 0; history.maxTimeMillisecs = 0; history.minTimePercent = 1; history.minTimeMillisecs = 100000; history.currentTimePercent = 0; history.currentTimeMillisecs = 0; frame.frameTime = 0; frame.calls = 0; } ProfileInstance::~ProfileInstance() { destroyAllChildren(); } //----------------------------------------------------------------------- Profiler::~Profiler() { if( !mRoot.children.empty() ) { // log the results of our profiling before we quit logResults(); } // clear all our lists mDisabledProfiles.clear(); #if OGRE_PROFILING == OGRE_PROFILING_REMOTERY if( mRemotery ) { Root::getSingleton().getRenderSystem()->deinitGPUProfiling(); rmt_DestroyGlobalInstance( mRemotery ); mRemotery = 0; } #endif } //----------------------------------------------------------------------- void Profiler::setTimer( Timer *t ) { mTimer = t; } //----------------------------------------------------------------------- Timer *Profiler::getTimer() { assert( mTimer && "Timer not set!" ); return mTimer; } //----------------------------------------------------------------------- void Profiler::setEnabled( bool enabled ) { #if OGRE_PROFILING != OGRE_PROFILING_INTERNAL_OFFLINE if( !mInitialized && enabled ) { for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i ) ( *i )->initializeSession(); # if OGRE_PROFILING == OGRE_PROFILING_REMOTERY rmtSettings *settings = rmt_Settings(); settings->messageQueueSizeInBytes *= 10; settings->maxNbMessagesPerUpdate *= 10; rmt_CreateGlobalInstance( &mRemotery ); rmt_SetCurrentThreadName( "Main Ogre Thread" ); Root::getSingleton().getRenderSystem()->initGPUProfiling(); # endif mInitialized = true; } else if( mInitialized ) { for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i ) ( *i )->finializeSession(); mInitialized = false; mEnabled = false; # if OGRE_PROFILING == OGRE_PROFILING_REMOTERY Root::getSingleton().getRenderSystem()->deinitGPUProfiling(); if( mRemotery ) { rmt_DestroyGlobalInstance( mRemotery ); mRemotery = 0; } # endif } #else mEnabled = enabled; mOfflineProfiler.setPaused( !enabled ); #endif // We store this enable/disable request until the frame ends // (don't want to screw up any open profiles!) mNewEnableState = enabled; } //----------------------------------------------------------------------- bool Profiler::getEnabled() const { return mEnabled; } //----------------------------------------------------------------------- void Profiler::setUseStableMarkers( bool useStableMarkers ) { mUseStableMarkers = useStableMarkers; } //----------------------------------------------------------------------- bool Profiler::getUseStableMarkers() const { return mUseStableMarkers; } //----------------------------------------------------------------------- void Profiler::changeEnableState() { for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i ) ( *i )->changeEnableState( mNewEnableState ); mEnabled = mNewEnableState; } //----------------------------------------------------------------------- void Profiler::disableProfile( const String &profileName ) { // even if we are in the middle of this profile, endProfile() will still end it. mDisabledProfiles.insert( profileName ); } //----------------------------------------------------------------------- void Profiler::enableProfile( const String &profileName ) { mDisabledProfiles.erase( profileName ); } //----------------------------------------------------------------------- void Profiler::beginProfile( const String &profileName, uint32 groupID, ProfileSampleFlags::ProfileSampleFlags flags ) { #if OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE mOfflineProfiler.profileBegin( profileName.c_str(), flags ); #else // regardless of whether or not we are enabled, we need the application's root profile (ie the // first profile started each frame) we need this so bogus profiles don't show up when users // enable profiling mid frame so we check // if the profiler is enabled if( !mEnabled ) return; // mask groups if( ( groupID & mProfileMask ) == 0 ) return; // we only process this profile if isn't disabled if( mDisabledProfiles.find( profileName ) != mDisabledProfiles.end() ) return; // empty string is reserved for the root // not really fatal anymore, however one shouldn't name one's profile as an empty string anyway. assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) ); // this would be an internal error. assert( mCurrent ); // need a timer to profile! assert( mTimer && "Timer not set!" ); ProfileInstance *&instance = mCurrent->childrenMap[profileName]; if( instance ) { // found existing child. // Sanity check. assert( instance->name == profileName ); if( instance->frameNumber != mCurrentFrame ) { // new frame, reset stats instance->frame.calls = 0; instance->frame.frameTime = 0; instance->frameNumber = mCurrentFrame; } } else { // new child! instance = OGRE_NEW ProfileInstance(); instance->name = profileName; instance->parent = mCurrent; instance->hierarchicalLvl = mCurrent->hierarchicalLvl + 1; mCurrent->children.push_back( instance ); } instance->frameNumber = mCurrentFrame; mCurrent = instance; // we do this at the very end of the function to get the most // accurate timing results mCurrent->currTime = mTimer->getMicroseconds(); #endif } //----------------------------------------------------------------------- void Profiler::endProfile( const String &profileName, uint32 groupID ) { #if OGRE_PROFILING == OGRE_PROFILING_INTERNAL_OFFLINE mOfflineProfiler.profileEnd(); #else if( !mEnabled ) { // if the profiler received a request to be enabled or disabled if( mNewEnableState != mEnabled ) { // note mNewEnableState == true to reach this. changeEnableState(); // NOTE we will be in an 'error' state until the next begin. ie endProfile will likely // get invoked using a profileName that was never started. even then, we can't be sure // that the next beginProfile will be the true start of a new frame } return; } else { if( mNewEnableState != mEnabled ) { // note mNewEnableState == false to reach this. changeEnableState(); // unwind the hierarchy, should be easy enough mCurrent = &mRoot; mLast = NULL; } if( &mRoot == mCurrent && mLast ) { // profiler was enabled this frame, but the first subsequent beginProfile was NOT the // beinging of a new frame as we had hoped. // we have a bogus ProfileInstance in our hierarchy, we will need to remove it, then // update the overlays so as not to confuse ze user // we could use mRoot.children.find() instead of this, except we'd be compairing strings // instead of a pointer. the string way could be faster, but i don't believe it would. ProfileChildrenVec::iterator it = mRoot.children.begin(), endit = mRoot.children.end(); for( ; it != endit; ++it ) { if( mLast == *it ) { mRoot.childrenMap.erase( ( *it )->name ); mRoot.children.erase( it ); break; } } // with mLast == NULL we won't reach this code, in case this isn't the end of the top // level profile ProfileInstance *last = mLast; mLast = NULL; OGRE_DELETE last; processFrameStats(); displayResults(); } } if( &mRoot == mCurrent ) return; // mask groups if( ( groupID & mProfileMask ) == 0 ) return; // need a timer to profile! assert( mTimer && "Timer not set!" ); // get the end time of this profile // we do this as close the beginning of this function as possible // to get more accurate timing results const uint64 endTime = mTimer->getMicroseconds(); // empty string is reserved for designating an empty parent assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) ); // we only process this profile if isn't disabled // we check the current instance name against the provided profileName as a guard against // disabling a profile name /after/ said profile began if( mCurrent->name != profileName && mDisabledProfiles.find( profileName ) != mDisabledProfiles.end() ) return; // calculate the elapsed time of this profile const uint64 timeElapsed = endTime - mCurrent->currTime; // update parent's accumulator if it isn't the root if( &mRoot != mCurrent->parent ) { // add this profile's time to the parent's accumlator mCurrent->parent->accum += timeElapsed; } mCurrent->frame.frameTime += timeElapsed; ++mCurrent->frame.calls; mLast = mCurrent; mCurrent = mCurrent->parent; if( &mRoot == mCurrent ) { // the stack is empty and all the profiles have been completed // we have reached the end of the frame so process the frame statistics // we know that the time elapsed of the main loop is the total time the frame took mTotalFrameTime = timeElapsed; if( timeElapsed > mMaxTotalFrameTime ) mMaxTotalFrameTime = timeElapsed; // we got all the information we need, so process the profiles // for this frame processFrameStats(); // we display everything to the screen displayResults(); } #endif } //----------------------------------------------------------------------- void Profiler::beginGPUEvent( const String &event ) { Root::getSingleton().getRenderSystem()->beginProfileEvent( event ); } //----------------------------------------------------------------------- void Profiler::endGPUEvent( const String &event ) { Root::getSingleton().getRenderSystem()->endProfileEvent(); } //----------------------------------------------------------------------- void Profiler::markGPUEvent( const String &event ) { Root::getSingleton().getRenderSystem()->markProfileEvent( event ); } //----------------------------------------------------------------------- void Profiler::beginGPUSample( const String &name, uint32 *hashCache ) { Root::getSingleton().getRenderSystem()->beginGPUSampleProfile( name, hashCache ); } //----------------------------------------------------------------------- void Profiler::endGPUSample( const String &name ) { Root::getSingleton().getRenderSystem()->endGPUSampleProfile( name ); } //----------------------------------------------------------------------- void Profiler::processFrameStats( ProfileInstance *instance, Real &maxFrameTime ) { // calculate what percentage of frame time this profile took const Real framePercentage = (Real)instance->frame.frameTime / (Real)mTotalFrameTime; const Real frameTimeMillisecs = (Real)instance->frame.frameTime / 1000.0f; // update the profile stats instance->history.currentTimePercent = framePercentage; instance->history.currentTimeMillisecs = frameTimeMillisecs; if( mResetExtents ) { instance->history.totalTimePercent = framePercentage; instance->history.totalTimeMillisecs = frameTimeMillisecs; instance->history.totalCalls = 1; } else { instance->history.totalTimePercent += framePercentage; instance->history.totalTimeMillisecs += frameTimeMillisecs; instance->history.totalCalls++; } instance->history.numCallsThisFrame = instance->frame.calls; // if we find a new minimum for this profile, update it if( frameTimeMillisecs < instance->history.minTimeMillisecs || mResetExtents ) { instance->history.minTimePercent = framePercentage; instance->history.minTimeMillisecs = frameTimeMillisecs; } // if we find a new maximum for this profile, update it if( frameTimeMillisecs > instance->history.maxTimeMillisecs || mResetExtents ) { instance->history.maxTimePercent = framePercentage; instance->history.maxTimeMillisecs = frameTimeMillisecs; } if( instance->frame.frameTime > maxFrameTime ) maxFrameTime = (Real)instance->frame.frameTime; ProfileChildrenVec::iterator it = instance->children.begin(), endit = instance->children.end(); for( ; it != endit; ++it ) { ProfileInstance *child = *it; // we set the number of times each profile was called per frame to 0 // because not all profiles are called every frame child->history.numCallsThisFrame = 0; if( child->frame.calls > 0 ) { processFrameStats( child, maxFrameTime ); } } } //----------------------------------------------------------------------- void Profiler::processFrameStats() { Real maxFrameTime = 0; ProfileChildrenVec::iterator it = mRoot.children.begin(), endit = mRoot.children.end(); for( ; it != endit; ++it ) { ProfileInstance *child = *it; // we set the number of times each profile was called per frame to 0 // because not all profiles are called every frame child->history.numCallsThisFrame = 0; if( child->frame.calls > 0 ) { processFrameStats( child, maxFrameTime ); } } // Calculate whether the extents are now so out of date they need regenerating if( mCurrentFrame == 0 ) mAverageFrameTime = maxFrameTime; else mAverageFrameTime = ( mAverageFrameTime + maxFrameTime ) * 0.5f; if( (Real)mMaxTotalFrameTime > mAverageFrameTime * 4 ) { mResetExtents = true; mMaxTotalFrameTime = (ulong)mAverageFrameTime; } else mResetExtents = false; } //----------------------------------------------------------------------- void Profiler::displayResults() { // if its time to update the display if( !( mCurrentFrame % mUpdateDisplayFrequency ) ) { // ensure the root won't be culled mRoot.frame.calls = 1; for( TProfileSessionListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i ) ( *i )->displayResults( mRoot, mMaxTotalFrameTime ); } ++mCurrentFrame; } //----------------------------------------------------------------------- bool Profiler::watchForMax( const String &profileName ) { assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) ); return mRoot.watchForMax( profileName ); } //----------------------------------------------------------------------- bool ProfileInstance::watchForMax( const String &profileName ) { ProfileChildrenVec::iterator it = children.begin(), endit = children.end(); for( ; it != endit; ++it ) { ProfileInstance *child = *it; if( ( child->name == profileName && child->watchForMax() ) || child->watchForMax( profileName ) ) return true; } return false; } //----------------------------------------------------------------------- bool Profiler::watchForMin( const String &profileName ) { assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) ); return mRoot.watchForMin( profileName ); } //----------------------------------------------------------------------- bool ProfileInstance::watchForMin( const String &profileName ) { ProfileChildrenVec::iterator it = children.begin(), endit = children.end(); for( ; it != endit; ++it ) { ProfileInstance *child = *it; if( ( child->name == profileName && child->watchForMin() ) || child->watchForMin( profileName ) ) return true; } return false; } //----------------------------------------------------------------------- bool Profiler::watchForLimit( const String &profileName, Real limit, bool greaterThan ) { assert( ( profileName != "" ) && ( "Profile name can't be an empty string" ) ); return mRoot.watchForLimit( profileName, limit, greaterThan ); } //----------------------------------------------------------------------- bool ProfileInstance::watchForLimit( const String &profileName, Real limit, bool greaterThan ) { ProfileChildrenVec::iterator it = children.begin(), endit = children.end(); for( ; it != endit; ++it ) { ProfileInstance *child = *it; if( ( child->name == profileName && child->watchForLimit( limit, greaterThan ) ) || child->watchForLimit( profileName, limit, greaterThan ) ) return true; } return false; } //----------------------------------------------------------------------- void Profiler::logResults() { LogManager::getSingleton().logMessage( "----------------------Profiler Results----------------------" ); for( ProfileChildrenVec::iterator it = mRoot.children.begin(); it != mRoot.children.end(); ++it ) { ( *it )->logResults(); } LogManager::getSingleton().logMessage( "------------------------------------------------------------" ); } //----------------------------------------------------------------------- void ProfileInstance::logResults() { // create an indent that represents the hierarchical order of the profile String indent = ""; for( uint i = 0; i < hierarchicalLvl; ++i ) { indent = indent + "\t"; } LogManager::getSingleton().logMessage( indent + "Name " + name + " | Min " + StringConverter::toString( history.minTimePercent ) + " | Max " + StringConverter::toString( history.maxTimePercent ) + " | Avg " + StringConverter::toString( history.totalTimePercent / history.totalCalls ) ); for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it ) { ( *it )->logResults(); } } //----------------------------------------------------------------------- void Profiler::reset( bool deleteAll ) { mRoot.reset(); mMaxTotalFrameTime = 0; if( deleteAll ) mRoot.destroyAllChildren(); } //----------------------------------------------------------------------- void ProfileInstance::destroyAllChildren() { for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it ) { ProfileInstance *instance = *it; OGRE_DELETE instance; } children.clear(); childrenMap.clear(); } //----------------------------------------------------------------------- void ProfileInstance::reset() { history.currentTimePercent = history.maxTimePercent = history.totalTimePercent = 0; history.currentTimeMillisecs = history.maxTimeMillisecs = history.totalTimeMillisecs = 0; history.numCallsThisFrame = history.totalCalls = 0; history.minTimePercent = 1; history.minTimeMillisecs = 100000; for( ProfileChildrenVec::iterator it = children.begin(); it != children.end(); ++it ) { ( *it )->reset(); } } //----------------------------------------------------------------------- void Profiler::setUpdateDisplayFrequency( uint freq ) { mUpdateDisplayFrequency = freq; } //----------------------------------------------------------------------- uint Profiler::getUpdateDisplayFrequency() const { return mUpdateDisplayFrequency; } //----------------------------------------------------------------------- void Profiler::addListener( ProfileSessionListener *listener ) { mListeners.push_back( listener ); } //----------------------------------------------------------------------- void Profiler::removeListener( ProfileSessionListener *listener ) { mListeners.erase( std::find( mListeners.begin(), mListeners.end(), listener ) ); } //----------------------------------------------------------------------- } // namespace Ogre
26,635
6,791
/*ArnoldiResearch.cpp This code is used to run Arnoldi's method. */ #include <iostream> #include <string> #include <complex> #include "LinearSpaceSource.h" #include "ArnoldiMC.h" #include "ArnoldiArgs.hpp" #include "RandomLib/Random.hpp" #include "gnuFile.h" #include "gnuplot_i.hpp" #include "CartesianMesh1D.hh" #include "Field.hh" #include "Material.h" #include "HistSource.h" #include "Utilities.h" #include "boost/numeric/ublas/vector.hpp" #include "boost/numeric/ublas/vector_expression.hpp" #include "boost/numeric/bindings/traits/ublas_vector.hpp" #include "boost/numeric/ublas/io.hpp" using std::cout; using std::endl; using std::string; using std::complex; namespace ublas = boost::numeric::ublas; template<class S> Gnuplot& PlotVectors(ArnoldiArgs&, ArnoldiMC<S>&, S&, Gnuplot&, CartesianMesh<OneD>&, gnuFile&); template<> Gnuplot& PlotVectors(ArnoldiArgs& Args, ArnoldiMC<HistSource>& AMC, HistSource& InitialSource, Gnuplot& G, CartesianMesh<OneD>& M, gnuFile& Data){ G.set_style("histeps"); HistSource::ublas_vec_t Centers = InitialSource.Centers(); ArnoldiMC<HistSource>::c_vec_t Mean, SD; ublas::vector<double> mReal, mImag, sReal, sImag; for( int i = 0; i < Args.nEigs.getValue(); ++i ){ std::ostringstream title; title << "RAM l-" << i; AMC.MeanVector(i, Mean, SD); #ifndef NOPLOT G.plot_xy(Centers, real(Mean), title.str()); #endif // Append data to file title.str(""); title << "RAM eigenvector-" << i; Data.append(title.str(), Centers, Mean, SD ); } } Gnuplot& PlotVectors(ArnoldiArgs& Args, ArnoldiMC<LinearSpaceSource>& AMC, LinearSpaceSource& InitialSource, Gnuplot& G, CartesianMesh<OneD>& M, gnuFile& Data){ G.set_style("lines"); ArnoldiMC<HistSource>::c_vec_t Mean, SD; std::vector<double> Slopes, Intercepts; std::vector<double>::iterator sIter; std::vector<double>::iterator iIter; std::vector<double>::iterator mIter; std::vector<double> x,y; for( int i = 0; i < Args.nEigs.getValue(); ++i ){ std::ostringstream title; title << "RAM l-" << i; AMC.MeanVector(i, Mean, SD); // Make LinearSpaceSource from Arnoldi vector LinearSpaceSource LSS(AMC.Seed(), M, real(Mean)); LSS.PlotPoints(x,y); #ifndef NOPLOT G.plot_xy(x,y, title.str() ); #endif // Append data to file title.str(""); title << "RAM eigenvector-" << i; Data.append(title.str(), x,y); } } template<class S> void RunArnoldi(ArnoldiMC<S>& AMC, S& InitialSource, RestartMethod& RM, std::vector<unsigned long>& seed, CartesianMesh<OneD>& SourceMesh, ArnoldiArgs& Args){ AMC.RAM( InitialSource, Args.nEigs.getValue(), Args.Iterations.getValue(), Args.active.getValue(), Args.inactive.getValue(), Args.tracks.getValue(), RM); // Post Processing--------------------------------------------------------- std::ostringstream ChartTitle; ChartTitle << Args.cmdLine() << ", seed = " << seed[0]; std::string Title = ChartTitle.str(); // Make sure Title isn't too long and flow off of chart if( Title.size() > 120 ){ int j = Title.size()/120.0; for( int i = 0; i < j; ++i ){ // Find space after 120-th character int pos = Title.find(" ", (i+1)*120); if( pos > 0 ) Title.insert(pos, "\\n"); } } // Store date in Data gnuFile Data( Args.filename.getValue() ); Data.appendH( Title ); Data.appendH( Args.Args() ); #ifndef NOPLOT // Gnuplot plotting Gnuplot GValues("linespoints"); Gnuplot GVectors("histeps"); Gnuplot GEntropy("lines"); cout << "set terminal " + Args.terminal.getValue() << endl; GValues.cmd("set terminal " + Args.terminal.getValue() ); GVectors.cmd("set terminal " + Args.terminal.getValue() ); GVectors.cmd("set xzeroaxis"); GEntropy.cmd("set terminal " + Args.terminal.getValue() ); // Plot Eigenvalues GValues.set_title("Eigenvalues\\n" + Title ); GValues.set_xlabel("Histories Tracked"); GValues.set_ylabel("Mean Eigenvalues"); #endif std::vector<double> Tracks(AMC.Tracks(true)); std::vector<complex<double> > Mean, SD, Values; std::vector<double> mReal, mImag, sReal, sImag; for( int n = 0; n < Args.nEigs.getValue(); ++n ){ std::ostringstream title; title << "RAM l-" << n; AMC.MeanValues(Mean, SD, n, true); SplitComplexVector(Mean, mReal, mImag); SplitComplexVector(SD, sReal, sImag); #ifndef NOPLOT GValues.plot_xy_err( Tracks, mReal, sReal, title.str()); #endif title.str(""); title << "RAM eigenvalue-" << n; Data.append( title.str(), Tracks, Mean, SD); title.str(""); title << "raw value-0" << n; Values = AMC.Values(n, true); Data.append( title.str(), Tracks, Values ); } #ifndef NOPLOT // Plot Eigenvectors GVectors.set_title("Eigenvectors\\n" + Title ); PlotVectors(Args, AMC, InitialSource, GVectors, SourceMesh, Data); #endif // Get time and store it in Data file std::vector<double> time = AMC.Time(); Data.append("Arnoldi-Time", Tracks, time); // Get FOM and store it in Data file std::vector<double> FOM = AMC.FOM(); std::vector<double> ActiveTracks = AMC.Tracks(false); Data.append("FOM-Arnoldi", ActiveTracks, FOM); // Plot and store Entropy GEntropy.set_title("Entropy\\n" + Title ); std::vector<double> Entropy = AMC.Entropy(true); std::vector<double> IterationsTracks = AMC.TracksbyIteration(true); GEntropy.plot_xy( IterationsTracks, Entropy, "Entropy-Iterations"); Data.append("Entropy-Iterations", IterationsTracks, Entropy ); Entropy = AMC.EntropyRestart(true); GEntropy.plot_xy( Tracks, Entropy, "Entropy-Restarts"); Data.append("Entropy-Restarts", Tracks, Entropy ); } int main(int argc, char** argv){ cout << "Running ArnoldiResearch." << endl; try{ ArnoldiArgs Args("Arnoldi will run Arnoldi's method."); // Problem specific arguments // What Arnoldi methods are allowed // std::vector<string> AllowedMethods; // AllowedMethods.push_back("implicit"); AllowedMethods.push_back("explicit"); // TCLAP::ValuesConstraint<string> MethodAllow(AllowedMethods); // TCLAP::ValueArg<string> method("m", "method", "Restart Method", false, // "explicit","m"); // method.Constrain(&MethodAllow); // Args.cmd.add(method); // What Source types are allowed std::vector<string> AllowedSources; AllowedSources.push_back("Histogram"); AllowedSources.push_back("Linear"); TCLAP::ValuesConstraint<string> SourceAllow(AllowedSources); TCLAP::ValueArg<string> source("c", "source", "Fission Source Type", false, "Histogram", "c"); source.Constrain(&SourceAllow); Args.cmd.add(source); // Parse command line arguments Args.Parse(argc,argv); cout << "\n" << Args << endl; if( Args.run.getValue() ){ cout << "Running Arnoldi's Method" << endl; // // Set random seed std::vector<unsigned long> seed(2, 1); if( not Args.seed.getValue() ) seed[0] = RandomLib::Random::SeedWord(); else seed[0] = Args.seed.getValue(); cout << "Master seed: " << seed[0] << endl; // Material from Rathkopf and Martin (1986) // Material Absorber(0.5,0.5,0.0,1.0); // Absorbing // Material from Modak et al. (1995) Material Absorber(0.8,0.2,0.0,5.0); // Absorbing // Set up materials std::vector<double> ZoneWidths; ublas::vector<Material> Media; if( Args.MultiMedia.getValue() ){ // 5 slab problem from Ueki and Brown (2005) ZoneWidths.push_back(1.0); ZoneWidths.push_back(1.0); ZoneWidths.push_back(5.0); ZoneWidths.push_back(1.0); ZoneWidths.push_back(1.0); Material Scatter( 0.8, 0.0, 0.2, 0.0 ); Material Fuel( 0.8, 0.1, 0.1, 3.0 ); Material Absorber( 0.1, 0.0, 0.9, 0.0 ); Media.resize(5); Media[0] = Fuel; Media[1] = Scatter; Media[2] = Absorber; Media[3] = Scatter; Media[4] = Fuel; } else{ // One zone ZoneWidths.push_back( Args.width.getValue() ); Media.resize(1); Media[0] = Absorber; } // Geometry CartesianMesh<OneD> GeometryMesh( ZoneWidths ); Field<Zone<OneD>, Material, ublas::vector<Material> > GeometryField(GeometryMesh, Media); cout << "Materials:\n"; for( int i = 0; i < Media.size(); ++i ){ cout << Media[i] << endl; } // Restart Method RestartMethod RM = EXPLICIT; // Initial Uniform Source double totalWidth; totalWidth = std::accumulate(ZoneWidths.begin(), ZoneWidths.end(), 0.0); CartesianMesh<OneD> SourceMesh(totalWidth, 1.0, Args.bins.getValue()); if( source.getValue() == "Histogram" ){ ublas::vector<double, std::vector<double> > Probabilities(Args.bins.getValue(), 0.0); Probabilities[0] = 1.0; // Make initial source point source if two-media problem if( Args.MultiMedia.getValue() ){ // Multi-media problem Probabilities *= 0.0; Probabilities[0] = 1.0; } HistSource InitialSource(seed, SourceMesh, Probabilities); ArnoldiMC<HistSource> AMC(seed, GeometryField, SourceMesh, Args.relaxed.getValue(), Args.verbose.getValue(), Args.tolerance.getValue() ); RunArnoldi(AMC, InitialSource, RM, seed, SourceMesh, Args); } else if( source.getValue() == "Linear" ){ ublas::vector<double> S(SourceMesh.numZones(), 0.0); ublas::vector<double> I(SourceMesh.numZones(), 0.0); I[0] = 1.0; // Make initial source point source if two-media problem if( Args.MultiMedia.getValue() ){ // Multi-media problem I *= 0.0; I[0] = 1.0; } LinearSpaceSource InitialSource(S, I, SourceMesh, seed); ArnoldiMC<LinearSpaceSource> AMC(seed, GeometryField, SourceMesh, Args.relaxed.getValue(), Args.verbose.getValue(), Args.tolerance.getValue() ); RunArnoldi(AMC, InitialSource, RM, seed, SourceMesh, Args); } } } catch (TCLAP::ArgException &e){ std::cerr << "error: " << e.error() << " for arg " << e.argId() << endl; return 1; } return 0; }
10,792
3,749
#include <iostream> #include <climits> #include <cmath> using namespace std; int main(){ const int N = 7; int dp[N]; int M = 30; int cost[N][N]; int G[N]; for(int i = 0; i < N; ++i){ cin >> G[i]; } int temp; for(int i = 0; i < N; ++i){ for(int j = i; j < N; ++j){ if(i == j) cost[i][j] = G[j]; else cost[i][j] = cost[i][j - 1] + G[j] + 1; } } int last; for(int i = 0; i < N; ++i){ dp[i] = INT_MAX; for(int j = 0; j <= i; ++j){ if(cost[j][i] > M){ temp = INT_MAX; continue; } else if(i == N - 1){ temp = j == 0? 0 : dp[j - 1]; } else if(j == 0){ temp = M - cost[j][i]; } else{ temp = dp[j - 1] + M - cost[j][i]; } if(temp < dp[i]){ dp[i] = temp; last = j; } } } cout << dp[N - 1] << endl; return 0; }
1,099
425
// Copyright 2016 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 "third_party/blink/renderer/core/events/visual_viewport_scroll_event.h" #include "third_party/blink/renderer/core/frame/use_counter.h" namespace blink { VisualViewportScrollEvent::~VisualViewportScrollEvent() = default; VisualViewportScrollEvent::VisualViewportScrollEvent() : Event(EventTypeNames::scroll, Bubbles::kNo, Cancelable::kNo) {} void VisualViewportScrollEvent::DoneDispatchingEventAtCurrentTarget() { UseCounter::Count(currentTarget()->GetExecutionContext(), WebFeature::kVisualViewportScrollFired); } } // namespace blink
743
227
#include "couchview.h" #include "couchclient.h" #include "couchdatabase.h" #include "couchdesigndocument.h" #include "couchrequest.h" #include "couchresponse.h" class CouchViewPrivate { Q_DECLARE_PUBLIC(CouchView) public: CouchResponse *response(CouchResponse *response) { Q_Q(CouchView); QObject::connect(response, &CouchResponse::errorOccurred, [=](const CouchError &error) { emit q->errorOccurred(error); }); return response; } CouchView *q_ptr = nullptr; QString name; CouchDesignDocument *designDocument = nullptr; }; CouchView::CouchView(QObject *parent) : CouchView(QString(), nullptr, parent) { } CouchView::CouchView(const QString &name, CouchDesignDocument *designDocument, QObject *parent) : QObject(parent), d_ptr(new CouchViewPrivate) { Q_D(CouchView); d->q_ptr = this; d->name = name; setDesignDocument(designDocument); } CouchView::~CouchView() { } QUrl CouchView::url() const { Q_D(const CouchView); if (!d->designDocument || d->name.isEmpty()) return QUrl(); return Couch::viewUrl(d->designDocument->url(), d->name); } QString CouchView::name() const { Q_D(const CouchView); return d->name; } void CouchView::setName(const QString &name) { Q_D(CouchView); if (d->name == name) return; d->name = name; emit urlChanged(url()); emit nameChanged(name); } CouchClient *CouchView::client() const { Q_D(const CouchView); if (!d->designDocument) return nullptr; return d->designDocument->client(); } CouchDatabase *CouchView::database() const { Q_D(const CouchView); if (!d->designDocument) return nullptr; return d->designDocument->database(); } CouchDesignDocument *CouchView::designDocument() const { Q_D(const CouchView); return d->designDocument; } void CouchView::setDesignDocument(CouchDesignDocument *designDocument) { Q_D(CouchView); if (d->designDocument == designDocument) return; QUrl oldUrl = url(); CouchClient *oldClient = client(); CouchDatabase *oldDatabase = database(); if (d->designDocument) d->designDocument->disconnect(this); if (designDocument) { connect(designDocument, &CouchDesignDocument::urlChanged, this, &CouchView::urlChanged); connect(designDocument, &CouchDesignDocument::clientChanged, this, &CouchView::clientChanged); connect(designDocument, &CouchDesignDocument::databaseChanged, this, &CouchView::databaseChanged); } d->designDocument = designDocument; if (oldUrl != url()) emit urlChanged(url()); if (oldClient != client()) emit clientChanged(client()); if (oldDatabase != database()) emit databaseChanged(database()); emit designDocumentChanged(designDocument); } CouchResponse *CouchView::listRowIds() { return queryRows(CouchQuery()); } CouchResponse *CouchView::listFullRows() { return queryRows(CouchQuery::full()); } CouchResponse *CouchView::queryRows(const CouchQuery &query) { Q_D(CouchView); CouchClient *client = d->designDocument ? d->designDocument->client() : nullptr; if (!client) return nullptr; CouchRequest request = Couch::queryRows(url(), query); CouchResponse *response = client->sendRequest(request); if (!response) return nullptr; connect(response, &CouchResponse::received, [=](const QByteArray &data) { emit rowsListed(Couch::toDocumentList(data)); }); return d->response(response); }
3,573
1,164
#include "gearpch.h" #include "VertexBuffer.h" #include <glad/glad.h> VertexBuffer::VertexBuffer(const void* data, unsigned int size) { glGenBuffers(1, &m_RendererId); glBindBuffer(GL_ARRAY_BUFFER, m_RendererId); glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); } VertexBuffer::~VertexBuffer() { glDeleteBuffers(1, &m_RendererId); } void VertexBuffer::bind() const { glBindBuffer(GL_ARRAY_BUFFER, m_RendererId); } void VertexBuffer::unbind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); }
506
205
/*Copyright of Ashikul Hosen */ #include <iostream> #include <vector> int main(int argc, char *argv[]) { std::cout << "abada\n"; std::vector<int> vi; vi.push_back(10); vi.push_back(); for (auto it = vi.begin(); it != vi.end(); ++it) { std::cout << *it << "\n"; } return 0; }
297
126
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "DirectoryWatcherPrivatePCH.h" FDirectoryWatcherWindows::FDirectoryWatcherWindows() { NumRequests = 0; } FDirectoryWatcherWindows::~FDirectoryWatcherWindows() { if ( RequestMap.Num() != 0 ) { // Delete any remaining requests here. These requests are likely from modules which are still loaded at the time that this module unloads. for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(RequestMap); RequestIt; ++RequestIt) { if ( ensure(RequestIt.Value()) ) { // make sure we end the watch request, as we may get a callback if a request is in flight RequestIt.Value()->EndWatchRequest(); delete RequestIt.Value(); NumRequests--; } } RequestMap.Empty(); } if ( RequestsPendingDelete.Num() != 0 ) { for ( int32 RequestIdx = 0; RequestIdx < RequestsPendingDelete.Num(); ++RequestIdx ) { delete RequestsPendingDelete[RequestIdx]; NumRequests--; } } // Make sure every request that was created is destroyed ensure(NumRequests == 0); } bool FDirectoryWatcherWindows::RegisterDirectoryChangedCallback_Handle( const FString& Directory, const FDirectoryChanged& InDelegate, FDelegateHandle& Handle, uint32 Flags ) { FDirectoryWatchRequestWindows** RequestPtr = RequestMap.Find(Directory); FDirectoryWatchRequestWindows* Request = NULL; if ( RequestPtr ) { // There should be no NULL entries in the map check (*RequestPtr); Request = *RequestPtr; } else { Request = new FDirectoryWatchRequestWindows(Flags); NumRequests++; // Begin reading directory changes if ( !Request->Init(Directory) ) { uint32 Error = GetLastError(); UE_LOG(LogDirectoryWatcher, Warning, TEXT("Failed to begin reading directory changes for %s. Error: %d"), *Directory, Error); delete Request; NumRequests--; return false; } RequestMap.Add(Directory, Request); } Handle = Request->AddDelegate(InDelegate); return true; } bool FDirectoryWatcherWindows::UnregisterDirectoryChangedCallback_Handle( const FString& Directory, FDelegateHandle InHandle ) { FDirectoryWatchRequestWindows** RequestPtr = RequestMap.Find(Directory); if ( RequestPtr ) { // There should be no NULL entries in the map check (*RequestPtr); FDirectoryWatchRequestWindows* Request = *RequestPtr; if ( Request->RemoveDelegate(InHandle) ) { if ( !Request->HasDelegates() ) { // Remove from the active map and add to the pending delete list RequestMap.Remove(Directory); RequestsPendingDelete.AddUnique(Request); // Signal to end the watch which will mark this request for deletion Request->EndWatchRequest(); } return true; } } return false; } void FDirectoryWatcherWindows::Tick( float DeltaSeconds ) { TArray<HANDLE> DirectoryHandles; TMap<FString, FDirectoryWatchRequestWindows*> InvalidRequestsToDelete; // Find all handles to listen to and invalid requests to delete for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(RequestMap); RequestIt; ++RequestIt) { if ( RequestIt.Value()->IsPendingDelete() ) { InvalidRequestsToDelete.Add(RequestIt.Key(), RequestIt.Value()); } else { DirectoryHandles.Add(RequestIt.Value()->GetDirectoryHandle()); } } // Remove all invalid requests from the request map and add them to the pending delete list so they will be deleted below for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(InvalidRequestsToDelete); RequestIt; ++RequestIt) { RequestMap.Remove(RequestIt.Key()); RequestsPendingDelete.AddUnique(RequestIt.Value()); } // Trigger any file changed delegates that are queued up if ( DirectoryHandles.Num() > 0 ) { MsgWaitForMultipleObjectsEx(DirectoryHandles.Num(), DirectoryHandles.GetData(), 0, QS_ALLEVENTS, MWMO_ALERTABLE); } // Delete any stale or invalid requests for ( int32 RequestIdx = RequestsPendingDelete.Num() - 1; RequestIdx >= 0; --RequestIdx ) { FDirectoryWatchRequestWindows* Request = RequestsPendingDelete[RequestIdx]; if ( Request->IsPendingDelete() ) { // This request is safe to delete. Delete and remove it from the list delete Request; NumRequests--; RequestsPendingDelete.RemoveAt(RequestIdx); } } // Finally, trigger any file change notification delegates for (TMap<FString, FDirectoryWatchRequestWindows*>::TConstIterator RequestIt(RequestMap); RequestIt; ++RequestIt) { RequestIt.Value()->ProcessPendingNotifications(); } }
4,517
1,493
/******************************************************************************* * a_recoei.cpp * *-------------* * Description: * This module is the main implementation file for the CSpeechRecoEventInterests * automation methods. *------------------------------------------------------------------------------- * Created By: Leonro Date: 11/20/00 * Copyright (C) 2000 Microsoft Corporation * All Rights Reserved * *******************************************************************************/ //--- Additional includes #include "stdafx.h" #include "a_recoei.h" #ifdef SAPI_AUTOMATION /***************************************************************************** * CSpeechRecoEventInterests::FinalRelease * *------------------------* * Description: * destructor ********************************************************************* Leonro ***/ void CSpeechRecoEventInterests::FinalRelease() { SPDBG_FUNC( "CSpeechRecoEventInterests::FinalRelease" ); if( m_pCRecoCtxt ) { m_pCRecoCtxt->Release(); m_pCRecoCtxt = NULL; } } /* CSpeechRecoEventInterests::FinalRelease */ // //=== ICSpeechRecoEventInterests interface ================================================== // /***************************************************************************** * CSpeechRecoEventInterests::put_StreamEnd * *----------------------------------* * * This method enables and disables the interest in the SPEI_END_SR_STREAM event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_StreamEnd( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_StreamEnd" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); ULONGLONG test = SPFEI_ALL_SR_EVENTS; if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_END_SR_STREAM); } else { ullInterest &= ~(1ui64 << SPEI_END_SR_STREAM); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_StreamEnd */ /***************************************************************************** * CSpeechRecoEventInterests::get_StreamEnd * *----------------------------------* * * This method determines whether or not the SPEI_END_SR_STREAM interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_StreamEnd( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_StreamEnd" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_END_SR_STREAM) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_StreamEnd */ /***************************************************************************** * CSpeechRecoEventInterests::put_SoundStart * *----------------------------------* * * This method enables and disables the interest in the SPEI_SOUND_START event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_SoundStart( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_SoundStart" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_SOUND_START); } else { ullInterest &= ~(1ui64 << SPEI_SOUND_START); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_SoundStart */ /***************************************************************************** * CSpeechRecoEventInterests::get_SoundStart * *----------------------------------* * * This method determines whether or not the SPEI_SOUND_START interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_SoundStart( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_SoundStart" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_SOUND_START) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_SoundStart */ /***************************************************************************** * CSpeechRecoEventInterests::put_SoundEnd * *----------------------------------* * * This method enables and disables the interest in the SPEI_SOUND_END event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_SoundEnd( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_SoundEnd" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_SOUND_END); } else { ullInterest &= ~(1ui64 << SPEI_SOUND_END); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_SoundEnd */ /***************************************************************************** * CSpeechRecoEventInterests::get_SoundEnd * *----------------------------------* * * This method determines whether or not the SPEI_SOUND_END interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_SoundEnd( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_SoundEnd" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_SOUND_END) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_SoundEnd */ /***************************************************************************** * CSpeechRecoEventInterests::put_PhraseStart * *----------------------------------* * * This method enables and disables the interest in the SPEI_PHRASE_START event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_PhraseStart( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_PhraseStart" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_PHRASE_START); } else { ullInterest &= ~(1ui64 << SPEI_PHRASE_START); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_PhraseStart */ /***************************************************************************** * CSpeechRecoEventInterests::get_PhraseStart * *----------------------------------* * * This method determines whether or not the SPEI_PHRASE_START interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_PhraseStart( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_PhraseStart" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_PHRASE_START) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_PhraseStart */ /***************************************************************************** * CSpeechRecoEventInterests::put_Recognition * *----------------------------------* * * This method enables and disables the interest in the SPEI_RECOGNITION event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_Recognition( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_Recognition" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_RECOGNITION); } else { ullInterest &= ~(1ui64 << SPEI_RECOGNITION); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_Recognition */ /***************************************************************************** * CSpeechRecoEventInterests::get_Recognition * *----------------------------------* * * This method determines whether or not the SPEI_RECOGNITION interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_Recognition( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_Recognition" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_RECOGNITION) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_Recognition */ /***************************************************************************** * CSpeechRecoEventInterests::put_Hypothesis * *----------------------------------* * * This method enables and disables the interest in the SPEI_HYPOTHESIS event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_Hypothesis( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_Hypothesis" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_HYPOTHESIS); } else { ullInterest &= ~(1ui64 << SPEI_HYPOTHESIS); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_Hypothesis */ /***************************************************************************** * CSpeechRecoEventInterests::get_Hypothesis * *----------------------------------* * * This method determines whether or not the SPEI_HYPOTHESIS interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_Hypothesis( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_Hypothesis" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_HYPOTHESIS) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_Hypothesis */ /***************************************************************************** * CSpeechRecoEventInterests::put_Bookmark * *----------------------------------* * * This method enables and disables the interest in the SPEI_SR_BOOKMARK event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_Bookmark( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_Bookmark" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_SR_BOOKMARK); } else { ullInterest &= ~(1ui64 << SPEI_SR_BOOKMARK); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_Bookmark */ /***************************************************************************** * CSpeechRecoEventInterests::get_Bookmark * *----------------------------------* * * This method determines whether or not the SPEI_SR_BOOKMARK interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_Bookmark( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_Bookmark" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_SR_BOOKMARK) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_Bookmark */ /***************************************************************************** * CSpeechRecoEventInterests::put_PropertyNumChange * *----------------------------------* * * This method enables and disables the interest in the SPEI_PROPERTY_NUM_CHANGE event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_PropertyNumChange( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_PropertyNumChange" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_PROPERTY_NUM_CHANGE); } else { ullInterest &= ~(1ui64 << SPEI_PROPERTY_NUM_CHANGE); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_PropertyNumChange */ /***************************************************************************** * CSpeechRecoEventInterests::get_PropertyNumChange * *----------------------------------* * * This method determines whether or not the SPEI_PROPERTY_NUM_CHANGE interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_PropertyNumChange( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_PropertyNumChange" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_PROPERTY_NUM_CHANGE) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_PropertyNumChange */ /***************************************************************************** * CSpeechRecoEventInterests::put_PropertyStringChange * *----------------------------------* * * This method enables and disables the interest in the SPEI_PROPERTY_STRING_CHANGE event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_PropertyStringChange( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_PropertyStringChange" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_PROPERTY_STRING_CHANGE); } else { ullInterest &= ~(1ui64 << SPEI_PROPERTY_STRING_CHANGE); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_PropertyStringChange */ /***************************************************************************** * CSpeechRecoEventInterests::get_PropertyStringChange * *----------------------------------* * * This method determines whether or not the SPEI_PROPERTY_STRING_CHANGE interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_PropertyStringChange( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_PropertyStringChange" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_PROPERTY_STRING_CHANGE) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_PropertyStringChange */ /***************************************************************************** * CSpeechRecoEventInterests::put_FalseRecognition * *----------------------------------* * * This method enables and disables the interest in the SPEI_FALSE_RECOGNITION event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_FalseRecognition( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_FalseRecognition" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_FALSE_RECOGNITION); } else { ullInterest &= ~(1ui64 << SPEI_FALSE_RECOGNITION); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_FalseRecognition */ /***************************************************************************** * CSpeechRecoEventInterests::get_FalseRecognition * *----------------------------------* * * This method determines whether or not the SPEI_FALSE_RECOGNITION interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_FalseRecognition( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_FalseRecognition" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_FALSE_RECOGNITION) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_FalseRecognition */ /***************************************************************************** * CSpeechRecoEventInterests::put_Interference * *----------------------------------* * * This method enables and disables the interest in the SPEI_INTERFERENCE event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_Interference( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_Interference" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_INTERFERENCE); } else { ullInterest &= ~(1ui64 << SPEI_INTERFERENCE); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_Interference */ /***************************************************************************** * CSpeechRecoEventInterests::get_Interference * *----------------------------------* * * This method determines whether or not the SPEI_INTERFERENCE interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_Interference( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_Interference" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_INTERFERENCE) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_Interference */ /***************************************************************************** * CSpeechRecoEventInterests::put_RequestUI * *----------------------------------* * * This method enables and disables the interest in the SPEI_REQUEST_UI event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_RequestUI( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_RequestUI" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_REQUEST_UI); } else { ullInterest &= ~(1ui64 << SPEI_REQUEST_UI); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_RequestUI */ /***************************************************************************** * CSpeechRecoEventInterests::get_RequestUI * *----------------------------------* * * This method determines whether or not the SPEI_REQUEST_UI interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_RequestUI( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_RequestUI" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_REQUEST_UI) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_RequestUI */ /***************************************************************************** * CSpeechRecoEventInterests::put_StateChange * *----------------------------------* * * This method enables and disables the interest in the SPEI_RECO_STATE_CHANGE event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_StateChange( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_StateChange" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_RECO_STATE_CHANGE); } else { ullInterest &= ~(1ui64 << SPEI_RECO_STATE_CHANGE); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_StateChange */ /***************************************************************************** * CSpeechRecoEventInterests::get_StateChange * *----------------------------------* * * This method determines whether or not the SPEI_RECO_STATE_CHANGE interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_StateChange( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_StateChange" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_RECO_STATE_CHANGE) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_StateChange */ /***************************************************************************** * CSpeechRecoEventInterests::put_Adaptation * *----------------------------------* * * This method enables and disables the interest in the SPEI_ADAPTATION event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_Adaptation( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_Adaptation" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_ADAPTATION); } else { ullInterest &= ~(1ui64 << SPEI_ADAPTATION); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_Adaptation */ /***************************************************************************** * CSpeechRecoEventInterests::get_Adaptation * *----------------------------------* * * This method determines whether or not the SPEI_ADAPTATION interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_Adaptation( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_Adaptation" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_ADAPTATION) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_Adaptation */ /***************************************************************************** * CSpeechRecoEventInterests::put_StreamStart * *----------------------------------* * * This method enables and disables the interest in the SPEI_START_SR_STREAM event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_StreamStart( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_StreamStart" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_START_SR_STREAM); } else { ullInterest &= ~(1ui64 << SPEI_START_SR_STREAM); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_StreamStart */ /***************************************************************************** * CSpeechRecoEventInterests::get_StreamStart * *----------------------------------* * * This method determines whether or not the SPEI_START_SR_STREAM interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_StreamStart( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_StreamStart" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_START_SR_STREAM) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_StreamStart */ /***************************************************************************** * CSpeechRecoEventInterests::put_OtherContext * *----------------------------------* * * This method enables and disables the interest in the SPEI_RECO_OTHER_CONTEXT event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_OtherContext( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_OtherContext" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_RECO_OTHER_CONTEXT); } else { ullInterest &= ~(1ui64 << SPEI_RECO_OTHER_CONTEXT); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_OtherContext */ /***************************************************************************** * CSpeechRecoEventInterests::get_OtherContext * *----------------------------------* * * This method determines whether or not the SPEI_RECO_OTHER_CONTEXT interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_OtherContext( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_OtherContext" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_RECO_OTHER_CONTEXT) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_OtherContext */ /***************************************************************************** * CSpeechRecoEventInterests::put_AudioLevel * *----------------------------------* * * This method enables and disables the interest in the SPEI_SR_AUDIO_LEVEL event on * the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::put_AudioLevel( VARIANT_BOOL Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::put_AudioLevel" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( Enabled ) { ullInterest |= (1ui64 << SPEI_SR_AUDIO_LEVEL); } else { ullInterest &= ~(1ui64 << SPEI_SR_AUDIO_LEVEL); } hr = m_pCRecoCtxt->SetInterest( ullInterest, ullInterest ); } return hr; } /* CSpeechRecoEventInterests::put_AudioLevel */ /***************************************************************************** * CSpeechRecoEventInterests::get_AudioLevel * *----------------------------------* * * This method determines whether or not the SPFEI(SPEI_SR_AUDIO_LEVEL interest is * enabled on the Reco Context object. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::get_AudioLevel( VARIANT_BOOL* Enabled ) { SPDBG_FUNC( "CSpeechRecoEventInterests::get_AudioLevel" ); ULONGLONG ullInterest = 0; HRESULT hr = S_OK; if( SP_IS_BAD_WRITE_PTR( Enabled ) ) { hr = E_POINTER; } else { hr = m_pCRecoCtxt->GetInterests( &ullInterest, NULL ); if( SUCCEEDED( hr ) ) { if( ullInterest & (1ui64 << SPEI_SR_AUDIO_LEVEL) ) { *Enabled = VARIANT_TRUE; } else { *Enabled = VARIANT_FALSE; } } } return hr; } /* CSpeechRecoEventInterests::get_AudioLevel */ /***************************************************************************** * CSpeechRecoEventInterests::SetAll * *----------------------------------* * * This method sets all the interests on the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::SetAll() { SPDBG_FUNC( "CSpeechRecoEventInterests::SetAll" ); HRESULT hr = S_OK; hr = m_pCRecoCtxt->SetInterest( SPFEI_ALL_SR_EVENTS, SPFEI_ALL_SR_EVENTS ); return hr; } /* CSpeechRecoEventInterests::SetAll */ /***************************************************************************** * CSpeechRecoEventInterests::ClearAll * *----------------------------------* * * This method clears all the interests on the Reco Context. * ********************************************************************* Leonro ***/ STDMETHODIMP CSpeechRecoEventInterests::ClearAll() { SPDBG_FUNC( "CSpeechRecoEventInterests::ClearAll" ); HRESULT hr = S_OK; hr = m_pCRecoCtxt->SetInterest( 0, 0 ); return hr; } /* CSpeechRecoEventInterests::ClearAll */ #endif // SAPI_AUTOMATION
38,971
13,216
// Copyright 2018 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 "ui/ozone/platform/scenic/scenic_surface_factory.h" #include <lib/sys/cpp/component_context.h> #include <lib/zx/event.h> #include <memory> #include "base/bind.h" #include "base/containers/contains.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/fuchsia/process_context.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "third_party/angle/src/common/fuchsia_egl/fuchsia_egl.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/native_pixmap.h" #include "ui/gfx/vsync_provider.h" #include "ui/gl/gl_surface_egl.h" #include "ui/ozone/common/egl_util.h" #include "ui/ozone/common/gl_ozone_egl.h" #include "ui/ozone/platform/scenic/scenic_gpu_service.h" #include "ui/ozone/platform/scenic/scenic_surface.h" #include "ui/ozone/platform/scenic/scenic_window.h" #include "ui/ozone/platform/scenic/scenic_window_canvas.h" #include "ui/ozone/platform/scenic/scenic_window_manager.h" #include "ui/ozone/platform/scenic/sysmem_buffer_collection.h" #if BUILDFLAG(ENABLE_VULKAN) #include "ui/ozone/platform/scenic/vulkan_implementation_scenic.h" #endif namespace ui { namespace { struct FuchsiaEGLWindowDeleter { void operator()(fuchsia_egl_window* egl_window) { fuchsia_egl_window_destroy(egl_window); } }; fuchsia::ui::scenic::ScenicPtr ConnectToScenic() { fuchsia::ui::scenic::ScenicPtr scenic = base::ComponentContextForProcess() ->svc() ->Connect<fuchsia::ui::scenic::Scenic>(); scenic.set_error_handler( base::LogFidlErrorAndExitProcess(FROM_HERE, "fuchsia.ui.scenic.Scenic")); return scenic; } class GLSurfaceFuchsiaImagePipe : public gl::NativeViewGLSurfaceEGL { public: explicit GLSurfaceFuchsiaImagePipe( ScenicSurfaceFactory* scenic_surface_factory, gfx::AcceleratedWidget widget) : NativeViewGLSurfaceEGL(0, nullptr), scenic_surface_factory_(scenic_surface_factory), widget_(widget) {} GLSurfaceFuchsiaImagePipe(const GLSurfaceFuchsiaImagePipe&) = delete; GLSurfaceFuchsiaImagePipe& operator=(const GLSurfaceFuchsiaImagePipe&) = delete; // gl::NativeViewGLSurfaceEGL: bool InitializeNativeWindow() override { fuchsia::images::ImagePipe2Ptr image_pipe; ScenicSurface* scenic_surface = scenic_surface_factory_->GetSurface(widget_); scenic_surface->SetTextureToNewImagePipe(image_pipe.NewRequest()); egl_window_.reset( fuchsia_egl_window_create(image_pipe.Unbind().TakeChannel().release(), size_.width(), size_.height())); window_ = reinterpret_cast<EGLNativeWindowType>(egl_window_.get()); return true; } bool Resize(const gfx::Size& size, float scale_factor, const gfx::ColorSpace& color_space, bool has_alpha) override { fuchsia_egl_window_resize(egl_window_.get(), size.width(), size.height()); return gl::NativeViewGLSurfaceEGL::Resize(size, scale_factor, color_space, has_alpha); } private: ~GLSurfaceFuchsiaImagePipe() override {} ScenicSurfaceFactory* const scenic_surface_factory_; gfx::AcceleratedWidget widget_ = gfx::kNullAcceleratedWidget; std::unique_ptr<fuchsia_egl_window, FuchsiaEGLWindowDeleter> egl_window_; }; class GLOzoneEGLScenic : public GLOzoneEGL { public: explicit GLOzoneEGLScenic(ScenicSurfaceFactory* scenic_surface_factory) : scenic_surface_factory_(scenic_surface_factory) {} GLOzoneEGLScenic(const GLOzoneEGLScenic&) = delete; GLOzoneEGLScenic& operator=(const GLOzoneEGLScenic&) = delete; ~GLOzoneEGLScenic() override = default; // GLOzone: scoped_refptr<gl::GLSurface> CreateViewGLSurface( gfx::AcceleratedWidget window) override { return gl::InitializeGLSurface( base::MakeRefCounted<GLSurfaceFuchsiaImagePipe>(scenic_surface_factory_, window)); } scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface( const gfx::Size& size) override { return gl::InitializeGLSurface( base::MakeRefCounted<gl::SurfacelessEGL>(size)); } gl::EGLDisplayPlatform GetNativeDisplay() override { return gl::EGLDisplayPlatform(EGL_DEFAULT_DISPLAY); } protected: bool LoadGLES2Bindings( const gl::GLImplementationParts& implementation) override { return LoadDefaultEGLGLES2Bindings(implementation); } private: ScenicSurfaceFactory* const scenic_surface_factory_; }; fuchsia::sysmem::AllocatorHandle ConnectSysmemAllocator() { fuchsia::sysmem::AllocatorHandle allocator; base::ComponentContextForProcess()->svc()->Connect(allocator.NewRequest()); return allocator; } } // namespace ScenicSurfaceFactory::ScenicSurfaceFactory() : egl_implementation_(std::make_unique<GLOzoneEGLScenic>(this)), sysmem_buffer_manager_(this), weak_ptr_factory_(this) {} ScenicSurfaceFactory::~ScenicSurfaceFactory() { Shutdown(); } void ScenicSurfaceFactory::Initialize( mojo::PendingRemote<mojom::ScenicGpuHost> gpu_host) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); base::AutoLock lock(surface_lock_); DCHECK(surface_map_.empty()); main_thread_task_runner_ = base::ThreadTaskRunnerHandle::Get(); DCHECK(main_thread_task_runner_); DCHECK(!gpu_host_); gpu_host_.Bind(std::move(gpu_host)); sysmem_buffer_manager_.Initialize(ConnectSysmemAllocator()); // Scenic is lazily connected to avoid a dependency in headless mode. DCHECK(!scenic_); } void ScenicSurfaceFactory::Shutdown() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); base::AutoLock lock(surface_lock_); DCHECK(surface_map_.empty()); main_thread_task_runner_ = nullptr; gpu_host_.reset(); sysmem_buffer_manager_.Shutdown(); scenic_ = nullptr; } std::vector<gl::GLImplementationParts> ScenicSurfaceFactory::GetAllowedGLImplementations() { return std::vector<gl::GLImplementationParts>{ gl::GLImplementationParts(gl::kGLImplementationEGLANGLE), gl::GLImplementationParts(gl::kGLImplementationSwiftShaderGL), gl::GLImplementationParts(gl::kGLImplementationEGLGLES2), gl::GLImplementationParts(gl::kGLImplementationStubGL), }; } GLOzone* ScenicSurfaceFactory::GetGLOzone( const gl::GLImplementationParts& implementation) { switch (implementation.gl) { case gl::kGLImplementationSwiftShaderGL: case gl::kGLImplementationEGLGLES2: case gl::kGLImplementationEGLANGLE: return egl_implementation_.get(); default: return nullptr; } } std::unique_ptr<PlatformWindowSurface> ScenicSurfaceFactory::CreatePlatformWindowSurface( gfx::AcceleratedWidget window) { DCHECK_NE(window, gfx::kNullAcceleratedWidget); auto surface = std::make_unique<ScenicSurface>(this, &sysmem_buffer_manager_, window, CreateScenicSession()); main_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ScenicSurfaceFactory::AttachSurfaceToWindow, weak_ptr_factory_.GetWeakPtr(), window, surface->CreateView())); return surface; } std::unique_ptr<SurfaceOzoneCanvas> ScenicSurfaceFactory::CreateCanvasForWidget( gfx::AcceleratedWidget widget) { ScenicSurface* surface = GetSurface(widget); return std::make_unique<ScenicWindowCanvas>(surface); } scoped_refptr<gfx::NativePixmap> ScenicSurfaceFactory::CreateNativePixmap( gfx::AcceleratedWidget widget, VkDevice vk_device, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, absl::optional<gfx::Size> framebuffer_size) { DCHECK(!framebuffer_size || framebuffer_size == size); if (widget != gfx::kNullAcceleratedWidget && usage == gfx::BufferUsage::SCANOUT) { // The usage SCANOUT is for a primary plane buffer. auto* surface = GetSurface(widget); CHECK(surface); return surface->AllocatePrimaryPlanePixmap(vk_device, size, format); } auto collection = sysmem_buffer_manager_.CreateCollection(vk_device, size, format, usage, 1); if (!collection) return nullptr; return collection->CreateNativePixmap(0); } void ScenicSurfaceFactory::CreateNativePixmapAsync( gfx::AcceleratedWidget widget, VkDevice vk_device, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, NativePixmapCallback callback) { std::move(callback).Run( CreateNativePixmap(widget, vk_device, size, format, usage)); } #if BUILDFLAG(ENABLE_VULKAN) std::unique_ptr<gpu::VulkanImplementation> ScenicSurfaceFactory::CreateVulkanImplementation(bool use_swiftshader, bool allow_protected_memory) { return std::make_unique<ui::VulkanImplementationScenic>( this, &sysmem_buffer_manager_, allow_protected_memory); } #endif void ScenicSurfaceFactory::AddSurface(gfx::AcceleratedWidget widget, ScenicSurface* surface) { base::AutoLock lock(surface_lock_); DCHECK(!base::Contains(surface_map_, widget)); surface->AssertBelongsToCurrentThread(); surface_map_.emplace(widget, surface); } void ScenicSurfaceFactory::RemoveSurface(gfx::AcceleratedWidget widget) { base::AutoLock lock(surface_lock_); auto it = surface_map_.find(widget); DCHECK(it != surface_map_.end()); ScenicSurface* surface = it->second; surface->AssertBelongsToCurrentThread(); surface_map_.erase(it); } ScenicSurface* ScenicSurfaceFactory::GetSurface(gfx::AcceleratedWidget widget) { base::AutoLock lock(surface_lock_); auto it = surface_map_.find(widget); if (it == surface_map_.end()) return nullptr; ScenicSurface* surface = it->second; surface->AssertBelongsToCurrentThread(); return surface; } scenic::SessionPtrAndListenerRequest ScenicSurfaceFactory::CreateScenicSession() { fuchsia::ui::scenic::SessionPtr session; fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> listener_handle; auto listener_request = listener_handle.NewRequest(); { // Cache Scenic connection for main thread. For other treads create // one-shot connection. fuchsia::ui::scenic::ScenicPtr local_scenic; fuchsia::ui::scenic::ScenicPtr* scenic = main_thread_task_runner_->BelongsToCurrentThread() ? &scenic_ : &local_scenic; if (!*scenic) *scenic = ConnectToScenic(); (*scenic)->CreateSession(session.NewRequest(), std::move(listener_handle)); } return {std::move(session), std::move(listener_request)}; } void ScenicSurfaceFactory::AttachSurfaceToWindow( gfx::AcceleratedWidget window, mojo::PlatformHandle surface_view_holder_token_mojo) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); gpu_host_->AttachSurfaceToWindow(window, std::move(surface_view_holder_token_mojo)); } } // namespace ui
11,096
3,819
#include "Utility.h" Utility::Utility(void) { } Utility::~Utility(void) { } bool Utility::checking_prime_integer(uint32_t v) { for (int i = 2; i < v; i++) { if (v % i == 0) { return 0; } } return 1; } uint32_t Utility::find_smallest_prime_integer(uint32_t v) { bool r = 0; uint32_t prime = v; r = checking_prime_integer(prime); while(r == 0) { prime++; r = checking_prime_integer(prime); } //prime--; return prime; } ublas::vector<uint8_t> Utility::matrix_row_XOR(ublas::vector<uint8_t> row_1, ublas::vector<uint8_t> row_2) { if (row_1.size() != row_2.size()) { std::cout << "The columns are not the same in two rows!" << std::endl; exit(-1); } ublas::vector<uint8_t> r(row_1.size()); for (int i = 0; i < row_1.size(); ++i) { r(i) = row_1(i) ^ row_2(i); } return r; } // template<class T> // bool Utility::InvertMatrix (const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse) // { // using namespace boost::numeric::ublas; // typedef permutation_matrix<std::size_t> pmatrix; // // create a working copy of the input // matrix<T> A(input); // // create a permutation matrix for the LU-factorization // pmatrix pm(A.size1()); // // perform LU-factorization // int res = lu_factorize(A,pm); // if( res != 0 ) return false; // // create identity matrix of "inverse" // inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1())); // // backsubstitute to get the inverse // lu_substitute(A, pm, inverse); // return true; // }
1,553
686
#include "chatroomwindow.h" using namespace chat_room; ChatRoomWindow::ChatRoomWindow() : QMainWindow(nullptr), initialized(false) { // Set up Window this->setGeometry(150, 150, 640, 480); setWindowTitle(tr("Chat")); setMinimumSize(640, 480); // Menu Bar exit_chat_action = new QAction(QString("Exit"), this); chat_menu = menuBar()->addMenu(tr("Chat")); chat_menu->addAction(exit_chat_action); connect(exit_chat_action, &QAction::triggered, this, &ChatRoomWindow::exitCurrentChat); menuBar()->hide(); // Conversation List conversation_model = new ConversationModel(this); conversation_list = new QListView(this); conversation_list->setModel(conversation_model); conversation_list->setGeometry(0, 0, 640, 480); connect(conversation_list, &QListView::clicked, this, &ChatRoomWindow::onConversationListClicked); // Additional set-up app_data_directory = QString(getenv("LOCALAPPDATA")) + QString("/ChatApp/"); connect(client_socket, &QWebSocket::textMessageReceived, this, &ChatRoomWindow::onTextMessageReceived); connect(client_socket, &QWebSocket::binaryMessageReceived, this, &ChatRoomWindow::onBinaryMessageReceived); std::clog << "Chat : ChatRoomWindow set up!" << std::endl; } ChatRoomWindow::~ChatRoomWindow() { if (message_list) { delete message_list; } if (conversation_list) { delete conversation_list; } if (message_model) { delete message_model; } if (conversation_model) { delete conversation_model; } if (send_text_button) { delete send_text_button; } if (message_input_box) { delete message_input_box; } if (chat_menu_bar) { delete chat_menu_bar; } if (chat_menu) { delete chat_menu; } if (exit_chat_action) { delete exit_chat_action; } } void ChatRoomWindow::onConversationListClicked(const QModelIndex& model_index) { std::clog << "Chat : ChatRoomWindow - Chat list item clicked" << std::endl; unsigned int index = model_index.row(); User clicked_user = user_list[index]; current_receiver = clicked_user; // Open the particular conversation this->setUpChatRoom(); // Add pending messages std::stringstream file_name_stream; file_name_stream << current_receiver << current_user; std::string file_name; std::getline(file_name_stream, file_name); std::ifstream pending_message_file(file_name); if (pending_message_file.is_open()) { Message message; while (!(pending_message_file >> message).eof()) { message_model->addMessage(message); } pending_message_file.close(); std::remove(file_name.c_str()); } initialized = true; } void ChatRoomWindow::onSendTextButtonClicked() { std::clog << "Chat : ChatRoomWindow - Send text button clicked" << std::endl; QString text = message_input_box->text(); message_input_box->setText(QString("")); if (!text.isEmpty()) { Message message(current_user, current_receiver, text.toStdString()); message_model->addMessage(message); std::stringstream message_stream; message_stream << message; std::string data; std::getline(message_stream, data); client_socket->sendTextMessage(QString(data.c_str())); } } void ChatRoomWindow::onReturnKeyPressed() { std::clog << "Chat : ChatRoom - Return key pressed" << std::endl; QString text = message_input_box->text(); message_input_box->setText(QString("")); if (!text.isEmpty()) { Message message(current_user, current_receiver, text.toStdString()); message_model->addMessage(message); std::stringstream message_stream; message_stream << message; std::string data; std::getline(message_stream, data); client_socket->sendTextMessage(QString(data.c_str())); } } void ChatRoomWindow::onTextMessageReceived(const QString &data) { std::clog << "Chat : ChatRoomWindow - New message received" << std::endl; std::stringstream data_stream(data.toStdString()); User from, to; std::string text; std::getline(data_stream >> from >> to, text); Message message(from, to, text); if (!text.empty()) { if (from == current_receiver) { message_model->addMessage(message); } else { std::stringstream file_name_stream; file_name_stream >> from >> to; std::string file_name; std::getline(file_name_stream, file_name); std::ofstream pending_messages_file(file_name, std::ios::app); pending_messages_file << message << std::endl; } } } void ChatRoomWindow::onBinaryMessageReceived(const QByteArray &byte_stream) { std::clog << "Chat : ChatRoomWindow - Binary data received from server" << std::endl; std::stringstream data_stream(byte_stream.toStdString()); std::string type; data_stream >> type; if (type == "userlist") { User user; user_list.erase(user_list.begin(), user_list.end()); while (!(data_stream >> user).eof()) { user_list.push_back(user); } conversation_model->updateUserList(user_list); } else if (type == "userdata") { data_stream >> current_user; std::clog << "Chat : ChatRoomWindow - Current user data populated" << std::endl; } } void ChatRoomWindow::setUpChatRoom() { conversation_list->hide(); send_text_button = new QPushButton(SEND_TEXT_BUTTON_TEXT, this); message_input_box = new QLineEdit(this); message_list = new QListView(this); send_text_button->setGeometry(540, 460, 80, 40); message_input_box->setGeometry(0, 440, 560, 40); message_input_box->setFont(QFont("Default", 15)); message_model = new MessageModel(this); message_list->setModel(message_model); message_list->setGeometry(0, 25, 640, 415); message_list->setFont(QFont("Default", 15)); menuBar()->show(); send_text_button->show(); message_input_box->show(); message_list->show(); connect(send_text_button, &QPushButton::clicked, this, &ChatRoomWindow::onSendTextButtonClicked); connect(message_input_box, &QLineEdit::returnPressed, this, &ChatRoomWindow::onReturnKeyPressed); } void ChatRoomWindow::exitCurrentChat() { std::clog << "Chat : ChatRoom - Current chat exited" << std::endl; send_text_button->disconnect(); message_input_box->disconnect(); message_list->disconnect(); delete send_text_button; delete message_input_box; delete message_list; menuBar()->hide(); conversation_list->show(); }
7,016
2,321
/* Copyright <2021> <Hackathon and Coding Club, BIT Sindri (hnccbits@gmail.com)> MIT License 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 "engine.h" #include <iostream> #include <cstring> #include <fstream> #include <functional> #include <random> #include <filesystem> //Create definitions of the RandomEngine class here //Methods: RandomEngine::RandomEngine():length((uint8_t)8),symb(false),mod(symb?73:63){ //Reading 100 bytes of data from urandom file for seed generation. //this part is independent of user's input, hence defined in the default contructor. std::ifstream file("/dev/urandom", std::ios::in | std::ios::binary); if(!file){ throw std::filesystem::filesystem_error("Error opening file",std::error_code()); } file.read(seq, sizeof(char)*100); file.close(); std::seed_seq seed(seq, seq+100); gen = std::make_unique<std::mt19937_64>(seed); dist = std::make_unique<std::uniform_int_distribution<int64_t>>(0, mod); } RandomEngine::RandomEngine(uint8_t l,bool s): length(l), symb(s),mod(symb?73:63){ std::ifstream file("/dev/urandom", std::ios::in | std::ios::binary); if(!file){ throw std::filesystem::filesystem_error("Error opening file",std::error_code()); } file.read(seq, sizeof(char)*100); file.close(); std::seed_seq seed(seq, seq+100); gen = std::make_unique<std::mt19937_64>(seed); dist = std::make_unique<std::uniform_int_distribution<int64_t>>(0, mod); } RandomEngine::RandomEngine(uint8_t l):length(l),mod(symb?73:63){ std::ifstream file("/dev/urandom", std::ios::in | std::ios::binary); if(!file){ throw std::filesystem::filesystem_error("Error opening file",std::error_code()); } file.read(seq, sizeof(char)*100); file.close(); std::seed_seq seed(seq, seq+100); gen = std::make_unique<std::mt19937_64>(seed); dist = std::make_unique<std::uniform_int_distribution<int64_t>>(0, mod); } RandomEngine::RandomEngine(bool s): symb(s),mod(symb?73:63){ std::ifstream file("/dev/urandom", std::ios::in | std::ios::binary); if(!file){ throw std::filesystem::filesystem_error("Error opening file",std::error_code()); } file.read(seq, sizeof(char)*100); file.close(); std::seed_seq seed(seq, seq+100); gen = std::make_unique<std::mt19937_64>(seed); dist = std::make_unique<std::uniform_int_distribution<int64_t>>(0, mod); } void RandomEngine::setLength(uint8_t l){ length = l; } uint8_t RandomEngine::getLength(){ return length; } void RandomEngine::setSymbol(bool s){ symb = s; } bool RandomEngine::getSymbolStatus(){ return symb; } std::string RandomEngine::getString(){ //password generation: std::string password; auto dice = std::bind(*dist,*gen); while(password.length()!=length){ password=""; for(int i=0;i<length;i++){ uint8_t indx = dice(); if(symb && alpha_num_sym[indx]!='\0'){ password+= alpha_num_sym[indx]; } else if(!symb && alpha_num[indx]!='\0'){ password+=alpha_num[indx]; } } } return password; }
4,131
1,426
/* * TASK : AwitCat34 * AUTHOR : Hydrolyzed~ * LANG : C * SCHOOL : RYW * */ #include<stdio.h> #include<string.h> char a[510]; char *ptr; int main (){ int i,q,ch,ch2,len; gets(a); sscanf(a,"%d",&q); while(q--) { gets(a); if(a[strlen(a)-1]=='\r') a[strlen(a)-1]='\0'; ptr = strtok(a," "); ch = 1; while(ptr!= NULL) { len = strlen(ptr); if(len%4==0){ for(i=0,ch2=1;i<len;i+=4){ if(strncmp("meow",&ptr[i],4)){ ch2=0; break; } } if(ch2){ printf("YES\n"); ch= 0; break; } } ptr = strtok(NULL," "); } if(ch){ printf("NO\n"); } } }
677
421
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2000 Simon Hausmann (hausmann@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2006, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2009 Ericsson AB. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "third_party/blink/renderer/core/html/html_iframe_element.h" #include "base/metrics/histogram_macros.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/web_sandbox_flags.h" #include "services/network/public/mojom/trust_tokens.mojom-blink.h" #include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h" #include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_iframe_element.h" #include "third_party/blink/renderer/core/css/css_property_names.h" #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/feature_policy/document_policy_parser.h" #include "third_party/blink/renderer/core/feature_policy/feature_policy_parser.h" #include "third_party/blink/renderer/core/feature_policy/iframe_policy.h" #include "third_party/blink/renderer/core/fetch/trust_token_issuance_authorization.h" #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" #include "third_party/blink/renderer/core/frame/sandbox_flags.h" #include "third_party/blink/renderer/core/html/html_document.h" #include "third_party/blink/renderer/core/html/trust_token_attribute_parsing.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/layout/layout_iframe.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" #include "third_party/blink/renderer/platform/json/json_parser.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { HTMLIFrameElement::HTMLIFrameElement(Document& document) : HTMLFrameElementBase(html_names::kIFrameTag, document), collapsed_by_client_(false), sandbox_(MakeGarbageCollected<HTMLIFrameElementSandbox>(this)), referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {} void HTMLIFrameElement::Trace(Visitor* visitor) const { visitor->Trace(sandbox_); visitor->Trace(policy_); HTMLFrameElementBase::Trace(visitor); Supplementable<HTMLIFrameElement>::Trace(visitor); } HTMLIFrameElement::~HTMLIFrameElement() = default; const AttrNameToTrustedType& HTMLIFrameElement::GetCheckedAttributeTypes() const { DEFINE_STATIC_LOCAL(AttrNameToTrustedType, attribute_map, ({{"srcdoc", SpecificTrustedType::kHTML}})); return attribute_map; } void HTMLIFrameElement::SetCollapsed(bool collapse) { if (collapsed_by_client_ == collapse) return; collapsed_by_client_ = collapse; // This is always called in response to an IPC, so should not happen in the // middle of a style recalc. DCHECK(!GetDocument().InStyleRecalc()); // Trigger style recalc to trigger layout tree re-attachment. SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create( style_change_reason::kFrame)); } DOMTokenList* HTMLIFrameElement::sandbox() const { return sandbox_.Get(); } DOMFeaturePolicy* HTMLIFrameElement::featurePolicy() { if (!policy_ && GetExecutionContext()) { policy_ = MakeGarbageCollected<IFramePolicy>( GetExecutionContext(), GetFramePolicy().container_policy, GetOriginForFeaturePolicy()); } return policy_.Get(); } bool HTMLIFrameElement::IsPresentationAttribute( const QualifiedName& name) const { if (name == html_names::kWidthAttr || name == html_names::kHeightAttr || name == html_names::kAlignAttr || name == html_names::kFrameborderAttr) return true; return HTMLFrameElementBase::IsPresentationAttribute(name); } void HTMLIFrameElement::CollectStyleForPresentationAttribute( const QualifiedName& name, const AtomicString& value, MutableCSSPropertyValueSet* style) { if (name == html_names::kWidthAttr) { AddHTMLLengthToStyle(style, CSSPropertyID::kWidth, value); } else if (name == html_names::kHeightAttr) { AddHTMLLengthToStyle(style, CSSPropertyID::kHeight, value); } else if (name == html_names::kAlignAttr) { ApplyAlignmentAttributeToStyle(value, style); } else if (name == html_names::kFrameborderAttr) { // LocalFrame border doesn't really match the HTML4 spec definition for // iframes. It simply adds a presentational hint that the border should be // off if set to zero. if (!value.ToInt()) { // Add a rule that nulls out our border width. AddPropertyToPresentationAttributeStyle( style, CSSPropertyID::kBorderWidth, 0, CSSPrimitiveValue::UnitType::kPixels); } } else { HTMLFrameElementBase::CollectStyleForPresentationAttribute(name, value, style); } } void HTMLIFrameElement::ParseAttribute( const AttributeModificationParams& params) { const QualifiedName& name = params.name; const AtomicString& value = params.new_value; if (name == html_names::kNameAttr) { auto* document = DynamicTo<HTMLDocument>(GetDocument()); if (document && IsInDocumentTree()) { document->RemoveNamedItem(name_); document->AddNamedItem(value); } AtomicString old_name = name_; name_ = value; if (name_ != old_name) FrameOwnerPropertiesChanged(); } else if (name == html_names::kSandboxAttr) { sandbox_->DidUpdateAttributeValue(params.old_value, value); bool feature_policy_for_sandbox = RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled(); network::mojom::blink::WebSandboxFlags current_flags = network::mojom::blink::WebSandboxFlags::kNone; if (!value.IsNull()) { using network::mojom::blink::WebSandboxFlags; WebSandboxFlags ignored_flags = !RuntimeEnabledFeatures::StorageAccessAPIEnabled() ? WebSandboxFlags::kStorageAccessByUserActivation : WebSandboxFlags::kNone; auto parsed = network::ParseWebSandboxPolicy(sandbox_->value().Utf8(), ignored_flags); current_flags = parsed.flags; if (!parsed.error_message.empty()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, WebString::FromUTF8( "Error while parsing the 'sandbox' attribute: " + parsed.error_message))); } } SetAllowedToDownload( (current_flags & network::mojom::blink::WebSandboxFlags::kDownloads) == network::mojom::blink::WebSandboxFlags::kNone); // With FeaturePolicyForSandbox, sandbox flags are represented as part of // the container policies. However, not all sandbox flags are yet converted // and for now the residue will stay around in the stored flags. // (see https://crbug.com/812381). network::mojom::blink::WebSandboxFlags sandbox_to_set = current_flags; sandbox_flags_converted_to_feature_policies_ = network::mojom::blink::WebSandboxFlags::kNone; if (feature_policy_for_sandbox && current_flags != network::mojom::blink::WebSandboxFlags::kNone) { // Residue sandbox which will not be mapped to feature policies. sandbox_to_set = GetSandboxFlagsNotImplementedAsFeaturePolicy(current_flags); // The part of sandbox which will be mapped to feature policies. sandbox_flags_converted_to_feature_policies_ = current_flags & ~sandbox_to_set; } SetSandboxFlags(sandbox_to_set); if (RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) UpdateContainerPolicy(); UseCounter::Count(GetDocument(), WebFeature::kSandboxViaIFrame); } else if (name == html_names::kReferrerpolicyAttr) { referrer_policy_ = network::mojom::ReferrerPolicy::kDefault; if (!value.IsNull()) { SecurityPolicy::ReferrerPolicyFromString( value, kSupportReferrerPolicyLegacyKeywords, &referrer_policy_); UseCounter::Count(GetDocument(), WebFeature::kHTMLIFrameElementReferrerPolicyAttribute); } } else if (name == html_names::kAllowfullscreenAttr) { bool old_allow_fullscreen = allow_fullscreen_; allow_fullscreen_ = !value.IsNull(); if (allow_fullscreen_ != old_allow_fullscreen) { // TODO(iclelland): Remove this use counter when the allowfullscreen // attribute state is snapshotted on document creation. crbug.com/682282 if (allow_fullscreen_ && ContentFrame()) { UseCounter::Count( GetDocument(), WebFeature:: kHTMLIFrameElementAllowfullscreenAttributeSetAfterContentLoad); } FrameOwnerPropertiesChanged(); UpdateContainerPolicy(); } } else if (name == html_names::kAllowpaymentrequestAttr) { bool old_allow_payment_request = allow_payment_request_; allow_payment_request_ = !value.IsNull(); if (allow_payment_request_ != old_allow_payment_request) { FrameOwnerPropertiesChanged(); UpdateContainerPolicy(); } } else if (name == html_names::kCspAttr) { if (base::FeatureList::IsEnabled(network::features::kOutOfBlinkCSPEE)) { if (value.Contains('\n') || value.Contains('\r') || value.Contains(',')) { required_csp_ = g_null_atom; GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "'csp' attribute is invalid: " + value)); return; } if (required_csp_ != value) { required_csp_ = value; CSPAttributeChanged(); UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute); } } else { if (!ContentSecurityPolicy::IsValidCSPAttr( value.GetString(), GetDocument().RequiredCSP().GetString())) { required_csp_ = g_null_atom; GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "'csp' attribute is not a valid policy: " + value)); return; } if (required_csp_ != value) { required_csp_ = value; FrameOwnerPropertiesChanged(); UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute); } } } else if (name == html_names::kAllowAttr) { if (allow_ != value) { allow_ = value; UpdateContainerPolicy(); if (!value.IsEmpty()) { UseCounter::Count(GetDocument(), WebFeature::kFeaturePolicyAllowAttribute); } if (value.Contains(',')) { UseCounter::Count(GetDocument(), WebFeature::kCommaSeparatorInAllowAttribute); } } } else if (name == html_names::kDisallowdocumentaccessAttr && RuntimeEnabledFeatures::DisallowDocumentAccessEnabled()) { UseCounter::Count(GetDocument(), WebFeature::kDisallowDocumentAccess); SetDisallowDocumentAccesss(!value.IsNull()); // We don't need to call tell the client frame properties // changed since this attribute only stays inside the renderer. } else if (name == html_names::kPolicyAttr) { if (required_policy_ != value) { required_policy_ = value; UpdateRequiredPolicy(); } } else if (name == html_names::kTrusttokenAttr) { trust_token_ = value; } else { // Websites picked up a Chromium article that used this non-specified // attribute which ended up changing shape after the specification process. // This error message and use count will help developers to move to the // proper solution. // To avoid polluting the console, this is being recorded only once per // page. if (name == "gesture" && value == "media" && GetDocument().Loader() && !GetDocument().Loader()->GetUseCounterHelper().HasRecordedMeasurement( WebFeature::kHTMLIFrameElementGestureMedia)) { UseCounter::Count(GetDocument(), WebFeature::kHTMLIFrameElementGestureMedia); GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::ConsoleMessageSource::kOther, mojom::ConsoleMessageLevel::kWarning, "<iframe gesture=\"media\"> is not supported. " "Use <iframe allow=\"autoplay\">, " "https://goo.gl/ximf56")); } if (name == html_names::kSrcAttr) LogUpdateAttributeIfIsolatedWorldAndInDocument("iframe", params); HTMLFrameElementBase::ParseAttribute(params); } } DocumentPolicyFeatureState HTMLIFrameElement::ConstructRequiredPolicy() const { if (!RuntimeEnabledFeatures::DocumentPolicyNegotiationEnabled( GetExecutionContext())) return {}; if (!required_policy_.IsEmpty()) { UseCounter::Count( GetDocument(), mojom::blink::WebFeature::kDocumentPolicyIframePolicyAttribute); } PolicyParserMessageBuffer logger; DocumentPolicy::ParsedDocumentPolicy new_required_policy = DocumentPolicyParser::Parse(required_policy_, logger) .value_or(DocumentPolicy::ParsedDocumentPolicy{}); for (const auto& message : logger.GetMessages()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, message.level, message.content)); } if (!new_required_policy.endpoint_map.empty()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kWarning, "Iframe policy attribute cannot specify reporting endpoint.")); } for (const auto& policy_entry : new_required_policy.feature_state) { mojom::blink::DocumentPolicyFeature feature = policy_entry.first; if (!GetDocument().DocumentPolicyFeatureObserved(feature)) { UMA_HISTOGRAM_ENUMERATION( "Blink.UseCounter.DocumentPolicy.PolicyAttribute", feature); } } return new_required_policy.feature_state; } ParsedFeaturePolicy HTMLIFrameElement::ConstructContainerPolicy() const { if (!GetExecutionContext()) return ParsedFeaturePolicy(); scoped_refptr<const SecurityOrigin> src_origin = GetOriginForFeaturePolicy(); scoped_refptr<const SecurityOrigin> self_origin = GetExecutionContext()->GetSecurityOrigin(); PolicyParserMessageBuffer logger; // Start with the allow attribute ParsedFeaturePolicy container_policy = FeaturePolicyParser::ParseAttribute( allow_, self_origin, src_origin, logger, GetExecutionContext()); // Next, process sandbox flags. These all only take effect if a corresponding // policy does *not* exist in the allow attribute's value. if (RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) { // If the frame is sandboxed at all, then warn if feature policy attributes // will override the sandbox attributes. if ((sandbox_flags_converted_to_feature_policies_ & network::mojom::blink::WebSandboxFlags::kNavigation) != network::mojom::blink::WebSandboxFlags::kNone) { for (const auto& pair : SandboxFlagsWithFeaturePolicies()) { if ((sandbox_flags_converted_to_feature_policies_ & pair.first) != network::mojom::blink::WebSandboxFlags::kNone && IsFeatureDeclared(pair.second, container_policy)) { logger.Warn(String::Format( "Allow and Sandbox attributes both mention '%s'. Allow will take " "precedence.", GetNameForFeature(pair.second).Utf8().c_str())); } } } ApplySandboxFlagsToParsedFeaturePolicy( sandbox_flags_converted_to_feature_policies_, container_policy); } // Finally, process the allow* attribuets. Like sandbox attributes, they only // take effect if the corresponding feature is not present in the allow // attribute's value. // If allowfullscreen attribute is present and no fullscreen policy is set, // enable the feature for all origins. if (AllowFullscreen()) { bool policy_changed = AllowFeatureEverywhereIfNotPresent( mojom::blink::FeaturePolicyFeature::kFullscreen, container_policy); if (!policy_changed) { logger.Warn( "Allow attribute will take precedence over 'allowfullscreen'."); } } // If the allowpaymentrequest attribute is present and no 'payment' policy is // set, enable the feature for all origins. if (AllowPaymentRequest()) { bool policy_changed = AllowFeatureEverywhereIfNotPresent( mojom::blink::FeaturePolicyFeature::kPayment, container_policy); if (!policy_changed) { logger.Warn( "Allow attribute will take precedence over 'allowpaymentrequest'."); } } // Update the JavaScript policy object associated with this iframe, if it // exists. if (policy_) policy_->UpdateContainerPolicy(container_policy, src_origin); for (const auto& message : logger.GetMessages()) { GetDocument().AddConsoleMessage( MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, message.level, message.content), /* discard_duplicates */ true); } return container_policy; } bool HTMLIFrameElement::LayoutObjectIsNeeded(const ComputedStyle& style) const { return ContentFrame() && !collapsed_by_client_ && HTMLElement::LayoutObjectIsNeeded(style); } LayoutObject* HTMLIFrameElement::CreateLayoutObject(const ComputedStyle&, LegacyLayout) { return new LayoutIFrame(this); } Node::InsertionNotificationRequest HTMLIFrameElement::InsertedInto( ContainerNode& insertion_point) { InsertionNotificationRequest result = HTMLFrameElementBase::InsertedInto(insertion_point); auto* html_doc = DynamicTo<HTMLDocument>(GetDocument()); if (html_doc && insertion_point.IsInDocumentTree()) { html_doc->AddNamedItem(name_); if (!base::FeatureList::IsEnabled(network::features::kOutOfBlinkCSPEE) && !ContentSecurityPolicy::IsValidCSPAttr( required_csp_, GetDocument().RequiredCSP().GetString())) { if (!required_csp_.IsEmpty()) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::ConsoleMessageSource::kOther, mojom::ConsoleMessageLevel::kError, "'csp' attribute is not a valid policy: " + required_csp_)); } if (required_csp_ != GetDocument().RequiredCSP()) { required_csp_ = GetDocument().RequiredCSP(); FrameOwnerPropertiesChanged(); UseCounter::Count(GetDocument(), WebFeature::kIFrameCSPAttribute); } } } LogAddElementIfIsolatedWorldAndInDocument("iframe", html_names::kSrcAttr); return result; } void HTMLIFrameElement::RemovedFrom(ContainerNode& insertion_point) { HTMLFrameElementBase::RemovedFrom(insertion_point); auto* html_doc = DynamicTo<HTMLDocument>(GetDocument()); if (html_doc && insertion_point.IsInDocumentTree()) html_doc->RemoveNamedItem(name_); } bool HTMLIFrameElement::IsInteractiveContent() const { return true; } network::mojom::ReferrerPolicy HTMLIFrameElement::ReferrerPolicyAttribute() { return referrer_policy_; } network::mojom::blink::TrustTokenParamsPtr HTMLIFrameElement::ConstructTrustTokenParams() const { if (!trust_token_) return nullptr; JSONParseError parse_error; std::unique_ptr<JSONValue> parsed_attribute = ParseJSON(trust_token_, &parse_error); if (!parsed_attribute) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "iframe trusttoken attribute was invalid JSON: " + parse_error.message + String::Format(" (line %d, col %d)", parse_error.line, parse_error.column))); return nullptr; } network::mojom::blink::TrustTokenParamsPtr parsed_params = internal::TrustTokenParamsFromJson(std::move(parsed_attribute)); if (!parsed_params) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "Couldn't parse iframe trusttoken attribute (was it missing a " "field?)")); return nullptr; } // Trust token redemption and signing (but not issuance) require that the // trust-token-redemption feature policy be present. bool operation_requires_feature_policy = parsed_params->type == network::mojom::blink::TrustTokenOperationType::kRedemption || parsed_params->type == network::mojom::blink::TrustTokenOperationType::kSigning; if (operation_requires_feature_policy && (!GetExecutionContext()->IsFeatureEnabled( mojom::blink::FeaturePolicyFeature::kTrustTokenRedemption))) { GetExecutionContext()->AddConsoleMessage( MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "Trust Tokens: Attempted redemption or signing without the " "trust-token-redemption Feature Policy feature present.")); return nullptr; } if (parsed_params->type == network::mojom::blink::TrustTokenOperationType::kIssuance && !IsTrustTokenIssuanceAvailableInExecutionContext( *GetExecutionContext())) { GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kOther, mojom::blink::ConsoleMessageLevel::kError, "Trust Tokens issuance is disabled except in " "contexts with the TrustTokens Origin Trial enabled.")); return nullptr; } return parsed_params; } } // namespace blink
23,280
6,833
// // Created by sebas on 7/11/19. // #include "PuntuacionJugadores.h" void PuntuacionJugadores::setPuntuacion (string jugador, int puntuacion) { puntuaciones[jugador] = puntuacion; } unordered_map < string, int > PuntuacionJugadores::getPuntuaciones () { return puntuaciones; }
286
115
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); for(auto& item : QSerialPortInfo::availablePorts()){ ui->box_serial->addItem(item.portName()); } for(auto& item : QSerialPortInfo::standardBaudRates()){ ui->box_velocidade->addItem(QString::number(item)); } connect(&serial, SIGNAL(readyRead()), this, SLOT(dadosRecebidos())); } MainWindow::~MainWindow() { serial.close(); delete ui; } void MainWindow::dadosRecebidos() { auto data = serial.readAll(); auto dados = QJsonDocument::fromJson(data).object().toVariantMap(); if(dados.contains("POWER")){ power = dados["POWER"].toString(); ui->tabelaStats->setItem(1,1, new QTableWidgetItem(power)); } if(dados.contains("VOLT")){ volt = dados["VOLT"].toString(); ui->tabelaStats->setItem(2,1, new QTableWidgetItem(volt)); } if(dados.contains("AMPER")){ amper = dados["AMPER"].toString(); ui->tabelaStats->setItem(3,1, new QTableWidgetItem(amper)); } } void MainWindow::on_btnPlug_clicked() { plugStatus = !plugStatus; if(plugStatus){ serial.setPortName(ui->box_serial->currentText()); serial.setBaudRate(ui->box_velocidade->currentText().toInt()); if(serial.open(QIODevice::ReadWrite)){ ui->status_conexao->setText("Status: Conectado"); ui -> btnPlug ->setText("Desconectar"); } }else{ serial.close(); ui->status_conexao->setText("Status: Desconectado"); ui -> btnPlug ->setText("Conectar"); } } void MainWindow::on_btnAction_clicked() { action = !action; qDebug() << action; if(action){ ui->btnAction->setText("Desativar alimentação manual"); serial.write("{\"ACAO\": 1}"); }else{ ui->btnAction->setText("Ativar alimentação manual"); serial.write("{\"ACAO\": 0}"); } } void MainWindow::on_btnEmailEdu_clicked() { QUrl email = QUrl("mailto:freitas.eduardo@academico.ifpb.edu.br"); QDesktopServices::openUrl(email); } void MainWindow::on_btnEmailNeto_clicked() { QUrl email = QUrl("mailto:neto.batista@academico.ifpb.edu.br"); QDesktopServices::openUrl(email); } void MainWindow::on_btnGithub_clicked() { QUrl github = QUrl("https://github.com/EduFreit4s/Meown"); QDesktopServices::openUrl(github); } void MainWindow::on_btnSite_clicked() { QUrl github = QUrl("https://meown-engine.herokuapp.com/"); QDesktopServices::openUrl(github); }
2,768
983
// // FactoryBuilder.hpp // DesignPatterns // // Created by Shen Lu on 2018/8/18. // Copyright © 2018 Shen Lu. All rights reserved. // #ifndef FactoryBuilder_hpp #define FactoryBuilder_hpp #include <memory> namespace ls { typedef enum FactoryType { Factory1 = 0, Factory2 = 1 }FactoryType; class Factory; class FactoryBuilder { public: static std::shared_ptr<Factory> createFactory(FactoryType type); }; } #endif /* FactoryBuilder_hpp */
494
166
#include "randomFactory.hpp" RandomFactory::RandomFactory() : gen_((std::random_device())()) {} unsigned int RandomFactory::operator()() { return gen_(); }
160
52
// // Window.cpp -- implementation of the various function window classes // See the copyright notice and acknowledgment of authors in the file COPYRIGHT // #include "Window.h" #include <math.h> using namespace csl; Window::Window() : UnitGenerator(), mGain(1) { this->setSize(CGestalt::blockSize()); } // Gain is optional and defaults to 1 when not specified. Window::Window(unsigned windowSize, float gain) : UnitGenerator(), mGain(gain) { this->setSize(windowSize); } Window::~Window() { mWindowBuffer.freeBuffers(); } void Window::setGain(float gain) { mGain = gain; fillWindow(); // Re-caluclate window using new gain value. } void Window::setSize(unsigned windowSize) { mWindowBufferPos = 0; mWindowSize = windowSize; // If previously allocated, free me first. mWindowBuffer.freeBuffers(); mWindowBuffer.setSize(1, mWindowSize); // Allocate memory to store the window. mWindowBuffer.allocateBuffers(); fillWindow(); // Fill the buffer with the window data. } void Window::nextBuffer(Buffer &outputBuffer, unsigned outBufNum) throw (CException) { /// get everything into registers unsigned numFrames = outputBuffer.mNumFrames; sample* outputBufferPtr = outputBuffer.buffer(outBufNum); sample* windowBufferPtr = mWindowBuffer.buffer(0); unsigned windowBufferPos = mWindowBufferPos; unsigned windowBufferSize = mWindowSize; #ifdef CSL_DEBUG logMsg("Window::nextBuffer"); #endif for (unsigned i = 0; i < numFrames; i++) { if (windowBufferPos > windowBufferSize) windowBufferPos = 0; *outputBufferPtr++ = windowBufferPtr[windowBufferPos++]; } mWindowBufferPos = windowBufferPos; } void Window::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); // create the window -- I make a Hamming window, subclasses may override for (unsigned i = 0; i < mWindowSize; i++ ) *windowBufferPtr++ = (0.54 - 0.46*cos(CSL_TWOPI*i/(mWindowSize - 1) )); } void RectangularWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); for (unsigned i = 0; i < mWindowSize; i++ ) // create the window *windowBufferPtr++ = mGain; } void TriangularWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); float accum = 0.0f; unsigned winHalf = mWindowSize / 2; float step = 1.0f / ((float) winHalf); for (unsigned i = 0; i < winHalf; i++ ) { // create the rising half *windowBufferPtr++ = accum; accum += step; } for (unsigned i = winHalf; i < mWindowSize; i++ ) { // create the falling half *windowBufferPtr++ = accum; accum -= step; } } void HammingWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); sample increment = CSL_TWOPI/(mWindowSize - 1); for (unsigned i = 0; i < mWindowSize; i++ ) *windowBufferPtr++ = (0.54 - 0.46*cos(i * increment)); } void HannWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); sample increment = CSL_TWOPI/(mWindowSize - 1); for (unsigned i = 0; i < mWindowSize; i++ ) *windowBufferPtr++ = 0.5 * (1 - cos(i * increment)) * mGain; } void BlackmanWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); sample increment = CSL_TWOPI/(mWindowSize - 1); for (unsigned i = 0; i < mWindowSize; i++ ) *windowBufferPtr++ = (0.42 - 0.5 * cos(i * increment) + 0.08 * cos(2 * i * increment)) * mGain; } void BlackmanHarrisWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); sample increment = CSL_TWOPI/(mWindowSize - 1); for (unsigned i = 0; i < mWindowSize; i++ ) *windowBufferPtr++ = (0.35875 - 0.48829 * cos(i * increment) + 0.14128 * cos(2 * i * increment) - 0.01168 * cos(3 * i * increment)) * mGain; } void WelchWindow::fillWindow() { sample* windowBufferPtr = mWindowBuffer.buffer(0); sample increment = 2.f/(mWindowSize - 1); sample phase = -1.f; for (unsigned i = 0; i < mWindowSize; i++ ) { // create the window *windowBufferPtr++ = (1.f - phase * phase) * mGain; phase += increment; } } void Window::dump() { logMsg("Window of size: %d samples", mWindowSize); }
4,051
1,497
//===- LLVMTypes.cpp - MLIR LLVM Dialect types ----------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the types for the LLVM dialect in MLIR. These MLIR types // correspond to the LLVM IR type system. // //===----------------------------------------------------------------------===// #include "TypeDetail.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/LLVMIR/LLVMTypes.h" #include "mlir/IR/DialectImplementation.h" #include "mlir/IR/TypeSupport.h" #include "llvm/ADT/TypeSwitch.h" #include "llvm/Support/TypeSize.h" using namespace mlir; using namespace mlir::LLVM; //===----------------------------------------------------------------------===// // LLVMType. //===----------------------------------------------------------------------===// bool LLVMType::classof(Type type) { return llvm::isa<LLVMDialect>(type.getDialect()); } LLVMDialect &LLVMType::getDialect() { return static_cast<LLVMDialect &>(Type::getDialect()); } //===----------------------------------------------------------------------===// // Array type. //===----------------------------------------------------------------------===// bool LLVMArrayType::isValidElementType(LLVMType type) { return !type.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType, LLVMFunctionType, LLVMTokenType, LLVMScalableVectorType>(); } LLVMArrayType LLVMArrayType::get(LLVMType elementType, unsigned numElements) { assert(elementType && "expected non-null subtype"); return Base::get(elementType.getContext(), elementType, numElements); } LLVMArrayType LLVMArrayType::getChecked(Location loc, LLVMType elementType, unsigned numElements) { assert(elementType && "expected non-null subtype"); return Base::getChecked(loc, elementType, numElements); } LLVMType LLVMArrayType::getElementType() { return getImpl()->elementType; } unsigned LLVMArrayType::getNumElements() { return getImpl()->numElements; } LogicalResult LLVMArrayType::verifyConstructionInvariants(Location loc, LLVMType elementType, unsigned numElements) { if (!isValidElementType(elementType)) return emitError(loc, "invalid array element type: ") << elementType; return success(); } //===----------------------------------------------------------------------===// // Function type. //===----------------------------------------------------------------------===// bool LLVMFunctionType::isValidArgumentType(LLVMType type) { return !type.isa<LLVMVoidType, LLVMFunctionType>(); } bool LLVMFunctionType::isValidResultType(LLVMType type) { return !type.isa<LLVMFunctionType, LLVMMetadataType, LLVMLabelType>(); } LLVMFunctionType LLVMFunctionType::get(LLVMType result, ArrayRef<LLVMType> arguments, bool isVarArg) { assert(result && "expected non-null result"); return Base::get(result.getContext(), result, arguments, isVarArg); } LLVMFunctionType LLVMFunctionType::getChecked(Location loc, LLVMType result, ArrayRef<LLVMType> arguments, bool isVarArg) { assert(result && "expected non-null result"); return Base::getChecked(loc, result, arguments, isVarArg); } LLVMType LLVMFunctionType::getReturnType() { return getImpl()->getReturnType(); } unsigned LLVMFunctionType::getNumParams() { return getImpl()->getArgumentTypes().size(); } LLVMType LLVMFunctionType::getParamType(unsigned i) { return getImpl()->getArgumentTypes()[i]; } bool LLVMFunctionType::isVarArg() { return getImpl()->isVariadic(); } ArrayRef<LLVMType> LLVMFunctionType::getParams() { return getImpl()->getArgumentTypes(); } LogicalResult LLVMFunctionType::verifyConstructionInvariants( Location loc, LLVMType result, ArrayRef<LLVMType> arguments, bool) { if (!isValidResultType(result)) return emitError(loc, "invalid function result type: ") << result; for (LLVMType arg : arguments) if (!isValidArgumentType(arg)) return emitError(loc, "invalid function argument type: ") << arg; return success(); } //===----------------------------------------------------------------------===// // Integer type. //===----------------------------------------------------------------------===// LLVMIntegerType LLVMIntegerType::get(MLIRContext *ctx, unsigned bitwidth) { return Base::get(ctx, bitwidth); } LLVMIntegerType LLVMIntegerType::getChecked(Location loc, unsigned bitwidth) { return Base::getChecked(loc, bitwidth); } unsigned LLVMIntegerType::getBitWidth() { return getImpl()->bitwidth; } LogicalResult LLVMIntegerType::verifyConstructionInvariants(Location loc, unsigned bitwidth) { constexpr int maxSupportedBitwidth = (1 << 24); if (bitwidth >= maxSupportedBitwidth) return emitError(loc, "integer type too wide"); return success(); } //===----------------------------------------------------------------------===// // Pointer type. //===----------------------------------------------------------------------===// bool LLVMPointerType::isValidElementType(LLVMType type) { return !type.isa<LLVMVoidType, LLVMTokenType, LLVMMetadataType, LLVMLabelType>(); } LLVMPointerType LLVMPointerType::get(LLVMType pointee, unsigned addressSpace) { assert(pointee && "expected non-null subtype"); return Base::get(pointee.getContext(), pointee, addressSpace); } LLVMPointerType LLVMPointerType::getChecked(Location loc, LLVMType pointee, unsigned addressSpace) { return Base::getChecked(loc, pointee, addressSpace); } LLVMType LLVMPointerType::getElementType() { return getImpl()->pointeeType; } unsigned LLVMPointerType::getAddressSpace() { return getImpl()->addressSpace; } LogicalResult LLVMPointerType::verifyConstructionInvariants(Location loc, LLVMType pointee, unsigned) { if (!isValidElementType(pointee)) return emitError(loc, "invalid pointer element type: ") << pointee; return success(); } //===----------------------------------------------------------------------===// // Struct type. //===----------------------------------------------------------------------===// bool LLVMStructType::isValidElementType(LLVMType type) { return !type.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType, LLVMFunctionType, LLVMTokenType, LLVMScalableVectorType>(); } LLVMStructType LLVMStructType::getIdentified(MLIRContext *context, StringRef name) { return Base::get(context, name, /*opaque=*/false); } LLVMStructType LLVMStructType::getIdentifiedChecked(Location loc, StringRef name) { return Base::getChecked(loc, name, /*opaque=*/false); } LLVMStructType LLVMStructType::getNewIdentified(MLIRContext *context, StringRef name, ArrayRef<LLVMType> elements, bool isPacked) { std::string stringName = name.str(); unsigned counter = 0; do { auto type = LLVMStructType::getIdentified(context, stringName); if (type.isInitialized() || failed(type.setBody(elements, isPacked))) { counter += 1; stringName = (Twine(name) + "." + std::to_string(counter)).str(); continue; } return type; } while (true); } LLVMStructType LLVMStructType::getLiteral(MLIRContext *context, ArrayRef<LLVMType> types, bool isPacked) { return Base::get(context, types, isPacked); } LLVMStructType LLVMStructType::getLiteralChecked(Location loc, ArrayRef<LLVMType> types, bool isPacked) { return Base::getChecked(loc, types, isPacked); } LLVMStructType LLVMStructType::getOpaque(StringRef name, MLIRContext *context) { return Base::get(context, name, /*opaque=*/true); } LLVMStructType LLVMStructType::getOpaqueChecked(Location loc, StringRef name) { return Base::getChecked(loc, name, /*opaque=*/true); } LogicalResult LLVMStructType::setBody(ArrayRef<LLVMType> types, bool isPacked) { assert(isIdentified() && "can only set bodies of identified structs"); assert(llvm::all_of(types, LLVMStructType::isValidElementType) && "expected valid body types"); return Base::mutate(types, isPacked); } bool LLVMStructType::isPacked() { return getImpl()->isPacked(); } bool LLVMStructType::isIdentified() { return getImpl()->isIdentified(); } bool LLVMStructType::isOpaque() { return getImpl()->isIdentified() && (getImpl()->isOpaque() || !getImpl()->isInitialized()); } bool LLVMStructType::isInitialized() { return getImpl()->isInitialized(); } StringRef LLVMStructType::getName() { return getImpl()->getIdentifier(); } ArrayRef<LLVMType> LLVMStructType::getBody() { return isIdentified() ? getImpl()->getIdentifiedStructBody() : getImpl()->getTypeList(); } LogicalResult LLVMStructType::verifyConstructionInvariants(Location, StringRef, bool) { return success(); } LogicalResult LLVMStructType::verifyConstructionInvariants(Location loc, ArrayRef<LLVMType> types, bool) { for (LLVMType t : types) if (!isValidElementType(t)) return emitError(loc, "invalid LLVM structure element type: ") << t; return success(); } //===----------------------------------------------------------------------===// // Vector types. //===----------------------------------------------------------------------===// bool LLVMVectorType::isValidElementType(LLVMType type) { return type.isa<LLVMIntegerType, LLVMPointerType>() || mlir::LLVM::isCompatibleFloatingPointType(type); } /// Support type casting functionality. bool LLVMVectorType::classof(Type type) { return type.isa<LLVMFixedVectorType, LLVMScalableVectorType>(); } LLVMType LLVMVectorType::getElementType() { // Both derived classes share the implementation type. return static_cast<detail::LLVMTypeAndSizeStorage *>(impl)->elementType; } llvm::ElementCount LLVMVectorType::getElementCount() { // Both derived classes share the implementation type. return llvm::ElementCount::get( static_cast<detail::LLVMTypeAndSizeStorage *>(impl)->numElements, isa<LLVMScalableVectorType>()); } /// Verifies that the type about to be constructed is well-formed. LogicalResult LLVMVectorType::verifyConstructionInvariants(Location loc, LLVMType elementType, unsigned numElements) { if (numElements == 0) return emitError(loc, "the number of vector elements must be positive"); if (!isValidElementType(elementType)) return emitError(loc, "invalid vector element type"); return success(); } LLVMFixedVectorType LLVMFixedVectorType::get(LLVMType elementType, unsigned numElements) { assert(elementType && "expected non-null subtype"); return Base::get(elementType.getContext(), elementType, numElements); } LLVMFixedVectorType LLVMFixedVectorType::getChecked(Location loc, LLVMType elementType, unsigned numElements) { assert(elementType && "expected non-null subtype"); return Base::getChecked(loc, elementType, numElements); } unsigned LLVMFixedVectorType::getNumElements() { return getImpl()->numElements; } LLVMScalableVectorType LLVMScalableVectorType::get(LLVMType elementType, unsigned minNumElements) { assert(elementType && "expected non-null subtype"); return Base::get(elementType.getContext(), elementType, minNumElements); } LLVMScalableVectorType LLVMScalableVectorType::getChecked(Location loc, LLVMType elementType, unsigned minNumElements) { assert(elementType && "expected non-null subtype"); return Base::getChecked(loc, elementType, minNumElements); } unsigned LLVMScalableVectorType::getMinNumElements() { return getImpl()->numElements; } //===----------------------------------------------------------------------===// // Utility functions. //===----------------------------------------------------------------------===// llvm::TypeSize mlir::LLVM::getPrimitiveTypeSizeInBits(Type type) { assert(isCompatibleType(type) && "expected a type compatible with the LLVM dialect"); return llvm::TypeSwitch<Type, llvm::TypeSize>(type) .Case<LLVMHalfType, LLVMBFloatType>( [](LLVMType) { return llvm::TypeSize::Fixed(16); }) .Case<LLVMFloatType>([](LLVMType) { return llvm::TypeSize::Fixed(32); }) .Case<LLVMDoubleType, LLVMX86MMXType>( [](LLVMType) { return llvm::TypeSize::Fixed(64); }) .Case<LLVMIntegerType>([](LLVMIntegerType intTy) { return llvm::TypeSize::Fixed(intTy.getBitWidth()); }) .Case<LLVMX86FP80Type>([](LLVMType) { return llvm::TypeSize::Fixed(80); }) .Case<LLVMPPCFP128Type, LLVMFP128Type>( [](LLVMType) { return llvm::TypeSize::Fixed(128); }) .Case<LLVMVectorType>([](LLVMVectorType t) { llvm::TypeSize elementSize = getPrimitiveTypeSizeInBits(t.getElementType()); llvm::ElementCount elementCount = t.getElementCount(); assert(!elementSize.isScalable() && "vector type should have fixed-width elements"); return llvm::TypeSize(elementSize.getFixedSize() * elementCount.getKnownMinValue(), elementCount.isScalable()); }) .Default([](Type ty) { assert((ty.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType, LLVMTokenType, LLVMStructType, LLVMArrayType, LLVMPointerType, LLVMFunctionType>()) && "unexpected missing support for primitive type"); return llvm::TypeSize::Fixed(0); }); }
14,691
4,096
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <C2Debug.h> #include <C2ParamInternal.h> #include <util/C2InterfaceHelper.h> #include <android-base/stringprintf.h> using ::android::base::StringPrintf; /* --------------------------------- ReflectorHelper --------------------------------- */ void C2ReflectorHelper::addStructDescriptors( std::vector<C2StructDescriptor> &structs, _Tuple<> *) { std::lock_guard<std::mutex> lock(_mMutex); for (C2StructDescriptor &strukt : structs) { // TODO: check if structure descriptions conflict with existing ones addStructDescriptor(std::move(strukt)); } } std::unique_ptr<C2StructDescriptor> C2ReflectorHelper::describe(C2Param::CoreIndex paramIndex) const { std::lock_guard<std::mutex> lock(_mMutex); auto it = _mStructs.find(paramIndex); if (it == _mStructs.end()) { return nullptr; } else { return std::make_unique<C2StructDescriptor>(it->second); } }; void C2ReflectorHelper::addStructDescriptor(C2StructDescriptor &&strukt) { if (_mStructs.find(strukt.coreIndex()) != _mStructs.end()) { // already added // TODO: validate that descriptor matches stored descriptor } // validate that all struct fields are known to this reflector for (const C2FieldDescriptor &fd : strukt) { if (fd.type() & C2FieldDescriptor::STRUCT_FLAG) { C2Param::CoreIndex coreIndex = fd.type() &~ C2FieldDescriptor::STRUCT_FLAG; if (_mStructs.find(coreIndex) == _mStructs.end()) { C2_LOG(INFO) << "missing struct descriptor #" << coreIndex << " for field " << fd.name() << " of struct #" << strukt.coreIndex(); } } } _mStructs.emplace(strukt.coreIndex(), strukt); } /* ---------------------------- ParamHelper ---------------------------- */ class C2InterfaceHelper::ParamHelper::Impl { public: Impl(ParamRef param, C2StringLiteral name, C2StructDescriptor &&strukt) : mParam(param), mName(name), _mStruct(strukt) { } Impl(Impl&&) = default; void addDownDependency(C2Param::Index index) { mDownDependencies.push_back(index); } C2InterfaceHelper::ParamHelper::attrib_t& attrib() { return mAttrib; } void build() { // move dependencies into descriptor mDescriptor = std::make_shared<C2ParamDescriptor>( index(), (C2ParamDescriptor::attrib_t)mAttrib, std::move(mName), std::move(mDependencies)); } void createFieldsAndSupportedValues(const std::shared_ptr<C2ParamReflector> &reflector) { for (const C2FieldUtils::Info &f : C2FieldUtils::enumerateFields(*mDefaultValue, reflector)) { if (!f.isArithmetic()) { continue; } std::unique_ptr<C2FieldSupportedValues> fsvPointer; // create a breakable structure do { C2FieldSupportedValues fsv; switch (f.type()) { case C2FieldDescriptor::INT32: fsv = C2SupportedRange<int32_t>::Any(); break; case C2FieldDescriptor::UINT32: fsv = C2SupportedRange<uint32_t>::Any(); break; case C2FieldDescriptor::INT64: fsv = C2SupportedRange<int64_t>::Any(); break; case C2FieldDescriptor::UINT64: fsv = C2SupportedRange<uint64_t>::Any(); break; case C2FieldDescriptor::FLOAT: fsv = C2SupportedRange<float>::Any(); break; case C2FieldDescriptor::BLOB: fsv = C2SupportedRange<uint8_t>::Any(); break; case C2FieldDescriptor::STRING: fsv = C2SupportedRange<char>::Any(); break; default: continue; // break out of do {} while } fsvPointer = std::make_unique<C2FieldSupportedValues>(fsv); } while (false); mFields.emplace_hint( mFields.end(), _C2FieldId(f.offset(), f.size()), std::make_shared<FieldHelper>( mParam, _C2FieldId(f.offset(), f.size()), std::move(fsvPointer))); } } /** * Finds a field descriptor. */ std::shared_ptr<FieldHelper> findField(size_t baseOffs, size_t baseSize) const { auto it = mFields.find(_C2FieldId(baseOffs, baseSize)); if (it == mFields.end()) { return nullptr; } return it->second; } const std::vector<ParamRef> getDependenciesAsRefs() const { return mDependenciesAsRefs; } std::shared_ptr<const C2ParamDescriptor> getDescriptor() const { return mDescriptor; } const std::vector<C2Param::Index> getDownDependencies() const { return mDownDependencies; } C2Param::Index index() const { if (!mDefaultValue) { fprintf(stderr, "%s missing default value\n", mName.c_str()); } return mDefaultValue->index(); } C2String name() const { return mName; } const ParamRef ref() const { return mParam; } C2StructDescriptor retrieveStructDescriptor() { return std::move(_mStruct); } void setDefaultValue(std::shared_ptr<C2Param> default_) { mDefaultValue = default_; } void setDependencies(std::vector<C2Param::Index> indices, std::vector<ParamRef> refs) { mDependencies = indices; mDependenciesAsRefs = refs; } void setFields(std::vector<C2ParamFieldValues> &&fields) { // do not allow adding fields multiple times, or to const values if (!mFields.empty()) { C2_LOG(FATAL) << "Trying to add fields to param " << mName << " multiple times"; } else if (mAttrib & attrib_t::IS_CONST) { C2_LOG(FATAL) << "Trying to add fields to const param " << mName; } for (C2ParamFieldValues &pfv : fields) { mFields.emplace_hint( mFields.end(), // _C2FieldId constructor _C2ParamInspector::GetField(pfv.paramOrField), // Field constructor std::make_shared<FieldHelper>(mParam, _C2ParamInspector::GetField(pfv.paramOrField), std::move(pfv.values))); } } void setGetter(std::function<std::shared_ptr<C2Param>(bool)> getter) { mGetter = getter; } void setSetter(std::function<C2R(const C2Param *, bool, bool *, Factory &)> setter) { mSetter = setter; } c2_status_t trySet( const C2Param *value, bool mayBlock, bool *changed, Factory &f, std::vector<std::unique_ptr<C2SettingResult>>* const failures) { C2R result = mSetter(value, mayBlock, changed, f); return result.retrieveFailures(failures); } c2_status_t validate(const std::shared_ptr<C2ParamReflector> &reflector) { if (!mSetter && mFields.empty()) { C2_LOG(WARNING) << "Param " << mName << " has no setter, making it const"; // dependencies are empty in this case mAttrib |= attrib_t::IS_CONST; } else if (!mSetter) { C2_LOG(FATAL) << "Param " << mName << " has no setter"; } if (mAttrib & attrib_t::IS_CONST) { createFieldsAndSupportedValues(reflector); } else { // TODO: update default based on setter and verify that FSV covers the values } if (mFields.empty()) { C2_LOG(FATAL) << "Param " << mName << " has no fields"; } return C2_OK; } std::shared_ptr<C2Param> value() { return mParam.get(); } std::shared_ptr<const C2Param> value() const { return mParam.get(); } private: typedef _C2ParamInspector::attrib_t attrib_t; ParamRef mParam; C2String mName; C2StructDescriptor _mStruct; std::shared_ptr<C2Param> mDefaultValue; attrib_t mAttrib; std::function<C2R(const C2Param *, bool, bool *, Factory &)> mSetter; std::function<std::shared_ptr<C2Param>(bool)> mGetter; std::vector<C2Param::Index> mDependencies; std::vector<ParamRef> mDependenciesAsRefs; std::vector<C2Param::Index> mDownDependencies; // TODO: this does not work for stream dependencies std::map<_C2FieldId, std::shared_ptr<FieldHelper>> mFields; std::shared_ptr<C2ParamDescriptor> mDescriptor; }; C2InterfaceHelper::ParamHelper::ParamHelper( ParamRef param, C2StringLiteral name, C2StructDescriptor &&strukt) : mImpl(std::make_unique<C2InterfaceHelper::ParamHelper::Impl>( param, name, std::move(strukt))) { } C2InterfaceHelper::ParamHelper::ParamHelper(C2InterfaceHelper::ParamHelper &&) = default; C2InterfaceHelper::ParamHelper::~ParamHelper() = default; void C2InterfaceHelper::ParamHelper::addDownDependency(C2Param::Index index) { return mImpl->addDownDependency(index); } C2InterfaceHelper::ParamHelper::attrib_t& C2InterfaceHelper::ParamHelper::attrib() { return mImpl->attrib(); } std::shared_ptr<C2InterfaceHelper::ParamHelper> C2InterfaceHelper::ParamHelper::build() { mImpl->build(); return std::make_shared<C2InterfaceHelper::ParamHelper>(std::move(*this)); } std::shared_ptr<C2InterfaceHelper::FieldHelper> C2InterfaceHelper::ParamHelper::findField(size_t baseOffs, size_t baseSize) const { return mImpl->findField(baseOffs, baseSize); } const std::vector<C2InterfaceHelper::ParamRef> C2InterfaceHelper::ParamHelper::getDependenciesAsRefs() const { return mImpl->getDependenciesAsRefs(); } std::shared_ptr<const C2ParamDescriptor> C2InterfaceHelper::ParamHelper::getDescriptor() const { return mImpl->getDescriptor(); } const std::vector<C2Param::Index> C2InterfaceHelper::ParamHelper::getDownDependencies() const { return mImpl->getDownDependencies(); } C2Param::Index C2InterfaceHelper::ParamHelper::index() const { return mImpl->index(); } C2String C2InterfaceHelper::ParamHelper::name() const { return mImpl->name(); } const C2InterfaceHelper::ParamRef C2InterfaceHelper::ParamHelper::ref() const { return mImpl->ref(); } C2StructDescriptor C2InterfaceHelper::ParamHelper::retrieveStructDescriptor() { return mImpl->retrieveStructDescriptor(); } void C2InterfaceHelper::ParamHelper::setDefaultValue(std::shared_ptr<C2Param> default_) { mImpl->setDefaultValue(default_); } void C2InterfaceHelper::ParamHelper::setDependencies( std::vector<C2Param::Index> indices, std::vector<ParamRef> refs) { mImpl->setDependencies(indices, refs); } void C2InterfaceHelper::ParamHelper::setFields(std::vector<C2ParamFieldValues> &&fields) { return mImpl->setFields(std::move(fields)); } void C2InterfaceHelper::ParamHelper::setGetter( std::function<std::shared_ptr<C2Param>(bool)> getter) { mImpl->setGetter(getter); } void C2InterfaceHelper::ParamHelper::setSetter( std::function<C2R(const C2Param *, bool, bool *, Factory &)> setter) { mImpl->setSetter(setter); } c2_status_t C2InterfaceHelper::ParamHelper::trySet( const C2Param *value, bool mayBlock, bool *changed, Factory &f, std::vector<std::unique_ptr<C2SettingResult>>* const failures) { return mImpl->trySet(value, mayBlock, changed, f, failures); } c2_status_t C2InterfaceHelper::ParamHelper::validate( const std::shared_ptr<C2ParamReflector> &reflector) { return mImpl->validate(reflector); } std::shared_ptr<C2Param> C2InterfaceHelper::ParamHelper::value() { return mImpl->value(); } std::shared_ptr<const C2Param> C2InterfaceHelper::ParamHelper::value() const { return mImpl->value(); } /* ---------------------------- FieldHelper ---------------------------- */ C2ParamField C2InterfaceHelper::FieldHelper::makeParamField(C2Param::Index index) const { return _C2ParamInspector::CreateParamField(index, mFieldId); } C2InterfaceHelper::FieldHelper::FieldHelper(const ParamRef &param, const _C2FieldId &field, std::unique_ptr<C2FieldSupportedValues> &&values) : mParam(param), mFieldId(field), mPossible(std::move(values)) { C2_LOG(VERBOSE) << "Creating field helper " << field << " " << C2FieldSupportedValuesHelper<uint32_t>(*mPossible); } void C2InterfaceHelper::FieldHelper::setSupportedValues( std::unique_ptr<C2FieldSupportedValues> &&values) { mSupported = std::move(values); } const C2FieldSupportedValues *C2InterfaceHelper::FieldHelper::getSupportedValues() const { return (mSupported ? mSupported : mPossible).get(); } const C2FieldSupportedValues *C2InterfaceHelper::FieldHelper::getPossibleValues() const { return mPossible.get(); } /* ---------------------------- Field ---------------------------- */ /** * Wrapper around field-supported-values builder that gets stored in the * field helper when the builder goes out of scope. */ template<typename T> struct SupportedValuesBuilder : C2ParamFieldValuesBuilder<T> { SupportedValuesBuilder( C2ParamField &field, std::shared_ptr<C2InterfaceHelper::FieldHelper> helper) : C2ParamFieldValuesBuilder<T>(field), _mHelper(helper), _mField(field) { } /** * Save builder values on destruction. */ virtual ~SupportedValuesBuilder() override { _mHelper->setSupportedValues(std::move(C2ParamFieldValues(*this).values)); } private: std::shared_ptr<C2InterfaceHelper::FieldHelper> _mHelper; C2ParamField _mField; }; template<typename T> C2ParamFieldValuesBuilder<T> C2InterfaceHelper::Field<T>::shouldBe() const { return C2ParamFieldValuesBuilder<T>(_mField); } template<typename T> C2ParamFieldValuesBuilder<T> C2InterfaceHelper::Field<T>::mustBe() { return SupportedValuesBuilder<T>(_mField, _mHelper); } /* template<typename T> C2SettingResultsBuilder C2InterfaceHelper::Field<T>::validatePossible(T &value) const { /// TODO return C2SettingResultsBuilder::Ok(); } */ template<typename T> C2InterfaceHelper::Field<T>::Field(std::shared_ptr<FieldHelper> helper, C2Param::Index index) : _mHelper(helper), _mField(helper->makeParamField(index)) { } template struct C2InterfaceHelper::Field<uint8_t>; template struct C2InterfaceHelper::Field<char>; template struct C2InterfaceHelper::Field<int32_t>; template struct C2InterfaceHelper::Field<uint32_t>; //template struct C2InterfaceHelper::Field<c2_cntr32_t>; template struct C2InterfaceHelper::Field<int64_t>; template struct C2InterfaceHelper::Field<uint64_t>; //template struct C2InterfaceHelper::Field<c2_cntr64_t>; template struct C2InterfaceHelper::Field<float>; /* --------------------------------- Factory --------------------------------- */ struct C2InterfaceHelper::FactoryImpl : public C2InterfaceHelper::Factory { virtual std::shared_ptr<C2ParamReflector> getReflector() const override { return _mReflector; } virtual std::shared_ptr<ParamHelper> getParamHelper(const ParamRef &param) const override { return _mParams.find(param)->second; } public: FactoryImpl(std::shared_ptr<C2ParamReflector> reflector) : _mReflector(reflector) { } virtual ~FactoryImpl() = default; void addParam(std::shared_ptr<ParamHelper> param) { _mParams.insert({ param->ref(), param }); _mIndexToHelper.insert({param->index(), param}); // add down-dependencies (and validate dependencies as a result) size_t ix = 0; for (const ParamRef &ref : param->getDependenciesAsRefs()) { // dependencies must already be defined if (!_mParams.count(ref)) { C2_LOG(FATAL) << "Parameter " << param->name() << " has a dependency at index " << ix << " that is not yet defined"; } _mParams.find(ref)->second->addDownDependency(param->index()); ++ix; } _mDependencyIndex.emplace(param->index(), _mDependencyIndex.size()); } std::shared_ptr<ParamHelper> getParam(C2Param::Index ix) const { // TODO: handle streams separately const auto it = _mIndexToHelper.find(ix); if (it == _mIndexToHelper.end()) { return nullptr; } return it->second; } /** * TODO: this could return a copy using proper pointer cast. */ std::shared_ptr<C2Param> getParamValue(C2Param::Index ix) const { std::shared_ptr<ParamHelper> helper = getParam(ix); return helper ? helper->value() : nullptr; } c2_status_t querySupportedParams( std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const { for (const auto &it : _mParams) { // TODO: change querySupportedParams signature? params->push_back( std::const_pointer_cast<C2ParamDescriptor>(it.second->getDescriptor())); } // TODO: handle errors return C2_OK; } size_t getDependencyIndex(C2Param::Index ix) { // in this version of the helper there is only a single stream so // we can look up directly by index auto it = _mDependencyIndex.find(ix); return it == _mDependencyIndex.end() ? SIZE_MAX : it->second; } private: std::map<ParamRef, std::shared_ptr<ParamHelper>> _mParams; std::map<C2Param::Index, std::shared_ptr<ParamHelper>> _mIndexToHelper; std::shared_ptr<C2ParamReflector> _mReflector; std::map<C2Param::Index, size_t> _mDependencyIndex; }; /* --------------------------------- Helper --------------------------------- */ namespace { static std::string asString(C2Param *p) { char addr[20]; sprintf(addr, "%p:[", p); std::string v = addr; for (size_t i = 0; i < p->size(); ++i) { char d[4]; sprintf(d, " %02x", *(((uint8_t *)p) + i)); v += d + (i == 0); } return v + "]"; } } C2InterfaceHelper::C2InterfaceHelper(std::shared_ptr<C2ReflectorHelper> reflector) : mReflector(reflector), _mFactory(std::make_shared<FactoryImpl>(reflector)) { } size_t C2InterfaceHelper::GetBaseOffset(const std::shared_ptr<C2ParamReflector> &reflector, C2Param::CoreIndex index, size_t offset) { std::unique_ptr<C2StructDescriptor> param = reflector->describe(index); if (param == nullptr) { return ~(size_t)0; // param structure not described } for (const C2FieldDescriptor &field : *param) { size_t fieldOffset = _C2ParamInspector::GetOffset(field); size_t fieldSize = _C2ParamInspector::GetSize(field); size_t fieldExtent = field.extent(); if (offset < fieldOffset) { return ~(size_t)0; // not found } if (offset == fieldOffset) { // exact match return offset; } if (field.extent() == 0 || offset < fieldOffset + fieldSize * fieldExtent) { // reduce to first element in case of array offset = fieldOffset + (offset - fieldOffset) % fieldSize; if (field.type() >= C2FieldDescriptor::STRUCT_FLAG) { // this offset is within a field offset = GetBaseOffset( reflector, field.type() & ~C2FieldDescriptor::STRUCT_FLAG, offset - fieldOffset); return ~offset ? fieldOffset + offset : offset; } } } return ~(size_t)0; // not found } void C2InterfaceHelper::addParameter(std::shared_ptr<ParamHelper> param) { mReflector->addStructDescriptor(param->retrieveStructDescriptor()); c2_status_t err = param->validate(mReflector); if (err != C2_CORRUPTED) { _mFactory->addParam(param); } } c2_status_t C2InterfaceHelper::config( const std::vector<C2Param*> &params, c2_blocking_t mayBlock, std::vector<std::unique_ptr<C2SettingResult>>* const failures, bool updateParams, std::vector<std::shared_ptr<C2Param>> *changes __unused /* TODO */) { bool paramWasInvalid = false; // TODO is this the same as bad value? bool paramNotFound = false; bool paramBadValue = false; bool paramNoMemory = false; bool paramBlocking = false; bool paramTimedOut = false; bool paramCorrupted = false; // dependencies // down dependencies are marked dirty, but params set are not immediately // marked dirty (unless they become down dependency) so that we can // avoid setting them if they did not change // TODO: there could be multiple indices for the same dependency index // { depIx, paramIx } may be a suitable key std::map<size_t, std::pair<C2Param::Index, bool>> dependencies; // we cannot determine the last valid parameter, so add an extra // loop iteration after the last parameter for (size_t p_ix = 0; p_ix <= params.size(); ++p_ix) { C2Param *p = nullptr; C2Param::Index paramIx = 0u; size_t paramDepIx = SIZE_MAX; bool last = p_ix == params.size(); if (!last) { p = params[p_ix]; if (!*p) { paramWasInvalid = true; p->invalidate(); continue; } paramIx = p->index(); paramDepIx = getDependencyIndex(paramIx); if (paramDepIx == SIZE_MAX) { // unsupported parameter paramNotFound = true; continue; } // // first insert - mark not dirty // it may have been marked dirty by a dependency update // this does not overrwrite(!) (void)dependencies.insert({ paramDepIx, { paramIx, false /* dirty */ }}); auto it = dependencies.find(paramDepIx); C2_LOG(VERBOSE) << "marking dependency for setting at #" << paramDepIx << ": " << it->second.first << ", update " << (it->second.second ? "always (dirty)" : "only if changed"); } else { // process any remaining dependencies if (dependencies.empty()) { continue; } C2_LOG(VERBOSE) << "handling dirty down dependencies after last setting"; } // process any dirtied down-dependencies until the next param while (dependencies.size() && dependencies.begin()->first <= paramDepIx) { auto min = dependencies.begin(); C2Param::Index ix = min->second.first; bool dirty = min->second.second; dependencies.erase(min); std::shared_ptr<ParamHelper> param = _mFactory->getParam(ix); C2_LOG(VERBOSE) << "old value " << asString(param->value().get()); if (!last) { C2_LOG(VERBOSE) << "new value " << asString(p); } if (!last && !dirty && ix == paramIx && *param->value() == *p) { // no change in value - and dependencies were not updated // no need to update C2_LOG(VERBOSE) << "ignoring setting unchanged param " << ix; continue; } // apply setting bool changed = false; C2_LOG(VERBOSE) << "setting param " << ix; std::shared_ptr<C2Param> oldValue = param->value(); c2_status_t res = param->trySet( (!last && paramIx == ix) ? p : param->value().get(), mayBlock, &changed, *_mFactory, failures); std::shared_ptr<C2Param> newValue = param->value(); C2_CHECK_EQ(oldValue == newValue, *oldValue == *newValue); switch (res) { case C2_OK: break; case C2_BAD_VALUE: paramBadValue = true; break; case C2_NO_MEMORY: paramNoMemory = true; break; case C2_TIMED_OUT: paramTimedOut = true; break; case C2_BLOCKING: paramBlocking = true; break; case C2_CORRUPTED: paramCorrupted = true; break; default: ;// TODO fatal } // copy back result for configured values (or invalidate if it does not fit or match) if (updateParams && !last && paramIx == ix) { if (!p->updateFrom(*param->value())) { p->invalidate(); } } // compare ptrs as params are copy on write if (changed) { C2_LOG(VERBOSE) << "param " << ix << " value changed"; // value changed update down-dependencies and mark them dirty for (const C2Param::Index ix : param->getDownDependencies()) { C2_LOG(VERBOSE) << 1; auto insert_res = dependencies.insert( { getDependencyIndex(ix), { ix, true /* dirty */ }}); if (!insert_res.second) { (*insert_res.first).second.second = true; // mark dirty } auto it = dependencies.find(getDependencyIndex(ix)); C2_CHECK(it->second.second); C2_LOG(VERBOSE) << "marking down dependencies to update at #" << getDependencyIndex(ix) << ": " << it->second.first; } } } } return (paramCorrupted ? C2_CORRUPTED : paramBlocking ? C2_BLOCKING : paramTimedOut ? C2_TIMED_OUT : paramNoMemory ? C2_NO_MEMORY : (paramBadValue || paramWasInvalid) ? C2_BAD_VALUE : paramNotFound ? C2_BAD_INDEX : C2_OK); } size_t C2InterfaceHelper::getDependencyIndex(C2Param::Index ix) const { return _mFactory->getDependencyIndex(ix); } c2_status_t C2InterfaceHelper::query( const std::vector<C2Param*> &stackParams, const std::vector<C2Param::Index> &heapParamIndices, c2_blocking_t mayBlock __unused /* TODO */, std::vector<std::unique_ptr<C2Param>>* const heapParams) const { bool paramWasInvalid = false; bool paramNotFound = false; bool paramDidNotFit = false; bool paramNoMemory = false; for (C2Param* const p : stackParams) { if (!*p) { paramWasInvalid = true; p->invalidate(); } else { std::shared_ptr<C2Param> value = _mFactory->getParamValue(p->index()); if (!value) { paramNotFound = true; p->invalidate(); } else if (!p->updateFrom(*value)) { paramDidNotFit = true; p->invalidate(); } } } for (const C2Param::Index ix : heapParamIndices) { std::shared_ptr<C2Param> value = _mFactory->getParamValue(ix); if (value) { std::unique_ptr<C2Param> p = C2Param::Copy(*value); if (p != nullptr) { heapParams->push_back(std::move(p)); } else { paramNoMemory = true; } } else { paramNotFound = true; } } return paramNoMemory ? C2_NO_MEMORY : paramNotFound ? C2_BAD_INDEX : // the following errors are not marked in the return value paramDidNotFit ? C2_OK : paramWasInvalid ? C2_OK : C2_OK; } c2_status_t C2InterfaceHelper::querySupportedParams( std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const { return _mFactory->querySupportedParams(params); } c2_status_t C2InterfaceHelper::querySupportedValues( std::vector<C2FieldSupportedValuesQuery> &fields, c2_blocking_t mayBlock __unused) const { for (C2FieldSupportedValuesQuery &query : fields) { C2_LOG(VERBOSE) << "querying field " << query.field(); C2Param::Index ix = _C2ParamInspector::GetIndex(query.field()); std::shared_ptr<ParamHelper> param = _mFactory->getParam(ix); if (!param) { C2_LOG(VERBOSE) << "bad param"; query.status = C2_BAD_INDEX; continue; } size_t offs = GetBaseOffset( mReflector, ix, _C2ParamInspector::GetOffset(query.field()) - sizeof(C2Param)); if (~offs == 0) { C2_LOG(VERBOSE) << "field could not be found"; query.status = C2_NOT_FOUND; continue; } offs += sizeof(C2Param); C2_LOG(VERBOSE) << "field resolved to " << StringPrintf("@%02zx+%02x", offs, _C2ParamInspector::GetSize(query.field())); std::shared_ptr<FieldHelper> field = param->findField(offs, _C2ParamInspector::GetSize(query.field())); if (!field) { C2_LOG(VERBOSE) << "bad field"; query.status = C2_NOT_FOUND; continue; } const C2FieldSupportedValues *values = nullptr; switch (query.type()) { case C2FieldSupportedValuesQuery::CURRENT: values = field->getSupportedValues(); break; case C2FieldSupportedValuesQuery::POSSIBLE: values = field->getPossibleValues(); break; default: C2_LOG(VERBOSE) << "bad query type: " << query.type(); query.status = C2_BAD_VALUE; } if (values) { query.values = *values; query.status = C2_OK; } else { C2_LOG(DEBUG) << "no values published by component"; query.status = C2_CORRUPTED; } } return C2_OK; }
30,115
9,042
// // $Id: Hello.cpp 91672 2010-09-08 18:44:58Z johnnyw $ // #include "Hello.h" Hello::Hello (CORBA::ORB_ptr orb, Test::Hello_ptr, CORBA::ULong) : orb_ (CORBA::ORB::_duplicate (orb)) { } void Hello::shutdown (void) { this->orb_->shutdown (0); } void Hello::ping (void) { return; } void Hello::throw_location_forward (void) { return; }
349
176
#ifndef STRF_DETAIL_PRINTERS_TUPLE_HPP #define STRF_DETAIL_PRINTERS_TUPLE_HPP // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <strf/detail/facets/encoding.hpp> namespace strf { namespace detail { template <typename Arg> using opt_val_or_cref = std::conditional_t < std::is_array<Arg>::value, const Arg&, Arg > ; template <std::size_t I, typename T> struct indexed_obj { constexpr STRF_HD indexed_obj(const T& cp) : obj(cp) { } T obj; }; struct simple_tuple_from_args {}; template <typename ISeq, typename ... T> class simple_tuple_impl; template <std::size_t ... I, typename ... T> class simple_tuple_impl<std::index_sequence<I...>, T...> : private indexed_obj<I, T> ... { template <std::size_t J, typename U> static constexpr STRF_HD const indexed_obj<J, U>& _get(const indexed_obj<J, U>& r) { return r; } public: static constexpr std::size_t size = sizeof...(T); template <typename ... Args> constexpr STRF_HD explicit simple_tuple_impl(simple_tuple_from_args, Args&& ... args) : indexed_obj<I, T>(args)... { } template <std::size_t J> constexpr STRF_HD const auto& get() const { return _get<J>(*this).obj; } }; template <typename ... T> class simple_tuple : public strf::detail::simple_tuple_impl < std::make_index_sequence<sizeof...(T)>, T...> { using strf::detail::simple_tuple_impl < std::make_index_sequence<sizeof...(T)>, T...> ::simple_tuple_impl; }; template <typename ... Args> constexpr STRF_HD strf::detail::simple_tuple < strf::detail::opt_val_or_cref<Args>... > make_simple_tuple(const Args& ... args) { return strf::detail::simple_tuple < strf::detail::opt_val_or_cref<Args>... > { strf::detail::simple_tuple_from_args{}, args... }; } template <std::size_t J, typename ... T> constexpr STRF_HD const auto& get(const simple_tuple<T...>& tp) { return tp.template get<J>(); } template <std::size_t I, typename Printer> struct indexed_printer { using char_type = typename Printer::char_type; template <typename FPack, typename Preview, typename Arg> STRF_HD indexed_printer( const FPack& fp , Preview& preview , const Arg& arg ) : printer(make_printer<char_type>(strf::rank<5>(), fp, preview, arg)) { } STRF_HD indexed_printer(const indexed_printer& other) : printer(other.printer) { } STRF_HD indexed_printer(indexed_printer&& other) : printer(other.printer) { } Printer printer; }; template < typename CharT , typename ISeq , typename ... Printers > class printers_tuple_impl; template < typename CharT , std::size_t ... I , typename ... Printers > class printers_tuple_impl<CharT, std::index_sequence<I...>, Printers...> : private detail::indexed_printer<I, Printers> ... { template <std::size_t J, typename T> static STRF_HD const indexed_printer<J, T>& _get(const indexed_printer<J, T>& r) { return r; } public: using char_type = CharT; static constexpr std::size_t size = sizeof...(Printers); template < typename FPack, typename Preview, typename ... Args > STRF_HD printers_tuple_impl ( const FPack& fp , Preview& preview , const strf::detail::simple_tuple<Args...>& args ) : indexed_printer<I, Printers>(fp, preview, args.template get<I>()) ... { } template <std::size_t J> STRF_HD const auto& get() const { return _get<J>(*this).printer; } }; template< typename CharT, std::size_t ... I, typename ... Printers > STRF_HD void write( strf::basic_outbuf<CharT>& ob , const strf::detail::printers_tuple_impl < CharT, std::index_sequence<I...>, Printers... >& printers ) { strf::detail::write_args<CharT>(ob, printers.template get<I>()...); } template < typename CharT, typename ... Printers > using printers_tuple = printers_tuple_impl < CharT , std::make_index_sequence<sizeof...(Printers)> , Printers... >; template < typename CharT , typename FPack , typename Preview , typename ISeq , typename ... Args > class printers_tuple_alias { template <typename Arg> using _printer = decltype(make_printer<CharT>( strf::rank<5>() , std::declval<const FPack&>() , std::declval<Preview&>() , std::declval<const Arg&>())); public: using type = printers_tuple_impl<CharT, ISeq, _printer<Args>...>; }; template < typename CharT, typename FPack, typename Preview, typename ... Args > using printers_tuple_from_args = typename printers_tuple_alias < CharT, FPack, Preview, std::make_index_sequence<sizeof...(Args)>, Args... > :: type; } // namespace detail } // namespace strf #endif // STRF_DETAIL_PRINTERS_TUPLE_HPP
5,123
1,771
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: DisneyDescriptor.proto #include "DisneyDescriptor.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace Persistance { class DisneyDescriptorDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DisneyDescriptor> _instance; } _DisneyDescriptor_default_instance_; } // namespace Persistance namespace protobuf_DisneyDescriptor_2eproto { static void InitDefaultsDisneyDescriptor() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Persistance::_DisneyDescriptor_default_instance_; new (ptr) ::Persistance::DisneyDescriptor(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::Persistance::DisneyDescriptor::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_DisneyDescriptor = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDisneyDescriptor}, {}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_DisneyDescriptor.base); } ::google::protobuf::Metadata file_level_metadata[1]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Persistance::DisneyDescriptor, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Persistance::DisneyDescriptor, grid_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::Persistance::DisneyDescriptor)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::Persistance::_DisneyDescriptor_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "DisneyDescriptor.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\026DisneyDescriptor.proto\022\013Persistance\032\014V" "ector.proto\" \n\020DisneyDescriptor\022\014\n\004grid\030" "\001 \001(\014b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 93); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "DisneyDescriptor.proto", &protobuf_RegisterTypes); ::protobuf_Vector_2eproto::AddDescriptors(); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_DisneyDescriptor_2eproto namespace Persistance { // =================================================================== void DisneyDescriptor::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DisneyDescriptor::kGridFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DisneyDescriptor::DisneyDescriptor() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_DisneyDescriptor_2eproto::scc_info_DisneyDescriptor.base); SharedCtor(); // @@protoc_insertion_point(constructor:Persistance.DisneyDescriptor) } DisneyDescriptor::DisneyDescriptor(const DisneyDescriptor& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); grid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.grid().size() > 0) { grid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.grid_); } // @@protoc_insertion_point(copy_constructor:Persistance.DisneyDescriptor) } void DisneyDescriptor::SharedCtor() { grid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } DisneyDescriptor::~DisneyDescriptor() { // @@protoc_insertion_point(destructor:Persistance.DisneyDescriptor) SharedDtor(); } void DisneyDescriptor::SharedDtor() { grid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void DisneyDescriptor::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DisneyDescriptor::descriptor() { ::protobuf_DisneyDescriptor_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_DisneyDescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const DisneyDescriptor& DisneyDescriptor::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_DisneyDescriptor_2eproto::scc_info_DisneyDescriptor.base); return *internal_default_instance(); } void DisneyDescriptor::Clear() { // @@protoc_insertion_point(message_clear_start:Persistance.DisneyDescriptor) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; grid_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } bool DisneyDescriptor::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:Persistance.DisneyDescriptor) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // bytes grid = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->mutable_grid())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:Persistance.DisneyDescriptor) return true; failure: // @@protoc_insertion_point(parse_failure:Persistance.DisneyDescriptor) return false; #undef DO_ } void DisneyDescriptor::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:Persistance.DisneyDescriptor) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // bytes grid = 1; if (this->grid().size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( 1, this->grid(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:Persistance.DisneyDescriptor) } ::google::protobuf::uint8* DisneyDescriptor::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:Persistance.DisneyDescriptor) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // bytes grid = 1; if (this->grid().size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( 1, this->grid(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:Persistance.DisneyDescriptor) return target; } size_t DisneyDescriptor::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Persistance.DisneyDescriptor) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // bytes grid = 1; if (this->grid().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::BytesSize( this->grid()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DisneyDescriptor::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Persistance.DisneyDescriptor) GOOGLE_DCHECK_NE(&from, this); const DisneyDescriptor* source = ::google::protobuf::internal::DynamicCastToGenerated<const DisneyDescriptor>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Persistance.DisneyDescriptor) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Persistance.DisneyDescriptor) MergeFrom(*source); } } void DisneyDescriptor::MergeFrom(const DisneyDescriptor& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Persistance.DisneyDescriptor) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.grid().size() > 0) { grid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.grid_); } } void DisneyDescriptor::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Persistance.DisneyDescriptor) if (&from == this) return; Clear(); MergeFrom(from); } void DisneyDescriptor::CopyFrom(const DisneyDescriptor& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Persistance.DisneyDescriptor) if (&from == this) return; Clear(); MergeFrom(from); } bool DisneyDescriptor::IsInitialized() const { return true; } void DisneyDescriptor::Swap(DisneyDescriptor* other) { if (other == this) return; InternalSwap(other); } void DisneyDescriptor::InternalSwap(DisneyDescriptor* other) { using std::swap; grid_.Swap(&other->grid_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata DisneyDescriptor::GetMetadata() const { protobuf_DisneyDescriptor_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_DisneyDescriptor_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace Persistance namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::Persistance::DisneyDescriptor* Arena::CreateMaybeMessage< ::Persistance::DisneyDescriptor >(Arena* arena) { return Arena::CreateInternal< ::Persistance::DisneyDescriptor >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
13,225
4,367
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Reflection // Name: AssemblyVersionAttribute // C++ Typed Name: mscorlib::System::Reflection::AssemblyVersionAttribute #include <gtest/gtest.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyVersionAttribute.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Reflection { //Constructors Tests //AssemblyVersionAttribute(mscorlib::System::String version) TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,Constructor_1) { } //Public Methods Tests //Public Properties Tests // Property Version // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,get_Version_Test) { } // Property TypeId // Return Type: mscorlib::System::Object // Property Get Method TEST(mscorlib_System_Reflection_AssemblyVersionAttribute_Fixture,get_TypeId_Test) { } } } }
1,175
477
/** Copyright (c) Audi Autonomous Driving Cup. 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: “This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.” 4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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. ********************************************************************** * $Author:: spiesra $ $Date:: 2015-05-13 08:29:07#$ $Rev:: 35003 $ **********************************************************************/ #include "stdafx.h" #include "coder_description.h" #include "cJuryModule.h" #include "QFileDialog" #include "QMessageBox" #include "QDomDocument" #include "QTimer" cJuryConnectionThread::cJuryConnectionThread() : m_pJuryModule(NULL) { } void cJuryConnectionThread::run() { if (m_pJuryModule) { // if jury module is set, call the connect/disconnect method m_pJuryModule->ConnectDisconnectNetworkClients(); } } tResult cJuryConnectionThread::RegisterJuryModule(cJuryModule* pJuryModule) { m_pJuryModule = pJuryModule; RETURN_NOERROR; } cJuryModule::cJuryModule(QWidget *parent) : QWidget(parent), m_i16LastDriverEntryId(-1), m_pDataRemoteSystemData(NULL), m_pDataSystemDataSender(NULL), m_pLocalSystemSender(NULL), m_pRemoteSystem(NULL), m_pNetwork(NULL), m_bConnected(false), m_oLastReceiveTimestamp(QTime()), m_pWidget(new Ui::cDisplayWidget), m_strManeuverList("") { // setup the widget m_pWidget->setupUi(this); // initialize the Qt connections Init(); // set the jury module pointer m_oConnectionThread.RegisterJuryModule(this); } void cJuryModule::OnCloseWindows() { close(); } cJuryModule::~cJuryModule() { // delete the widget if (m_pWidget != NULL) { delete m_pWidget; m_pWidget = NULL; } // cleanup any network conection CleanUpNetwork(); } tResult cJuryModule::Init() { // connect the widgets and methods connect(m_pWidget->m_btnFileSelection, SIGNAL(released()), this, SLOT(OnManeuverListButton())); connect(m_pWidget->m_btnFileSelectionDescr, SIGNAL(released()), this, SLOT(OnDescriptionFileButton())); connect(m_pWidget->m_edtManeuverFile, SIGNAL(returnPressed()), this, SLOT(OnManeuverListSelected())); connect(m_pWidget->m_edtManeuverFile, SIGNAL(editingFinished()), this, SLOT(OnManeuverListSelected())); connect(m_pWidget->m_btnEmergencyStop, SIGNAL(released()), this, SLOT(OnEmergencyStop())); connect(m_pWidget->m_btnStart, SIGNAL(released()), this, SLOT(OnStart())); connect(m_pWidget->m_btnStop, SIGNAL(released()), this, SLOT(OnStop())); connect(m_pWidget->m_btnRequest, SIGNAL(released()), this, SLOT(OnRequestReady())); connect(m_pWidget->m_btnConnectDisconnect, SIGNAL(released()), this, SLOT(OnConnectDisconnect())); connect(m_pWidget->m_btnManeuverlist, SIGNAL(released()), this, SLOT(SendManeuverList())); connect(this, SIGNAL(SetDriverState(int, int)), this, SLOT(OnDriverState(int, int))); connect(this, SIGNAL(SetLogText(QString)), this, SLOT(OnAppendText(QString))); connect(this, SIGNAL(SetConnectionState()), this, SLOT(OnConnectionStateChange())); connect(this, SIGNAL(SetControlState()), this, SLOT(OnControlState())); connect(m_pWidget->m_comboSector, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboSectionBoxChanged(int))); connect(m_pWidget->m_comboManeuver, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboActionBoxChanged(int))); connect(m_pWidget->m_cbxLocalHost, SIGNAL(stateChanged(int)), this, SLOT(OnLocalhostCheckChanged(int))); connect(m_pWidget->m_btnOpenTerminal, SIGNAL(released()), this, SLOT(OnOpenTerminalProcess())); connect(&m_oTerminalProcess, SIGNAL(started()), this, SLOT(OnProcessStarted())); connect(&m_oTerminalProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(OnProcessFinished(int,QProcess::ExitStatus))); connect(&m_oTerminalProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnProcessError(QProcess::ProcessError))); // set the connection and control state SetConnectionState(); SetControlState(); RETURN_NOERROR; } void cJuryModule::OnConnectionStateChange() { if(m_pWidget) { // control the button text and background if (m_bConnected) { m_pWidget->m_btnConnectDisconnect->setText("disconnect"); m_pWidget->m_btnConnectDisconnect->setStyleSheet("background:green"); } else { m_pWidget->m_btnConnectDisconnect->setText("connect"); m_pWidget->m_btnConnectDisconnect->setStyleSheet(""); } SetControlState(); } } void cJuryModule::OnControlState() { // control the emergency button and the maneuver control group tBool bEnabled = false; if (m_bConnected && !m_strManeuverList.empty()) { bEnabled = true; } m_pWidget->grpManeuverCtrl->setEnabled(bEnabled); m_pWidget->m_btnEmergencyStop->setEnabled(m_bConnected); } tResult cJuryModule::CleanUpNetwork() { // delete the network m_pLocalSystemSender = NULL; m_pRemoteSystem = NULL; m_pDataSystemDataSender = NULL; m_pDataRemoteSystemData = NULL; if (m_pNetwork) { delete m_pNetwork; m_pNetwork = NULL; } RETURN_NOERROR; } tResult cJuryModule::ConnectDisconnectNetworkClients() { if (m_pNetwork) { // network is present, so we have to disconnect QString strText = QString("Disconnecting..."); SetLogText(strText); m_bConnected = false; SetConnectionState(); m_pNetwork->DestroySystem(m_pLocalSystemSender); m_pNetwork->DestroySystem(m_pRemoteSystem); CleanUpNetwork(); strText = QString("Disconnected"); SetLogText(strText); RETURN_NOERROR; } // network is not present, connect QString strText = QString("Trying to connect to ") + QString(GetIpAdress().c_str()) + QString(" ..."); SetLogText(strText); // create new network m_pNetwork = new cNetwork(""); cNetwork::SetLogLevel(cNetwork::eLOG_LVL_ERROR); //Initialize the network tResult nRes = m_pNetwork->Init(); if (ERR_NOERROR != nRes) //Never forget the error check { CleanUpNetwork(); return nRes; } const tInt nFlags = 0; tString strIp = GetIpAdress(); //Create one local system which is part of the network //this is to send data to the world !! const tString strDataSendUrl("tcp://" + strIp + ":5000"); m_pLocalSystemSender = NULL; //Gets assigned while created const tString strLocalSystemNameData("JuryModuleData"); //Name of the first system nRes = m_pNetwork->CreateLocalSystem(&m_pLocalSystemSender, strLocalSystemNameData, strDataSendUrl, nFlags);//if not given, default = 0 if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } //the system can also have some data available nRes = m_pLocalSystemSender->GetDataServer(&m_pDataSystemDataSender); if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } // check if there is a description file set, otherwise use the coded description QString strDescriptionFile = m_pWidget->m_edtDescriptionFile->text(); tString strMyDDLDefinitionAsString; if (!QFile::exists(strDescriptionFile)) { SetLogText("No valid media description file set. Will use the internal description."); strMyDDLDefinitionAsString = CONNLIB_JURY_MODULE_DDL_AS_STRING; } else { SetLogText(QString("Using media description file ") + strDescriptionFile); strMyDDLDefinitionAsString = strDescriptionFile.toStdString(); } nRes = m_pDataSystemDataSender->AddDDL(strMyDDLDefinitionAsString); if (ERR_NOERROR != nRes) { SetLogText("Media description not valid. Please set a valid file."); CleanUpNetwork(); return nRes; } // define the description of outgoing data tDataDesc sDescEmergencyStopRaw; sDescEmergencyStopRaw.strName = CONLIB_OUT_PORT_NAME_EMERGENCY_STOP; sDescEmergencyStopRaw.strDescriptionComment = "The emergency stop struct in raw mode"; sDescEmergencyStopRaw.strType = "plainraw"; nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_EMERGENCY_STOP, sDescEmergencyStopRaw); if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } tDataDesc sDescJuryStruct; sDescJuryStruct.strName = CONLIB_OUT_PORT_NAME_JURY_STRUCT; sDescJuryStruct.strDescriptionComment = "the jury data as struct"; sDescJuryStruct.strType = "plainraw"; nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_JURY_STRUCT, sDescJuryStruct); if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } tDataDesc sDescManeuverList; sDescManeuverList.strName = CONLIB_OUT_PORT_NAME_MANEUVER_LIST; sDescManeuverList.strDescriptionComment = "the Manuverlist as string"; sDescManeuverList.strType = "plainraw"; nRes = m_pDataSystemDataSender->PublishPlainData(CONLIB_STREAM_NAME_MANEUVER_LIST, sDescManeuverList); if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } //this is to receive data from a specific sender!! //Create one local system which is part of the network const tString strDataUrl("tcp://" + strIp + ":5000"); m_pRemoteSystem = NULL; //Gets assigned while created const tString strSystemNameData("ADTFData"); //Name of the first system nRes = m_pNetwork->CreateRemoteSystem(&m_pRemoteSystem, strSystemNameData, strDataUrl, nFlags);//if not given, default = 0 if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } nRes = m_pRemoteSystem->GetDataServer(&m_pDataRemoteSystemData); if (ERR_NOERROR != nRes) { CleanUpNetwork(); return nRes; } //this is only required if you subscribe to raw data, otherwise the DDL will be transmitted by the sender. m_pDataRemoteSystemData->AddDDL(strMyDDLDefinitionAsString); m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_DRIVER_STRUCT, CONLIB_STREAM_NAME_DRIVER_STRUCT, this); m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK, CONLIB_STREAM_NAME_JURY_STRUCT, this); m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK, CONLIB_STREAM_NAME_EMERGENCY_STOP, this); m_pDataRemoteSystemData->SubscribeForPlainDataRaw(CONLIB_IN_PORT_NAME_MANEUVER_LIST, CONLIB_STREAM_NAME_MANEUVER_LIST, this); // set the connection state in ui strText = QString("Connected to ") + QString(GetIpAdress().c_str()); SetLogText(strText); m_bConnected = true; SetConnectionState(); RETURN_NOERROR; } void cJuryModule::OnManeuverListButton() { // open file dialog to get the maneuver list file QString strManeuverFile = QFileDialog::getOpenFileName(this, tr("Open Maneuver List"), m_strManeuverFile, tr("AADC Maneuver List (*.xml)")); if(!strManeuverFile.isEmpty()) { m_pWidget->m_edtManeuverFile->setText(strManeuverFile); emit OnManeuverListSelected(); } } void cJuryModule::OnDescriptionFileButton() { // open a file dialog to get the description file QString strDescriptionFile = QFileDialog::getOpenFileName(this, tr("Open media description file"), "", tr("ADTF media description file (*.description)")); if(!strDescriptionFile.isEmpty()) { m_pWidget->m_edtDescriptionFile->setText(strDescriptionFile); } } tResult cJuryModule::OnOpenTerminalProcess() { // start the given terminal process (detached because otherwise no terminal window will be opened if(m_oTerminalProcess.startDetached(m_pWidget->m_edtTerminalProgram->text() )) { OnProcessStarted(); } else { OnProcessError(m_oTerminalProcess.error()); } RETURN_NOERROR; } void cJuryModule::OnProcessStarted() { // set text in log SetLogText("Terminal program started"); } void cJuryModule::OnProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { // set text in log SetLogText(QString("Process finished with ") + QString::number(exitCode) + QString("and state ") + QString(exitStatus)); } void cJuryModule::OnProcessError(QProcess::ProcessError error) { // set text in log SetLogText(QString("Process failed with error code ") + QString::number(error) + QString(": ") + m_oTerminalProcess.errorString()); } void cJuryModule::OnManeuverListSelected() { // get the maneuver file from edit field QString strManeuverFile = m_pWidget->m_edtManeuverFile->text(); if (!strManeuverFile.isEmpty()) { // check if file exists if (QFile::exists(strManeuverFile) && strManeuverFile.contains(".xml")) { // load the file m_strManeuverFile = strManeuverFile; LoadManeuverList(); } else { // file not found, show message box QMessageBox::critical(this, tr("File not found or valid"), tr("The given Maneuver List can not be found or is not valid.")); m_pWidget->m_edtManeuverFile->setFocus(); } } else { // do nothing } } tResult cJuryModule::OnDataUpdate(const tString& strName, const tVoid* pData, const tSize& szSize) { // called from the connection lib on new data // check data size RETURN_IF_POINTER_NULL(pData); if (szSize <= 0) { RETURN_ERROR(ERR_INVALID_ARG); } // check the name of the data if (strName == CONLIB_IN_PORT_NAME_DRIVER_STRUCT) { // data from driver const tDriverStruct* sDriverData = (const tDriverStruct*) pData; //update the gui emit SetDriverState(sDriverData->i8StateID, sDriverData->i16ManeuverEntry); //update the timeline if (m_i16LastDriverEntryId < sDriverData->i16ManeuverEntry || m_i16LastDriverEntryId == -1 || sDriverData->i8StateID == -1 || sDriverData->i8StateID == 2) { // set the first time manually if (m_oLastReceiveTimestamp.isNull()) { m_oLastReceiveTimestamp = QTime::currentTime(); m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry; } // calc the time diff tTimeStamp timeDiff = (m_oLastReceiveTimestamp.msecsTo(QTime::currentTime())); //time in milliseconds QString Message; switch (stateCar(sDriverData->i8StateID)) { case stateCar_READY: Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Ready"; break; case stateCar_RUNNING: Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: OK"; break; case stateCar_COMPLETE: Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Complete"; break; case stateCar_ERROR: Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Error"; break; case stateCar_STARTUP: break; } // set the last time m_oLastReceiveTimestamp = QTime::currentTime(); m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry; //update the ui SetLogText(Message); } } else if (strName == CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK) { // data from jury loopback const tJuryStruct* sJuryLoopbackData = (const tJuryStruct*) pData; QString strText = QString("Loopback Jury: Received jury struct loopback with action "); switch(juryActions(sJuryLoopbackData->i8ActionID)) { case action_GETREADY: strText += "GETREADY "; break; case action_START: strText += "START "; break; case action_STOP: strText += "STOP "; break; default: strText += "UNKNOWN "; break; } strText += QString(" and maneuver ") + QString::number(sJuryLoopbackData->i16ManeuverEntry); // write text to log (just for checking the connection) SetLogText(strText); //QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText)); } else if (strName == CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK) { // data from emergency loopback const tJuryEmergencyStop* sJuryLoopbackData = (const tJuryEmergencyStop*) pData; QString strText = QString("Loopback Emergency: Received emergency loopback with "); strText += (sJuryLoopbackData->bEmergencyStop == true) ? QString("true") : QString("false"); // write text to log (just for checking the connection) SetLogText(strText); //QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText)); } else if (strName == CONLIB_IN_PORT_NAME_MANEUVER_LIST) { // data from maneuverlist loopback const tInt32* i32DataSize = (const tInt32*) pData; const tChar* pcString = (const tChar*) ((tChar*)pData + sizeof(tInt32)); tString strManeuver(pcString); QString strText = QString("Loopback ManeuverList received"); // check the data content if(*i32DataSize != (m_strManeuverList.size() + sizeof(char))) { strText += QString(" size does not match"); } if(strManeuver != m_strManeuverList) { strText += QString(" content does not match"); } strText += "!!!"; // write text to log (just for checking the connection) SetLogText(strText); //QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText)); } RETURN_NOERROR; } tResult cJuryModule::OnPlainDataDescriptionUpdate(const tChar* strDataName, const tChar* strStructName, const tChar* strDDL) { // will be called, if we are using NON-RAW-Mode // write text to log (just for checking the connection) SetLogText(QString("Received description update for ") + QString(strDataName)); RETURN_NOERROR; } tResult cJuryModule::OnEmergencyStop() { // emergency stop button pressed // send emergency stop 3 times m_nEmergencyCounter = 3; QTimer::singleShot(0, this, SLOT(SendEmergencyStop())); RETURN_NOERROR; } tResult cJuryModule::OnRequestReady() { // request button pressed // setup jury struct and send 3 times m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex(); m_actionID = action_GETREADY; m_iJuryStructCounter = 3; QTimer::singleShot(0, this, SLOT(SendJuryStruct())); RETURN_NOERROR; } tResult cJuryModule::OnStop() { // stop button pressed // setup jury struct and send 3 times m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex(); m_actionID = action_STOP; m_iJuryStructCounter = 3; QTimer::singleShot(0, this, SLOT(SendJuryStruct())); RETURN_NOERROR; } tResult cJuryModule::OnStart() { // start button pressed // setup jury struct and send 3 times m_i16ManeuverEntry = m_pWidget->m_comboManeuver->currentIndex(); m_actionID = action_START; m_iJuryStructCounter = 3; QTimer::singleShot(0, this, SLOT(SendJuryStruct())); RETURN_NOERROR; } tResult cJuryModule::OnLocalhostCheckChanged(int nState) { // localhost checkbox state changed bool bEnable = false; if (nState == 0) { bEnable = true; } // enable/disable ip settings m_pWidget->m_spinBoxIP1->setEnabled(bEnable); m_pWidget->m_spinBoxIP2->setEnabled(bEnable); m_pWidget->m_spinBoxIP3->setEnabled(bEnable); m_pWidget->m_spinBoxIP4->setEnabled(bEnable); RETURN_NOERROR; } tResult cJuryModule::LoadManeuverList() { // load the maneuver list // clear old list m_strManeuverList.clear(); // use QDom for parsing QDomDocument oDoc("maneuver_list"); QFile oFile(m_strManeuverFile); // open file if(!oFile.open(QIODevice::ReadOnly)) { RETURN_ERROR(ERR_FILE_NOT_FOUND); } if (!oDoc.setContent(&oFile)) { oFile.close(); RETURN_ERROR(ERR_INVALID_FILE); } // get the root element QDomElement oRoot = oDoc.documentElement(); // get all sectors from DOM QDomNodeList lstSectors = oRoot.elementsByTagName("AADC-Sector"); // iterate over all sectors for (int nIdxSectors = 0; nIdxSectors < lstSectors.size(); ++nIdxSectors) { // get the ids and maneuver from sector QDomNode oNodeSector = lstSectors.item(nIdxSectors); QDomElement oElementSector = oNodeSector.toElement(); QString strIdSector = oElementSector.attribute("id"); tSector sSector; sSector.id = strIdSector.toInt(); QDomNodeList lstManeuver = oElementSector.elementsByTagName("AADC-Maneuver"); // iterate over all maneuver for (int nIdxManeuver = 0; nIdxManeuver < lstManeuver.size(); ++nIdxManeuver) { // get the id and the action QDomNode oNodeManeuver = lstManeuver.item(nIdxManeuver); QDomElement oElementManeuver = oNodeManeuver.toElement(); QString strIdManeuver = oElementManeuver.attribute("id"); tAADC_Maneuver sManeuver; sManeuver.nId = strIdManeuver.toInt(); sManeuver.action = oElementManeuver.attribute("action").toStdString(); // fill the internal maneuver list sSector.lstManeuvers.push_back(sManeuver); } // fill the internal sector list m_lstSections.push_back(sSector); } // check sector list if (m_lstSections.size() > 0) { SetLogText("Jury Module: Loaded Maneuver file successfully."); } else { SetLogText("Jury Module: no valid Maneuver Data found!"); } // fill the combo boxes FillComboBoxes(); // get the xml string for transmission m_strManeuverList = oDoc.toString().toStdString(); // set the controls (enable/disable) SetControlState(); RETURN_NOERROR; } tResult cJuryModule::SendEmergencyStop() { // the signal was transmitted as long as emergency counter is set if(m_nEmergencyCounter > 0) { tJuryEmergencyStop sEmergencyStop; sEmergencyStop.bEmergencyStop = true; m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_EMERGENCY_STOP, &sEmergencyStop, sizeof(sEmergencyStop)); --m_nEmergencyCounter; QTimer::singleShot(1000, this, SLOT(SendEmergencyStop())); } RETURN_NOERROR; } tResult cJuryModule::SendJuryStruct() { // the signal was transmitted as long as jury struct counter is set if (m_iJuryStructCounter > 0) { tJuryStruct sJury; sJury.i8ActionID = m_actionID; sJury.i16ManeuverEntry = m_i16ManeuverEntry; m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_JURY_STRUCT, &sJury, sizeof(sJury)); --m_iJuryStructCounter; QTimer::singleShot(1000, this, SLOT(SendJuryStruct())); } RETURN_NOERROR; } tResult cJuryModule::SendManeuverList() { // only if maneuver file is set it will be transmitted if (!m_strManeuverList.empty()) { // hack to transmit data with dynamic size tInt32 i32StringSize = (tInt32) (m_strManeuverList.size() + sizeof(tChar)); // plus one more char for terminating /0 tSize szBufferSize = i32StringSize * sizeof(char) + sizeof(i32StringSize); // buffer size is string size plus also transmitted size-value // create a buffer tUInt8 *pui8Buffer = new tUInt8[szBufferSize]; tInt32* pi32SizeInBuffer = (tInt32*) pui8Buffer; // set the string size (needed for serialization/deserialization) *pi32SizeInBuffer = i32StringSize; // copy the maneuverlist string into the buffer memcpy(pui8Buffer + sizeof(i32StringSize), m_strManeuverList.c_str(), i32StringSize * sizeof(char)); // transmit the data buffer m_pDataSystemDataSender->UpdateData(CONLIB_OUT_PORT_NAME_MANEUVER_LIST, pui8Buffer, szBufferSize); // cleanup delete [] pui8Buffer; //QTimer::singleShot(1000, this, SLOT(SendManeuverList())); } RETURN_NOERROR; } void cJuryModule::OnDriverState(int state, int entryId) { // set the driver state SetDriverManeuverID(entryId); switch (stateCar(state)) { case stateCar_ERROR: SetDriverStateError(); break; case stateCar_READY: SetDriverStateReady(); break; case stateCar_RUNNING: SetDriverStateRun(); break; case stateCar_COMPLETE: SetDriverStateComplete(); break; case stateCar_STARTUP: break; } } void cJuryModule::OnAppendText(QString text) { // append the given text to the log field if(m_pWidget) { m_pWidget->m_edtLogField->append(text); } } void cJuryModule::OnComboActionBoxChanged(int index) { // search for the right section entry for(unsigned int nIdxSection = 0; nIdxSection < m_lstSections.size(); nIdxSection++) { for(unsigned int nIdxManeuver = 0; nIdxManeuver < m_lstSections[nIdxSection].lstManeuvers.size(); nIdxManeuver++) { if(index == m_lstSections[nIdxSection].lstManeuvers[nIdxManeuver].nId) { m_pWidget->m_comboSector->setCurrentIndex(nIdxSection); break; } } } } void cJuryModule::OnComboSectionBoxChanged(int index) { //get the action id from selected section and write it to action combo box m_pWidget->m_comboManeuver->setCurrentIndex(m_lstSections[index].lstManeuvers[0].nId); } void cJuryModule::SetDriverStateError() { // set the background and text m_pWidget->m_lblState->setStyleSheet("background-color: rgb(255,0,0);"); m_pWidget->m_lblState->setText("Error"); } void cJuryModule::SetDriverStateRun() { // set the background and text m_pWidget->m_lblState->setStyleSheet("background-color: rgb(0,255,0);"); m_pWidget->m_lblState->setText("Running"); } void cJuryModule::SetDriverStateReady() { // set the background and text m_pWidget->m_lblState->setStyleSheet("background-color: rgb(255,255,0);"); m_pWidget->m_lblState->setText("Ready"); } void cJuryModule::SetDriverStateComplete() { // set the background and text m_pWidget->m_lblState->setStyleSheet("background-color: rgb(0,0,255);"); m_pWidget->m_lblState->setText("Complete"); } tString cJuryModule::GetIpAdress() { // get the ip adress from the spinners or if localhost checkbox is checked use "localhost" if (m_pWidget->m_cbxLocalHost->isChecked()) { m_strIPAdress = "localhost"; } else { QString strIp1 = m_pWidget->m_spinBoxIP1->text(); QString strIp2 = m_pWidget->m_spinBoxIP2->text(); QString strIp3 = m_pWidget->m_spinBoxIP3->text(); QString strIp4 = m_pWidget->m_spinBoxIP4->text(); m_strIPAdress = strIp1.toStdString() + "." + strIp2.toStdString() + "." + strIp3.toStdString() + "." + strIp4.toStdString(); } return m_strIPAdress; } void cJuryModule::OnConnectDisconnect() { // connect / disconnect button pressed // check for already running connection thread if (!m_oConnectionThread.isRunning()) { m_oConnectionThread.start(); } // the timer will use the main thread which freezes the UI while connecting //QTimer::singleShot(0, this, SLOT(ConnectDisconnectNetworkClients())); } void cJuryModule::SetDriverManeuverID(tInt16 id) { // set the id from received driver struct m_pWidget->m_lblDriverManeuverID->setText(QString::number(id)); } void cJuryModule::FillComboBoxes() { int nLastManeuverId = 0; int nLastSectionId = 0; // vector of maneuver names to fill the combobox also with names std::vector<std::string> lstManeuverNames; // find the last maneuver and section id for(unsigned int i = 0; i < m_lstSections.size(); i++) { nLastSectionId++; for(unsigned int j = 0; j < m_lstSections[i].lstManeuvers.size(); j++) { nLastManeuverId++; lstManeuverNames.push_back(m_lstSections[i].lstManeuvers[j].action); } } // clear the old entries m_pWidget->m_comboManeuver->clear(); m_pWidget->m_comboSector->clear(); // fill the combo boxes for(int i = 0; i < nLastManeuverId; i++) { m_pWidget->m_comboManeuver->addItem(QString::number(i) + QString(" - ") + QString(lstManeuverNames[i].c_str())); } for(int i = 0; i < nLastSectionId; i++) { m_pWidget->m_comboSector->addItem(QString::number(i)); } }
31,155
10,451
#include "Box.hpp" Box::Box() { lleno = false; } Box::~Box() { } void Box::meter(Pasajero p, int tiempo) { pasajero_box = p; lleno = true; pasajero_box.setTiempo_espera(tiempo - pasajero_box.getHora_llegada() + 1); // una vez el pasajero entra al Box, defino el tiempo que ha estado esperando (en la lista) pasajero_box.setTiempo_box(tiempo); } void Box::sacar() { lleno = false; } void Box::imprimir(int tiempo) { if (lleno) { cout << " " << endl; cout << "*************** BOX ***************" << endl; cout << " " << endl; cout << "En el BOX esta el pasajero con ID = " << pasajero_box.getId_pasajero() << " con tiempo: " << tiempo << endl; cout << "Con tiempo de espera = " << pasajero_box.getTiempo_espera() << endl; } else { cout << "BOX VACIO --> no se puede imprimir" << endl; } cout << " " << endl; } //GETTERS Y SETTERS bool Box::isVacio() { return !lleno; } Pasajero Box::getPasajero() { return pasajero_box; } void Box::setPasajero(Pasajero pasajeroBox) { pasajero_box = pasajeroBox; }
1,118
451
#include <iostream> #include <iomanip> int main() { std::cout<<"\n\nThe text without any formating\n"; std::cout<<"Ints"<<"Floats"<<"Doubles"<< "\n"; std::cout<<"\nThe text with setw(15)\n"; std::cout<<"Ints"<<std::setw(15)<<"Floats"<<std::setw(15)<<"Doubles"<< "\n"; std::cout<<"\n\nThe text with tabs\n"; std::cout<<"Ints\t"<<"Floats\t"<<"Doubles"<< "\n"; return 0; }
400
187
/*=================================================================== BlueBerry Platform 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 "berrySaveablesLifecycleEvent.h" namespace berry { const int SaveablesLifecycleEvent::POST_OPEN = 1; const int SaveablesLifecycleEvent::PRE_CLOSE = 2; const int SaveablesLifecycleEvent::POST_CLOSE = 3; const int SaveablesLifecycleEvent::DIRTY_CHANGED = 4; SaveablesLifecycleEvent::SaveablesLifecycleEvent(Object::Pointer source_, int eventType_, const QList<Saveable::Pointer>& saveables_, bool force_) : eventType(eventType_), saveables(saveables_), force(force_), veto(false), source(source_) { } int SaveablesLifecycleEvent::GetEventType() { return eventType; } Object::Pointer SaveablesLifecycleEvent::GetSource() { return source; } QList<Saveable::Pointer> SaveablesLifecycleEvent::GetSaveables() { return saveables; } bool SaveablesLifecycleEvent::IsVeto() { return veto; } void SaveablesLifecycleEvent::SetVeto(bool veto) { this->veto = veto; } bool SaveablesLifecycleEvent::IsForce() { return force; } }
1,498
483
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/companyreg/model/GetInitFlowResult.h> #include <json/json.h> using namespace AlibabaCloud::Companyreg; using namespace AlibabaCloud::Companyreg::Model; GetInitFlowResult::GetInitFlowResult() : ServiceResult() {} GetInitFlowResult::GetInitFlowResult(const std::string &payload) : ServiceResult() { parse(payload); } GetInitFlowResult::~GetInitFlowResult() {} void GetInitFlowResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allNodeListNode = value["NodeList"]["NodeListItem"]; for (auto valueNodeListNodeListItem : allNodeListNode) { NodeListItem nodeListObject; if(!valueNodeListNodeListItem["Index"].isNull()) nodeListObject.index = std::stoi(valueNodeListNodeListItem["Index"].asString()); if(!valueNodeListNodeListItem["Status"].isNull()) nodeListObject.status = valueNodeListNodeListItem["Status"].asString(); if(!valueNodeListNodeListItem["Description"].isNull()) nodeListObject.description = valueNodeListNodeListItem["Description"].asString(); if(!valueNodeListNodeListItem["Code"].isNull()) nodeListObject.code = valueNodeListNodeListItem["Code"].asString(); if(!valueNodeListNodeListItem["Name"].isNull()) nodeListObject.name = valueNodeListNodeListItem["Name"].asString(); if(!valueNodeListNodeListItem["FailReason"].isNull()) nodeListObject.failReason = valueNodeListNodeListItem["FailReason"].asString(); if(!valueNodeListNodeListItem["Id"].isNull()) nodeListObject.id = std::stoi(valueNodeListNodeListItem["Id"].asString()); nodeList_.push_back(nodeListObject); } if(!value["FlowStatus"].isNull()) flowStatus_ = value["FlowStatus"].asString(); } std::vector<GetInitFlowResult::NodeListItem> GetInitFlowResult::getNodeList()const { return nodeList_; } std::string GetInitFlowResult::getFlowStatus()const { return flowStatus_; }
2,570
798
/* Università di Bologna Corso di laurea in Informatica 00819 - Programmazione Stefano Volpe #969766 20/10/2020 35_4.cpp "Array", d. 35, es. 4 */ #include <iostream> using namespace std; void parola(const char str[], int n, char dest[]); int main() { const char s[]{ "Alma Mater Studiorum" }; constexpr size_t dim{ 100 }; char d[dim]; parola(s, 2, d); cout << '"' << d << "\"\n"; } void parola(const char str[], const int n, char dest[]) { constexpr char space{ ' ' }, end{ '\0' }; size_t i{ 0 }; // Spazi iniziali while (str[i] == space) ++i; if (str[i] == end) { // Nessuna parola trovata dest[0] = end; return; } int k; for (k = 1; k < n && str[i] != end; ++k) { // Parola non interessante do ++i; while (str[i] != space && str[i] != end); if (str[i] == end) { // Non abbastanza parole dest[0] = end; return; } // Spazi fra parole do ++i; while (str[i] == space); } if (k < n) { // Nessuna parola trovata dest[0] = end; return; } size_t j{ 0 }; while (str[i] != space && str[i] != end) { dest[j++] = str[i++]; } dest[j] = end; }
1,336
518
#include "Sphere.h" #include "GLee.h" Sphere::Sphere() : Sphere(1.0) {} Sphere::Sphere(double radius) { this->radius = radius; this->slices = 64; this->stacks = 64; this->set_bouding_box(Vector3(radius, 0, 0), Vector3(0, radius, 0), Vector3(0, 0, radius)); } Sphere::~Sphere() { } void Sphere::render() { glutSolidSphere(this->radius, this->slices, this->stacks); }
391
174
/* BugEngine <bugengine.devel@gmail.com> see LICENSE for detail */ #ifndef BE_SCHEDULER_TASK_KERNELTASK_HH_ #define BE_SCHEDULER_TASK_KERNELTASK_HH_ /**************************************************************************************************/ #include <bugengine/scheduler/stdafx.h> #include <bugengine/scheduler/kernel/kernel.script.hh> #include <bugengine/scheduler/kernel/parameters/iparameter.script.hh> #include <bugengine/scheduler/task/itask.hh> namespace BugEngine { namespace KernelScheduler { class Kernel; class IScheduler; }} // namespace BugEngine::KernelScheduler namespace BugEngine { class Scheduler; } namespace BugEngine { namespace Task { class be_api(SCHEDULER) KernelTask : public ITask { friend class ::BugEngine::Scheduler; BE_NOCOPY(KernelTask); private: weak< const KernelScheduler::Kernel > const m_kernel; weak< KernelScheduler::IScheduler > m_targetScheduler; minitl::array< weak< KernelScheduler::IParameter > > const m_parameters; u32 m_subTaskCount; public: KernelTask(istring name, KernelScheduler::SchedulerType type, color32 color, Scheduler::Priority priority, weak< const BugEngine::KernelScheduler::Kernel > kernel, minitl::array< weak< KernelScheduler::IParameter > > parameters); ~KernelTask(); virtual void schedule(weak< Scheduler > scheduler) override; }; }} // namespace BugEngine::Task /**************************************************************************************************/ #endif
1,671
477
#include <dirent.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <string> #include <vector> #include "io.h" // Note that stat() is very slow. We've replaced the call to stat() with // a call to open(). bool FileExists(const char *filename) { int fd = open(filename, O_RDONLY, 0); if (fd == -1) { if (errno == ENOENT) { // I believe this is what happens when there is no such file return false; } fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno); if (errno == 24) { fprintf(stderr, "errno 24 may indicate too many open files\n"); } exit(-1); } else { close(fd); return true; } #if 0 struct stat stbuf; int ret = stat(filename, &stbuf); if (ret == -1) { return false; } else { return true; } #endif } long long int FileSize(const char *filename) { struct stat stbuf; if (stat(filename, &stbuf) == -1) { fprintf(stderr, "FileSize: Couldn't access: %s\n", filename); exit(-1); } return stbuf.st_size; } void Reader::OpenFile(const char *filename) { filename_ = filename; struct stat stbuf; if (stat(filename, &stbuf) == -1) { fprintf(stderr, "Reader::OpenFile: Couldn't access: %s\n", filename); exit(-1); } file_size_ = stbuf.st_size; remaining_ = file_size_; fd_ = open(filename, O_RDONLY, 0); if (fd_ == -1) { fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno); if (errno == 24) { fprintf(stderr, "errno 24 may indicate too many open files\n"); } exit(-1); } overflow_size_ = 0; byte_pos_ = 0; } Reader::Reader(const char *filename) { OpenFile(filename); buf_size_ = kBufSize; if (remaining_ < buf_size_) buf_size_ = remaining_; buf_.reset(new unsigned char[buf_size_]); buf_ptr_ = buf_.get(); end_read_ = buf_.get(); if (! Refresh()) { fprintf(stderr, "Warning: empty file: %s\n", filename); } } // This constructor for use by NewReaderMaybe(). Doesn't call stat(). // I should clean up this code to avoid redundancy. Reader::Reader(const char *filename, long long int file_size) { filename_ = filename; file_size_ = file_size; remaining_ = file_size; fd_ = open(filename, O_RDONLY, 0); if (fd_ == -1) { fprintf(stderr, "Failed to open \"%s\", errno %i\n", filename, errno); if (errno == 24) { fprintf(stderr, "errno 24 may indicate too many open files\n"); } exit(-1); } overflow_size_ = 0; byte_pos_ = 0; buf_size_ = kBufSize; if (remaining_ < buf_size_) buf_size_ = remaining_; buf_.reset(new unsigned char[buf_size_]); buf_ptr_ = buf_.get(); end_read_ = buf_.get(); if (! Refresh()) { fprintf(stderr, "Warning: empty file: %s\n", filename); } } // Returns NULL if no file by this name exists Reader *NewReaderMaybe(const char *filename) { struct stat stbuf; if (stat(filename, &stbuf) == -1) { return NULL; } long long int file_size = stbuf.st_size; return new Reader(filename, file_size); } Reader::~Reader(void) { close(fd_); } bool Reader::AtEnd(void) const { // This doesn't work for CompressedReader // return byte_pos_ == file_size_; return (buf_ptr_ == end_read_ && remaining_ == 0 && overflow_size_ == 0); } void Reader::SeekTo(long long int offset) { long long int ret = lseek(fd_, offset, SEEK_SET); if (ret == -1) { fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n", offset, ret, errno, fd_); fprintf(stderr, "File: %s\n", filename_.c_str()); exit(-1); } remaining_ = file_size_ - offset; overflow_size_ = 0; byte_pos_ = offset; Refresh(); } bool Reader::Refresh(void) { if (remaining_ == 0 && overflow_size_ == 0) return false; if (overflow_size_ > 0) { memcpy(buf_.get(), overflow_, overflow_size_); } buf_ptr_ = buf_.get(); unsigned char *read_into = buf_.get() + overflow_size_; int to_read = buf_size_ - overflow_size_; if (to_read > remaining_) to_read = remaining_; int ret; if ((ret = read(fd_, read_into, to_read)) != to_read) { fprintf(stderr, "Read returned %i not %i\n", ret, to_read); fprintf(stderr, "File: %s\n", filename_.c_str()); fprintf(stderr, "remaining_ %lli\n", remaining_); exit(-1); } remaining_ -= to_read; end_read_ = read_into + to_read; overflow_size_ = 0; return true; } bool Reader::GetLine(string *s) { s->clear(); while (true) { if (buf_ptr_ == end_read_) { if (! Refresh()) { return false; } } if (*buf_ptr_ == '\r') { ++buf_ptr_; ++byte_pos_; continue; } if (*buf_ptr_ == '\n') { ++buf_ptr_; ++byte_pos_; break; } s->push_back(*buf_ptr_); ++buf_ptr_; ++byte_pos_; } return true; } bool Reader::ReadInt(int *i) { if (buf_ptr_ + sizeof(int) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } char my_buf[4]; my_buf[0] = *buf_ptr_++; my_buf[1] = *buf_ptr_++; my_buf[2] = *buf_ptr_++; my_buf[3] = *buf_ptr_++; byte_pos_ += 4; int *int_ptr = reinterpret_cast<int *>(my_buf); *i = *int_ptr; return true; } int Reader::ReadIntOrDie(void) { int i; if (! ReadInt(&i)) { fprintf(stderr, "Couldn't read int; file %s byte pos %lli\n", filename_.c_str(), byte_pos_); exit(-1); } return i; } bool Reader::ReadUnsignedInt(unsigned int *u) { if (buf_ptr_ + sizeof(int) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } char my_buf[4]; my_buf[0] = *buf_ptr_++; my_buf[1] = *buf_ptr_++; my_buf[2] = *buf_ptr_++; my_buf[3] = *buf_ptr_++; byte_pos_ += 4; unsigned int *u_int_ptr = reinterpret_cast<unsigned int *>(my_buf); *u = *u_int_ptr; return true; } unsigned int Reader::ReadUnsignedIntOrDie(void) { unsigned int u; if (! ReadUnsignedInt(&u)) { fprintf(stderr, "Couldn't read unsigned int\n"); fprintf(stderr, "File: %s\n", filename_.c_str()); fprintf(stderr, "Byte pos: %lli\n", byte_pos_); exit(-1); } return u; } bool Reader::ReadLong(long long int *l) { if (buf_ptr_ + sizeof(long long int) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *l = *(long long int *)buf_ptr_; buf_ptr_ += sizeof(long long int); byte_pos_ += sizeof(long long int); return true; } long long int Reader::ReadLongOrDie(void) { long long int l; if (! ReadLong(&l)) { fprintf(stderr, "Couldn't read long\n"); exit(-1); } return l; } bool Reader::ReadUnsignedLong(unsigned long long int *u) { if (buf_ptr_ + sizeof(unsigned long long int) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *u = *(unsigned long long int *)buf_ptr_; buf_ptr_ += sizeof(unsigned long long int); byte_pos_ += sizeof(unsigned long long int); return true; } unsigned long long int Reader::ReadUnsignedLongOrDie(void) { unsigned long long int u; if (! ReadUnsignedLong(&u)) { fprintf(stderr, "Couldn't read unsigned long\n"); exit(-1); } return u; } bool Reader::ReadShort(short *s) { if (buf_ptr_ + sizeof(short) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } // Possible alignment issue? *s = *(short *)buf_ptr_; buf_ptr_ += sizeof(short); byte_pos_ += sizeof(short); return true; } short Reader::ReadShortOrDie(void) { short s; if (! ReadShort(&s)) { fprintf(stderr, "Couldn't read short\n"); exit(-1); } return s; } bool Reader::ReadUnsignedShort(unsigned short *u) { if (buf_ptr_ + sizeof(unsigned short) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *u = *(unsigned short *)buf_ptr_; buf_ptr_ += sizeof(unsigned short); byte_pos_ += sizeof(unsigned short); return true; } unsigned short Reader::ReadUnsignedShortOrDie(void) { unsigned short s; if (! ReadUnsignedShort(&s)) { fprintf(stderr, "Couldn't read unsigned short; file %s byte pos %lli " "file_size %lli\n", filename_.c_str(), byte_pos_, file_size_); exit(-1); } return s; } bool Reader::ReadChar(char *c) { if (buf_ptr_ + sizeof(char) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *c = *(char *)buf_ptr_; buf_ptr_ += sizeof(char); byte_pos_ += sizeof(char); return true; } char Reader::ReadCharOrDie(void) { char c; if (! ReadChar(&c)) { fprintf(stderr, "Couldn't read char\n"); exit(-1); } return c; } bool Reader::ReadUnsignedChar(unsigned char *u) { if (buf_ptr_ + sizeof(unsigned char) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *u = *(unsigned char *)buf_ptr_; buf_ptr_ += sizeof(unsigned char); byte_pos_ += sizeof(unsigned char); return true; } unsigned char Reader::ReadUnsignedCharOrDie(void) { unsigned char u; if (! ReadUnsignedChar(&u)) { fprintf(stderr, "Couldn't read unsigned char\n"); fprintf(stderr, "File: %s\n", filename_.c_str()); fprintf(stderr, "Byte pos: %lli\n", byte_pos_); exit(-1); } return u; } void Reader::ReadOrDie(unsigned char *c) { *c = ReadUnsignedCharOrDie(); } void Reader::ReadOrDie(unsigned short *s) { *s = ReadUnsignedShortOrDie(); } void Reader::ReadOrDie(unsigned int *u) { *u = ReadUnsignedIntOrDie(); } void Reader::ReadOrDie(int *i) { *i = ReadIntOrDie(); } void Reader::ReadOrDie(double *d) { *d = ReadDoubleOrDie(); } void Reader::ReadNBytesOrDie(unsigned int num_bytes, unsigned char *buf) { for (unsigned int i = 0; i < num_bytes; ++i) { if (buf_ptr_ + 1 > end_read_) { if (! Refresh()) { fprintf(stderr, "Couldn't read %i bytes\n", num_bytes); fprintf(stderr, "Filename: %s\n", filename_.c_str()); fprintf(stderr, "File size: %lli\n", file_size_); fprintf(stderr, "Before read byte pos: %lli\n", byte_pos_); fprintf(stderr, "Overflow size: %i\n", overflow_size_); fprintf(stderr, "i %i\n", i); exit(-1); } } buf[i] = *buf_ptr_++; ++byte_pos_; } } void Reader::ReadEverythingLeft(unsigned char *data) { unsigned long long int data_pos = 0ULL; unsigned long long int left = file_size_ - byte_pos_; while (left > 0) { unsigned long long int num_bytes = end_read_ - buf_ptr_; memcpy(data + data_pos, buf_ptr_, num_bytes); buf_ptr_ = end_read_; data_pos += num_bytes; if (data_pos > left) { fprintf(stderr, "ReadEverythingLeft: read too much?!?\n"); exit(-1); } else if (data_pos == left) { break; } if (! Refresh()) { fprintf(stderr, "ReadEverythingLeft: premature EOF?!?\n"); exit(-1); } } } bool Reader::ReadCString(string *s) { *s = ""; while (true) { if (buf_ptr_ + 1 > end_read_) { if (! Refresh()) { return false; } } char c = *buf_ptr_++; ++byte_pos_; if (c == 0) return true; *s += c; } } string Reader::ReadCStringOrDie(void) { string s; if (! ReadCString(&s)) { fprintf(stderr, "Couldn't read string\n"); exit(-1); } return s; } bool Reader::ReadDouble(double *d) { if (buf_ptr_ + sizeof(double) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *d = *(double *)buf_ptr_; buf_ptr_ += sizeof(double); byte_pos_ += sizeof(double); return true; } double Reader::ReadDoubleOrDie(void) { double d; if (! ReadDouble(&d)) { fprintf(stderr, "Couldn't read double: file %s byte pos %lli\n", filename_.c_str(), byte_pos_); exit(-1); } return d; } bool Reader::ReadFloat(float *f) { if (buf_ptr_ + sizeof(float) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *f = *(float *)buf_ptr_; buf_ptr_ += sizeof(float); byte_pos_ += sizeof(float); return true; } float Reader::ReadFloatOrDie(void) { float f; if (! ReadFloat(&f)) { fprintf(stderr, "Couldn't read float: file %s\n", filename_.c_str()); exit(-1); } return f; } // Identical to ReadDouble() bool Reader::ReadReal(double *d) { if (buf_ptr_ + sizeof(double) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *d = *(double *)buf_ptr_; buf_ptr_ += sizeof(double); byte_pos_ += sizeof(double); return true; } // Identical to ReadFloat() bool Reader::ReadReal(float *f) { if (buf_ptr_ + sizeof(float) > end_read_) { if (buf_ptr_ < end_read_) { overflow_size_ = (int)(end_read_ - buf_ptr_); memcpy(overflow_, buf_ptr_, overflow_size_); } if (! Refresh()) { return false; } } *f = *(float *)buf_ptr_; buf_ptr_ += sizeof(float); byte_pos_ += sizeof(float); return true; } void Writer::Init(const char *filename, bool modify, int buf_size) { filename_ = filename; if (modify) { fd_ = open(filename, O_WRONLY, 0666); if (fd_ < 0 && errno == ENOENT) { // If file doesn't exist, open it with creat() fd_ = creat(filename, 0666); } } else { // creat() is supposedly equivalent to passing // O_WRONLY|O_CREAT|O_TRUNC to open(). fd_ = creat(filename, 0666); } if (fd_ < 0) { // Is this how errors are indicated? fprintf(stderr, "Couldn't open %s for writing (errno %i)\n", filename, errno); exit(-1); } buf_size_ = buf_size; buf_.reset(new unsigned char[buf_size_]); end_buf_ = buf_.get() + buf_size_; buf_ptr_ = buf_.get(); } Writer::Writer(const char *filename, int buf_size) { Init(filename, false, buf_size); } Writer::Writer(const char *filename, bool modify) { Init(filename, modify, kBufSize); } Writer::Writer(const char *filename) { Init(filename, false, kBufSize); } Writer::~Writer(void) { Flush(); close(fd_); } // Generally write() writes everything in one call. Haven't seen any cases // that justify the loop I do below. Could take it out. void Writer::Flush(void) { if (buf_ptr_ > buf_.get()) { int left_to_write = (int)(buf_ptr_ - buf_.get()); while (left_to_write > 0) { int written = write(fd_, buf_.get(), left_to_write); if (written < 0) { fprintf(stderr, "Error in flush: tried to write %i, return of %i; errno %i; " "fd %i\n", left_to_write, written, errno, fd_); exit(-1); } else if (written == 0) { // Stall for a bit to avoid busy loop sleep(1); } left_to_write -= written; } } buf_ptr_ = buf_.get(); } // Only makes sense to call if we created the Writer with modify=true void Writer::SeekTo(long long int offset) { Flush(); long long int ret = lseek(fd_, offset, SEEK_SET); if (ret == -1) { fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n", offset, ret, errno, fd_); fprintf(stderr, "File: %s\n", filename_.c_str()); exit(-1); } } long long int Writer::Tell(void) { Flush(); return lseek(fd_, 0LL, SEEK_CUR); } void Writer::WriteInt(int i) { if (buf_ptr_ + sizeof(int) > end_buf_) { Flush(); } // Couldn't we have an alignment issue if we write a char and then an int, // for example? // *(int *)buf_ptr_ = i; memcpy(buf_ptr_, (void *)&i, sizeof(int)); buf_ptr_ += sizeof(int); } void Writer::WriteUnsignedInt(unsigned int u) { if (buf_ptr_ + sizeof(unsigned int) > end_buf_) { Flush(); } *(unsigned int *)buf_ptr_ = u; buf_ptr_ += sizeof(unsigned int); } void Writer::WriteLong(long long int l) { if (buf_ptr_ + sizeof(long long int) > end_buf_) { Flush(); } *(long long int *)buf_ptr_ = l; buf_ptr_ += sizeof(long long int); } void Writer::WriteUnsignedLong(unsigned long long int u) { if (buf_ptr_ + sizeof(unsigned long long int) > end_buf_) { Flush(); } *(unsigned long long int *)buf_ptr_ = u; buf_ptr_ += sizeof(unsigned long long int); } void Writer::WriteShort(short s) { if (buf_ptr_ + sizeof(short) > end_buf_) { Flush(); } *(short *)buf_ptr_ = s; buf_ptr_ += sizeof(short); } void Writer::WriteChar(char c) { if (buf_ptr_ + sizeof(char) > end_buf_) { Flush(); } *(char *)buf_ptr_ = c; buf_ptr_ += sizeof(char); } void Writer::WriteUnsignedChar(unsigned char c) { if (buf_ptr_ + sizeof(unsigned char) > end_buf_) { Flush(); } *(unsigned char *)buf_ptr_ = c; buf_ptr_ += sizeof(unsigned char); } void Writer::WriteUnsignedShort(unsigned short s) { if (buf_ptr_ + sizeof(unsigned short) > end_buf_) { Flush(); } *(unsigned short *)buf_ptr_ = s; buf_ptr_ += sizeof(unsigned short); } void Writer::WriteFloat(float f) { if (buf_ptr_ + sizeof(float) > end_buf_) { Flush(); } *(float *)buf_ptr_ = f; buf_ptr_ += sizeof(float); } void Writer::WriteDouble(double d) { if (buf_ptr_ + sizeof(double) > end_buf_) { Flush(); } *(double *)buf_ptr_ = d; buf_ptr_ += sizeof(double); } // Identical to WriteFloat() void Writer::WriteReal(float f) { if (buf_ptr_ + sizeof(float) > end_buf_) { Flush(); } *(float *)buf_ptr_ = f; buf_ptr_ += sizeof(float); } // Identical to WriteDouble() void Writer::WriteReal(double d) { if (buf_ptr_ + sizeof(double) > end_buf_) { Flush(); } *(double *)buf_ptr_ = d; buf_ptr_ += sizeof(double); } void Writer::Write(unsigned char c) { WriteUnsignedChar(c); } void Writer::Write(unsigned short s) { WriteUnsignedShort(s); } void Writer::Write(int i) { WriteInt(i); } void Writer::Write(unsigned int u) { WriteUnsignedInt(u); } void Writer::Write(double d) { WriteDouble(d); } void Writer::WriteCString(const char *s) { int len = strlen(s); if (buf_ptr_ + len + 1 > end_buf_) { Flush(); } memcpy(buf_ptr_, s, len); buf_ptr_[len] = 0; buf_ptr_ += len + 1; } // Does not write num_bytes into file void Writer::WriteNBytes(unsigned char *bytes, unsigned int num_bytes) { if ((int)num_bytes > buf_size_) { Flush(); while ((int)num_bytes > buf_size_) { buf_size_ *= 2; buf_.reset(new unsigned char[buf_size_]); buf_ptr_ = buf_.get(); end_buf_ = buf_.get() + buf_size_; } } if (buf_ptr_ + num_bytes > end_buf_) { Flush(); } memcpy(buf_ptr_, bytes, num_bytes); buf_ptr_ += num_bytes; } void Writer::WriteBytes(unsigned char *bytes, int num_bytes) { WriteInt(num_bytes); if (num_bytes > buf_size_) { Flush(); while (num_bytes > buf_size_) { buf_size_ *= 2; buf_.reset(new unsigned char[buf_size_]); buf_ptr_ = buf_.get(); end_buf_ = buf_.get() + buf_size_; } } if (buf_ptr_ + num_bytes > end_buf_) { Flush(); } memcpy(buf_ptr_, bytes, num_bytes); buf_ptr_ += num_bytes; } void Writer::WriteText(const char *s) { int len = strlen(s); if (buf_ptr_ + len + 1 > end_buf_) { Flush(); } memcpy(buf_ptr_, s, len); buf_ptr_ += len; } unsigned int Writer::BufPos(void) { return (unsigned int)(buf_ptr_ - buf_.get()); } ReadWriter::ReadWriter(const char *filename) { filename_ = filename; fd_ = open(filename, O_RDWR, 0666); if (fd_ < 0 && errno == ENOENT) { fprintf(stderr, "Can only create a ReadWriter on an existing file\n"); fprintf(stderr, "Filename: %s\n", filename); exit(-1); } } ReadWriter::~ReadWriter(void) { close(fd_); } void ReadWriter::SeekTo(long long int offset) { long long int ret = lseek(fd_, offset, SEEK_SET); if (ret == -1) { fprintf(stderr, "lseek failed, offset %lli, ret %lli, errno %i, fd %i\n", offset, ret, errno, fd_); fprintf(stderr, "File: %s\n", filename_.c_str()); exit(-1); } } int ReadWriter::ReadIntOrDie(void) { int i, ret; if ((ret = read(fd_, &i, 4)) != 4) { fprintf(stderr, "ReadWriter::ReadInt returned %i not 4\n", ret); fprintf(stderr, "File: %s\n", filename_.c_str()); exit(-1); } return i; } void ReadWriter::WriteInt(int i) { int written = write(fd_, &i, 4); if (written != 4) { fprintf(stderr, "Error: tried to write 4 bytes, return of %i; fd %i\n", written, fd_); exit(-1); } } bool IsADirectory(const char *path) { struct stat statbuf; if (stat(path, &statbuf) != 0) return 0; return S_ISDIR(statbuf.st_mode); } // Filenames in listing returned are full paths void GetDirectoryListing(const char *dir, vector<string> *listing) { int dirlen = strlen(dir); bool ends_in_slash = (dir[dirlen - 1] == '/'); listing->clear(); DIR *dfd = opendir(dir); if (dfd == NULL) { fprintf(stderr, "GetDirectoryListing: could not open directory %s\n", dir); exit(-1); } dirent *dp; while ((dp = readdir(dfd))) { if (strcmp(dp->d_name, ".") && strcmp(dp->d_name, "..")) { string full_path = dir; if (! ends_in_slash) { full_path += "/"; } full_path += dp->d_name; listing->push_back(full_path); } } closedir(dfd); } static void RecursivelyDelete(const string &path) { if (! IsADirectory(path.c_str())) { // fprintf(stderr, "Removing file %s\n", path.c_str()); RemoveFile(path.c_str()); return; } vector<string> listing; GetDirectoryListing(path.c_str(), &listing); unsigned int num = listing.size(); for (unsigned int i = 0; i < num; ++i) { RecursivelyDelete(listing[i]); } // fprintf(stderr, "Removing dir %s\n", path.c_str()); RemoveFile(path.c_str()); } void RecursivelyDeleteDirectory(const char *dir) { if (! IsADirectory(dir)) { fprintf(stderr, "Path supplied is not a directory: %s\n", dir); return; } vector<string> listing; GetDirectoryListing(dir, &listing); unsigned int num = listing.size(); for (unsigned int i = 0; i < num; ++i) { RecursivelyDelete(listing[i]); } // fprintf(stderr, "Removing dir %s\n", dir); RemoveFile(dir); } // Gives read/write/execute permissions to everyone void Mkdir(const char *dir) { int ret = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO); if (ret != 0) { if (errno == 17) { // File or directory by this name already exists. We'll just assume // it's a directory and return successfully. return; } fprintf(stderr, "mkdir returned %i; errno %i\n", ret, errno); fprintf(stderr, "Directory: %s\n", dir); exit(-1); } } // FileExists() calls stat() which is very expensive. Try calling // remove() without a preceding FileExists() check. void RemoveFile(const char *filename) { int ret = remove(filename); if (ret) { // ENOENT just signifies that there is no file by the given name if (errno != ENOENT) { fprintf(stderr, "Error removing file: %i; errno %i\n", ret, errno); exit(-1); } } } // How is this different from RemoveFile()? void UnlinkFile(const char *filename) { int ret = unlink(filename); if (ret) { // ENOENT just signifies that there is no file by the given name if (errno != ENOENT) { fprintf(stderr, "Error unlinking file: %i; errno %i\n", ret, errno); exit(-1); } } } void MoveFile(const char *old_location, const char *new_location) { if (! FileExists(old_location)) { fprintf(stderr, "MoveFile: old location \"%s\" does not exist\n", old_location); exit(-1); } if (FileExists(new_location)) { fprintf(stderr, "MoveFile: new location \"%s\" already exists\n", new_location); exit(-1); } int ret = rename(old_location, new_location); if (ret != 0) { fprintf(stderr, "MoveFile: rename() returned %i\n", ret); fprintf(stderr, "Old location: %s\n", old_location); fprintf(stderr, "New location: %s\n", new_location); exit(-1); } } void CopyFile(const char *old_location, const char *new_location) { Reader reader(old_location); Writer writer(new_location); unsigned char uc; while (reader.ReadUnsignedChar(&uc)) { writer.WriteUnsignedChar(uc); } }
25,002
9,720
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeHomeBasePower struct UResults_PlayerScoreRow_C_InitializeHomeBasePower_Params { struct FUniqueNetIdRepl PlayerID; // (Parm) }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializePlayerName struct UResults_PlayerScoreRow_C_InitializePlayerName_Params { class UFortUIScoreReport* ScoreReport; // (Parm, ZeroConstructor, IsPlainOldData) int ScoreReportReferece; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeScores struct UResults_PlayerScoreRow_C_InitializeScores_Params { class UFortUIScoreReport* InScoreReport; // (Parm, ZeroConstructor, IsPlainOldData) int InScoreReportIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.InitializeBackground struct UResults_PlayerScoreRow_C_InitializeBackground_Params { }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.Initialize struct UResults_PlayerScoreRow_C_Initialize_Params { class UFortUIScoreReport* ScoreReport; // (Parm, ZeroConstructor, IsPlainOldData) int ScoreReportIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.Manual Pre Construct struct UResults_PlayerScoreRow_C_Manual_Pre_Construct_Params { bool bIsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.PreConstruct struct UResults_PlayerScoreRow_C_PreConstruct_Params { bool* IsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Results_PlayerScoreRow.Results_PlayerScoreRow_C.ExecuteUbergraph_Results_PlayerScoreRow struct UResults_PlayerScoreRow_C_ExecuteUbergraph_Results_PlayerScoreRow_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
3,021
748
/* * Interactive disassembler (IDA). * Copyright (c) 1990-97 by Ilfak Guilfanov. * ALL RIGHTS RESERVED. * E-mail: ig@estar.msk.su * FIDO: 2:5020/209 * */ #ifndef _LOADER_HPP #define _LOADER_HPP #pragma pack(push, 1) // IDA uses 1 byte alignments! // // This file contains: // - definitions of IDP, LDR, PLUGIN module interfaces. // - functions to load files into the database // - functions to generate output files // - high level functions to work with the database (open, save, close) // // The LDR interface consists of one structure loader_t // The IDP interface consists of one structure processor_t (see idp.hpp) // The PLUGIN interface consists of one structure plugin_t // // Modules can't use standard FILE* functions. // They must use functions from <fpro.h> // // Modules can't use standard memory allocation functions. // They must use functions from <pro.h> // // The exported entry #1 in the module should point to the // the appropriate structure. (loader_t for LDR module, for example) // //---------------------------------------------------------------------- // DEFINITION OF LDR MODULES //---------------------------------------------------------------------- class linput_t; // loader input source. see diskio.hpp for the functions // Loader description block - must be exported from the loader module #define MAX_FILE_FORMAT_NAME 64 struct loader_t { ulong version; // api version, should be IDP_INTERFACE_VERSION ulong flags; // loader flags #define LDRF_RELOAD 0x0001 // loader recognizes NEF_RELOAD flag // // check input file format. if recognized, then return 1 // and fill 'fileformatname'. // otherwise return 0 // This function will be called many times till it returns !=0. // 'n' parameter will be incremented after each call. // Initially, n==0 for each loader. // This function may return a unique file format number instead of 1. // To get this unique number, please contact the author. // // If the return value is ORed with ACCEPT_FIRST, then this format // should be placed first in the "load file" dialog box // #define ACCEPT_FIRST 0x8000 int (idaapi* accept_file)(linput_t *li, char fileformatname[MAX_FILE_FORMAT_NAME], int n); // // load file into the database. // fp - pointer to file positioned at the start of the file // fileformatname - name of type of the file (it was returned // by the accept_file) // neflags - user-supplied flags. They determine how to // load the file. // in the case of failure loader_failure() should be called // void (idaapi* load_file)(linput_t *li, ushort neflags, const char *fileformatname); #define NEF_SEGS 0x0001 // Create segments #define NEF_RSCS 0x0002 // Load resources #define NEF_NAME 0x0004 // Rename entries #define NEF_MAN 0x0008 // Manual load #define NEF_FILL 0x0010 // Fill segment gaps #define NEF_IMPS 0x0020 // Create imports section #define NEF_TIGHT 0x0040 // Don't align segments (OMF) #define NEF_FIRST 0x0080 // This is the first file loaded // into the database. #define NEF_CODE 0x0100 // for load_binary_file: // load as a code segment #define NEF_RELOAD 0x0200 // reload the file at the same place: // don't create segments // don't create fixup info // don't import segments // etc // load only the bytes into the base. // a loader should have LDRF_RELOAD // bit set #define NEF_FLAT 0x0400 // Autocreate FLAT group (PE) #define NEF_MINI 0x0800 // Create mini database (do not copy #define NEF_LOPT 0x1000 // Display additional loader options dialog // // create output file from the database. // this function may be absent. // if fp == NULL, then this function returns: // 0 - can't create file of this type // 1 - ok, can create file of this type // if fp != NULL, then this function should create the output file // int (idaapi* save_file)(FILE *fp, const char *fileformatname); // take care of a moved segment (fix up relocations, for example) // this function may be absent. // from - previous linear address of the segment // to - current linear address of the segment // size - size of the moved segment // fileformatname - the file format // a special calling method move_segm(BADADDR, delta, 0, formatname) // means that the whole program has been moved in the memory (rebased) by delta bytes // returns: 1-ok, 0-failure int (idaapi* move_segm)(ea_t from, ea_t to, asize_t size, const char *fileformatname); // initialize user configurable options based on the input file. // this function may be absent. // fp - pointer to file positioned at the start of the file // This function is called as soon as a loader is selected, and allow the loader // to populate XML variables, select a default processor, ... // returns: true-ok, false-cancel bool (idaapi* init_loader_options)(linput_t *li); }; #ifdef __BORLANDC__ #if sizeof(loader_t) % 4 #error "Size of loader_t is incorrect" #endif #endif extern "C" loader_t LDSC; // (declaration for loaders) // Display a message about a loader failure and stop the loading process // The kernel will destroy the database // If format == NULL, no message will be displayed // This function does not return (it longjumps)! // It may be called only from loader_t.load_file() idaman void ida_export vloader_failure(const char *format, va_list va); inline void loader_failure(const char *format=NULL, ...) { va_list va; va_start(va, format); vloader_failure(format, va); va_end(va); } //---------------------------------------------------------------------- // LDR module file name extensions: #ifdef __NT__ #ifdef __EA64__ #ifdef __AMD64__ #define LOADER_EXT "x64" #else #define LOADER_EXT "l64" #endif #else #define LOADER_EXT "ldw" #endif #endif #ifdef __LINUX__ #ifdef __EA64__ #define LOADER_EXT "llx64" #else #define LOADER_EXT "llx" #endif #endif #ifdef __EA64__ #define LOADER_DLL "*64." LOADER_EXT #else #define LOADER_DLL "*." LOADER_EXT #endif //---------------------------------------------------------------------- // Functions for the UI to load files //---------------------------------------------------------------------- struct load_info_t // List of loaders { load_info_t *next; char dllname[QMAXPATH]; char ftypename[MAX_FILE_FORMAT_NAME]; filetype_t ftype; int pri; // 1-place first, 0-normal priority }; // Build list of potential loaders idaman load_info_t *ida_export build_loaders_list(linput_t *li); // Free the list of loaders idaman void ida_export free_loaders_list(load_info_t *list); // Get name of loader from its DLL file. // (for example, for PE files we will get "PE") idaman char *ida_export get_loader_name_from_dll(char *dllname); // Get name of loader used to load the input file into the database // If no external loader was used, returns -1 // Otherwise copies the loader file name without the extension in the buf // and returns its length // (for example, for PE files we will get "PE") idaman ssize_t ida_export get_loader_name(char *buf, size_t bufsize); // Initialize user configurable options from the given loader // based on the input file. idaman bool ida_export init_loader_options(linput_t *li, load_info_t *loader); // Load a binary file into the database. // This function usually is called from ui. // filename - the name of input file as is // (if the input file is from library, then // this is the name from the library) // li - loader input source // _neflags - see NEF_.. constants. For the first file // the flag NEF_FIRST must be set. // fileoff - Offset in the input file // basepara - Load address in paragraphs // binoff - Load offset (load_address=(basepara<<4)+binoff) // nbytes - Number of bytes to load from the file // 0 - up to the end of the file // If nbytes is bigger than the number of // bytes rest, the kernel will load as much // as possible // Returns: 1-ok, 0-failed (couldn't open the file) idaman bool ida_export load_binary_file( const char *filename, linput_t *li, ushort _neflags, long fileoff, ea_t basepara, ea_t binoff, ulong nbytes); // Load a non-binary file into the database. // This function usually is called from ui. // filename - the name of input file as is // (if the input file is from library, then // this is the name from the library) // li - loader input source // sysdlldir - a directory with system dlls. Pass "." if unknown. // _neflags - see NEF_.. constants. For the first file // the flag NEF_FIRST must be set. // loader - pointer to load_info_t structure. // If the current IDP module has ph.loader != NULL // then this argument is ignored. // Returns: 1-ok, 0-failed idaman bool ida_export load_nonbinary_file( const char *filename, linput_t *li, const char *sysdlldir, ushort _neflags, load_info_t *loader); //-------------------------------------------------------------------------- // Output file types: typedef int ofile_type_t; const ofile_type_t OFILE_MAP = 0, // MAP file OFILE_EXE = 1, // Executable file OFILE_IDC = 2, // IDC file OFILE_LST = 3, // Disassembly listing OFILE_ASM = 4, // Assembly OFILE_DIF = 5; // Difference // Callback functions to output lines: typedef int idaapi html_header_cb_t(FILE *fp); typedef int idaapi html_footer_cb_t(FILE *fp); typedef int idaapi html_line_cb_t(FILE *fp, const char *line, bgcolor_t prefix_color, bgcolor_t bg_color); #define gen_outline_t html_line_cb_t //------------------------------------------------------------------ // Generate an output file // otype - type of output file. // fp - the output file handle // ea1 - start address. For some file types this argument is ignored // ea2 - end address. For some file types this argument is ignored // as usual in ida, the end address of the range is not included // flags - bit combination of GENFLG_... // returns: number of the generated lines. // -1 if an error occured // ofile_exe: 0-can't generate exe file, 1-ok idaman int ida_export gen_file(ofile_type_t otype, FILE *fp, ea_t ea1, ea_t ea2, int flags); // 'flag' is a combination of the following: #define GENFLG_MAPSEG 0x0001 // map: generate map of segments #define GENFLG_MAPNAME 0x0002 // map: include dummy names #define GENFLG_MAPDMNG 0x0004 // map: demangle names #define GENFLG_MAPLOC 0x0008 // map: include local names #define GENFLG_IDCTYPE 0x0008 // idc: gen only information about types #define GENFLG_ASMTYPE 0x0010 // asm&lst: gen information about types too #define GENFLG_GENHTML 0x0020 // asm&lst: generate html (ui_genfile_callback will be used) #define GENFLG_ASMINC 0x0040 // asm&lst: gen information only about types //---------------------------------------------------------------------- // Helper functions for the loaders & ui //---------------------------------------------------------------------- // Load portion of file into the database // This function will include (ea1..ea2) into the addressing space of the // program (make it enabled) // li - pointer ot input source // pos - position in the file // (ea1..ea2) - range of destination linear addresses // patchable - should the kernel remember correspondance of // file offsets to linear addresses. // returns: 1-ok,0-read error, a warning is displayed idaman int ida_export file2base(linput_t *li, long pos, ea_t ea1, ea_t ea2, int patchable); #define FILEREG_PATCHABLE 1 // means that the input file may be // patched (i.e. no compression, // no iterated data, etc) #define FILEREG_NOTPATCHABLE 0 // the data is kept in some encoded // form in the file. // Load database from the memory. // memptr - pointer to buffer with bytes // (ea1..ea2) - range of destination linear addresses // fpos - position in the input file the data is taken from. // if == -1, then no file position correspond to the data. // This function works for wide byte processors too. // returns: always 1 idaman int ida_export mem2base(const void *memptr,ea_t ea1,ea_t ea2,long fpos); // Unload database to a binary file. // fp - pointer to file // pos - position in the file // (ea1..ea2) - range of source linear addresses // This function works for wide byte processors too. // returns: 1-ok(always), write error leads to immediate exit idaman int ida_export base2file(FILE *fp,long pos,ea_t ea1,ea_t ea2); // Load information from DBG file into the database // li - handler to opened input. If NULL, then fname is checked // lname - name of loader module without extension and path // fname - name of file to load (only if fp == NULL) // is_remote - is the file located on a remote computer with // the debugger server? // Returns: 1-ok, 0-error (message is displayed) idaman int ida_export load_loader_module(linput_t *li, const char *lname, const char *fname, bool is_remote); // Add long comment at inf.minEA: // Input file: .... // File format: .... // This function should be called only from the loader to describe the input file. idaman void ida_export create_filename_cmt(void); // Get the input file type // This function can recognize libraries and zip files. idaman filetype_t ida_export get_basic_file_type(linput_t *li); // Get name of the current file type // The current file type is kept in inf.filetype. // buf - buffer for the file type name // bufsize - its size // Returns: size of answer, this function always succeeds idaman size_t ida_export get_file_type_name(char *buf, size_t bufsize); //---------------------------------------------------------------------- // Work with IDS files: read and use information from them // // This structure is used in import_module(): struct impinfo_t { const char *dllname; void (idaapi*func)(uval_t num, const char *name, uval_t node); uval_t node; }; // Find and import DLL module. // This function adds information to the database (renames functions, etc) // module - name of DLL // windir - system directory with dlls // modnode - node with information about imported entries // imports by ordinals: // altval(ord) contains linear address // imports by name: // supval(ea) contains the imported name // Either altval or supval arrays may be absent. // The node should never be deleted. // importer- callback function (may be NULL): // check dll module // call 'func' for all exported entries in the file // fp - pointer to file opened in binary mode. // file position is 0. // ud - pointer to impinfo_t structure // this function checks that 'dllname' match the name of module // if not, it returns 0 // otherwise it calls 'func' for each exported entry // if dllname==NULL then 'func' will be called with num==0 and name==dllname // and returns: // 0 - dllname doesn't match, should continue // 1 - ok // ostype - type of operating system (subdir name) // NULL means the IDS directory itself (not recommended) idaman void ida_export import_module(const char *module, const char *windir, uval_t modnode, int (idaapi*importer)(linput_t *li,impinfo_t *ii), const char *ostype); // Load and apply IDS file // fname - name of file to apply // This function loads the specified IDS file and applies it to the database // If the program imports functions from a module with the same name // as the name of the ids file being loaded, then only functions from this // module will be affected. Otherwise (i.e. when the program does not import // a module with this name) any function in the program may be affected. // Returns: // 1 - ok // 0 - some error (a message is displayed) // if the ids file does not exist, no message is displayed idaman int ida_export load_ids_module(char *fname); //---------------------------------------------------------------------- // DEFINITION OF PLUGIN MODULES //---------------------------------------------------------------------- // A plugin is a module in plugins subdirectory which can be called by // pressing a hotkey. It usually performs an action asked by the user. class plugin_t { public: int version; // Should be equal to IDP_INTERFACE_VERSION int flags; // Features of the plugin: #define PLUGIN_MOD 0x0001 // Plugin changes the database. // IDA won't call the plugin if // the processor prohibited any changes // by setting PR_NOCHANGES in processor_t. #define PLUGIN_DRAW 0x0002 // IDA should redraw everything after calling // the plugin #define PLUGIN_SEG 0x0004 // Plugin may be applied only if the // current address belongs to a segment #define PLUGIN_UNL 0x0008 // Unload the plugin immediately after // calling 'run'. // This flag may be set anytime. // The kernel checks it after each call to 'run' // The main purpose of this flag is to ease // the debugging of new plugins. #define PLUGIN_HIDE 0x0010 // Plugin should not appear in the Edit, Plugins menu // This flag is checked at the start #define PLUGIN_DBG 0x0020 // A debugger plugin. init() should put // the address of debugger_t to dbg // See idd.hpp for details #define PLUGIN_PROC 0x0040 // Load plugin when a processor module is loaded and keep it // until the processor module is unloaded #define PLUGIN_FIX 0x0080 // Load plugin when IDA starts and keep it in the // memory until IDA stops int (idaapi* init)(void); // Initialize plugin #define PLUGIN_SKIP 0 // Plugin doesn't want to be loaded #define PLUGIN_OK 1 // Plugin agrees to work with the current database // It will be loaded as soon as the user presses the hotkey #define PLUGIN_KEEP 2 // Plugin agrees to work with the current database // and wants to stay in the memory void (idaapi* term)(void); // Terminate plugin. This function will be called // when the plugin is unloaded. May be NULL. void (idaapi* run)(int arg); // Invoke plugin char *comment; // Long comment about the plugin // it could appear in the status line // or as a hint char *help; // Multiline help about the plugin char *wanted_name; // The preferred short name of the plugin char *wanted_hotkey; // The preferred hotkey to run the plugin }; extern "C" plugin_t PLUGIN; // (declaration for plugins) //-------------------------------------------------------------------------- // A plugin can hook to the notification point and receive notifications // of all major events in IDA. The callback function will be called // for each event. The parameters of the callback: // user_data - data supplied in call to hook_to_notification_point() // notification_code - idp_notify or ui_notification_t code, depending on // the hoot type // va - additional parameters supplied with the notification // see the event descriptions for information // The callback should return: // 0 - ok, the event should be processed further // !=0 - the event is blocked and should be discarded // in the case of processor modules, the returned value is used // as the return value of notify() typedef int idaapi hook_cb_t(void *user_data, int notification_code, va_list va); enum hook_type_t { HT_IDP, // Hook to the processor module. // The callback will receive all idp_notify events. // See file idp.hpp for the list of events. HT_UI, // Hook to the user interface. // The callback will receive all ui_notification_t events. // See file kernwin.hpp for the list of events. HT_DBG, // Hook to the debugger. // The callback will receive all dbg_notification_t events. // See file dbg.hpp for the list of events. HT_GRAPH, // Hook to the graph events // The callback will receive all graph_notification_t events. // See file graph.hpp for the list of events. HT_LAST }; idaman bool ida_export hook_to_notification_point(hook_type_t hook_type, hook_cb_t *cb, void *user_data); // The plugin should unhook before being unloaded: // (preferably in its termination function) // Returns number of unhooked functions. // If different callbacks have the same callback function pointer // and user_data is not NULL, only the callback whose associated // user defined data matchs will be removed. idaman int ida_export unhook_from_notification_point(hook_type_t hook_type, hook_cb_t *cb, void *user_data = NULL); // A well behaved processor module should call this function // in his notify() function. If this function returns 0, then // the processor module should process the notification itself // Otherwise the code should be returned to the caller, like this: // // int code = invoke_callbacks(HT_IDP, what, va); // if ( code ) return code; // ... // idaman int ida_export invoke_callbacks(hook_type_t hook_type, int notification_code, va_list va); // Method to generate graph notifications: inline int idaapi grcall(int code, ...) { va_list va; va_start(va, code); int result = invoke_callbacks(HT_GRAPH, code, va); va_end(va); return result; } // Get plugin options from the command line // If the user has specified the options in the -Oplugin_name:options // format, them this function will return the 'options' part of it // The 'plugin' parameter should denote the plugin name // Returns NULL if there we no options specified idaman const char *ida_export get_plugin_options(const char *plugin); //-------------------------------------------------------------------------- // PLUGIN module file name extensions: #ifdef __NT__ #ifdef __EA64__ #ifdef __AMD64__ #define PLUGIN_EXT "x64" #else #define PLUGIN_EXT "p64" #endif #else #define PLUGIN_EXT "plw" #endif #endif #ifdef __LINUX__ #ifdef __EA64__ #define PLUGIN_EXT "plx64" #else #define PLUGIN_EXT "plx" #endif #endif #define PLUGIN_DLL "*." PLUGIN_EXT //---------------------------------------------------------------------- // LOW LEVEL DLL LOADING FUNCTIONS // Only the kernel should use these functions! #define LNE_MAXSEG 10 // Max number of segments #if 0 extern char dlldata[4096]; // Reserved place for DLL data #define DLLDATASTART 0xA0 // Absolute offset of dlldata extern char ldrdata[64]; // Reserved place for LOADER data #define LDRDATASTART (DLLDATASTART+sizeof(dlldata)) // Absolute offset of ldrdata #endif struct idadll_t { void *dllinfo[LNE_MAXSEG]; void *entry; // first entry point of DLL bool is_loaded(void) const { return dllinfo[0] != NULL; } }; int load_dll(const char *file, idadll_t *dllmem); // dllmem - allocated segments // dos: segment 1 (data) isn't allocated // Returns 0 - ok, else: #define RE_NOFILE 1 /* No such file */ #define RE_NOTIDP 2 /* Not IDP file */ #define RE_NOPAGE 3 /* Can't load: bad segments */ #define RE_NOLINK 4 /* No linkage info */ #define RE_BADRTP 5 /* Bad relocation type */ #define RE_BADORD 6 /* Bad imported ordinal */ #define RE_BADATP 7 /* Bad relocation atype */ #define RE_BADMAP 8 /* DLLDATA offset is invalid */ void load_dll_or_die(const char *file, idadll_t *dllmem); idaman int ida_export load_dll_or_say(const char *file, idadll_t *dllmem); idaman void ida_export free_dll(idadll_t *dllmem); // The processor description string should be at the offset 0x80 of the IDP file // (the string consists of the processor types separated by colons) #define IDP_DESC_START 0x80 #define IDP_DESC_END 0x200 idaman char *ida_export get_idp_desc(const char *file, char *buf, size_t bufsize); // Get IDP module name //-------------------------------------------------------------------------- // IDP module file name extensions: #ifdef __NT__ #ifdef __EA64__ #ifdef __AMD64__ #define IDP_EXT "x64" #else #define IDP_EXT "w64" #endif #else #define IDP_EXT "w32" #endif #endif #ifdef __LINUX__ #ifdef __EA64__ #define IDP_EXT "ilx64" #else #define IDP_EXT "ilx" #endif #endif #ifdef __EA64__ #define IDP_DLL "*64." IDP_EXT #else #define IDP_DLL "*." IDP_EXT #endif //-------------------------------------------------------------------------- // Plugin information in IDA is stored in the following structure: struct plugin_info_t { plugin_info_t *next; // next plugin information char *path; // full path to the plugin char *org_name; // original short name of the plugin char *name; // short name of the plugin // it will appear in the menu ushort org_hotkey; // original hotkey to run the plugin ushort hotkey; // current hotkey to run the plugin int arg; // argument used to call the plugin plugin_t *entry; // pointer to the plugin if it is already loaded idadll_t dllmem; int flags; // a copy of plugin_t.flags }; // Get pointer to the list of plugins (some plugins might be listed several times // in the list - once for each configured argument) idaman plugin_info_t *ida_export get_plugins(void); // Load a user-defined plugin // name - short plugin name without path and extension // or absolute path to the file name // Returns: pointer to plugin description block idaman plugin_t *ida_export load_plugin(const char *name); // Run a loaded plugin with the specified argument // ptr - pointer to plugin description block // arg - argument to run with idaman bool ida_export run_plugin(plugin_t *ptr, int arg); // Load & run a plugin inline bool idaapi load_and_run_plugin(const char *name, int arg) { return run_plugin(load_plugin(name), arg); } // Run a plugin as configured // ptr - pointer to plugin information block idaman bool ida_export invoke_plugin(plugin_info_t *ptr); // Information for the user interface about available debuggers struct dbg_info_t { plugin_info_t *pi; struct debugger_t *dbg; dbg_info_t(plugin_info_t *_pi, struct debugger_t *_dbg) : pi(_pi), dbg(_dbg) {} }; idaman size_t ida_export get_debugger_plugins(const dbg_info_t **array); // Initialize plugins with the specified flag idaman void ida_export init_plugins(int flag); // Terminate plugins with the specified flag idaman void ida_export term_plugins(int flag); //------------------------------------------------------------------------ // // work with file regions (for patching) // void init_fileregions(void); // called by the kernel void term_fileregions(void); // called by the kernel inline void save_fileregions(void) {} // called by the kernel void add_fileregion(ea_t ea1,ea_t ea2,long fpos); // called by the kernel void move_fileregions(ea_t from, ea_t to, asize_t size);// called by the kernel // Get offset in the input file which corresponds to the given ea // If the specified ea can't be mapped into the input file offset, // return -1. idaman long ida_export get_fileregion_offset(ea_t ea); // Get linear address which corresponds to the specified input file offset. // If can't be found, then return BADADDR idaman ea_t ida_export get_fileregion_ea(long offset); //------------------------------------------------------------------------ // Generate an exe file (unload the database in binary form) // fp - the output file handle // if fp == NULL then returns: // 1 - can generate an executable file // 0 - can't generate an executable file // returns: 1-ok, 0-failed idaman int ida_export gen_exe_file(FILE *fp); //------------------------------------------------------------------------ // Reload the input file // This function reloads the byte values from the input file // It doesn't modify the segmentation, names, comments, etc. // file - name of the input file // if file == NULL then returns: // 1 - can reload the input file // 0 - can't reload the input file // is_remote - is the file located on a remote computer with // the debugger server? // returns: 1-ok, 0-failed idaman int ida_export reload_file(const char *file, bool is_remote); //------------------------------------------------------------------------ // Generate an IDC file (unload the database in text form) // fp - the output file handle // onlytypes - if true then generate idc about enums, structs and // other type definitions used in the program // returns: 1-ok, 0-failed int local_gen_idc_file(FILE *fp, ea_t ea1, ea_t ea2, bool onlytypes); //------------------------------------------------------------------------ // Output to a file all lines controlled by place 'pl' // These functions are for the kernel only. class place_t; long print_all_places(FILE *fp,place_t *pl, html_line_cb_t *line_cb = NULL); extern html_line_cb_t save_text_line; long idaapi print_all_structs(FILE *fp, html_line_cb_t *line_cb = NULL); long idaapi print_all_enums(FILE *fp, html_line_cb_t *line_cb = NULL); //-------------------------------------------------------------------------- // // KERNEL ONLY functions & data // idaman ida_export_data char command_line_file[QMAXPATH]; // full path to the file specified in the command line idaman ida_export_data char database_idb[QMAXPATH]; // full path of IDB file extern char database_id0[QMAXPATH]; // full path of original ID0 file (not exported) idaman bool ida_export is_database_ext(const char *ext); // check the file extension extern ulong ida_database_memory; // Database buffer size in bytes. idaman ulong ida_export_data database_flags; // close_database() will: #define DBFL_KILL 0x01 // delete unpacked database #define DBFL_COMP 0x02 // compress database #define DBFL_BAK 0x04 // create backup file // (only if idb file is created) #define DBFL_TEMP 0x08 // temporary database inline bool is_temp_database(void) { return (database_flags & DBFL_TEMP) != 0; } extern bool pe_create_idata; extern bool pe_load_resources; extern bool pe_create_flat_group; // database check codes typedef int dbcheck_t; const dbcheck_t DBCHK_NONE = 0, // database doesn't exist DBCHK_OK = 1, // database exists DBCHK_BAD = 2, // database exists but we can't use it DBCHK_NEW = 3; // database exists but we the user asked to destroy it dbcheck_t check_database(const char *file); int open_database(bool isnew, const char *file, ulong input_size, bool is_temp_database); // returns 'waspacked' idaman int ida_export flush_buffers(void); // Flush buffers to disk idaman void ida_export save_database(const char *outfile, bool delete_unpacked); // Flush buffers and make // a copy of database void close_database(void); // see database_flags bool compress_btree(const char *btree_file); // (internal) compress .ID0 bool get_input_file_from_archive(char *filename, size_t namesize, bool is_remote, char **temp_file_ptr); bool loader_move_segm(ea_t from, ea_t to, asize_t size, bool keep); int generate_ida_copyright(FILE *fp, const char *cmt, html_line_cb_t *line_cb); bool is_in_loader(void); void get_ids_filename(char *buf, size_t bufsize, const char *idsname, const char *ostype, bool *use_ordinals, char **autotils, int maxtils); #pragma pack(pop) #endif
36,728
10,620
#include "Neuron.h" #include <stdlib.h> #include <time.h> #include <math.h> Neuron::Neuron(int x, int y, int pocetVstupu, int seedNeuron,int poziceVNeuronovesiti, double Mink) { srand(seedNeuron); LIMITITERACE = 50; ZERO= 0.0000000001; vahy=new double[pocetVstupu]; nonZeroVahy = new int[pocetVstupu]; seznamNenulAll = new bool[pocetVstupu]; //0=x, 1=y souradnice[0]=x; souradnice[1]=y; poziceVRikosti=poziceVNeuronovesiti; MinkowskehoNumber=Mink; numberOfdimension=pocetVstupu; numberOfseznamNenul=0; VahyX = 0; nonZeroCount = 0; VstupY = 0.0; for (int i = 0; i < pocetVstupu; i++) { vahy[i]=r2(); VahyX += vahy[i] * vahy[i]; nonZeroVahy[i] = i; seznamNenulAll[i]=false; } nonZeroCount = pocetVstupu; } Neuron::Neuron(int x, int y) { LIMITITERACE = 50; ZERO= 0.0000000001; souradnice[0]=x; souradnice[1]=y; numberOfseznamNenul=0; VahyX = 0; nonZeroCount = 0; VstupY = 0.0; } Neuron::~Neuron(void) { delete vahy; delete nonZeroVahy; delete seznamNenulAll; } double Neuron::Minkowskeho(void) { double suma = 0; double pom = 0; int coutner = 0; for (int i = 0; i < numberOfdimension; i++) { if (i == seznamNenul[coutner]) { pom = vstupy[coutner] - vahy[i]; suma += pow(abs(pom),MinkowskehoNumber); coutner++; if (coutner == numberOfseznamNenul) coutner = 0; } else { suma += pow(vahy[i],MinkowskehoNumber); } } return pow(suma,1/MinkowskehoNumber);// sqrt(suma); } double Neuron::Euklid2(void) { if(cosin) return Cosin2(); else { double suma = 0; int pocet = numberOfseznamNenul; for (int i = 0; i < pocet; i++) { suma -= 2 * vstupy[i] * vahy[seznamNenul[i]]; } suma += VahyX; suma += VstupY; return sqrt(suma); } } double Neuron::Cosin2() { double suma = 0; int pocet = numberOfseznamNenul; for (int i = 0; i < pocet; i++) { suma += vstupy[i] * vahy[seznamNenul[i]]; } return 1-(suma/(sqrt(VahyX)*sqrt(VstupY))); } bool Neuron::UpdateWeigh(int coordinatesOfWinnerX,int coordinatesOfWinnerY, double fiNa2, double learningRatio) { bool jeVetsiVahaNez0 = false; //Potrebuji vzdalenost mezi prvky int rozdilX = souradnice[0] - coordinatesOfWinnerX; int rozdilY = souradnice[1] - coordinatesOfWinnerY; //Nedelam odmocninu protoze pro dalsi vypocty potrebuji mit euklida ^2 float euklid = rozdilX * rozdilX + rozdilY * rozdilY; if (euklid < fiNa2) { int counter = 0; int maxCounte = numberOfseznamNenul; double omega = exp(-(double)euklid / (2 * fiNa2)); omega *= learningRatio; //zmena int pocet = numberOfdimension; // double pomocnaNasob = 0; counter = Compute(counter, maxCounte, omega, pocet); } return jeVetsiVahaNez0; } int Neuron::Compute(int counter, int maxCounte, double omega, int count) { VahyX = 0; for (int i = 0; i < numberOfseznamNenul; i++) { seznamNenulAll[seznamNenul[i]] = true; } int tmpNonZero = 0; for (int i = 0; i < nonZeroCount; i++) { int index = nonZeroVahy[i]; if (seznamNenulAll[index]) continue; double vahyI = vahy[index]; vahyI -= omega * vahyI; if (vahyI < ZERO) { vahy[index] = 0; } else { VahyX += vahyI * vahyI; nonZeroVahy[tmpNonZero] = index; tmpNonZero++; vahy[index] = vahyI; } } for (int i = 0; i < numberOfseznamNenul; i++) { int index = seznamNenul[i]; double vahyI = vahy[index]; vahyI += omega * (vstupy[i] - vahyI); VahyX += vahyI * vahyI; vahy[index] = vahyI; seznamNenulAll[index] = false; nonZeroVahy[tmpNonZero] = index; tmpNonZero++; } nonZeroCount = tmpNonZero; return counter; } void Neuron::RecalculateWeight(void) { VahyX = 0; for (int i = 0; i < numberOfdimension; i++) { VahyX += vahy[i] * vahy[i]; } } int Neuron::GetNumberOfZero(void) { int result = 0; for (int i = 0; i < numberOfdimension; i++) { if (vahy[i] < ZERO) result++; } return result; } double Neuron::r2(void) { return (double)0.6+(((double)rand() / (double)RAND_MAX)/100) ; } double Neuron::RidkostVypocet(int x) { return ((double)pocetNulvEpochach[x]) / numberOfdimension; } double Neuron::EuklidMikowsky(void) { if (gngCosin) return Cosin(); double suma = 0; double pom = 0; for (int i = 0; i < numberOfdimension; i++) { pom = vstupy[i] - vahy[i]; suma += pow(abs(pom), gngMinkowskehoNumber); } return pow(suma, 1 / gngMinkowskehoNumber);// sqrt(suma); } double Neuron::Euklid(void) { double suma = 0; double pom = 0; for (int i = 0; i < numberOfdimension; i++) { pom = vstupy[i] - vahy[i]; suma +=pom*pom; } return sqrt(suma); } double Neuron::Cosin() { double suma = 0; // int pocet = numberOfseznamNenul; double vs=0; double va=0; for (int i = 0; i < numberOfdimension; i++) { suma += vstupy[i] * vahy[i]; va+=vahy[i]*vahy[i]; vs+=vstupy[i] *vstupy[i]; } return 1-(suma/(sqrt(va)*sqrt(vs))); }
6,523
2,681
////////////////////////////////////////////////////////////////////// // // TriangleMeshLoaderBezier.cpp - Implementation of the bezier mesh // loader // // Author: Aravind Krishnaswamy // Date of Birth: August 7, 2002 // Tabs: 4 // Comments: // // License Information: Please see the attached LICENSE.TXT file // ////////////////////////////////////////////////////////////////////// #include "pch.h" #include "TriangleMeshLoaderBezier.h" #include "BezierTesselation.h" #include "GeometryUtilities.h" #include "../Interfaces/ILog.h" #include "../Utilities/MediaPathLocator.h" #include <stdio.h> using namespace RISE; using namespace RISE::Implementation; TriangleMeshLoaderBezier::TriangleMeshLoaderBezier( const char * szFile, const unsigned int detail, const bool bCombineSharedVertices_, const bool bCenterObject_, const IFunction2D* displacement_, Scalar disp_scale_ ) : nDetail( detail ), bCombineSharedVertices( bCombineSharedVertices_ ), bCenterObject( bCenterObject_ ), displacement( displacement_ ), disp_scale( disp_scale_ ) { strncpy( szFilename, GlobalMediaPathLocator().Find(szFile).c_str(), 256 ); } TriangleMeshLoaderBezier::~TriangleMeshLoaderBezier( ) { } bool TriangleMeshLoaderBezier::LoadTriangleMesh( ITriangleMeshGeometryIndexed* pGeom ) { FILE* inputFile = fopen( szFilename, "r" ); if( !inputFile || !pGeom ) { GlobalLog()->Print( eLog_Error, "TriangleMeshLoaderBezier:: Failed to open file or bad geometry object" ); return false; } pGeom->BeginIndexedTriangles(); char line[4096]; if( fgets( (char*)&line, 4096, inputFile ) != NULL ) { // Read that first line, it tells us how many // patches are dealing with here unsigned int numPatches = 0; sscanf( line, "%u", &numPatches ); BezierPatchesListType patches; for( unsigned int i=0; i<numPatches; i++ ) { // We assume every 16 lines gives us a patch BezierPatch patch; for( int j=0; j<4; j++ ) { for( int k=0; k<4; k++ ) { double x, y, z; if( fscanf( inputFile, "%lf %lf %lf", &x, &y, &z ) == EOF ) { GlobalLog()->PrintSourceError( "TriangleMeshLoaderBezier:: Fatal error while reading file. Nothing will be loaded", __FILE__, __LINE__ ); return false; } patch.c[j].pts[k] = Point3( x, y, z ); } } patches.push_back( patch ); } GlobalLog()->PrintEx( eLog_Event, "TriangleMeshLoaderBezier:: Tesselating %u bezier patches...", numPatches ); // Now tesselate all the patches together and then add them to // the geometry object IndexTriangleListType indtris; VerticesListType vertices; NormalsListType normals; TexCoordsListType coords; GeneratePolygonsFromBezierPatches( indtris, vertices, normals, coords, patches, nDetail ); if( bCombineSharedVertices ) { GlobalLog()->PrintEx( eLog_Event, "TriangleMeshLoaderBezier:: Attempting to combine shared vertices..." ); CombineSharedVerticesFromGrids( indtris, vertices, numPatches, nDetail, nDetail ); } CalculateVertexNormals( indtris, normals, vertices ); if( bCenterObject ) { CenterObject( vertices ); } if( displacement ) { RemapTextureCoords( coords ); ApplyDisplacementMapToObject( indtris, vertices, normals, coords, *displacement, disp_scale ); // After applying displacement, recalculate the vertex normals normals.clear(); CalculateVertexNormals( indtris, normals, vertices ); } pGeom->AddVertices( vertices ); pGeom->AddNormals( normals ); pGeom->AddTexCoords( coords ); pGeom->AddIndexedTriangles( indtris ); GlobalLog()->PrintEx( eLog_Event, "TriangleMeshGeometryIndexed:: Constructing acceleration structures for %u triangles", indtris.size() ); } pGeom->DoneIndexedTriangles(); fclose( inputFile ); return true; }
3,777
1,446
/*************************************************************************** testqgssettings.cpp -------------------------------------- Date : 17.02.2018 Copyright : (C) 2018 by Denis Rouzaud Email : denis.rouzaud@gmail.com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <QObject> #include "qgssettings.h" #include "qgsunittypes.h" #include "qgsmaplayerproxymodel.h" #include "qgstest.h" /** * \ingroup UnitTests * This is a unit test for the operations on curve geometries */ class TestQgsSettings : public QObject { Q_OBJECT private slots: void enumValue(); void flagValue(); }; void TestQgsSettings::enumValue() { QgsSettings settings; // assign to inexisting value settings.setValue( QStringLiteral( "qgis/testing/my_value_for_units" ), -1 ); settings.setValue( QStringLiteral( "qgis/testing/my_value_for_units_as_string" ), QStringLiteral( "myString" ) ); // just to be sure it really doesn't exist QVERIFY( static_cast<int>( QgsUnitTypes::LayoutMeters ) != -1 ); // standard method returns invalid value int v1 = settings.value( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters ).toInt(); QCOMPARE( v1, -1 ); // enum method returns default value if current setting is incorrect QgsUnitTypes::LayoutUnit v2 = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters ); QCOMPARE( v2, QgsUnitTypes::LayoutMeters ); QgsUnitTypes::LayoutUnit v2s = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units_as_string" ), QgsUnitTypes::LayoutMeters ); QCOMPARE( v2s, QgsUnitTypes::LayoutMeters ); // test a different value than default settings.setValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutCentimeters ); QgsUnitTypes::LayoutUnit v3 = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters ); QCOMPARE( v3, QgsUnitTypes::LayoutCentimeters ); settings.setEnumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutCentimeters ); // auto conversion of old settings (int to str) QCOMPARE( settings.value( "qgis/testing/my_value_for_units" ).toString(), QStringLiteral( "LayoutCentimeters" ) ); QgsUnitTypes::LayoutUnit v3s = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_units" ), QgsUnitTypes::LayoutMeters ); QCOMPARE( v3s, QgsUnitTypes::LayoutCentimeters ); QString v3ss = settings.value( QStringLiteral( "qgis/testing/my_value_for_units" ), QStringLiteral( "myDummyValue" ) ).toString(); QCOMPARE( v3ss, QStringLiteral( "LayoutCentimeters" ) ); } void TestQgsSettings::flagValue() { QgsSettings settings; QgsMapLayerProxyModel::Filters pointAndLine = QgsMapLayerProxyModel::Filters( QgsMapLayerProxyModel::PointLayer | QgsMapLayerProxyModel::LineLayer ); QgsMapLayerProxyModel::Filters pointAndPolygon = QgsMapLayerProxyModel::Filters( QgsMapLayerProxyModel::PointLayer | QgsMapLayerProxyModel::PolygonLayer ); settings.setValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), 1e8 ); // invalid QgsMapLayerProxyModel::Filters v4 = settings.enumValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), pointAndLine ); QCOMPARE( v4, pointAndLine ); settings.setValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), static_cast<int>( pointAndPolygon ) ); QgsMapLayerProxyModel::Filters v5 = settings.flagValue( QStringLiteral( "qgis/testing/my_value_for_a_flag" ), pointAndLine, QgsSettings::NoSection ); QCOMPARE( v5, pointAndPolygon ); // auto conversion of old settings (int to str) QCOMPARE( settings.value( "qgis/testing/my_value_for_a_flag" ).toString(), QStringLiteral( "PointLayer|PolygonLayer" ) ); settings.setFlagValue( QStringLiteral( "qgis/testing/my_value_for_a_flag_as_string" ), pointAndPolygon, QgsSettings::NoSection ); QgsMapLayerProxyModel::Filters v5s = settings.flagValue( QStringLiteral( "qgis/testing/my_value_for_a_flag_as_string" ), pointAndLine, QgsSettings::NoSection ); QCOMPARE( v5s, pointAndPolygon ); QString v5ss = settings.value( QStringLiteral( "qgis/testing/my_value_for_a_flag_as_string" ), QStringLiteral( "myDummyString" ), QgsSettings::NoSection ).toString(); QCOMPARE( v5ss, QStringLiteral( "PointLayer|PolygonLayer" ) ); } QGSTEST_MAIN( TestQgsSettings ) #include "testqgssettings.moc"
5,011
1,646
//============================================================================ // Name : Proj1.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <string.h> #include "vetor.h" #include <iostream> #include <fstream> using namespace std; int numberWords = 0, numberNonDuplicates = 0; int main() { vetor* vec = vetor_novo(); FILE *wordlist = fopen("wordlist.txt", "r"); if(!wordlist) { cout << "Error: Could Not Open File\n"; return 2; } cout << "Going through the data please wait..."<< endl; char line[100]; while (fgets(line, sizeof(line), wordlist)) { if(line[strlen(line)-1] == '\n') line[strlen(line)-1] = ','; char * word; word = strtok (line," ,.-;'"); numberWords++; while (word != NULL) { if(vetor_pesquisa(vec, word) == -1){ vetor_insere(vec, word, vec->tamanho); numberNonDuplicates++; } word = strtok (NULL," ,.-;'"); } } fclose(wordlist); cout << endl << "Sorting Words . . . " << endl; vetor_ordena(vec); char currentChar = ','; int totalLetter = 0; for(int i = 0; i < vec->tamanho; i++){ totalLetter++; if(vetor_elemento(vec, i)[0] != currentChar){ currentChar = vetor_elemento(vec, i)[0]; cout << endl << vetor_elemento(vec, i) << endl; totalLetter = 0; }else if(totalLetter % 100 == 0) cout << "."; if(totalLetter % 1000 == 0 && totalLetter != 0) cout << endl; } cout << endl << endl << "Number Of simple Words: " << numberWords << endl; cout << endl << "Number Of Non Duplicate Words: " << numberNonDuplicates << endl; cout << endl << "Saving to File Vec.txt..." << endl; if(vetor_guarda_ficheiro(vec, "vec.txt") == 0) cout << endl << "Save Successful" << endl; vetor_apaga(vec); return 0; }
1,924
777
//============================================================================================================= /** * @file natusproducer.cpp * @author Gabriel B Motta <gabrielbenmotta@gmail.com>; * Lorenz Esch <lesch@mgh.harvard.edu> * @version dev * @date June, 2018 * * @section LICENSE * * Copyright (C) 2018, Gabriel B Motta, Lorenz Esch. 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 MNE-CPP authors 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. * * * @brief Contains the definition of the NatusProducer class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "natusproducer.h" #include <iostream> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> #include <QDataStream> #include <QScopedArrayPointer> //************************************************************************************************************* //============================================================================================================= // EIGEN INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace NATUSPLUGIN; using namespace Eigen; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= NatusProducer::NatusProducer(int iBlockSize, int iChannelSize, QObject *parent) : QObject(parent) , m_iMatDataSampleIterator(1) { //qRegisterMetaType<Eigen::MatrixXd>(); //Init socket m_pUdpSocket = QSharedPointer<QUdpSocket>(new QUdpSocket(this)); m_pUdpSocket->bind(QHostAddress::AnyIPv4, 50000); connect(m_pUdpSocket.data(), &QUdpSocket::readyRead, this, &NatusProducer::readPendingDatagrams); m_matData.resize(iChannelSize, iBlockSize); m_fSampleFreq = 0; m_fChannelSize = 0; } //************************************************************************************************************* void NatusProducer::readPendingDatagrams() { while (m_pUdpSocket->hasPendingDatagrams()) { QNetworkDatagram datagram = m_pUdpSocket->receiveDatagram(); //qDebug() << "Datagram on port 50000 from IP "<<datagram.senderAddress(); processDatagram(datagram); } } //************************************************************************************************************* void NatusProducer::processDatagram(const QNetworkDatagram &datagram) { QByteArray data = datagram.data(); QDataStream stream(data); // Read info float fPackageNumber, fNumberSamples, fNumberChannels; char cInfo[3*sizeof(float)]; stream.readRawData(cInfo, sizeof(cInfo)); float* fInfo = reinterpret_cast<float*>(cInfo); fPackageNumber = fInfo[0]; fNumberSamples = fInfo[1]; fNumberChannels = fInfo[2]; // // Print info about received data // qDebug()<<"fPackageNumber "<<fPackageNumber; // qDebug()<<"fNumberSamples "<<fNumberSamples; // qDebug()<<"fNumberChannels "<<fNumberChannels; // qDebug()<<"data.size() "<<data.size(); // qDebug()<<"data.size() "<<data.size(); // qDebug()<<"data.size() "<<data.size(); // Read actual data int iDataSize = int(fNumberSamples * fNumberChannels); QScopedArrayPointer<char> cData(new char[iDataSize*sizeof(float)]); //char *cData = new char[iDataSize*sizeof(float)]; stream.readRawData(cData.data(), iDataSize*sizeof(float)); float* fData = reinterpret_cast<float*>(cData.data()); //Get data Eigen::MatrixXf matData; matData.resize(fNumberChannels, fNumberSamples); int itr = 0; for(int j = 0; j < fNumberSamples; ++j) { for(int i = 0; i < fNumberChannels; ++i) { matData(i,j) = fData[itr++]/10e06; } } if(m_iMatDataSampleIterator+matData.cols() <= m_matData.cols()) { m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), matData.cols()) = matData.cast<double>(); m_iMatDataSampleIterator += matData.cols(); } else { m_matData.block(0, m_iMatDataSampleIterator, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator) = matData.block(0, 0, matData.rows(), m_matData.cols()-m_iMatDataSampleIterator).cast<double>(); m_iMatDataSampleIterator = 0; } //qDebug() << "m_iMatDataSampleIterator" << m_iMatDataSampleIterator; if(m_iMatDataSampleIterator == m_matData.cols()) { m_iMatDataSampleIterator = 0; //qDebug()<<"Emit data"; MatrixXd matEmit = m_matData.cast<double>(); emit newDataAvailable(matEmit); } }
7,166
2,035
///////////////////////////////////////////////// // Attribute-Estimator PAttrEst TAttrEst::Load(TSIn& SIn){ TStr TypeNm(SIn); if (TypeNm==TTypeNm<TAttrEstRnd>()){return new TAttrEstRnd(SIn);} else if (TypeNm==TTypeNm<TAttrEstIGain>()){return new TAttrEstIGain(SIn);} else if (TypeNm==TTypeNm<TAttrEstIGainNorm>()){return new TAttrEstIGainNorm(SIn);} else if (TypeNm==TTypeNm<TAttrEstIGainRatio>()){return new TAttrEstIGainRatio(SIn);} else if (TypeNm==TTypeNm<TAttrEstMantarasDist>()){return new TAttrEstMantarasDist(SIn);} else if (TypeNm==TTypeNm<TAttrEstMdl>()){return new TAttrEstMdl(SIn);} else if (TypeNm==TTypeNm<TAttrEstGStat>()){return new TAttrEstGStat(SIn);} else if (TypeNm==TTypeNm<TAttrEstChiSquare>()){return new TAttrEstChiSquare(SIn);} else if (TypeNm==TTypeNm<TAttrEstOrt>()){return new TAttrEstOrt(SIn);} else if (TypeNm==TTypeNm<TAttrEstGini>()){return new TAttrEstGini(SIn);} else if (TypeNm==TTypeNm<TAttrEstWgtEvd>()){return new TAttrEstWgtEvd(SIn);} else if (TypeNm==TTypeNm<TAttrEstTextWgtEvd>()){return new TAttrEstTextWgtEvd(SIn);} else if (TypeNm==TTypeNm<TAttrEstOddsRatio>()){return new TAttrEstOddsRatio(SIn);} else if (TypeNm==TTypeNm<TAttrEstWgtOddsRatio>()){return new TAttrEstWgtOddsRatio(SIn);} else if (TypeNm==TTypeNm<TAttrEstCondOddsRatio>()){return new TAttrEstCondOddsRatio(SIn);} else if (TypeNm==TTypeNm<TAttrEstLogPRatio>()){return new TAttrEstLogPRatio(SIn);} else if (TypeNm==TTypeNm<TAttrEstExpPDiff>()){return new TAttrEstExpPDiff(SIn);} else if (TypeNm==TTypeNm<TAttrEstMutInf>()){return new TAttrEstMutInf(SIn);} else if (TypeNm==TTypeNm<TAttrEstCrossEnt>()){return new TAttrEstCrossEnt(SIn);} else if (TypeNm==TTypeNm<TAttrEstTermFq>()){return new TAttrEstTermFq(SIn);} else {Fail; return NULL;} } PTbValDs TAttrEst::GetCSValDs(const int& AttrN, const int& SplitN, const PTbValSplit& ValSplit, const PDmDs& DmDs){ PTbValDs CSValDs=new TTbValDs(DmDs->GetCDs()->GetDscs()); for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){ TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN); for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double ValW=DmDs->GetCAVDs(CDsc, AttrN)->GetValW(Val); CSValDs->AddVal(CDsc, ValW); } } CSValDs->Def(); return CSValDs; } PTbValDs TAttrEst::GetSValDs(const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs){ PTbValDs SValDs=new TTbValDs(ValSplit->GetSplits()); for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){ TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN); double ValW=DmDs->GetAVDs(AttrN)->GetValW(Val); SValDs->AddVal(SplitN, ValW); } } SValDs->Def(); return SValDs; } PTbValDs TAttrEst::GetSCValDs(const int& CDsc, const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs){ PTbValDs SCValDs=new TTbValDs(ValSplit->GetSplits()); for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){ TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN); double ValW=DmDs->GetCAVDs(CDsc, AttrN)->GetValW(Val); SCValDs->AddVal(SplitN, ValW); } } SCValDs->Def(); return SCValDs; } double TAttrEst::GetCEntropy( const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){ double CEntropy=0; for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs); if (CPrb>0){CEntropy-=CPrb*TMath::Log2(CPrb);} } return CEntropy; } double TAttrEst::GetAEntropy(const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){ PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double AEntropy=0; for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ double SPrb=PrbEst->GetVPrb(SplitN, SValDs, PriorSValDs); if (SPrb>0){AEntropy-=SPrb*TMath::Log2(SPrb);} } return AEntropy; } double TAttrEst::GetCAEntropy(const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){ double CAEntropy=0; for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs); double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW()); double SEntropy=0; for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double CAPrb=SPrb*PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs()); if (CAPrb>0){SEntropy-=CAPrb*TMath::Log2(CAPrb);} } CAEntropy+=SEntropy; } return CAEntropy; } PPrbEst TAttrEst::GetPrbEst(const PPrbEst& PrbEst){ if (!PrbEst.Empty()){return PrbEst;} else {return PPrbEst(new TPrbEstRelFq());} } PPp TAttrEst::GetPrbEstPp(const TStr& Nm, const TStr& DNm){ PPp Pp=new TPp(Nm, DNm, ptSet); Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm)); return Pp; } const TStr TAttrEst::DNm("Attribute Estimate"); PPp TAttrEst::GetPp(const TStr& Nm, const TStr& DNm){ PPp Pp=new TPp(Nm, DNm, ptSel); Pp->AddPp(TAttrEstRnd::GetPp(TTypeNm<TAttrEstRnd>(), TAttrEstRnd::DNm)); Pp->AddPp(TAttrEstIGain::GetPp(TTypeNm<TAttrEstIGain>(), TAttrEstIGain::DNm)); Pp->AddPp(TAttrEstIGainNorm::GetPp(TTypeNm<TAttrEstIGainNorm>(), TAttrEstIGainNorm::DNm)); Pp->AddPp(TAttrEstIGainRatio::GetPp(TTypeNm<TAttrEstIGainRatio>(), TAttrEstIGainRatio::DNm)); Pp->AddPp(TAttrEstMantarasDist::GetPp(TTypeNm<TAttrEstMantarasDist>(), TAttrEstMantarasDist::DNm)); Pp->AddPp(TAttrEstMdl::GetPp(TTypeNm<TAttrEstMdl>(), TAttrEstMdl::DNm)); Pp->AddPp(TAttrEstGStat::GetPp(TTypeNm<TAttrEstGStat>(), TAttrEstGStat::DNm)); Pp->AddPp(TAttrEstChiSquare::GetPp(TTypeNm<TAttrEstChiSquare>(), TAttrEstChiSquare::DNm)); Pp->AddPp(TAttrEstOrt::GetPp(TTypeNm<TAttrEstOrt>(), TAttrEstOrt::DNm)); Pp->AddPp(TAttrEstGini::GetPp(TTypeNm<TAttrEstGini>(), TAttrEstGini::DNm)); Pp->AddPp(TAttrEstWgtEvd::GetPp(TTypeNm<TAttrEstWgtEvd>(), TAttrEstWgtEvd::DNm)); Pp->AddPp(TAttrEstTextWgtEvd::GetPp(TTypeNm<TAttrEstTextWgtEvd>(), TAttrEstTextWgtEvd::DNm)); Pp->AddPp(TAttrEstOddsRatio::GetPp(TTypeNm<TAttrEstOddsRatio>(), TAttrEstOddsRatio::DNm)); Pp->AddPp(TAttrEstWgtOddsRatio::GetPp(TTypeNm<TAttrEstWgtOddsRatio>(), TAttrEstWgtOddsRatio::DNm)); Pp->AddPp(TAttrEstCondOddsRatio::GetPp(TTypeNm<TAttrEstCondOddsRatio>(), TAttrEstCondOddsRatio::DNm)); Pp->AddPp(TAttrEstLogPRatio::GetPp(TTypeNm<TAttrEstLogPRatio>(), TAttrEstLogPRatio::DNm)); Pp->AddPp(TAttrEstExpPDiff::GetPp(TTypeNm<TAttrEstExpPDiff>(), TAttrEstExpPDiff::DNm)); Pp->AddPp(TAttrEstMutInf::GetPp(TTypeNm<TAttrEstMutInf>(), TAttrEstMutInf::DNm)); Pp->AddPp(TAttrEstCrossEnt::GetPp(TTypeNm<TAttrEstCrossEnt>(), TAttrEstCrossEnt::DNm)); Pp->AddPp(TAttrEstTermFq::GetPp(TTypeNm<TAttrEstTermFq>(), TAttrEstTermFq::DNm)); Pp->PutDfVal(TTypeNm<TAttrEstIGain>()); return Pp; } PAttrEst TAttrEst::New(const PPp& Pp){ if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstRnd>())){ return new TAttrEstRnd(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGain>())){ return new TAttrEstIGain(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGainNorm>())){ return new TAttrEstIGainNorm(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGainRatio>())){ return new TAttrEstIGainRatio(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMantarasDist>())){ return new TAttrEstMantarasDist(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMdl>())){ return new TAttrEstMdl(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstGStat>())){ return new TAttrEstGStat(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstChiSquare>())){ return new TAttrEstChiSquare(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstOrt>())){ return new TAttrEstOrt(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstGini>())){ return new TAttrEstGini(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstWgtEvd>())){ return new TAttrEstWgtEvd(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstTextWgtEvd>())){ return new TAttrEstTextWgtEvd(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstOddsRatio>())){ return new TAttrEstOddsRatio(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstWgtOddsRatio>())){ return new TAttrEstWgtOddsRatio(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstCondOddsRatio>())){ return new TAttrEstCondOddsRatio(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstLogPRatio>())){ return new TAttrEstLogPRatio(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstExpPDiff>())){ return new TAttrEstExpPDiff(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMutInf>())){ return new TAttrEstMutInf(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstCrossEnt>())){ return new TAttrEstCrossEnt(Pp->GetSelPp());} else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstTermFq>())){ return new TAttrEstTermFq(Pp->GetSelPp());} else {Fail; return NULL;} } ///////////////////////////////////////////////// // Attribute-Estimator-Random const TStr TAttrEstRnd::DNm("Random"); PPp TAttrEstRnd::GetPp(const TStr& Nm, const TStr& DNm){ PPp Pp=new TPp(Nm, DNm, ptSet); Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm)); Pp->AddPpInt("Seed", "Random-Seed", 0, TInt::Mx, 1); return Pp; } ///////////////////////////////////////////////// // Attribute-Estimator-Information-Gain const TStr TAttrEstIGain::DNm("Inf-Gain"); ///////////////////////////////////////////////// // Attribute-Estimator-Information-Gain-Normalized const TStr TAttrEstIGainNorm::DNm("Inf-Gain-Normalized"); ///////////////////////////////////////////////// // Attribute-Estimator-Information-Gain-Ratio const TStr TAttrEstIGainRatio::DNm("Inf-Gain-Ratio"); ///////////////////////////////////////////////// // Attribute-Estimator-Mantaras-Distance const TStr TAttrEstMantarasDist::DNm("Mantaras-Distance"); ///////////////////////////////////////////////// // Attribute-Estimator-MDL double TAttrEstMdl::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ double SumW=DmDs->GetSumW(); int CDscs=DmDs->GetCDs()->GetDscs(); double IGainAttrQ=IGain.GetAttrQ(AttrN, ValSplit, DmDs, PriorDmDs); double LnPart=TSpecFunc::LnComb(TFlt::Round(SumW)+CDscs-1, CDscs-1); for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ double SSumW=0; for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){ TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN); double ValW=DmDs->GetAVDs(AttrN)->GetValW(Val); SSumW+=ValW; } LnPart-=TSpecFunc::LnComb(TFlt::Round(SSumW+CDscs-1), CDscs-1); } return IGainAttrQ+LnPart/SumW; } const TStr TAttrEstMdl::DNm("MDL"); ///////////////////////////////////////////////// // Attribute-Estimator-G-Statistics const TStr TAttrEstGStat::DNm("G-Statistics"); ///////////////////////////////////////////////// // Attribute-Estimator-Chi-Square double TAttrEstChiSquare::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs&){ double ChiSquare=0; for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs); double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW()); for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double Frac=SPrb*DmDs->GetCDs()->GetValW(CDsc); if (Frac>0){ChiSquare+=TMath::Sqr(Frac-CSValDs->GetValW(CDsc))/Frac;} } } return ChiSquare; } const TStr TAttrEstChiSquare::DNm("Chi-Square"); ///////////////////////////////////////////////// // Attribute-Estimator-ORT double TAttrEstOrt::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(ValSplit->GetSplits()==2); // **make exception PTbValDs CSValDs1=GetCSValDs(AttrN, 0, ValSplit, DmDs); PTbValDs CSValDs2=GetCSValDs(AttrN, 1, ValSplit, DmDs); double Cos=0; double Norm1=0; double Norm2=0; for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double CSPrb1=PrbEst->GetVPrb(CDsc, CSValDs1, PriorDmDs->GetCDs()); double CSPrb2=PrbEst->GetVPrb(CDsc, CSValDs2, PriorDmDs->GetCDs()); Cos+=CSPrb1*CSPrb2; Norm1+=TMath::Sqr(CSPrb1); Norm2+=TMath::Sqr(CSPrb2); } if ((Norm1==0)||(Norm2==0)){Cos=1;} else {Cos=Cos/(sqrt(Norm1)*sqrt(Norm2));} return 1-Cos; } const TStr TAttrEstOrt::DNm("ORT"); ///////////////////////////////////////////////// // Attribute-Estimator-Gini double TAttrEstGini::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ double Gini=0; for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs); double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW()); double Sum=0; for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ Sum+=TMath::Sqr(PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs()));} Gini+=SPrb*Sum; } for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs); Gini-=TMath::Sqr(CPrb); } return Gini; } const TStr TAttrEstGini::DNm("Gini-Index"); ///////////////////////////////////////////////// // Attribute-Estimator-Weight-Of-Evidence double TAttrEstWgtEvd::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ double PriorSumW=PriorDmDs->GetSumW(); if (PriorSumW==0){return 0;} double WgtEvd=0; for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){ PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs); double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW()); for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double OrigCPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs); double CPrb=OrigCPrb; if (CPrb==0){CPrb=1/TMath::Sqr(PriorSumW);} if (CPrb==1){CPrb=1-(1/TMath::Sqr(PriorSumW));} double OddsC=CPrb/(1-CPrb); double CSPrb=PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs()); if (CSPrb==0){CSPrb=1/TMath::Sqr(PriorSumW);} if (CSPrb==1){CSPrb=1-(1/TMath::Sqr(PriorSumW));} double OddsCS=CSPrb/(1-CSPrb); WgtEvd+=OrigCPrb*SPrb*fabs(log(OddsCS/OddsC)); } } return WgtEvd; } const TStr TAttrEstWgtEvd::DNm("Weight-Of-Evidence"); ///////////////////////////////////////////////// // Attribute-Estimator-Text-Weight-Of-Evidence double TAttrEstTextWgtEvd::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ double PriorSumW=PriorDmDs->GetSumW(); if (PriorSumW==0){return 0;} double WgtEvd=0; PTbValDs CS1ValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs); double S1Prb=CS1ValDs->GetSumPrb(DmDs->GetSumW()); for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double OrigCPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs); double CPrb=OrigCPrb; if (CPrb==0){CPrb=1/TMath::Sqr(PriorSumW);} if (CPrb==1){CPrb=1-(1/TMath::Sqr(PriorSumW));} double OddsC=CPrb/(1-CPrb); double CS1Prb=PrbEst->GetVPrb(CDsc, CS1ValDs, PriorDmDs->GetCDs()); if (CS1Prb==0){CS1Prb=1/TMath::Sqr(PriorSumW);} if (CS1Prb==1){CS1Prb=1-(1/TMath::Sqr(PriorSumW));} double OddsCS1=CS1Prb/(1-CS1Prb); WgtEvd+=OrigCPrb*S1Prb*fabs(log(OddsCS1/OddsC)); } return WgtEvd; } const TStr TAttrEstTextWgtEvd::DNm("Text-Weight-Of-Evidence"); ///////////////////////////////////////////////// // Attribute-Estimator-Odds-Ratio double TAttrEstOddsRatio::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception IAssert(ValSplit->GetSplits()==2); // **make exception double PriorSumW=PriorDmDs->GetSumW(); if (PriorSumW==0){return TFlt::Mn;} // split-number-0: false; split-number-1: true PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs); PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs); double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs); if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);} if (S1C0Prb==1){S1C0Prb=1-(1/TMath::Sqr(PriorSumW));} double OddsS1C0=S1C0Prb/(1-S1C0Prb); if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);} if (S1C1Prb==1){S1C1Prb=1-(1/TMath::Sqr(PriorSumW));} double OddsS1C1=S1C1Prb/(1-S1C1Prb); double OddsRatio=log(OddsS1C1/OddsS1C0); return OddsRatio; } const TStr TAttrEstOddsRatio::DNm("Odds-Ratio"); ///////////////////////////////////////////////// // Attribute-Estimator-Weighted-Odds-Ratio double TAttrEstWgtOddsRatio::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception IAssert(ValSplit->GetSplits()==2); // **make exception PTbValDs CSValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs); double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW()); double WgtOddsRatio=SPrb*OddsRatio.GetAttrQ(AttrN, ValSplit, DmDs, PriorDmDs); return WgtOddsRatio; } const TStr TAttrEstWgtOddsRatio::DNm("Weighted-Odds-Ratio"); ///////////////////////////////////////////////// // Attribute-Estimator-Conditional-Odds-Ratio double TAttrEstCondOddsRatio::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception IAssert(ValSplit->GetSplits()==2); // **make exception double PriorSumW=PriorDmDs->GetSumW(); if (PriorSumW==0){return TFlt::Mn;} // split-number-0: false; split-number-1: true PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs); PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs); double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs); if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);} if (S1C0Prb==1){S1C0Prb=1-(1/TMath::Sqr(PriorSumW));} double OddsS1C0=S1C0Prb/(1-S1C0Prb); if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);} if (S1C1Prb==1){S1C1Prb=1-(1/TMath::Sqr(PriorSumW));} double OddsS1C1=S1C1Prb/(1-S1C1Prb); double CondOddsRatio; if (S1C0Prb-S1C1Prb>InvTsh){ CondOddsRatio=InvWgt*log(OddsS1C0/OddsS1C1); } else { CondOddsRatio=log(OddsS1C1/OddsS1C0); } return CondOddsRatio; } const TStr TAttrEstCondOddsRatio::DNm("Conditional-Odds-Ratio"); PPp TAttrEstCondOddsRatio::GetPp(const TStr& Nm, const TStr& DNm){ PPp Pp=new TPp(Nm, DNm, ptSet); Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm)); Pp->AddPpFlt("InvTsh", "Inversion-Treshold", 0, 1, 0.9); Pp->AddPpFlt("InvWgt", "Inversion-Weight", 0, 1, 0.1); return Pp; } ///////////////////////////////////////////////// // Attribute-Estimator-Log-Probability-Ratio double TAttrEstLogPRatio::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception IAssert(ValSplit->GetSplits()==2); // **make exception double PriorSumW=PriorDmDs->GetSumW(); if (PriorSumW==0){return TFlt::Mn;} // split-number-0: false; split-number-1: true PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs); PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs); double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs); if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);} if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);} double LogPRatio=log(S1C1Prb/S1C0Prb); return LogPRatio; } const TStr TAttrEstLogPRatio::DNm("Log-Probability-Ratio"); ///////////////////////////////////////////////// // Attribute-Estimator-Exp-Probability-Difference double TAttrEstExpPDiff::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception IAssert(ValSplit->GetSplits()==2); // **make exception double SumW=DmDs->GetSumW(); if (SumW==0){return TFlt::Mn;} // split-number-0: false; split-number-1: true PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs); PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs); double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs); double ExpPDiff=exp(S1C1Prb-S1C0Prb); return ExpPDiff; } const TStr TAttrEstExpPDiff::DNm("Exp-Probability-Difference"); ///////////////////////////////////////////////// // Attribute-Estimator-Mutual-Information double TAttrEstMutInf::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(ValSplit->GetSplits()==2); // **make exception // split-number-0: false; split-number-1: true PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double S1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SValDs, PriorSValDs); if (S1Prb==0){return TFlt::Mn;} double MutInf=0; for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs); PTbValDs SCValDs=GetSCValDs(CDsc, AttrN, ValSplit, DmDs); double S1CPrb=PrbEst->GetVPrb(TTbVal::PosVal, SCValDs, PriorSValDs); if (S1CPrb==0){S1CPrb=1/TMath::Sqr(DmDs->GetSumW());} MutInf+=CPrb*log(S1CPrb/S1Prb); } return MutInf; } const TStr TAttrEstMutInf::DNm("Mutual-Information"); ///////////////////////////////////////////////// // Attribute-Estimator-Cross-Entropy double TAttrEstCrossEnt::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs& PriorDmDs){ IAssert(ValSplit->GetSplits()==2); // **make exception // split-number-0: false; split-number-1: true PTbValDs CS1ValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs); PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs); PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs); double S1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SValDs, PriorSValDs); if (S1Prb==0){return TFlt::Mn;} double CrossEnt=0; for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){ double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs); double CS1Prb=PrbEst->GetVPrb(CDsc, CS1ValDs, PriorDmDs->GetCDs()); if (CS1Prb>0){Assert(CPrb>0); CrossEnt+=CS1Prb*log(CS1Prb/CPrb);} } CrossEnt*=S1Prb; return CrossEnt; } const TStr TAttrEstCrossEnt::DNm("Cross-Entropy"); ///////////////////////////////////////////////// // Attribute-Estimator-Term-Frequency double TAttrEstTermFq::GetAttrQ( const int& AttrN, const PTbValSplit& ValSplit, const PDmDs& DmDs, const PDmDs&){ IAssert(ValSplit->GetSplits()==2); // **make exception PTbValDs CSValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs); return CSValDs->GetSumW(); } const TStr TAttrEstTermFq::DNm("Term-Frequency");
24,055
11,210
/* * rptrafficmanager.hh * - A traffic manager for Router Parking * * Author: Jiayi Huang */ #ifndef _RPTRAFFICMANAGER_HPP_ #define _RPTRAFFICMANAGER_HPP_ #include <cassert> #include "mem/ruby/network/booksim2/trafficmanager.hh" class RPTrafficManager : public TrafficManager { private: vector<vector<int> > _packet_size; vector<vector<int> > _packet_size_rate; vector<int> _packet_size_max_val; // ============ Internal methods ============ protected: virtual void _Inject(); virtual void _Step( ); virtual void _GeneratePacket( int source, int size, int cl, uint64_t time ); public: RPTrafficManager( const Configuration &config, const vector<BSNetwork *> & net ); virtual ~RPTrafficManager( ); }; #endif
743
272
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; static_assert(sizeof(int) == 4 && sizeof(long) == 8); struct disjoint_set { int N, S; vector<int> next, size; explicit disjoint_set(int N = 0) : N(N), S(N), next(N), size(N, 1) { iota(begin(next), end(next), 0); } void assign(int N) { *this = disjoint_set(N); } bool same(int i, int j) { return find(i) == find(j); } bool unit(int i) { return i == next[i] && size[i] == 1; } bool root(int i) { return find(i) == i; } void reroot(int u) { if (u != find(u)) { size[u] = size[find(u)]; next[u] = next[find(u)] = u; } } int find(int i) { while (i != next[i]) { i = next[i] = next[next[i]]; } return i; } bool join(int i, int j) { i = find(i); j = find(j); if (i != j) { if (size[i] < size[j]) { swap(i, j); } next[j] = i; size[i] += size[j]; S--; return true; } return false; } }; auto solve() { int N, M; cin >> N >> M; vector<string> grid(N); for (int i = 0; i < N; i++) { cin >> grid[i]; } disjoint_set dsu(N * M); auto id = [&](int i, int j) { return i * M + j; }; // columns for (int i = 0; i < N; i++) { int j = 0; do { while (j < M && grid[i][j] == '#') j++; int a = j; while (j < M && grid[i][j] != '#') j++; int b = j; for (int c = a, d = b - 1; c < d; c++, d--) { dsu.join(id(i, c), id(i, d)); } } while (j < M); } // rows for (int j = 0; j < M; j++) { int i = 0; do { while (i < N && grid[i][j] == '#') i++; int a = i; while (i < N && grid[i][j] != '#') i++; int b = i; for (int c = a, d = b - 1; c < d; c++, d--) { dsu.join(id(c, j), id(d, j)); } } while (i < N); } vector<string> ans = grid; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (grid[i][j] != '.' && grid[i][j] != '#') { int x = dsu.find(id(i, j)); int r = x / M, c = x - r * M; ans[r][c] = grid[i][j]; } } } int filled = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (ans[i][j] != '#') { int x = dsu.find(id(i, j)); int r = x / M, c = x - r * M; ans[i][j] = ans[r][c]; filled += ans[i][j] != '.' && grid[i][j] == '.'; } } } cout << filled << '\n'; for (int i = 0; i < N; i++) { cout << ans[i] << '\n'; } } int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int T; cin >> T; for (int t = 1; t <= T; t++) { cout << "Case #" << t << ": "; solve(); } return 0; }
3,213
1,238
#include "StockOrder.h"
24
11
#pragma once enum class DPadDirection { UP, DOWN, LEFT, RIGHT }; // these are matched to SDL key map scancodes enum class Scancode { S_UNKNOWN = 0, S_A = 4, S_B = 5, S_C = 6, S_D = 7, S_E = 8, S_F = 9, S_G = 10, S_H = 11, S_I = 12, S_J = 13, S_K = 14, S_L = 15, S_M = 16, S_N = 17, S_O = 18, S_P = 19, S_Q = 20, S_R = 21, S_S = 22, S_T = 23, S_U = 24, S_V = 25, S_W = 26, S_X = 27, S_Y = 28, S_Z = 29, S_1 = 30, S_2 = 31, S_3 = 32, S_4 = 33, S_5 = 34, S_6 = 35, S_7 = 36, S_8 = 37, S_9 = 38, S_0 = 39, S_RETURN = 40, S_ESCAPE = 41, S_BACKSPACE = 42, S_TAB = 43, S_SPACE = 44, S_MINUS = 45, S_EQUALS = 46, S_LEFTBRACKET = 47, S_RIGHTBRACKET = 48, S_BACKSLASH = 49, S_NONUSHASH = 50, S_SEMICOLON = 51, S_APOSTROPHE = 52, S_GRAVE = 53, S_COMMA = 54, S_PERIOD = 55, S_SLASH = 56, S_CAPSLOCK = 57, S_F1 = 58, S_F2 = 59, S_F3 = 60, S_F4 = 61, S_F5 = 62, S_F6 = 63, S_F7 = 64, S_F8 = 65, S_F9 = 66, S_F10 = 67, S_F11 = 68, S_F12 = 69, S_PRINTSCREEN = 70, S_SCROLLLOCK = 71, S_PAUSE = 72, S_INSERT = 73, S_HOME = 74, S_PAGEUP = 75, S_DELETE = 76, S_END = 77, S_PAGEDOWN = 78, S_RIGHT = 79, S_LEFT = 80, S_DOWN = 81, S_UP = 82, S_NUMLOCKCLEAR = 83, S_KP_DIVIDE = 84, S_KP_MULTIPLY = 85, S_KP_MINUS = 86, S_KP_PLUS = 87, S_KP_ENTER = 88, S_KP_1 = 89, S_KP_2 = 90, S_KP_3 = 91, S_KP_4 = 92, S_KP_5 = 93, S_KP_6 = 94, S_KP_7 = 95, S_KP_8 = 96, S_KP_9 = 97, S_KP_0 = 98, S_KP_PERIOD = 99, S_NONUSBACKSLASH = 100, S_APPLICATION = 101, S_POWER = 102, S_KP_EQUALS = 103, S_F13 = 104, S_F14 = 105, S_F15 = 106, S_F16 = 107, S_F17 = 108, S_F18 = 109, S_F19 = 110, S_F20 = 111, S_F21 = 112, S_F22 = 113, S_F23 = 114, S_F24 = 115, S_EXECUTE = 116, S_HELP = 117, S_MENU = 118, S_SELECT = 119, S_STOP = 120, S_AGAIN = 121, S_UNDO = 122, S_CUT = 123, S_COPY = 124, S_PASTE = 125, S_FIND = 126, S_MUTE = 127, S_VOLUMEUP = 128, S_VOLUMEDOWN = 129, S_KP_COMMA = 133, S_KP_EQUALSAS400 = 134, S_INTERNATIONAL1 = 135, S_INTERNATIONAL2 = 136, S_INTERNATIONAL3 = 137, S_INTERNATIONAL4 = 138, S_INTERNATIONAL5 = 139, S_INTERNATIONAL6 = 140, S_INTERNATIONAL7 = 141, S_INTERNATIONAL8 = 142, S_INTERNATIONAL9 = 143, S_LANG1 = 144, S_LANG2 = 145, S_LANG3 = 146, S_LANG4 = 147, S_LANG5 = 148, S_LANG6 = 149, S_LANG7 = 150, S_LANG8 = 151, S_LANG9 = 152, S_ALTERASE = 153, S_SYSREQ = 154, S_CANCEL = 155, S_CLEAR = 156, S_PRIOR = 157, S_RETURN2 = 158, S_SEPARATOR = 159, S_OUT = 160, S_OPER = 161, S_CLEARAGAIN = 162, S_CRSEL = 163, S_EXSEL = 164, S_KP_00 = 176, S_KP_000 = 177, S_THOUSANDSSEPARATOR = 178, S_DECIMALSEPARATOR = 179, S_CURRENCYUNIT = 180, S_CURRENCYSUBUNIT = 181, S_KP_LEFTPAREN = 182, S_KP_RIGHTPAREN = 183, S_KP_LEFTBRACE = 184, S_KP_RIGHTBRACE = 185, S_KP_TAB = 186, S_KP_BACKSPACE = 187, S_KP_A = 188, S_KP_B = 189, S_KP_C = 190, S_KP_D = 191, S_KP_E = 192, S_KP_F = 193, S_KP_XOR = 194, S_KP_POWER = 195, S_KP_PERCENT = 196, S_KP_LESS = 197, S_KP_GREATER = 198, S_KP_AMPERSAND = 199, S_KP_DBLAMPERSAND = 200, S_KP_VERTICALBAR = 201, S_KP_DBLVERTICALBAR = 202, S_KP_COLON = 203, S_KP_HASH = 204, S_KP_SPACE = 205, S_KP_AT = 206, S_KP_EXCLAM = 207, S_KP_MEMSTORE = 208, S_KP_MEMRECALL = 209, S_KP_MEMCLEAR = 210, S_KP_MEMADD = 211, S_KP_MEMSUBTRACT = 212, S_KP_MEMMULTIPLY = 213, S_KP_MEMDIVIDE = 214, S_KP_PLUSMINUS = 215, S_KP_CLEAR = 216, S_KP_CLEARENTRY = 217, S_KP_BINARY = 218, S_KP_OCTAL = 219, S_KP_DECIMAL = 220, S_KP_HEXADECIMAL = 221, S_LCTRL = 224, S_LSHIFT = 225, S_LALT = 226, S_LGUI = 227, S_RCTRL = 228, S_RSHIFT = 229, S_RALT = 230, S_RGUI = 231, S_MODE = 257, S_AUDIONEXT = 258, S_AUDIOPREV = 259, S_AUDIOSTOP = 260, S_AUDIOPLAY = 261, S_AUDIOMUTE = 262, S_MEDIASELECT = 263, S_WWW = 264, S_MAIL = 265, S_CALCULATOR = 266, S_COMPUTER = 267, S_AC_SEARCH = 268, S_AC_HOME = 269, S_AC_BACK = 270, S_AC_FORWARD = 271, S_AC_STOP = 272, S_AC_REFRESH = 273, S_AC_BOOKMARKS = 274, S_BRIGHTNESSDOWN = 275, S_BRIGHTNESSUP = 276, S_DISPLAYSWITCH = 277, S_KBDILLUMTOGGLE = 278, S_KBDILLUMDOWN = 279, S_KBDILLUMUP = 280, S_EJECT = 281, S_SLEEP = 282, S_APP1 = 283, S_APP2 = 284, S_AUDIOREWIND = 285, S_AUDIOFASTFORWARD = 286, NUM_SCANCODES = 512 };
5,028
3,316
//Coresponding header #include "utils/drawing/Point.h" //C system includes //C++ system includes //Thitrd-party includes //Own includes //Forward Declarations const Point Point::ZERO(0, 0); const Point Point::UNDEFINED(1000, 1000); Point::Point(int32_t inputX, int32_t inputY) : x(inputX), y(inputY) {} bool Point::operator==(const Point & other) const { return ((this->x == other.x) && (this->y == other.y)); } bool Point::operator!=(const Point& other) const { return !(*this == other); }
507
201
/** @file "/owlcpp/lib/logic/triple_to_fact.cpp" part of owlcpp project. @n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt. @n Copyright Mikhail K Levin 2013 *******************************************************************************/ #ifndef OWLCPP_LOGIC_SOURCE #define OWLCPP_LOGIC_SOURCE #endif #include "owlcpp/logic/triple_to_fact.hpp" #include "boost/foreach.hpp" #include "fact++/Kernel.h" #include "owlcpp/logic/detail/triple_to_fact_adaptor.hpp" #include "owlcpp/rdf/triple_store.hpp" #include "owlcpp/rdf/print_triple.hpp" namespace owlcpp { /* *******************************************************************************/ TDLAxiom* submit( Triple const& t, Triple_store const& ts, ReasoningKernel& kernel, const bool strict ) { logic::factpp::Adaptor_triple at(ts, kernel, strict); try{ return at.submit(t); } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } } /* *******************************************************************************/ TDLAxiom* submit_check( Triple const& t, Triple_store const& ts, ReasoningKernel& kernel, const bool strict ) { logic::factpp::Adaptor_triple at(ts, kernel, strict); TDLAxiom* a = 0; try{ a = at.submit(t); } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } if( a ) try{ kernel.isKBConsistent(); }catch(EFaCTPlusPlus const& e) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("reasoning error after submitting triple") << Logic_err::str1_t(e.what()) << Logic_err::str2_t(to_string(t, ts)) << Logic_err::str3_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } return a; } /* *******************************************************************************/ std::size_t submit( Triple_store const& ts, ReasoningKernel& kernel, const bool strict, const bool diagnose ) { if( diagnose ) return submit_check(ts, kernel, strict); std::size_t n = 0; logic::factpp::Adaptor_triple at(ts, kernel, strict); BOOST_FOREACH(Triple const& t, ts.map_triple()) { try{ if( at.submit(t) ) ++n; } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } } return n; } /* *******************************************************************************/ std::size_t submit_check( Triple_store const& ts, ReasoningKernel& kernel, const bool strict ) { std::size_t n = 0; logic::factpp::Adaptor_triple at(ts, kernel, strict); BOOST_FOREACH(Triple const& t, ts.map_triple()) { TDLAxiom* a = 0; try{ a = at.submit(t); } catch(Logic_err const&) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("error submitting triple") << Logic_err::str1_t(to_string(t, ts)) << Logic_err::str2_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } if( a ) try{ ++n; kernel.isKBConsistent(); }catch(EFaCTPlusPlus const& e) { BOOST_THROW_EXCEPTION( Logic_err() << Logic_err::msg_t("reasoning error after submitting triple") << Logic_err::str1_t(e.what()) << Logic_err::str2_t(to_string(t, ts)) << Logic_err::str3_t(ts[t.doc_].path) << Logic_err::nested_t(boost::current_exception()) ); } } return n; } }//namespace owlcpp
4,549
1,548
#include "NuiPangoPolygonMeshShader.h" #include "Shape\NuiPolygonMesh.h" NuiPangoPolygonMeshShader::NuiPangoPolygonMeshShader() : m_numTriangles(0) { glGenBuffers(1, &m_vbo); glGenBuffers(1, &m_ibo); } NuiPangoPolygonMeshShader::~NuiPangoPolygonMeshShader() { uninitializeBuffers(); } bool NuiPangoPolygonMeshShader::initializeBuffers(NuiPolygonMesh* pMesh) { if(!pMesh) return false; int currentNumTriangles = pMesh->getTrianglesNum(); if (abs(currentNumTriangles - m_numTriangles) > 100) { pMesh->evaluateMesh(); m_numTriangles = currentNumTriangles; } if (0 == m_numTriangles) return false; glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBufferData(GL_ARRAY_BUFFER, pMesh->getVerticesBufferSize(), pMesh->getVerticesBuffer(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, pMesh->getIndicesBufferSize(), pMesh->getIndicesBuffer(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return true; } void NuiPangoPolygonMeshShader::drawMesh(const pangolin::OpenGlMatrix& mvp, bool bNormals) { glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glVertexPointer(3, GL_FLOAT, sizeof(pcl::PointXYZRGBNormal), 0); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); if (bNormals) { glColorPointer(3, GL_FLOAT, sizeof(pcl::PointXYZRGBNormal), (void *)(sizeof(float) * 4)); } else { glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(pcl::PointXYZRGBNormal), (void *)(sizeof(float) * 8)); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo); glDrawElements(GL_TRIANGLES, m_numTriangles * 3, GL_UNSIGNED_INT, 0); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void NuiPangoPolygonMeshShader::uninitializeBuffers() { glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ibo); }
1,961
888
#include <pybind11/pybind11.h> #include <pybind11/chrono.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <string> #include <multitouch_device.hpp> #include <touch_point.hpp> namespace py = pybind11; using namespace wand; PYBIND11_MODULE(wand, m) { m.doc() = ""; py::class_<TouchPoint, std::shared_ptr<TouchPoint>>{m, "TouchPoint"} .def(py::init<int>(), py::arg("id")) .def("__repr__", [](const TouchPoint& touch) { return "<wand.TouchPoint " + std::to_string(touch.id()) + ">"; }) .def_property_readonly("id", &TouchPoint::id) .def_property_readonly("active", &TouchPoint::active) .def_property_readonly("start_time", &TouchPoint::start_time) .def_property_readonly("update_time", &TouchPoint::update_time) .def_property_readonly("end_time", &TouchPoint::end_time) .def_property_readonly("duration", &TouchPoint::duration) .def_property_readonly("start_x", &TouchPoint::start_x) .def_property_readonly("start_y", &TouchPoint::start_y) .def_property_readonly("start_pos", [](const TouchPoint& touch) { std::array<double, 2> pos = {touch.start_x(), touch.start_y()}; return py::array_t<double>(2, pos.data()); }) .def_property_readonly("x", &TouchPoint::x) .def_property_readonly("y", &TouchPoint::y) .def_property_readonly("pos", [](const TouchPoint& touch) { std::array<double, 2> pos = {touch.x(), touch.y()}; return py::array_t<double>(2, pos.data()); }) .def_property_readonly( "direction", [](const TouchPoint& touch) { std::array<double, 2> direction = {touch.x() - touch.start_x(), touch.y() - touch.start_y()}; return py::array_t<double>(2, direction.data()); }) .def_property_readonly("timestamps", &TouchPoint::timestamps) .def_property_readonly("x_positions", &TouchPoint::x_positions) .def_property_readonly("y_positions", &TouchPoint::y_positions); py::class_<MultitouchDevice, std::shared_ptr<MultitouchDevice>>{m, "MultitouchDevice"} .def(py::init<std::string>(), py::arg("path")) .def("__repr__", [](const MultitouchDevice& device) { return "<wand.MultitouchDevice \"" + device.name() + "\">"; }) .def_property_readonly("name", &MultitouchDevice::name) .def_property_readonly("num_slots", &MultitouchDevice::num_slots) .def_property_readonly("touch_points", &MultitouchDevice::touch_points) .def_property_readonly("running", &MultitouchDevice::running) .def("start", &MultitouchDevice::start) .def("stop", &MultitouchDevice::stop) .def("poll_events", [](MultitouchDevice& dev) { TouchPtrSet new_touch_points, updated_touch_points, finished_touch_points; dev.poll_events(new_touch_points, updated_touch_points, finished_touch_points); return std::make_tuple(std::move(new_touch_points), std::move(updated_touch_points), std::move(finished_touch_points)); }); }
3,235
1,049
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<iomanip> #include<algorithm> #include<vector> #include<queue> #include<stack> #define ri register int #define ll long long using namespace std; const int MAXN=50005; const int MAXM=100005; int c[MAXN],dep[MAXN]; int n,m,sill=320,p[MAXN][16],g[MAXN][330]; vector<int>a[MAXN]; inline int GetInt() { int num=0,bj=1; char c=getchar(); while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(isdigit(c))num=num*10+c-'0',c=getchar(); return num*bj; } inline int Climb(int u,int k) { for(ri dk=0;k;k>>=1,++dk)if(k&1)u=p[u][dk]; return u; } void DFS(int u,int fa,int depth) { dep[u]=depth; vector<int>::iterator it; for(it=a[u].begin();it!=a[u].end();++it) { if(*it==fa)continue; p[*it][0]=u; DFS(*it,u,depth+1); } } void Tree_DP(int u) { for(ri i=1;i<=sill;i++) { int anc=Climb(u,i); g[u][i]=g[anc][i]+c[u]; } vector<int>::iterator it; for(it=a[u].begin();it!=a[u].end();++it) { if(*it==p[u][0])continue; Tree_DP(*it); } } inline void ST() { int k=log2(n); for(ri j=1;j<=k;j++) for(ri i=1;i<=n;i++) p[i][j]=p[p[i][j-1]][j-1]; } int len; inline int LCA(int a,int b) { if(dep[a]<dep[b])swap(a,b); int k=log2(dep[a]); for(ri i=k;i>=0;i--) if(dep[a]-(1<<i)>=dep[b])a=p[a][i],len+=(1<<i); if(a==b)return a; for(ri i=k;i>=0;i--) if(p[a][i]!=-1&&p[a][i]!=p[b][i])a=p[a][i],b=p[b][i],len+=(1<<(i+1)); len+=2; return p[a][0]; } inline int Query(int s,int t,int k) { int lca=LCA(s,t),ret=0,len=dep[s]+dep[t]-2*dep[lca],u=s; if(s==t)return c[s]; if(k<=sill) { int step=int(ceil(double(dep[s]-dep[lca])/(double)k)); int aim=Climb(s,step*k); ret+=g[s][k]-g[aim][k]; if(len%k)ret+=c[t],t=Climb(t,len%k); step=int(ceil(double(dep[t]-dep[lca])/(double)k)); aim=Climb(t,step*k); ret+=g[t][k]-g[aim][k]; if(!((dep[u]-dep[lca])%k))ret+=c[lca]; return ret; } else { int lca=LCA(s,t),ret=0,u=s; if(s==t)return c[s]; while(dep[s]>=dep[lca])ret+=c[s],s=Climb(s,k); if(len%k)ret+=c[t],t=Climb(t,len%k); while(dep[t]>=dep[lca])ret+=c[t],t=Climb(t,k); if(!((dep[u]-dep[lca])%k))ret-=c[lca]; return ret; } } int main() { n=GetInt(),m=GetInt(); for(ri i=1;i<=n;i++)c[i]=GetInt(); for(ri i=1;i<n;i++) { int u=GetInt(),v=GetInt(); a[u].push_back(v); a[v].push_back(u); } DFS(1,0,1),ST(),Tree_DP(1); for(ri i=1;i<=m;i++) { int s=GetInt(),t=GetInt(),k=GetInt(); printf("%d\n",Query(s,t,k)); } return 0; }
2,480
1,436
/* * itp.cc * * Created on: Nov 13, 2015 */ #include <Wt/WApplication> #include "IdeaToProduct.h" Wt::WApplication *createApplication(const Wt::WEnvironment& env) { return new IdeaToProduct(env); } int main(int argc, char **argv) { return Wt::WRun(argc, argv, &createApplication); }
303
128
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGLocation.cpp Author: Jon S. Berndt Date started: 04/04/2004 Purpose: Store an arbitrary location on the globe ------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) ------------------ ------- (C) 2004 Mathias Froehlich (Mathias.Froehlich@web.de) ---- ------- (C) 2011 Ola Røer Thorsen (ola@silentwings.no) ----------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION ------------------------------------------------------------------------------ This class encapsulates an arbitrary position in the globe with its accessors. It has vector properties, so you can add multiply .... HISTORY ------------------------------------------------------------------------------ 04/04/2004 MF Created 11/01/2011 ORT Encapsulated ground callback code in FGLocation and removed it from FGFDMExec. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include <cmath> #include "FGLocation.h" namespace JSBSim { /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGLocation::FGLocation(void) : mECLoc(1.0, 0.0, 0.0), mCacheValid(false) { e2 = c = 0.0; a = ec = ec2 = 1.0; mLon = mLat = mRadius = 0.0; mGeodLat = GeodeticAltitude = 0.0; mTl2ec.InitMatrix(); mTec2l.InitMatrix(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(double lon, double lat, double radius) : mCacheValid(false) { e2 = c = 0.0; a = ec = ec2 = 1.0; mLon = mLat = mRadius = 0.0; mGeodLat = GeodeticAltitude = 0.0; mTl2ec.InitMatrix(); mTec2l.InitMatrix(); double sinLat = sin(lat); double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); mECLoc = { radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat }; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(const FGColumnVector3& lv) : mECLoc(lv), mCacheValid(false) { e2 = c = 0.0; a = ec = ec2 = 1.0; mLon = mLat = mRadius = 0.0; mGeodLat = GeodeticAltitude = 0.0; mTl2ec.InitMatrix(); mTec2l.InitMatrix(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(const FGLocation& l) : mECLoc(l.mECLoc), mCacheValid(l.mCacheValid) { a = l.a; e2 = l.e2; c = l.c; ec = l.ec; ec2 = l.ec2; mEllipseSet = l.mEllipseSet; /*ag * if the cache is not valid, all of the following values are unset. * They will be calculated once ComputeDerivedUnconditional is called. * If unset, they may possibly contain NaN and could thus trigger floating * point exceptions. */ if (!mCacheValid) return; mLon = l.mLon; mLat = l.mLat; mRadius = l.mRadius; mTl2ec = l.mTl2ec; mTec2l = l.mTec2l; mGeodLat = l.mGeodLat; GeodeticAltitude = l.GeodeticAltitude; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation& FGLocation::operator=(const FGLocation& l) { mECLoc = l.mECLoc; mCacheValid = l.mCacheValid; mEllipseSet = l.mEllipseSet; a = l.a; e2 = l.e2; c = l.c; ec = l.ec; ec2 = l.ec2; //ag See comment in constructor above if (!mCacheValid) return *this; mLon = l.mLon; mLat = l.mLat; mRadius = l.mRadius; mTl2ec = l.mTl2ec; mTec2l = l.mTec2l; mGeodLat = l.mGeodLat; GeodeticAltitude = l.GeodeticAltitude; return *this; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLongitude(double longitude) { double rtmp = mECLoc.Magnitude(eX, eY); // Check if we have zero radius. // If so set it to 1, so that we can set a position if (0.0 == mECLoc.Magnitude()) rtmp = 1.0; // Fast return if we are on the north or south pole ... if (rtmp == 0.0) return; mCacheValid = false; mECLoc(eX) = rtmp*cos(longitude); mECLoc(eY) = rtmp*sin(longitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLatitude(double latitude) { mCacheValid = false; double r = mECLoc.Magnitude(); if (r == 0.0) { mECLoc(eX) = 1.0; r = 1.0; } double rtmp = mECLoc.Magnitude(eX, eY); if (rtmp != 0.0) { double fac = r/rtmp*cos(latitude); mECLoc(eX) *= fac; mECLoc(eY) *= fac; } else { mECLoc(eX) = r*cos(latitude); mECLoc(eY) = 0.0; } mECLoc(eZ) = r*sin(latitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetRadius(double radius) { mCacheValid = false; double rold = mECLoc.Magnitude(); if (rold == 0.0) mECLoc(eX) = radius; else mECLoc *= radius/rold; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetPosition(double lon, double lat, double radius) { mCacheValid = false; double sinLat = sin(lat); double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); mECLoc = { radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat }; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetPositionGeodetic(double lon, double lat, double height) { assert(mEllipseSet); mCacheValid = false; double slat = sin(lat); double clat = cos(lat); double RN = a / sqrt(1.0 - e2*slat*slat); mECLoc(eX) = (RN + height)*clat*cos(lon); mECLoc(eY) = (RN + height)*clat*sin(lon); mECLoc(eZ) = ((1 - e2)*RN + height)*slat; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetEllipse(double semimajor, double semiminor) { mCacheValid = false; mEllipseSet = true; a = semimajor; ec = semiminor/a; ec2 = ec * ec; e2 = 1.0 - ec2; c = a * e2; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGLocation::GetSeaLevelRadius(void) const { assert(mEllipseSet); ComputeDerived(); double cosLat = cos(mLat); return a*ec/sqrt(1.0-e2*cosLat*cosLat); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::ComputeDerivedUnconditional(void) const { // The radius is just the Euclidean norm of the vector. mRadius = mECLoc.Magnitude(); // The distance of the location to the Z-axis, which is the axis // through the poles. double rxy = mECLoc.Magnitude(eX, eY); // Compute the longitude and its sin/cos values. double sinLon, cosLon; if (rxy == 0.0) { sinLon = 0.0; cosLon = 1.0; mLon = 0.0; } else { sinLon = mECLoc(eY)/rxy; cosLon = mECLoc(eX)/rxy; mLon = atan2(mECLoc(eY), mECLoc(eX)); } // Compute the geocentric & geodetic latitudes. double sinLat, cosLat; if (mRadius == 0.0) { mLat = 0.0; sinLat = 0.0; cosLat = 1.0; if (mEllipseSet) { mGeodLat = 0.0; GeodeticAltitude = -a; } } else { mLat = atan2( mECLoc(eZ), rxy ); // Calculate the geodetic latitude based on "Transformation from Cartesian to // geodetic coordinates accelerated by Halley's method", Fukushima T. (2006) // Journal of Geodesy, Vol. 79, pp. 689-693 // Unlike I. Sofair's method which uses a closed form solution, Fukushima's // method is an iterative method whose convergence is so fast that only one // iteration suffices. In addition, Fukushima's method has a much better // numerical stability over Sofair's method at the North and South poles and // it also gives the correct result for a spherical Earth. if (mEllipseSet) { double s0 = fabs(mECLoc(eZ)); double zc = ec * s0; double c0 = ec * rxy; double c02 = c0 * c0; double s02 = s0 * s0; double a02 = c02 + s02; double a0 = sqrt(a02); double a03 = a02 * a0; double s1 = zc*a03 + c*s02*s0; double c1 = rxy*a03 - c*c02*c0; double cs0c0 = c*c0*s0; double b0 = 1.5*cs0c0*((rxy*s0-zc*c0)*a0-cs0c0); s1 = s1*a03-b0*s0; double cc = ec*(c1*a03-b0*c0); mGeodLat = sign(mECLoc(eZ))*atan(s1 / cc); double s12 = s1 * s1; double cc2 = cc * cc; double norm = sqrt(s12 + cc2); cosLat = cc / norm; sinLat = sign(mECLoc(eZ)) * s1 / norm; GeodeticAltitude = (rxy*cc + s0*s1 - a*sqrt(ec2*s12 + cc2)) / norm; } else { sinLat = mECLoc(eZ)/mRadius; cosLat = rxy/mRadius; } } // Compute the transform matrices from and to the earth centered frame. // See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, // Eqn. 1.4-13, page 40. In Stevens and Lewis notation, this is C_n/e - the // orientation of the navigation (local) frame relative to the ECEF frame, // and a transformation from ECEF to nav (local) frame. mTec2l = { -cosLon*sinLat, -sinLon*sinLat, cosLat, -sinLon , cosLon , 0.0 , -cosLon*cosLat, -sinLon*cosLat, -sinLat }; // In Stevens and Lewis notation, this is C_e/n - the // orientation of the ECEF frame relative to the nav (local) frame, // and a transformation from nav (local) to ECEF frame. mTl2ec = mTec2l.Transposed(); // Mark the cached values as valid mCacheValid = true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The calculations, below, implement the Haversine formulas to calculate // heading and distance to a set of lat/long coordinates from the current // position. // // The basic equations are (lat1, long1 are source positions; lat2 // long2 are target positions): // // R = earth’s radius // Δlat = lat2 − lat1 // Δlong = long2 − long1 // // For the waypoint distance calculation: // // a = sin²(Δlat/2) + cos(lat1)∙cos(lat2)∙sin²(Δlong/2) // c = 2∙atan2(√a, √(1−a)) // d = R∙c double FGLocation::GetDistanceTo(double target_longitude, double target_latitude) const { ComputeDerived(); double delta_lat_rad = target_latitude - mLat; double delta_lon_rad = target_longitude - mLon; double distance_a = pow(sin(0.5*delta_lat_rad), 2.0) + (cos(mLat) * cos(target_latitude) * (pow(sin(0.5*delta_lon_rad), 2.0))); return 2.0 * GetRadius() * atan2(sqrt(distance_a), sqrt(1.0 - distance_a)); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The calculations, below, implement the Haversine formulas to calculate // heading and distance to a set of lat/long coordinates from the current // position. // // The basic equations are (lat1, long1 are source positions; lat2 // long2 are target positions): // // R = earth’s radius // Δlat = lat2 − lat1 // Δlong = long2 − long1 // // For the heading angle calculation: // // θ = atan2(sin(Δlong)∙cos(lat2), cos(lat1)∙sin(lat2) − sin(lat1)∙cos(lat2)∙cos(Δlong)) double FGLocation::GetHeadingTo(double target_longitude, double target_latitude) const { ComputeDerived(); double delta_lon_rad = target_longitude - mLon; double Y = sin(delta_lon_rad) * cos(target_latitude); double X = cos(mLat) * sin(target_latitude) - sin(mLat) * cos(target_latitude) * cos(delta_lon_rad); double heading_to_waypoint_rad = atan2(Y, X); if (heading_to_waypoint_rad < 0) heading_to_waypoint_rad += 2.0*M_PI; return heading_to_waypoint_rad; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } // namespace JSBSim
12,569
4,593
#include "duckdb/planner/logical_operator.hpp" #include "duckdb/common/printer.hpp" #include "duckdb/common/string_util.hpp" using namespace duckdb; using namespace std; string LogicalOperator::ParamsToString() const { string result = ""; if (expressions.size() > 0) { result += "["; result += StringUtil::Join(expressions, expressions.size(), ", ", [](const unique_ptr<Expression> &expression) { return expression->GetName(); }); result += "]"; } return result; } void LogicalOperator::ResolveOperatorTypes() { // if (types.size() > 0) { // // types already resolved for this node // return; // } types.clear(); // first resolve child types for (auto &child : children) { child->ResolveOperatorTypes(); } // now resolve the types for this operator ResolveTypes(); } vector<ColumnBinding> LogicalOperator::GenerateColumnBindings(idx_t table_idx, idx_t column_count) { vector<ColumnBinding> result; for (idx_t i = 0; i < column_count; i++) { result.push_back(ColumnBinding(table_idx, i)); } return result; } vector<TypeId> LogicalOperator::MapTypes(vector<TypeId> types, vector<idx_t> projection_map) { if (projection_map.size() == 0) { return types; } else { vector<TypeId> result_types; for (auto index : projection_map) { result_types.push_back(types[index]); } return result_types; } } vector<ColumnBinding> LogicalOperator::MapBindings(vector<ColumnBinding> bindings, vector<idx_t> projection_map) { if (projection_map.size() == 0) { return bindings; } else { vector<ColumnBinding> result_bindings; for (auto index : projection_map) { result_bindings.push_back(bindings[index]); } return result_bindings; } } string LogicalOperator::ToString(idx_t depth) const { string result = LogicalOperatorToString(type); result += ParamsToString(); if (children.size() > 0) { for (idx_t i = 0; i < children.size(); i++) { result += "\n" + string(depth * 4, ' '); auto &child = children[i]; result += child->ToString(depth + 1); } result += ""; } return result; } void LogicalOperator::Print() { Printer::Print(ToString()); }
2,140
761
#include "basic_op.h" /* float fmaxf(float x, float y){ /// Returns maximum of x, y /// return (((x)>(y))?(x):(y)); } float fminf(float x, float y){ /// Returns minimum of x, y /// return (((x)<(y))?(x):(y)); }*/ // float -> uint int float_to_uint(float x, float x_min, float x_max, int bits){ /// Converts a float to an unsigned int, given range and number of bits /// float span = x_max - x_min; float offset = x_min; return (int) ((x-offset)*((float)((1<<bits)-1))/span); } // uint -> float float uint_to_float(int x_int, float x_min, float x_max, int bits){ /// converts unsigned int to float, given range and number of bits /// float span = x_max - x_min; float offset = x_min; return ((float)x_int)*span/((float)((1<<bits)-1)) + offset; }
825
308
//==--- wrench/tests/all.cpp ------------------------------- -*- C++ -*- ---==// // // Wrench // // Copyright (c) 2020 Rob Clucas. // // This file is distributed under the MIT License. See LICENSE for details. // //==------------------------------------------------------------------------==// // /// \file all.cpp /// \brief This file implements all tests. // //==------------------------------------------------------------------------==// #include "algorithm/algorithm.hpp" #include "memory/memory.hpp" int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
667
188
// Copyright 2015 The Chromium OS 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 "fides/mock_settings_document.h" #include "fides/identifier_utils.h" namespace fides { MockSettingsDocument::MockSettingsDocument(const VersionStamp& version_stamp) : version_stamp_(version_stamp) {} MockSettingsDocument::~MockSettingsDocument() {} std::unique_ptr<MockSettingsDocument> MockSettingsDocument::Clone() const { std::unique_ptr<MockSettingsDocument> copy( new MockSettingsDocument(version_stamp_)); copy->deletions_ = deletions_; copy->key_value_map_ = key_value_map_; return copy; } BlobRef MockSettingsDocument::GetValue(const Key& key) const { auto entry = key_value_map_.find(key); return entry != key_value_map_.end() ? BlobRef(&entry->second) : BlobRef(); } std::set<Key> MockSettingsDocument::GetKeys(const Key& prefix) const { std::set<Key> result; for (const auto& entry : utils::GetRange(prefix, key_value_map_)) result.insert(entry.first); return result; } std::set<Key> MockSettingsDocument::GetDeletions(const Key& prefix) const { std::set<Key> result; for (const auto& entry : utils::GetRange(prefix, deletions_)) result.insert(entry); return result; } VersionStamp MockSettingsDocument::GetVersionStamp() const { return version_stamp_; } bool MockSettingsDocument::HasKeysOrDeletions(const Key& prefix) const { return utils::HasKeys(prefix, key_value_map_) || utils::HasKeys(prefix, deletions_); } void MockSettingsDocument::SetKey(const Key& key, const std::string& value) { key_value_map_.insert(std::make_pair(key, std::move(value))); } void MockSettingsDocument::ClearKey(const Key& key) { key_value_map_.erase(key); } void MockSettingsDocument::ClearKeys() { key_value_map_.clear(); } void MockSettingsDocument::SetDeletion(const Key& key) { deletions_.insert(key); } void MockSettingsDocument::ClearDeletion(const Key& key) { deletions_.erase(key); } void MockSettingsDocument::ClearDeletions() { deletions_.clear(); } } // namespace fides
2,137
698
#include "Graphics.h" #include <string.h> void Graphics::init(HWND hwnd) { cout << "GRAPHICS STARTED\n"; d3d = new D3D; d2d = new D2D; RQ2D = new RenderQueue_2D; fistscene = new StdScene; d3d->InitD3D(hwnd); InitSharedScreen(d3d->Adapter); d2d->InitD2D(sharedSurface10); d2d->UpdateClassResources(keyedMutex11, keyedMutex10); d3d->Adapter->Release(); sharedSurface10->Release(); keyedMutex11->Release(); keyedMutex10->Release(); cout << "GRAPHICS LOADED\n"; } void Graphics::startScene() { fistscene->LoadScene(); d2d->SetRenderArea(sharedTex11, 0, 0, 0, 0); sharedTex11->Release(); } void Graphics::Update(double FrameTime, double FPS) { fistscene->SceneInput(FrameTime); fistscene->UpdateScene(FrameTime,FPS); } void Graphics::Render() { //bckground color float bgColor[4] = { 0.0f,0.05f,0.1f,1.0f }; //Clear our backbuffer d3d->d3dDevCon->ClearRenderTargetView(d3d->renderTargetView, bgColor); d3d->d3dDevCon->ClearDepthStencilView(d3d->depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); fistscene->Renderscene(); RQ2D->Render(); d3d->SwapChain->Present(0, 0); } void Graphics::Release() { if (d2d)d2d->Release(); if (d3d)d3d->Release(); if (fistscene)fistscene->Release(); if (RQ2D)RQ2D->Release(); } void Graphics::InitSharedScreen(IDXGIAdapter1* Adapter) { //Create our Direc3D 10.1 Device/////////////////////////////////////////////////////////////////////////////////////// HRESULT hr = D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_BGRA_SUPPORT, D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device); //Create Shared Texture that Direct3D 10.1 will render on////////////////////////////////////////////////////////////// D3D11_TEXTURE2D_DESC sharedTexDesc; ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc)); sharedTexDesc.Width = H_res; sharedTexDesc.Height = V_res; sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; sharedTexDesc.MipLevels = 1; sharedTexDesc.ArraySize = 1; sharedTexDesc.SampleDesc.Count = 1; sharedTexDesc.Usage = D3D11_USAGE_DEFAULT; sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; hr = d3d->d3dDevice->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11); // Get the keyed mutex for the shared texture (for D3D11)/////////////////////////////////////////////////////////////// hr = sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex11); // Get the shared handle needed to open the shared texture in D3D10.1/////////////////////////////////////////////////// IDXGIResource* sharedResource10; HANDLE sharedHandle10; hr = sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource10); hr = sharedResource10->GetSharedHandle(&sharedHandle10); sharedResource10->Release(); // Open the surface for the shared texture in D3D10.1/////////////////////////////////////////////////////////////////// hr = d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void**)(&sharedSurface10)); hr = sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex10); d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); d3d101Device->Release(); }
3,509
1,367
/** * Copyright 2011-2015 Quickstep Technologies LLC. * Copyright 2015 Pivotal Software, 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. **/ #ifndef QUICKSTEP_QUERY_OPTIMIZER_STRATEGY_STRATEGY_HPP_ #define QUICKSTEP_QUERY_OPTIMIZER_STRATEGY_STRATEGY_HPP_ #include <string> #include <vector> #include "query_optimizer/logical/Logical.hpp" #include "query_optimizer/physical/Physical.hpp" #include "utility/Macros.hpp" namespace quickstep { namespace optimizer { class OptimizerContext; class LogicalToPhysicalMapper; namespace strategy { /** \addtogroup OptimizerStrategy * @{ */ /** * @brief Base class for strategies that implement how to convert a logical * plan to a physical plan for a type of operators. */ class Strategy { public: /** * @brief Destructor. */ virtual ~Strategy() {} /** * @brief Converts \p logical_input to \p physical_output if the strategy * can be applied to the input; otherwise, set physical_output to NULL. * * @param logical_input The logical plan to be converted * @param physical_output The physical plan output. NULL if the strategy * cannot be applied to the input. * @return True if the strategy has been applied to the input logical. */ virtual bool generatePlan(const logical::LogicalPtr &logical_input, physical::PhysicalPtr *physical_output) = 0; /** * @return The name of the strategy. */ virtual std::string getName() const = 0; protected: /** * @brief Constructor. * * @param physical_mapper The physical plan generator. A strategy can * interact with other strategies via the plan * generator to create a complete plan. */ explicit Strategy(LogicalToPhysicalMapper *physical_mapper) : physical_mapper_(physical_mapper) {} LogicalToPhysicalMapper *physical_mapper_; private: DISALLOW_COPY_AND_ASSIGN(Strategy); }; /** @} */ } // namespace strategy } // namespace optimizer } // namespace quickstep #endif /* QUICKSTEP_QUERY_OPTIMIZER_STRATEGY_STRATEGY_HPP_ */
2,661
832
/** * Process worker pool. * * Copyright (c) 2015 Alex Jin (toalexjin@hotmail.com) */ #include "c11httpd/worker_pool.h" #include <signal.h> namespace c11httpd { err_t worker_pool_t::create(int number) { if (!this->m_main_process) { return err_t(); } for (int i = 0; i < number; ++i) { const auto pid = fork(); if (pid == -1) { return err_t::current(); } if (pid == 0) { this->m_self_pid = getpid(); this->m_main_process = false; break; } else { assert(this->m_main_process); this->m_workers.insert(pid); } } return err_t(); } err_t worker_pool_t::kill(pid_t pid) { err_t ret; if (!this->m_main_process) { return ret; } auto pos = this->m_workers.find(pid); if (pos == this->m_workers.end()) { return ret; } if (::kill(pid, SIGTERM) == -1) { ret = err_t::current(); } this->m_workers.erase(pos); return ret; } void worker_pool_t::kill_all() { if (!this->m_main_process) { return; } for (auto it = this->m_workers.cbegin(); it != this->m_workers.cend(); ++it) { ::kill((*it), SIGTERM); } this->m_workers.clear(); } bool worker_pool_t::on_terminated(pid_t pid) { if (!this->m_main_process) { return false; } return this->m_workers.erase(pid) > 0; } } // namespace c11httpd.
1,263
592
// // Created by huang on 2019/1/25. // #include "log.h" static bool gIsLogOn = true; bool isLogOn() { return gIsLogOn; } void setLog(bool isOn) { gIsLogOn = isOn; }
176
85
/** @file ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef MCL_BN128_GT_HPP_ #define MCL_BN128_GT_HPP_ #include <iostream> #include "depends/mcl/include/mcl/bn256.hpp" #include <libff/algebra/fields/field_utils.hpp> #include <libff/algebra/fields/fp.hpp> namespace libff { class mcl_bn128_GT; std::ostream& operator<<(std::ostream &, const mcl_bn128_GT&); std::istream& operator>>(std::istream &, mcl_bn128_GT&); class mcl_bn128_GT { public: static mcl_bn128_GT &GT_one(); mcl::bn256::Fp12 elem; mcl_bn128_GT(); bool operator==(const mcl_bn128_GT &other) const; bool operator!=(const mcl_bn128_GT &other) const; mcl_bn128_GT operator*(const mcl_bn128_GT &other) const; mcl_bn128_GT unitary_inverse() const; static mcl_bn128_GT one(); void print() { std::cout << this->elem << "\n"; }; friend std::ostream& operator<<(std::ostream &out, const mcl_bn128_GT &g); friend std::istream& operator>>(std::istream &in, mcl_bn128_GT &g); }; template<mp_size_t m> mcl_bn128_GT operator^(const mcl_bn128_GT &rhs, const bigint<m> &lhs) { return power<mcl_bn128_GT, m>(rhs, lhs); } template<mp_size_t m, const bigint<m>& modulus_p> mcl_bn128_GT operator^(const mcl_bn128_GT &rhs, const Fp_model<m,modulus_p> &lhs) { return power<mcl_bn128_GT, m>(rhs, lhs.as_bigint()); } } // libff #endif // MCL_BN128_GT_HPP_
1,643
684
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzTest/AzTest.h> #include <AzCore/Component/ComponentApplication.h> #include <AzCore/Component/Entity.h> #include <AzCore/Memory/MemoryComponent.h> #include <Source/LandscapeCanvasSystemComponent.h> class LandscapeCanvasTest : public ::testing::Test { protected: void SetUp() override { // Setup a system allocator AZ::ComponentApplication::Descriptor appDesc; m_application.Create(appDesc); m_application.RegisterComponentDescriptor(LandscapeCanvas::LandscapeCanvasSystemComponent::CreateDescriptor()); } void TearDown() override { m_application.Destroy(); } AZ::ComponentApplication m_application; }; TEST_F(LandscapeCanvasTest, LandscapeCanvasSystemComponentCreatesAndDestroysSuccessfully) { LandscapeCanvas::LandscapeCanvasSystemComponent test; } TEST_F(LandscapeCanvasTest, LandscapeCanvasSystemComponentActivatesAndDeactivatesSuccessfully) { auto entity = AZStd::make_unique<AZ::Entity>(); entity->CreateComponent<LandscapeCanvas::LandscapeCanvasSystemComponent>(); entity->Init(); EXPECT_EQ(AZ::Entity::State::Init, entity->GetState()); entity->Activate(); EXPECT_EQ(AZ::Entity::State::Active, entity->GetState()); entity->Deactivate(); EXPECT_EQ(AZ::Entity::State::Init, entity->GetState()); } AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV);
1,595
498
/** * Copyright Žiga Sajovic, XLAB 2019 * Distributed under the MIT License * * https://github.com/ZigaSajovic/CppML **/ #ifndef CPPML_BIND_HPP #define CPPML_BIND_HPP #include "../Pack/Insert.hpp" #include "./Compose.hpp" #include "./Partial.hpp" namespace ml { /* * # Par: * Is a parameter holder for ml::Bind. */ template <int I, typename T> struct Par { template <typename Pipe> using f = ml::Insert<I, T, Pipe>; }; /* * # Bind: * Binds arguments, creating a partially evaluated metafunction * **NOTE** that Is must be in sorted order */ template <typename F, typename... Ts> struct Bind; template <typename F, int... Is, typename... Args> struct Bind<F, Par<Is, Args>...> : ml::Invoke<ml::Compose<Par<Is, Args>...>, F> {}; /* * Below are a few optimizations to avoid work. When we are binding * successive parameters, from the first forward, it is the same as * if we used ml::Partial, which is more efficient. */ template <typename F, typename T0> struct Bind<F, Par<0, T0>> : ml::Partial<F, T0> {}; template <typename F, typename T0, typename T1> struct Bind<F, Par<0, T0>, Par<1, T1>> : ml::Partial<F, T0, T1> {}; template <typename F, typename T0, typename T1, typename T2> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>> : ml::Partial<F, T0, T1, T2> {}; template <typename F, typename T0, typename T1, typename T2, typename T3> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>> : ml::Partial<F, T0, T1, T2, T3> {}; template <typename F, typename T0, typename T1, typename T2, typename T3, typename T4> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>, Par<4, T4>> : ml::Partial<F, T0, T1, T2, T3, T4> {}; template <typename F, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>, Par<4, T4>, Par<5, T5>> : ml::Partial<F, T0, T1, T2, T3, T4, T5> {}; /* * # _pi: */ template <typename T> using _p0 = Par<0, T>; template <typename T> using _p1 = Par<1, T>; template <typename T> using _p2 = Par<2, T>; template <typename T> using _p3 = Par<3, T>; template <typename T> using _p4 = Par<4, T>; template <typename T> using _p5 = Par<5, T>; template <typename T> using _p6 = Par<6, T>; template <typename T> using _p7 = Par<7, T>; template <typename T> using _p8 = Par<8, T>; template <typename T> using _p9 = Par<9, T>; template <typename T> using _p10 = Par<10, T>; template <typename T> using _p11 = Par<11, T>; template <typename T> using _p12 = Par<12, T>; template <typename T> using _p13 = Par<13, T>; template <typename T> using _p14 = Par<14, T>; template <typename T> using _p15 = Par<15, T>; template <typename T> using _p16 = Par<16, T>; template <typename T> using _p17 = Par<17, T>; template <typename T> using _p18 = Par<18, T>; template <typename T> using _p19 = Par<19, T>; template <typename T> using _p20 = Par<20, T>; } // namespace ml #endif
2,958
1,195