hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2471b6f6fb0b17ef35074b28a2af07d8eac4d4a9
1,203
cpp
C++
QSidePanel/QSidePanel/PanelLeftSide.cpp
inobelar/QSidePanel
4554e1bcd3f0942df66ed1357cdac7afdd08597d
[ "MIT" ]
16
2019-10-11T12:08:05.000Z
2022-01-02T05:59:16.000Z
QSidePanel/QSidePanel/PanelLeftSide.cpp
inobelar/QSidePanel
4554e1bcd3f0942df66ed1357cdac7afdd08597d
[ "MIT" ]
null
null
null
QSidePanel/QSidePanel/PanelLeftSide.cpp
inobelar/QSidePanel
4554e1bcd3f0942df66ed1357cdac7afdd08597d
[ "MIT" ]
9
2019-11-17T20:09:55.000Z
2021-10-31T14:54:02.000Z
#include "PanelLeftSide.hpp" #include "side_panel_helpers.hpp" PanelLeftSide::PanelLeftSide(QWidget *parent) : SidePanel(parent) { this->getOpenedRect = [this](const QRect& parent_rect) -> QRect { return q_sp::rect_opened_left(this->getPanelSize(), parent_rect); }; this->getClosedRect = [this](const QRect& parent_rect) -> QRect { return q_sp::rect_closed_left(this->getPanelSize(), parent_rect); }; this->alignedHandlerRect = [](const QRect& panel_geom, const QSize& handler_size, qreal) -> QRect { return q_sp::rect_aligned_right_center(panel_geom, handler_size); }; this->initialHandlerSize = []() -> QSize { return {60, 120}; }; this->updateHandler = [](const SidePanelState state, HandlerWidgetT* handler) { switch (state) { case SidePanelState::Opening: { handler->setText("<"); } break; case SidePanelState::Opened: { handler->setText("<"); } break; case SidePanelState::Closing: { handler->setText(">"); } break; case SidePanelState::Closed: { handler->setText(">"); } break; default: break; } }; } PanelLeftSide::~PanelLeftSide() { }
27.340909
101
0.630923
inobelar
247823b2fcf93eeb139a63caf4829f6b3aa21578
2,273
cc
C++
google/cloud/spanner/testing/pick_random_instance.cc
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
google/cloud/spanner/testing/pick_random_instance.cc
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
google/cloud/spanner/testing/pick_random_instance.cc
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // 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 "google/cloud/spanner/testing/pick_random_instance.h" #include "google/cloud/spanner/instance_admin_client.h" namespace google { namespace cloud { namespace spanner_testing { inline namespace SPANNER_CLIENT_NS { StatusOr<std::string> PickRandomInstance( google::cloud::internal::DefaultPRNG& generator, std::string const& project_id) { spanner::InstanceAdminClient client(spanner::MakeInstanceAdminConnection()); /** * We started to have integration tests for InstanceAdminClient which creates * and deletes temporary instances. If we pick one of those instances here, * the following tests will fail after the deletion. * InstanceAdminClient's integration tests are using instances prefixed with * "temporary-instances-", so we only pick instances prefixed with * "test-instance-" here for isolation. */ std::vector<std::string> instance_ids; for (auto& instance : client.ListInstances(project_id, "")) { if (!instance) return std::move(instance).status(); auto name = instance->name(); std::string const sep = "/instances/"; std::string const valid_instance_name = sep + "test-instance-"; auto pos = name.rfind(valid_instance_name); if (pos != std::string::npos) { instance_ids.push_back(name.substr(pos + sep.size())); } } if (instance_ids.empty()) { return Status(StatusCode::kInternal, "No available instances for test"); } auto random_index = std::uniform_int_distribution<std::size_t>(0, instance_ids.size() - 1); return instance_ids[random_index(generator)]; } } // namespace SPANNER_CLIENT_NS } // namespace spanner_testing } // namespace cloud } // namespace google
37.883333
79
0.730312
antfitch
247fe0aaaccabce6151516dcb6e2b2bd5f98a08c
375
cpp
C++
codeforces/contests/round/452-div2/a.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/contests/round/452-div2/a.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/contests/round/452-div2/a.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int n; cin >> n; int a = 0, b = 0; for(int i=0; i<n; ++i){ int x; cin >> x; if(x == 1) a++; else b++; } int ans = a/3; for(int i=1; i<=min(a, b); ++i) ans = max(ans, i + (a - i)/3); cout << ans << endl; return 0; }
17.045455
38
0.365333
tysm
248777dae7d01164b3d2928d2aed3fe2a25f6e7e
2,650
hpp
C++
src/ibeo_8l_sdk/src/ibeosdk/datablocks/PointCloudPlane7510.hpp
tomcamp0228/ibeo_ros2
ff56c88d6e82440ae3ce4de08f2745707c354604
[ "MIT" ]
1
2020-06-19T11:01:49.000Z
2020-06-19T11:01:49.000Z
include/ibeosdk/datablocks/PointCloudPlane7510.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
null
null
null
include/ibeosdk/datablocks/PointCloudPlane7510.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
2
2020-06-19T11:01:48.000Z
2020-10-29T03:07:14.000Z
//====================================================================== /*! \file PointCloudPlane7510.hpp *\verbatim * ------------------------------------------ * (C) 2016 Ibeo Automotive Systems GmbH, Hamburg, Germany * ------------------------------------------ * * Created on: Mar 15, 2016 * by: Kristian Bischoff *\endverbatim *///------------------------------------------------------------------- //====================================================================== #ifndef POINTCLOUDPLANE7510_HPP_SEEN #define POINTCLOUDPLANE7510_HPP_SEEN //====================================================================== #include <ibeosdk/misc/WinCompatibility.hpp> #include <ibeosdk/datablocks/RegisteredDataBlock.hpp> #include <ibeosdk/datablocks/snippets/PlanePoint.hpp> #include <ibeosdk/datablocks/snippets/PointCloudBase.hpp> #include <vector> //====================================================================== namespace ibeosdk { //====================================================================== class PointCloudPlane7510 : public RegisteredDataBlock<PointCloudPlane7510>, public PointCloudBase { public: PointCloudPlane7510() : PointCloudBase() {} virtual ~PointCloudPlane7510() {} public: virtual std::streamsize getSerializedSize() const; virtual DataTypeId getDataType() const; virtual bool deserialize(std::istream& is, const IbeoDataHeader& dh); virtual bool serialize(std::ostream& os) const; public: virtual bool empty() const { return m_points.empty(); } public: typedef CustomIterator<PlanePoint, std::vector<PlanePoint>::iterator, PlanePointProxy, PlanePointProxy, PointCloudPlane7510, PointCloudPlane7510> iterator; typedef CustomIterator<PlanePoint , std::vector<PlanePoint>::const_iterator, PlanePointProxy const, PlanePointProxy, PointCloudPlane7510 const, PointCloudPlane7510> const_iterator; virtual iterator begin() { return iterator(m_points.begin(), this); } virtual iterator end() { return iterator(m_points.end(), this); } virtual const_iterator begin() const { return const_iterator(m_points.begin(), this); } virtual const_iterator end() const { return const_iterator(m_points.end(), this); } void push_back(const PlanePoint& point) { m_points.push_back(point); } private: std::vector<PlanePoint> m_points; }; // PointCloudPlane7510 //====================================================================== } // namespace ibeosdk //====================================================================== #endif // POINTCLOUDPLANE7510_HPP_SEEN //======================================================================
35.333333
181
0.548679
tomcamp0228
2490d796d308211a5a203296e845088c5207edd0
15,105
cpp
C++
c/wikipedia/wikipedia_tuple_map_impl.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
3
2016-05-31T07:23:27.000Z
2018-02-16T00:06:04.000Z
c/wikipedia/wikipedia_tuple_map_impl.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
2
2020-08-31T20:51:20.000Z
2021-03-30T18:05:25.000Z
c/wikipedia/wikipedia_tuple_map_impl.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
4
2015-01-17T07:31:25.000Z
2020-08-31T20:49:41.000Z
#include "wikipedia_tuple_map_impl.h" #include "benchmark.h" #include <sys/stat.h> #include "wikipedia_stopword_list.h" #include "string_utils.h" #include <valgrind/callgrind.h> WikipediaTupleMapImpl::WikipediaTupleMapImpl() { id_tuple_table_ = NULL; tuples_.set_deleted_key(NULL); } void WikipediaTupleMapImpl::load(const char* index_root) { stop_words_ = new WordList(__wikipedia_stopwords); cout << sizeof(canonical_tuple_t) << endl; load_pages(index_root); load_redirects(index_root); load_images(index_root); load_redirect_overrides(index_root); delete stop_words_; stop_words_ = NULL; } /* This method returns false if no existence, true on existence, and the * image_link pointer will point to the image_link if it exists */ canonical_tuple_t* WikipediaTupleMapImpl::tuple_exists(const char* tuple) const { TupleImageHash::const_iterator res; res = tuples_.find(tuple); if (res != tuples_.end()) { return res->second; } else { return NULL; } } /* * This method looks up a word in the tuple map and appends it to the list if * it exists. It assumes that the word start points to a null terminated * string. If you passt the canonical ngram check, then it will ensure that * the canonical is at least a bigram (this helps prevent against too many stop * word unigrams) */ inline bool WikipediaTupleMapImpl::append_tuple_if_exists(start_finish_str* word, TupleImageList& list, bool do_canonical_ngram_check) { TupleImageHash::const_iterator res; res = tuples_.find(word->start); //cout << "Searching for '" << word->start << "'" << endl; if (res != tuples_.end()) { word->found = true; canonical_tuple_t* result = res->second; alias_canonical_pair_t pair; pair.canonical = result; pair.alias = res->first; //cout << "Found:'" << result->tuple << "'" << endl; if (do_canonical_ngram_check) { bool more_than_one_word = false; int j = 0; while(result->tuple[j] != '\0') { if (result->tuple[j] == ' ') { more_than_one_word = true; break; } j++; } if (more_than_one_word) { //cout << "MATCH: '" << word->start << "' --> '" << result->tuple << "' Ambiguous:" << (bool) result->ambiguous << endl; list.push_back(pair); } } else { //cout << "MATCH: '" << word->start << "' --> '" << result->tuple << "' Ambiguous:" << (bool) result->ambiguous << endl; list.push_back(pair); } return true; } else { return false; } } /* * Some crazy NLP that can do a sliding window on a snippet looking for tuples * * Step 1. Convert sentence in start_finish_str* of words (this is for * performance reasons, so we don't need to create multiple strings) * * Step 2. Do sliding ngram windows (starting with 3 down to 2 down to 1), and * keep track of words that are part of ngrams that hit in the tuples_ hash * * Step 3. On the unigram window, only take a unigram if it is an alias of a * canonical URL that is longer than one word */ void WikipediaTupleMapImpl::tuples_from_snippet(const char* snippet, TupleImageList& list, bool want_full_if_multiple_capitalized) /* variable want_full_if_multiple_capitalized now actually just means want_exact_match_unless_starts_with_"anything"_etc. */ { int len = strlen(snippet); char* dup = (char*) malloc(sizeof(char) * len + 1); memcpy(dup,snippet,len + 1); cout << "Snippet: " << snippet << endl; char* front = dup; char* cur = dup; int word_count = 0; //int capitalized_word_count = 0; start_finish_str* words = 0; int i=0; // leading whitespace while(dup[i] == ' ') { i++; } cur += i; while(i <= len) { if (dup[i] == ' ' || dup[i] == '-' || dup[i] == ',' || dup[i] == ';' || dup[i] == '"') { words = (start_finish_str*) realloc(words,(word_count + 1) * sizeof(start_finish_str)); words[word_count].start = cur; /* if (*cur >= 65 && *cur <= 90) capitalized_word_count++; */ words[word_count].finish = front + i; words[word_count].found = false; word_count++; i++; while(dup[i] == ' ' || dup[i] == '-' || dup[i] == ',' || dup[i] == ';' || dup[i] == '"') { i++; } cur = front + i; } else if (dup[i] == '\0') { words = (start_finish_str*) realloc(words,(word_count + 1) * sizeof(start_finish_str)); words[word_count].start = cur; /* if (*cur >= 65 && *cur <= 90) capitalized_word_count++; */ words[word_count].finish = front + i; words[word_count].found = false; word_count++; } i++; } if (word_count < 9) { *words[word_count-1].finish = '\0'; if (append_tuple_if_exists(&words[0],list)) { free(words); free(dup); return; } } //if (want_full_if_multiple_capitalized && capitalized_word_count > 1) { if (want_full_if_multiple_capitalized && (strcmp("i like",snippet) && strcmp("I like",snippet) && strcmp("everything",snippet) && strcmp("Everything",snippet) && strcmp("anything",snippet) && strcmp("Anything",snippet))) { free(words); free(dup); return; } /* don't need this anymore because of above block if (word_count == 1) { *words[0].finish = '\0'; append_tuple_if_exists(&words[0],list); free(words); free(dup); return; } */ if (word_count == 2) { /* don't need this anymore either because of above block *words[1].finish = '\0'; bool bigram_found = append_tuple_if_exists(&words[0],list); if (!bigram_found) { */ *words[0].finish = '\0'; append_tuple_if_exists(&words[0],list,true); append_tuple_if_exists(&words[1],list,true); //} free(words); free(dup); return; } // Do quadgram sliding window for(int i=0; i < word_count - 3; i++) { char orig = *(words[i+3].finish); *(words[i+3].finish) = '\0'; bool quadgram_found = append_tuple_if_exists(&words[i],list); *(words[i+3].finish) = orig; if (quadgram_found) { words[i].found = true; words[i+1].found = true; words[i+2].found = true; words[i+3].found = true; i += 3; } } // Do trigram sliding window for(int i=0; i < word_count - 2; i++) { char orig = *(words[i+2].finish); *(words[i+2].finish) = '\0'; bool trigram_found = append_tuple_if_exists(&words[i],list); *(words[i+2].finish) = orig; if (trigram_found) { words[i].found = true; words[i+1].found = true; words[i+2].found = true; i += 2; } } // Do Bigram sliding window of pairs of unfound words in trigram window for(int i=0; i < word_count - 1; i++) { if (!words[i].found && !words[i+1].found) { char orig = *(words[i+1].finish); *(words[i+1].finish) = '\0'; bool bigram_found = append_tuple_if_exists(&words[i],list); *(words[i+1].finish) = orig; if (bigram_found) { words[i].found = true; words[i+1].found = true; i++; } } } // Do unigram window. Only take a unigram in this case if it maps to a // canonical tuple with more than one word. This is to prevent an overflow // of possible stop words for(int i=0; i < word_count; i++) { if (!words[i].found && (words[i].start[0]>=65 && words[i].start[0]<=90)) { char orig = *(words[i].finish); *(words[i].finish) = '\0'; append_tuple_if_exists(&words[i],list,true); *(words[i].finish) = orig; } } free(words); free(dup); } size_t WikipediaTupleMapImpl::size() { return tuples_.size(); } void WikipediaTupleMapImpl::clear() { for(TupleImageHash::iterator ii = tuples_.begin(), end = tuples_.end(); ii != end; ii++) { char* tuple = (char*) ii->first; canonical_tuple_t* canonical = (canonical_tuple_t*) ii->second; if (strcmp(tuple,canonical->tuple)) { tuples_.erase(ii); free(tuple); } } // Only canonicals should be left for(TupleImageHash::iterator ii = tuples_.begin(), end = tuples_.end(); ii != end; ii++) { char* tuple = (char*) ii->first; canonical_tuple_t* canonical = (canonical_tuple_t*) ii->second; free((char*) canonical->image_link); free(canonical); free(tuple); } } void WikipediaTupleMapImpl::map(void(* fn_ptr)(const char*, const canonical_tuple_t*)) { TupleImageHash::const_iterator end = tuples_.end(); for(TupleImageHash::const_iterator ii = tuples_.begin(); ii != end; ii++) { fn_ptr(ii->first,ii->second); } } /* Entry Point into the Library */ WikipediaTupleMap* WikipediaTupleMap::instance_ = NULL; WikipediaTupleMap* WikipediaTupleMap::instance() { if (!instance_) { instance_ = new WikipediaTupleMapImpl(); } return instance_; } /* Static Implementation */ void WikipediaTupleMapImpl::load_pages(const char* index_root) { bench_start("Load Pages"); FILE* file = NULL; char buffer[4096]; tuples_.resize(10000000); // optimization id_tuple_table_ = NULL; size_t biggest_id_so_far = 0; string index_filename = string(index_root) + ".pages"; int page_count = 0; if ((file = fopen((char*)index_filename.c_str(),"r"))) { while (fgets(buffer,4096,file)) { char* first = NULL; char* second = NULL; char* third = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '|') { buffer[i] = '\0'; first = buffer; second = buffer + i + 1; for(int j=i; j < length; j++) { if (buffer[j] == '|') { buffer[j] = '\0'; third = buffer + j + 1; buffer[length-1] = '\0'; break; } } if (!first || !second || !third) break; int id = atoi(first); int ambiguous = atoi(third); char* key = strdup(second); downcase(second); if (id > (int) biggest_id_so_far) { id_tuple_table_ = (canonical_tuple_t**) realloc(id_tuple_table_,sizeof(canonical_tuple_t*) * (id + 1)); for(int k = biggest_id_so_far + 1; k < id + 1; k++) { id_tuple_table_[k] = NULL; } biggest_id_so_far = id; } if (!stop_words_->match(second)) { canonical_tuple_t* pair = (canonical_tuple_t*) malloc(sizeof(canonical_tuple_t)); pair->tuple = key; pair->image_link = NULL; pair->ambiguous = (ambiguous == 1); tuples_[key] = pair; page_count++; id_tuple_table_[id] = pair; } else { //cout << "Skipping " << key << endl; free(key); } break; } } } fclose(file); } else { cout << "Page File Open Error" << endl; } bench_finish("Load Pages"); cout << "Loaded:" << page_count << " pages." << endl; } void WikipediaTupleMapImpl::load_redirects(const char* index_root) { CALLGRIND_START_INSTRUMENTATION; bench_start("Load Redirects"); string redirects_filename = string(index_root) + ".redirects"; char buffer[4096]; FILE* redirects_file = NULL; if ((redirects_file = fopen((char*)redirects_filename.c_str(),"r"))) { while (fgets(buffer,4096,redirects_file)) { char* first = NULL; char* second = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '>') { buffer[i] = '\0'; first = buffer; buffer[length-1] = '\0'; second = buffer + i + 1; if (!first || !second) break; int id = atoi(second); canonical_tuple_t* pair = id_tuple_table_[id]; if (pair) { char* key = strdup(first); downcase(first); if (!stop_words_->match(first)) { tuples_[key] = pair; } else { free(key); } } break; } } } fclose(redirects_file); } else { cout << "Redirects File Open Error" << endl; } bench_finish("Load Redirects"); CALLGRIND_STOP_INSTRUMENTATION; } void WikipediaTupleMapImpl::load_redirect_overrides(const char* index_root) { bench_start("Load Redirect Overrides"); string redirects_filename = string(index_root) + ".overrides"; char buffer[4096]; FILE* redirects_file = NULL; if ((redirects_file = fopen((char*)redirects_filename.c_str(),"r"))) { while (fgets(buffer,4096,redirects_file)) { char* first = NULL; char* second = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '>') { buffer[i] = '\0'; first = buffer; buffer[length-1] = '\0'; second = buffer + i + 1; if (!first || !second) break; TupleImageHash::const_iterator canonical_it = tuples_.find(second); if (canonical_it != tuples_.end()) { canonical_tuple_t* canon = canonical_it->second; // Now look for the redirect TupleImageHash::const_iterator redirect_it = tuples_.find(first); if (redirect_it != tuples_.end()) { const char* key = redirect_it->first; cout << "Redirecting Existing: " << key << " to " << canon->tuple << endl; tuples_[key] = canon; } else { char* new_key = strdup(first); cout << "Redirecting New: " << new_key << " to " << canon->tuple << endl; tuples_[new_key] = canon; } } break; } } } fclose(redirects_file); } else { cout << "Overrides File Open Error" << endl; } bench_finish("Load Redirect Overrides"); } void WikipediaTupleMapImpl::load_images(const char* index_root) { bench_start("Load Images"); FILE* file = NULL; char buffer[4096]; string raw_images_filename = string(index_root) + ".images"; string validated_images_filename = string(index_root) + ".images.validated"; string images_filename = ""; struct stat stats; if (!stat(validated_images_filename.c_str(),&stats)) { images_filename = validated_images_filename; } else { images_filename = raw_images_filename; } cout << "Loading: " << images_filename << endl; if ((file = fopen((char*)images_filename.c_str(),"r"))) { while (fgets(buffer,4096,file)) { char* first = NULL; char* second = NULL; int length = strlen(buffer); for(int i = 0; i < length; i++) { if (buffer[i] == '|') { buffer[i] = '\0'; first = buffer; second = buffer + i + 1; buffer[length-1] = '\0'; TupleImageHash::const_iterator res; res = tuples_.find(first); if (res != tuples_.end()) { char* image = strdup(second); canonical_tuple_t* canonical = res->second; canonical->image_link = image; } break; } } } } else { cout << "File Open Error" << endl; } bench_finish("Load Images"); }
29.792899
250
0.583052
mmonto7
24922cc39bb9c95ecb2e31239adbbb1ae3876c47
6,327
cpp
C++
tests/main.cpp
8infy/XILoader
7e82d917cddb3c66be76c614637cdb05dde4dddf
[ "Apache-2.0" ]
null
null
null
tests/main.cpp
8infy/XILoader
7e82d917cddb3c66be76c614637cdb05dde4dddf
[ "Apache-2.0" ]
null
null
null
tests/main.cpp
8infy/XILoader
7e82d917cddb3c66be76c614637cdb05dde4dddf
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <fstream> #include <XILoader/XILoader.h> // variables for stbi to write // image size data to static int x, y, z; static uint16_t passed = 0; static uint16_t failed = 0; #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define PATH_TO(image) XIL_TEST_PATH image #define AS_INT(x) static_cast<int32_t>(x) #define CONCAT_(x, y) x##y #define CONCAT(x, y) CONCAT_(x, y) #define UNIQUE_VAR(x) CONCAT(x, __LINE__) #define PRINT_TITLE(str) \ std::cout << "================================= " \ << str \ << " =================================" \ << std::endl #define PRINT_END(str) PRINT_TITLE(str) << std::endl #define ASSERT_LOADED(image) \ if (!image) \ std::cout << "Failed! --> Couldn't load the image" << std::endl #define LOAD_AND_COMPARE_EACH(subject, path_to_image) \ std::cout << subject "... "; \ auto UNIQUE_VAR(xil_image) = XILoader::load(path_to_image); \ auto UNIQUE_VAR(stbi_image) = stbi_load(path_to_image, &x, &y, &z, 0); \ ASSERT_LOADED(UNIQUE_VAR(xil_image)); \ compare_each(UNIQUE_VAR(xil_image).data(), UNIQUE_VAR(stbi_image), static_cast<size_t>(x)* y* z) #define LOAD_AND_COMPARE_EACH_FLIPPED(subject, path_to_image) \ std::cout << subject "... "; \ auto UNIQUE_VAR(xil_image) = XILoader::load(path_to_image, true); \ stbi_set_flip_vertically_on_load(true); \ auto UNIQUE_VAR(stbi_image) = stbi_load(path_to_image, &x, &y, &z, 0); \ stbi_set_flip_vertically_on_load(false); \ ASSERT_LOADED(UNIQUE_VAR(xil_image)); \ compare_each(UNIQUE_VAR(xil_image).data(), UNIQUE_VAR(stbi_image), static_cast<size_t>(x)* y* z) #define PRINT_TEST_RESULTS(passed_count, failed_count) \ std::cout << "\n\nTEST RESULTS: " \ << "passed: " << passed_count \ << " / failed: " \ << failed_count \ << " (" << passed_count \ << "/" << passed_count + failed_count \ << ")" << std::endl; void compare_each(uint8_t* l, uint8_t* r, size_t size) { if (size == 0) { failed++; return; } if (!l) { failed++; return; } for (size_t i = 0; i < size; i++) { if (!(l[i] == r[i])) { std::cout << "FAILED " << "At pixel[" << i << "]" << " --> "; std::cout << "left was == " << AS_INT(l[i]) << ", right was == " << AS_INT(r[i]) << std::endl; failed++; return; } } passed++; std::cout << "PASSED" << std::endl; } void TEST_BMP() { PRINT_TITLE("BMP LOADING TEST STARTS"); LOAD_AND_COMPARE_EACH("1bpp 8x8", PATH_TO("1bpp_8x8.bmp")); LOAD_AND_COMPARE_EACH("1bpp 9x9", PATH_TO("1bpp_9x9.bmp")); LOAD_AND_COMPARE_EACH("1bpp 260x401", PATH_TO("1bpp_260x401.bmp")); LOAD_AND_COMPARE_EACH("1bpp 1419x1001", PATH_TO("1bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("flipped 1bpp 260x401", PATH_TO("1bpp_260x401_flipped.bmp")); LOAD_AND_COMPARE_EACH_FLIPPED("forced flip 1bpp 260x401", PATH_TO("1bpp_260x401_flipped.bmp")); LOAD_AND_COMPARE_EACH("4bpp 1419x1001", PATH_TO("4bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("8bpp 1419x1001", PATH_TO("8bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("16bpp 1419x1001", PATH_TO("16bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("24bpp 1419x1001", PATH_TO("24bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("flipped 24bpp 1419x1001", PATH_TO("24bpp_1419x1001_flipped.bmp")); LOAD_AND_COMPARE_EACH_FLIPPED("forced flip 24bpp 1419x1001", PATH_TO("24bpp_1419x1001_flipped.bmp")); LOAD_AND_COMPARE_EACH("32bpp 1419x1001", PATH_TO("32bpp_1419x1001.bmp")); LOAD_AND_COMPARE_EACH("nomask 32bpp 1419x1001", PATH_TO("32bpp_1419x1001_nomask.bmp")); PRINT_END("BMP LOADING TEST DONE"); // Cannot currently run this due to a bug in stb_image // https://github.com/nothings/stb/issues/870 // LOAD_AND_COMPARE_EACH("16bpp 4x4", PATH_TO("16bpp_4x4.bmp")); } void TEST_PNG() { PRINT_TITLE("PNG LOADING TEST STARTS"); LOAD_AND_COMPARE_EACH("8bpc RGB 400x268", PATH_TO("8pbc_rgb_400x268.png")); LOAD_AND_COMPARE_EACH("8bpc RGB 1419x1001", PATH_TO("8bpc_rgb_1419x1001.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 4x4", PATH_TO("8bpc_rgba_4x4.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 1473x1854", PATH_TO("8bpc_rgba_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 2816x3088", PATH_TO("8pbc_rgba_2816x3088.png")); LOAD_AND_COMPARE_EACH("8bpc RGB 1419x1001 UNCOMPRESSED", PATH_TO("8bpc_rgb_uncompressed_1419x1001.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA 2816x3088 UNCOMPRESSED", PATH_TO("8bpc_rgba_uncompressed_2816x3088.png")); LOAD_AND_COMPARE_EACH_FLIPPED("8bpc RGBA 2816x3088 FLIPPED", PATH_TO("8pbc_rgba_2816x3088.png")); LOAD_AND_COMPARE_EACH_FLIPPED("8bpc RGB 1419x1001 FLIPPED", PATH_TO("8bpc_rgb_1419x1001.png")); LOAD_AND_COMPARE_EACH("16bpc RGB 1419x1001", PATH_TO("16bpc_rgb_1419x1001.png")); LOAD_AND_COMPARE_EACH("16bpc RGBA 1473x1854", PATH_TO("16bpc_rgba_1473x1854.png")); LOAD_AND_COMPARE_EACH("1bpc RGBA PALETTED 1473x1854", PATH_TO("1bpp_rgba_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("1bpc RGB PALETTED 1473x1854", PATH_TO("1bpp_rgb_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("4bpc RGBA PALETTED 1419x1001", PATH_TO("4bpp_rgba_paletted_1419x1001.png")); LOAD_AND_COMPARE_EACH("4bpc RGB PALETTED 1419x1001", PATH_TO("4bpp_rgb_paletted_1419x1001.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA GRAYSCALE 1473x1854", PATH_TO("8bpc_rgba_grayscale_1473x1854.png")); LOAD_AND_COMPARE_EACH("16bpc RGBA GRAYSCALE 1473x1854", PATH_TO("16bpc_rgba_grayscale_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGBA PALETTED 1473x1854", PATH_TO("8bpc_rgba_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGB PALETTED 1473x1854", PATH_TO("8bpc_rgb_paletted_1473x1854.png")); LOAD_AND_COMPARE_EACH("8bpc RGB GRAYSCALE 1473x1854", PATH_TO("8bpc_rgb_grayscale_1419x1001.png")); LOAD_AND_COMPARE_EACH("16bpc RGB GRAYSCALE 1473x1854", PATH_TO("16bpc_rgb_grayscale_1419x1001.png")); PRINT_END("PNG LOADING TEST DONE"); } int main(int argc, char** argv) { TEST_BMP(); TEST_PNG(); PRINT_TEST_RESULTS(passed, failed); return 0; }
41.900662
111
0.684369
8infy
2492eca9ffd00a5653d65c9c4069f1959fb829a5
761
cpp
C++
src/Maths.cpp
elvisoric/hmi
4e80f0bb0e4ac459bef2ddbc439faf895e1b60cb
[ "MIT" ]
17
2019-03-02T14:59:32.000Z
2022-03-10T15:08:36.000Z
src/Maths.cpp
elvisoric/hmi
4e80f0bb0e4ac459bef2ddbc439faf895e1b60cb
[ "MIT" ]
1
2019-07-02T06:01:35.000Z
2019-07-02T08:25:22.000Z
src/Maths.cpp
elvisoric/hmi
4e80f0bb0e4ac459bef2ddbc439faf895e1b60cb
[ "MIT" ]
2
2019-05-15T21:05:32.000Z
2021-04-26T03:09:24.000Z
#include <Maths.h> namespace nrg { glm::mat4 createTransformation(const glm::vec3& translation, float rx, float ry, float rz, float scale) { glm::mat4 transformation{1.0f}; transformation = glm::translate(transformation, translation); transformation = glm::rotate(transformation, glm::radians(rx), glm::vec3(1.0f, 0.0f, 0.0f)); transformation = glm::rotate(transformation, glm::radians(ry), glm::vec3(0.0f, 1.0f, 0.0f)); transformation = glm::rotate(transformation, glm::radians(rz), glm::vec3(0.0f, 0.0f, 1.0f)); transformation = glm::scale(transformation, glm::vec3{scale}); return transformation; } } // namespace nrg
42.277778
80
0.599212
elvisoric
24940cf3fc62959bcbdcce907c6a46ac52bdefd2
842
hpp
C++
engine/graphics/renderer/Camera.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
1
2021-03-01T13:17:49.000Z
2021-03-01T13:17:49.000Z
engine/graphics/renderer/Camera.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
null
null
null
engine/graphics/renderer/Camera.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
null
null
null
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_RENDERER_CAMERA_HPP #define OUZEL_GRAPHICS_RENDERER_CAMERA_HPP #include "Renderer.hpp" #include "../../math/Matrix.hpp" namespace ouzel::graphics::renderer { class Camera final { public: enum class ProjectionMode { custom, orthographic, perspective }; enum class ScaleMode { noScale, exactFit, noBorder, showAll }; Camera(Renderer& initRenderer): renderer{initRenderer}, resource{initRenderer} { } private: Renderer& renderer; Renderer::Resource resource; Matrix4F transform; }; } #endif // OUZEL_GRAPHICS_RENDERER_CAMERA_HPP
19.581395
61
0.579572
taida957789
24983831d385f0eadab472fa5d34e904d7e2c7d4
1,045
cc
C++
fuzzers/tint_spv_reader_fuzzer.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
fuzzers/tint_spv_reader_fuzzer.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
fuzzers/tint_spv_reader_fuzzer.cc
dorba/tint
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include "src/reader/spirv/parser.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { size_t sizeInU32 = size / sizeof(uint32_t); const uint32_t* u32Data = reinterpret_cast<const uint32_t*>(data); std::vector<uint32_t> input(u32Data, u32Data + sizeInU32); if (input.size() != 0) { tint::Context ctx; tint::reader::spirv::Parser parser(&ctx, input); parser.Parse(); } return 0; }
32.65625
75
0.719617
dorba
2498f10a871dbe916e582f9a6f96d443a526416f
3,000
cpp
C++
Base/PLCore/src/System/ConsoleAndroid.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLCore/src/System/ConsoleAndroid.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLCore/src/System/ConsoleAndroid.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: ConsoleAndroid.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <android/log.h> #include "PLCore/String/String.h" #include "PLCore/System/ConsoleAndroid.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace PLCore { //[-------------------------------------------------------] //[ Public virtual Console functions ] //[-------------------------------------------------------] void ConsoleAndroid::Print(const String &sString) const { // Write into the Android in-kernel log buffer (use Androids "logcat" utility to access this system log) const String sLogMessage = "[Console] " + sString; __android_log_write(ANDROID_LOG_INFO, "PixelLight", (sLogMessage.GetFormat() == String::ASCII) ? sLogMessage.GetASCII() : sLogMessage.GetUTF8()); // Do also do the normal console output ConsoleLinux::Print(sString); } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ ConsoleAndroid::ConsoleAndroid() { } /** * @brief * Destructor */ ConsoleAndroid::~ConsoleAndroid() { } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCore
38.961039
146
0.505
ktotheoz
24a6f4ca879d1e340a083669874c78ed923e19a7
3,888
hpp
C++
utils.hpp
Instand/algorithms
079ac867932e65e0936eab08b3176dc2d68bf684
[ "MIT" ]
2
2019-10-29T03:25:21.000Z
2019-10-30T12:03:50.000Z
utils.hpp
Instand/Algorithms
079ac867932e65e0936eab08b3176dc2d68bf684
[ "MIT" ]
null
null
null
utils.hpp
Instand/Algorithms
079ac867932e65e0936eab08b3176dc2d68bf684
[ "MIT" ]
null
null
null
#ifndef UTILS_HPP #define UTILS_HPP #include <iostream> #include <utility> #include <random> #include <string> #include <chrono> #include <memory> #define forever for(;;) #define unused(x) (void)(x) namespace cs { struct Initializer { Initializer() { std::srand(seed); } inline static unsigned seed = static_cast<unsigned>(std::chrono::steady_clock::now().time_since_epoch().count()); }; struct Generator { inline static Initializer initializer; static int generateRandomValue(int min, int max) { static std::default_random_engine engine(Initializer::seed); std::uniform_int_distribution<int> distribution(min, max); return distribution(engine); } template<typename T> static T generateRandomValue(T min, T max) { static std::default_random_engine engine(Initializer::seed); if constexpr (std::is_floating_point_v<T>) { std::uniform_real_distribution<T> distribution(min, max); return static_cast<T>(distribution(engine)); } std::uniform_int_distribution<T> distribution(min, max); return static_cast<T>(distribution(engine)); } template<typename T> static std::vector<T> generateCollection(T min, T max, size_t count) { std::vector<T> container; for (size_t i = 0; i < count; ++i) { container.push_back(Generator::generateRandomValue<T>(min, max)); } return container; } template<typename T> static std::pair<std::unique_ptr<T[]>, size_t> generateArray(T min, T max, size_t count) { std::unique_ptr<T[]> array(new T[count]); for (size_t i = 0; i < count; ++i) { array[i] = Generator::generateRandomValue<T>(min, max); } return std::make_pair(std::move(array), count); } }; namespace helper { template <typename T> struct is_pair : public std::false_type {}; template <typename T, typename K> struct is_pair<std::pair<T, K>> : public std::true_type {}; template <typename T> void print(const T& container, std::false_type) { for (const auto& element : container) { std::cout << element << " "; } std::cout << "[end]" << std::endl; } template <typename T> void print(const T& container, std::true_type) { for (const auto& [key, value] : container) { std::cout << "Key " << key << ", value " << value << std::endl; } std::cout << std::endl; } } class Console { public: template <typename... Args> static void writeLine(Args&&... args) { (std::cout << ... << args) << std::endl; } template <typename T> static void print(const T& container) { helper::print(container, helper::is_pair<typename T::value_type>()); } template <typename T> static void print(const std::string& message, const T& container) { std::cout << message << ", size: " << container.size() << ", values "; print(container); } template<typename T> static void print(std::shared_ptr<T> container) { cs::Console::print(*container.get()); } template <typename T> static void size(const T& container) { writeLine(typeid (T).name(), " size ", std::size(container)); } template <typename Iter> static void print(Iter begin, Iter end) { using ValueType = typename Iter::value_type; print(std::vector<ValueType>{begin, end}); } }; } #endif // UTILS_HPP
29.233083
121
0.551698
Instand
24a92d1969bfe14239b7da65421c720798b39331
2,813
cpp
C++
source/SoloFeature_redistributeReadsByCB.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,315
2015-01-07T02:03:15.000Z
2022-03-30T09:48:17.000Z
source/SoloFeature_redistributeReadsByCB.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,429
2015-01-08T00:09:17.000Z
2022-03-31T08:12:14.000Z
source/SoloFeature_redistributeReadsByCB.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
495
2015-01-23T20:00:45.000Z
2022-03-31T13:24:50.000Z
#include "SoloFeature.h" #include "streamFuns.h" //#include "TimeFunctions.h" //#include "SequenceFuns.h" //#include "Stats.h" //#include "GlobalVariables.h" void SoloFeature::redistributeReadsByCB() {//redistribute reads in files by CB - each file with the approximately the same number of reads, each CB is on one file only /* SoloFeature vars that have to be setup: * nCB * readFeatSum->cbReadCount[] */ //find boundaries for cells uint64 nReadRec=std::accumulate(readFeatSum->cbReadCount.begin(), readFeatSum->cbReadCount.end(), 0LLU); //for ( auto &cbrc : readFeatSum->cbReadCount ) // nReadRec += cbrc; uint64 nReadRecBin=nReadRec/pSolo.redistrReadsNfiles; P.inOut->logMain << " Redistributing reads into "<< pSolo.redistrReadsNfiles <<"files; nReadRec="<< nReadRec <<"; nReadRecBin="<< nReadRecBin <<endl; redistrFilesCBfirst.push_back(0); redistrFilesCBindex.resize(nCB); uint64 nreads=0; uint32 ind=0; for (uint32 icb=0; icb<nCB; icb++){ redistrFilesCBindex[icb]=ind; nreads += readFeatSum->cbReadCount[indCB[icb]]; if (nreads>=nReadRecBin) { ind++; redistrFilesCBfirst.push_back(icb+1); redistrFilesNreads.push_back(nreads); nreads=0; }; }; if (nreads>0) { redistrFilesCBfirst.push_back(nCB); redistrFilesNreads.push_back(nreads); }; //open output files redistrFilesStreams.resize(redistrFilesNreads.size()); for (uint32 ii=0; ii<redistrFilesNreads.size(); ii++) { //open file with flagDelete=true redistrFilesStreams[ii] = &fstrOpen(P.outFileTmp + "solo"+SoloFeatureTypes::Names[featureType]+"_redistr_"+std::to_string(ii), ERROR_OUT, P, true); }; //main cycle for (int ii=0; ii<P.runThreadN; ii++) { readFeatAll[ii]->streamReads->clear();//this is needed if eof was reached before readFeatAll[ii]->streamReads->seekg(0,ios::beg); while ( true ) { string line1; getline(*readFeatAll[ii]->streamReads,line1); if (line1.empty()) { break; }; istringstream line1stream(line1); uint64 cb1, umi; line1stream >> umi >> cb1 >> cb1; if (featureType==SoloFeatureTypes::SJ) line1stream >> cb1; line1stream >> cb1; *redistrFilesStreams[redistrFilesCBindex[indCBwl[cb1]]] << line1 <<'\n'; }; //TODO: delete streamReads files one by one to save disk space }; //close files //for (uint32 ii=0; ii<pSolo.redistrReadsNfiles; ii++) // redistrFilesStreams[ii]->flush(); };
34.728395
163
0.596872
Gavin-Lijy
24c33c40653321a4e4db478187c783c22e089f39
10,897
cpp
C++
src/comm.cpp
ckrisgarrett/C3D-2015
76b751e8c33aa048e0e19c5aec53780735fd2144
[ "MIT" ]
null
null
null
src/comm.cpp
ckrisgarrett/C3D-2015
76b751e8c33aa048e0e19c5aec53780735fd2144
[ "MIT" ]
null
null
null
src/comm.cpp
ckrisgarrett/C3D-2015
76b751e8c33aa048e0e19c5aec53780735fd2144
[ "MIT" ]
null
null
null
/* File: comm.cpp Author: Kris Garrett Date: September 6, 2013 */ #include "global.h" #include "utils.h" #include <string.h> #include <stdlib.h> #ifdef USE_MPI #include <mpi.h> /* Returns MPI communication sizes in bytes. */ static double getBoundarySizeX() { return (g_gY[3] - g_gY[0] + 1) * (g_gZ[3] - g_gZ[0] + 1) * NUM_GHOST_CELLS * g_numMoments * sizeof(double); } static double getBoundarySizeY() { return (g_gX[3] - g_gX[0] + 1) * (g_gZ[3] - g_gZ[0] + 1) * NUM_GHOST_CELLS * g_numMoments * sizeof(double); } static double getBoundarySizeZ() { return (g_gX[3] - g_gX[0] + 1) * (g_gY[3] - g_gY[0] + 1) * NUM_GHOST_CELLS * g_numMoments * sizeof(double); } /* Returns the boundaries inside the domain (ie not the ghost cells). */ static void getInnerBoundaries(char *xPos, char *xNeg, char *yPos, char *yNeg, char *zPos, char *zNeg) { int x1 = g_gX[1]; int x2 = g_gX[2] + 1 - NUM_GHOST_CELLS; int y1 = g_gY[1]; int y2 = g_gY[2] + 1 - NUM_GHOST_CELLS; int z1 = g_gZ[1]; int z2 = g_gZ[2] + 1 - NUM_GHOST_CELLS; int index; // x for(int i = 0; i < NUM_GHOST_CELLS; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&xPos[index * g_numMoments * sizeof(double)], &g_u[IU(x2+i,j,k,0)], g_numMoments * sizeof(double)); memcpy(&xNeg[index * g_numMoments * sizeof(double)], &g_u[IU(x1+i,j,k,0)], g_numMoments * sizeof(double)); }}} // y for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = 0; j < NUM_GHOST_CELLS; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * NUM_GHOST_CELLS); memcpy(&yPos[index * g_numMoments * sizeof(double)], &g_u[IU(i,y2+j,k,0)], g_numMoments * sizeof(double)); memcpy(&yNeg[index * g_numMoments * sizeof(double)], &g_u[IU(i,y1+j,k,0)], g_numMoments * sizeof(double)); }}} // z for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = 0; k < NUM_GHOST_CELLS; k++) { index = k + NUM_GHOST_CELLS * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&zPos[index * g_numMoments * sizeof(double)], &g_u[IU(i,j,z2+k,0)], g_numMoments * sizeof(double)); memcpy(&zNeg[index * g_numMoments * sizeof(double)], &g_u[IU(i,j,z1+k,0)], g_numMoments * sizeof(double)); }}} } /* Puts the input data into the ghost cells. */ static void setOuterBoundaries(char *xPos, char *xNeg, char *yPos, char *yNeg, char *zPos, char *zNeg) { int x1 = g_gX[0]; int x2 = g_gX[3] + 1 - NUM_GHOST_CELLS; int y1 = g_gY[0]; int y2 = g_gY[3] + 1 - NUM_GHOST_CELLS; int z1 = g_gZ[0]; int z2 = g_gZ[3] + 1 - NUM_GHOST_CELLS; int index; // x for(int i = 0; i < NUM_GHOST_CELLS; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&g_u[IU(x2+i,j,k,0)], &xPos[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); memcpy(&g_u[IU(x1+i,j,k,0)], &xNeg[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); }}} // y for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = 0; j < NUM_GHOST_CELLS; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { index = k + (g_gZ[2] - g_gZ[1] + 1) * (j + i * NUM_GHOST_CELLS); memcpy(&g_u[IU(i,y2+j,k,0)], &yPos[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); memcpy(&g_u[IU(i,y1+j,k,0)], &yNeg[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); }}} // z for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = 0; k < NUM_GHOST_CELLS; k++) { index = k + NUM_GHOST_CELLS * (j + i * (g_gY[2] - g_gY[1] + 1)); memcpy(&g_u[IU(i,j,z2+k,0)], &zPos[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); memcpy(&g_u[IU(i,j,z1+k,0)], &zNeg[index * g_numMoments * sizeof(double)], g_numMoments * sizeof(double)); }}} } /* Given the node for the x,y,z direction, returns the 1D index for the node. */ static int mpiIndex(char direction, int node) { int nodeX = g_nodeX; int nodeY = g_nodeY; int nodeZ = g_nodeZ; if(direction == 'x') nodeX = (node + g_mpix) % g_mpix; else if(direction == 'y') nodeY = (node + g_mpiy) % g_mpiy; else if(direction == 'z') nodeZ = (node + g_mpiz) % g_mpiz; else { printf("Direction MPI Error.\n"); utils_abort(); } return nodeZ + g_mpiz * (nodeY + g_mpiy * nodeX); } /* MPI version of communicateBoundaries. It implements periodic boundary conditions. */ void communicateBoundaries() { // Variables. int boundarySizeX = getBoundarySizeX(); int boundarySizeY = getBoundarySizeY(); int boundarySizeZ = getBoundarySizeZ(); int sendXPosTag = 1; int recvXNegTag = 1; int sendXNegTag = 2; int recvXPosTag = 2; int sendYPosTag = 3; int recvYNegTag = 3; int sendYNegTag = 4; int recvYPosTag = 4; int sendZPosTag = 5; int recvZNegTag = 5; int sendZNegTag = 6; int recvZPosTag = 6; MPI_Request mpiRequest[12]; int mpiError; // Variables to allocate only once. static bool firstTime = true; static char *sendXPos = NULL; static char *sendXNeg = NULL; static char *recvXPos = NULL; static char *recvXNeg = NULL; static char *sendYPos = NULL; static char *sendYNeg = NULL; static char *recvYPos = NULL; static char *recvYNeg = NULL; static char *sendZPos = NULL; static char *sendZNeg = NULL; static char *recvZPos = NULL; static char *recvZNeg = NULL; // First time initialization. if(firstTime) { firstTime = false; sendXPos = (char*)malloc(boundarySizeX); sendXNeg = (char*)malloc(boundarySizeX); recvXPos = (char*)malloc(boundarySizeX); recvXNeg = (char*)malloc(boundarySizeX); sendYPos = (char*)malloc(boundarySizeY); sendYNeg = (char*)malloc(boundarySizeY); recvYPos = (char*)malloc(boundarySizeY); recvYNeg = (char*)malloc(boundarySizeY); sendZPos = (char*)malloc(boundarySizeZ); sendZNeg = (char*)malloc(boundarySizeZ); recvZPos = (char*)malloc(boundarySizeZ); recvZNeg = (char*)malloc(boundarySizeZ); if(sendXPos == NULL || sendXNeg == NULL || recvXPos == NULL || recvXNeg == NULL || sendYPos == NULL || sendYNeg == NULL || recvYPos == NULL || recvYNeg == NULL || sendZPos == NULL || sendZNeg == NULL || recvZPos == NULL || recvZNeg == NULL) { printf("comm.cpp: Memory allocation failed.\n"); utils_abort(); } } // Get boundaries to send. getInnerBoundaries(sendXPos, sendXNeg, sendYPos, sendYNeg, sendZPos, sendZNeg); // Send MPI_Isend(sendXPos, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX + 1), sendXPosTag, MPI_COMM_WORLD, &mpiRequest[0]); MPI_Isend(sendXNeg, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX - 1), sendXNegTag, MPI_COMM_WORLD, &mpiRequest[1]); MPI_Isend(sendYPos, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY + 1), sendYPosTag, MPI_COMM_WORLD, &mpiRequest[2]); MPI_Isend(sendYNeg, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY - 1), sendYNegTag, MPI_COMM_WORLD, &mpiRequest[3]); MPI_Isend(sendZPos, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ + 1), sendZPosTag, MPI_COMM_WORLD, &mpiRequest[4]); MPI_Isend(sendZNeg, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ - 1), sendZNegTag, MPI_COMM_WORLD, &mpiRequest[5]); // Recv MPI_Irecv(recvXPos, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX + 1), recvXPosTag, MPI_COMM_WORLD, &mpiRequest[6]); MPI_Irecv(recvXNeg, boundarySizeX, MPI_CHAR, mpiIndex('x', g_nodeX - 1), recvXNegTag, MPI_COMM_WORLD, &mpiRequest[7]); MPI_Irecv(recvYPos, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY + 1), recvYPosTag, MPI_COMM_WORLD, &mpiRequest[8]); MPI_Irecv(recvYNeg, boundarySizeY, MPI_CHAR, mpiIndex('y', g_nodeY - 1), recvYNegTag, MPI_COMM_WORLD, &mpiRequest[9]); MPI_Irecv(recvZPos, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ + 1), recvZPosTag, MPI_COMM_WORLD, &mpiRequest[10]); MPI_Irecv(recvZNeg, boundarySizeZ, MPI_CHAR, mpiIndex('z', g_nodeZ - 1), recvZNegTag, MPI_COMM_WORLD, &mpiRequest[11]); // Wait for Send/Recv mpiError = MPI_Waitall(12, mpiRequest, MPI_STATUSES_IGNORE); if(mpiError != MPI_SUCCESS) { printf("comm.cpp: MPI Error %d.\n", mpiError); utils_abort(); } // Set ghost boundaries. setOuterBoundaries(recvXPos, recvXNeg, recvYPos, recvYNeg, recvZPos, recvZNeg); } #else /* Serial version of communicateBoundaries. It implements periodic boundary conditions. */ void communicateBoundaries() { int x0 = g_gX[0]; int x1 = g_gX[1]; int x2 = g_gX[2] + 1 - NUM_GHOST_CELLS; int x3 = g_gX[3] + 1 - NUM_GHOST_CELLS; int y0 = g_gY[0]; int y1 = g_gY[1]; int y2 = g_gY[2] + 1 - NUM_GHOST_CELLS; int y3 = g_gY[3] + 1 - NUM_GHOST_CELLS; int z0 = g_gZ[0]; int z1 = g_gZ[1]; int z2 = g_gZ[2] + 1 - NUM_GHOST_CELLS; int z3 = g_gZ[3] + 1 - NUM_GHOST_CELLS; // x for(int i = 0; i < NUM_GHOST_CELLS; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { for(int m = 0; m < g_numMoments; m++) { g_u[IU(x0+i,j,k,m)] = g_u[IU(x2+i,j,k,m)]; g_u[IU(x3+i,j,k,m)] = g_u[IU(x1+i,j,k,m)]; }}}} // y for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = 0; j < NUM_GHOST_CELLS; j++) { for(int k = g_gZ[1]; k <= g_gZ[2]; k++) { for(int m = 0; m < g_numMoments; m++) { g_u[IU(i,y0+j,k,m)] = g_u[IU(i,y2+j,k,m)]; g_u[IU(i,y3+j,k,m)] = g_u[IU(i,y1+j,k,m)]; }}}} // z for(int i = g_gX[1]; i <= g_gX[2]; i++) { for(int j = g_gY[1]; j <= g_gY[2]; j++) { for(int k = 0; k < NUM_GHOST_CELLS; k++) { for(int m = 0; m < g_numMoments; m++) { g_u[IU(i,j,z0+k,m)] = g_u[IU(i,j,z2+k,m)]; g_u[IU(i,j,z3+k,m)] = g_u[IU(i,j,z1+k,m)]; }}}} } #endif
33.42638
95
0.564834
ckrisgarrett
24c43e8624709e2201d2e79d6f1f08627e8678a3
439
cpp
C++
Kattis-Solutions/Backspace.cpp
SurgicalSteel/Competitive-Programming
3662b676de94796f717b25dc8d1b93c6851fb274
[ "MIT" ]
14
2016-02-11T09:26:13.000Z
2022-03-27T01:14:29.000Z
Kattis-Solutions/Backspace.cpp
SurgicalSteel/Competitive-Programming
3662b676de94796f717b25dc8d1b93c6851fb274
[ "MIT" ]
null
null
null
Kattis-Solutions/Backspace.cpp
SurgicalSteel/Competitive-Programming
3662b676de94796f717b25dc8d1b93c6851fb274
[ "MIT" ]
7
2016-10-25T19:29:35.000Z
2021-12-05T18:31:39.000Z
#include <bits/stdc++.h> using namespace std; #define psb push_back int main() { string s; cin>>s; if(s.length()==1){cout<<s<<"\n";} else { stack<string> ss; for(int i=0;i<s.length();++i) { if(s.substr(i,1)!="<"){ss.push(s.substr(i,1));} else{ss.pop();} } vector<string> vs; while(!ss.empty()) { vs.psb(ss.top()); ss.pop(); } for(int i=vs.size()-1;i>=0;--i){cout<<vs[i];} printf("\n"); } return 0; }
16.259259
50
0.530752
SurgicalSteel
24c45235ff20b5f80136dc02bf808429808375b4
5,663
cc
C++
tensorflow/core/grappler/costs/virtual_placer.cc
tianhm/tensorflow
e55574f28257bdacd744dcdba86c839e661b1b2a
[ "Apache-2.0" ]
47
2017-03-08T20:58:54.000Z
2021-06-24T07:07:49.000Z
tensorflow/core/grappler/costs/virtual_placer.cc
genSud/tensorflow
ec8216568d8cd9810004067558041c11a8356685
[ "Apache-2.0" ]
1
2019-07-11T16:29:54.000Z
2019-07-11T16:29:54.000Z
tensorflow/core/grappler/costs/virtual_placer.cc
genSud/tensorflow
ec8216568d8cd9810004067558041c11a8356685
[ "Apache-2.0" ]
19
2017-04-17T01:28:40.000Z
2020-08-15T13:01:33.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/costs/virtual_placer.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/grappler/clusters/cluster.h" #include "tensorflow/core/grappler/devices.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace grappler { VirtualPlacer::VirtualPlacer(const Cluster* cluster) { CHECK(cluster); devices_ = cluster->GetDevices(); if (devices_.empty()) { // If there are no devices in the cluster, add a single device, "UNKNOWN" to // the cluster. default_device_ = "UNKNOWN"; DeviceProperties& prop = devices_["UNKNOWN"]; prop.set_type("UNKNOWN"); } else if (devices_.size() == 1) { // If there is only one device in the cluster, use it as default device, // whatever it is. default_device_ = devices_.begin()->first; } else { // Default device is set from the devices in the cluster in the following // priority: /gpu:0, /cpu:0, or any device. // TODO(dyoon): This logic assumes single machine with CPU and GPU devices. // Make it more general to support multiple machines, job types, and devices // other than CPU and GPU. std::map<int, string> cpu_devices; // CPU device map: id -> device name. std::map<int, string> gpu_devices; // GPU device map: id -> device name. for (const auto& device : devices_) { DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(device.first, &parsed_name); if (parsed) { // Parsed devices are stored to cpu_devices or gpu_devices map, // addressed (and orderd) by device id. if (str_util::Lowercase(parsed_name.type) == "gpu") { gpu_devices[parsed_name.id] = device.first; } else if (str_util::Lowercase(parsed_name.type) == "cpu") { cpu_devices[parsed_name.id] = device.first; } } } if (!gpu_devices.empty()) { // GPU:0 (or GPU with smallest device id). default_device_ = gpu_devices.begin()->second; } else if (!cpu_devices.empty()) { // CPU:0 (or CPU with smallest device id). default_device_ = cpu_devices.begin()->second; } else { default_device_ = devices_.begin()->first; // Any device. } } // Default job name for canonical device name. default_job_name_ = "localhost"; // Scan the device names from the cluster, and if there is one job name used, // use it for canonical device name. std::unordered_set<string> job_names_from_cluster; for (const auto& device : devices_) { const auto& device_name = device.first; DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(device_name, &parsed_name); if (parsed && !parsed_name.job.empty()) { job_names_from_cluster.insert(parsed_name.job); } } // If there is only type of job name in all the devices in the cluster, use // that one as default job name; otherwise, use localhost. // TODO(dyoon): this should be improved, especially when the cluster is // composed of multiple worker, PS, and other types of jobs. if (job_names_from_cluster.size() == 1) { auto it = job_names_from_cluster.begin(); default_job_name_ = *it; } } const DeviceProperties& VirtualPlacer::get_device(const NodeDef& node) const { string device = get_canonical_device_name(node); VLOG(3) << "Device name: " << device; auto it = devices_.find(device); DCHECK(it != devices_.end()); return it->second; } string VirtualPlacer::get_canonical_device_name(const NodeDef& node) const { string device; if (!node.device().empty()) { if (devices_.find(node.device()) != devices_.end()) { return node.device(); } DeviceNameUtils::ParsedName parsed_name; bool parsed = DeviceNameUtils::ParseFullName(node.device(), &parsed_name); if (!parsed) { parsed = DeviceNameUtils::ParseLocalName(node.device(), &parsed_name); parsed_name.job = "localhost"; } if (!parsed) { if (node.device() == "GPU" || node.device() == "CPU" || node.device() == "gpu" || node.device() == "cpu") { parsed_name.job = "localhost"; parsed_name.type = node.device(); parsed = true; } } if (!parsed) { return get_default_device_name(); } else { if (parsed_name.job.empty()) { parsed_name.job = default_job_name_; } device = strings::StrCat( "/job:", parsed_name.job, "/replica:", parsed_name.replica, "/task:", parsed_name.task, "/", str_util::Lowercase(parsed_name.type), ":", parsed_name.id); } } else { return get_default_device_name(); } if (devices_.find(device) == devices_.end()) { return get_default_device_name(); } return device; } const string& VirtualPlacer::get_default_device_name() const { return default_device_; } } // end namespace grappler } // end namespace tensorflow
37.753333
80
0.666961
tianhm
24c72f6b20c435a4c35c6da2ddfdddbaeb5fc1a1
34,826
cpp
C++
cpp/nvgraph/cpp/tests/nvgraph_capi_tests_clustering.cpp
seunghwak/cugraph
f2f6f9147ce8c2f46b7b6dbc335f885c11b69004
[ "Apache-2.0" ]
16
2019-09-13T11:43:26.000Z
2022-03-02T10:11:59.000Z
cpp/nvgraph/cpp/tests/nvgraph_capi_tests_clustering.cpp
seunghwak/cugraph
f2f6f9147ce8c2f46b7b6dbc335f885c11b69004
[ "Apache-2.0" ]
5
2020-02-12T14:55:25.000Z
2021-12-06T17:55:12.000Z
cpp/nvgraph/cpp/tests/nvgraph_capi_tests_clustering.cpp
seunghwak/cugraph
f2f6f9147ce8c2f46b7b6dbc335f885c11b69004
[ "Apache-2.0" ]
6
2020-04-06T01:34:45.000Z
2021-01-21T17:13:24.000Z
#include <utility> #include "gtest/gtest.h" #include "nvgraph_test_common.h" #include "valued_csr_graph.hxx" #include "readMatrix.hxx" #include "nvgraphP.h" #include "nvgraph.h" #include "nvgraph_experimental.h" #include "stdlib.h" #include <algorithm> extern "C" { #include "mmio.h" } #include "mm.hxx" // do the perf measurements, enabled by command line parameter '--perf' static int PERF = 0; // minimum vertices in the graph to perform perf measurements #define PERF_ROWS_LIMIT 1000 // number of repeats = multiplier/num_vertices #define PARTITIONER_ITER_MULTIPLIER 1 #define SELECTOR_ITER_MULTIPLIER 1 // iterations for stress tests = this multiplier * iterations for perf tests static int STRESS_MULTIPLIER = 10; static std::string ref_data_prefix = ""; static std::string graph_data_prefix = ""; // utility template <typename T> struct nvgraph_Const; template <> struct nvgraph_Const<double> { static const cudaDataType_t Type = CUDA_R_64F; static const double inf; static const double tol; typedef union fpint { double f; unsigned long u; } fpint_st; }; const double nvgraph_Const<double>::inf = DBL_MAX; const double nvgraph_Const<double>::tol = 1e-6; // this is what we use as a tolerance in the algorithms, more precision than this is useless for CPU reference comparison template <> struct nvgraph_Const<float> { static const cudaDataType_t Type = CUDA_R_32F; static const float inf; static const float tol; typedef union fpint { float f; unsigned u; } fpint_st; }; const float nvgraph_Const<float>::inf = FLT_MAX; const float nvgraph_Const<float>::tol = 1e-4; template <typename T> bool enough_device_memory(int n, int nnz, size_t add) { size_t mtotal, mfree; cudaMemGetInfo(&mfree, &mtotal); if (mfree > add + sizeof(T)*3*(n + nnz)) return true; return false; } std::string convert_to_local_path(const std::string& in_file) { std::string wstr = in_file; if ((wstr != "dummy") & (wstr != "")) { std::string prefix; if (graph_data_prefix.length() > 0) { prefix = graph_data_prefix; } else { #ifdef _WIN32 //prefix = "C:\\mnt\\eris\\test\\matrices_collection\\"; prefix = "Z:\\matrices_collection\\"; std::replace(wstr.begin(), wstr.end(), '/', '\\'); #else prefix = "/mnt/nvgraph_test_data/"; #endif } wstr = prefix + wstr; } return wstr; } std::string convert_to_local_path_refdata(const std::string& in_file) { std::string wstr = in_file; if ((wstr != "dummy") & (wstr != "")) { std::string prefix; if (ref_data_prefix.length() > 0) { prefix = ref_data_prefix; } else { #ifdef _WIN32 //prefix = "C:\\mnt\\eris\\test\\ref_data\\"; prefix = "Z:\\ref_data\\"; std::replace(wstr.begin(), wstr.end(), '/', '\\'); #else prefix = "/mnt/nvgraph_test_data/ref_data/"; #endif } wstr = prefix + wstr; } return wstr; } /**************************** * SPECTRAL CLUSTERING *****************************/ typedef struct SpectralClustering_Usecase_t { std::string graph_file; int clusters; int eigenvalues; nvgraphSpectralClusteringType_t algorithm; nvgraphClusteringMetric_t metric; SpectralClustering_Usecase_t(const std::string& a, int b, int c, nvgraphSpectralClusteringType_t d, nvgraphClusteringMetric_t e) : clusters(b), eigenvalues(c), algorithm(d), metric(e){ graph_file = convert_to_local_path(a);}; SpectralClustering_Usecase_t& operator=(const SpectralClustering_Usecase_t& rhs) { graph_file = rhs.graph_file; clusters = rhs.clusters; eigenvalues = rhs.eigenvalues; algorithm = rhs.algorithm; metric = rhs.metric; return *this; } } SpectralClustering_Usecase; class NVGraphCAPITests_SpectralClustering : public ::testing::TestWithParam<SpectralClustering_Usecase> { public: NVGraphCAPITests_SpectralClustering() : handle(NULL) {} static void SetupTestCase() {} static void TearDownTestCase() {} virtual void SetUp() { if (handle == NULL) { status = nvgraphCreate(&handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } } virtual void TearDown() { if (handle != NULL) { status = nvgraphDestroy(handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); handle = NULL; } } nvgraphStatus_t status; nvgraphHandle_t handle; template <typename T> void run_current_test(const SpectralClustering_Usecase& param) { const ::testing::TestInfo* const test_info =::testing::UnitTest::GetInstance()->current_test_info(); std::stringstream ss; ss << param.clusters; ss << param.eigenvalues; ss << param.algorithm; ss << param.metric; std::string test_id = std::string(test_info->test_case_name()) + std::string(".") + std::string(test_info->name()) + std::string("_") + getFileName(param.graph_file) + std::string("_") + ss.str().c_str(); nvgraphStatus_t status; int m, n, nnz; MM_typecode mc; FILE* fpin = fopen(param.graph_file.c_str(),"r"); ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; ASSERT_EQ(mm_properties<int>(fpin, 1, &mc, &m, &n, &nnz),0) << "could not read Matrix Market file properties"<< "\n"; ASSERT_TRUE(mm_is_matrix(mc)); ASSERT_TRUE(mm_is_coordinate(mc)); ASSERT_TRUE(m==n); ASSERT_FALSE(mm_is_complex(mc)); ASSERT_FALSE(mm_is_skew(mc)); // Allocate memory on host std::vector<int> cooRowIndA(nnz); std::vector<int> csrColIndA(nnz); std::vector<int> csrRowPtrA(n+1); std::vector<T> csrValA(nnz); ASSERT_EQ( (mm_to_coo<int,T>(fpin, 1, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL)) , 0)<< "could not read matrix data"<< "\n"; ASSERT_EQ( (coo_to_csr<int,T> (n, n, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL, &csrRowPtrA[0], NULL, NULL, NULL)), 0) << "could not covert COO to CSR "<< "\n"; ASSERT_EQ(fclose(fpin),0); //ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; int *clustering_d; if (!enough_device_memory<T>(n, nnz, sizeof(int)*(csrRowPtrA.size() + csrColIndA.size()))) { std::cout << "[ WAIVED ] " << test_info->test_case_name() << "." << test_info->name() << std::endl; return; } cudaMalloc((void**)&clustering_d , n*sizeof(int)); nvgraphGraphDescr_t g1 = NULL; status = nvgraphCreateGraphDescr(handle, &g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); // set up graph nvgraphCSRTopology32I_st topology = {n, nnz, &csrRowPtrA[0], &csrColIndA[0]}; status = nvgraphSetGraphStructure(handle, g1, (void*)&topology, NVGRAPH_CSR_32); // set up graph data size_t numsets = 1; void* edgeptr[1] = {(void*)&csrValA[0]}; cudaDataType_t type_e[1] = {nvgraph_Const<T>::Type}; status = nvgraphAllocateEdgeData(handle, g1, numsets, type_e ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); status = nvgraphSetEdgeData(handle, g1, (void *)edgeptr[0], 0 ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); int weight_index = 0; struct SpectralClusteringParameter clustering_params; clustering_params.n_clusters = param.clusters; clustering_params.n_eig_vects = param.eigenvalues; clustering_params.algorithm = param.algorithm; clustering_params.evs_tolerance = 0.0f ; clustering_params.evs_max_iter = 0; clustering_params.kmean_tolerance = 0.0f; clustering_params.kmean_max_iter = 0; std::vector<int> random_assignments_h(n); std::vector<T> eigVals_h(param.eigenvalues); std::vector<T> eigVecs_h(n*param.eigenvalues); float score = 0.0, random_score = 0.0; if (PERF && n > PERF_ROWS_LIMIT) { double start, stop; start = second(); int repeat = std::max((int)((float)(PARTITIONER_ITER_MULTIPLIER)/n), 1); for (int i = 0; i < repeat; i++) status =nvgraphSpectralClustering(handle, g1, weight_index, &clustering_params, clustering_d, &eigVals_h[0], &eigVecs_h[0]); stop = second(); printf("&&&& PERF Time_%s %10.8f -ms\n", test_id.c_str(), 1000.0*(stop-start)/repeat); } else status =nvgraphSpectralClustering(handle, g1, weight_index, &clustering_params, clustering_d, &eigVals_h[0], &eigVecs_h[0]); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); // Analyse quality status = nvgraphAnalyzeClustering(handle, g1, weight_index, param.clusters, clustering_d, param.metric, &score); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); //printf("Score = %f\n", score); // === // Synthetic random for (int i=0; i<n; i++) { random_assignments_h[i] = rand() % param.clusters; //printf("%d ", random_assignments_h[i]); } status = nvgraphAnalyzeClustering(handle, g1, weight_index, param.clusters, &random_assignments_h[0], param.metric, &random_score); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); //printf("Random modularity = %f\n", modularity2); if (param.metric == NVGRAPH_MODULARITY) EXPECT_GE(score, random_score); // we want higher modularity else EXPECT_GE(random_score, score); //we want less edge cut cudaFree(clustering_d); status = nvgraphDestroyGraphDescr(handle, g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } }; TEST_P(NVGraphCAPITests_SpectralClustering, CheckResultDouble) { run_current_test<double>(GetParam()); } TEST_P(NVGraphCAPITests_SpectralClustering, CheckResultFloat) { run_current_test<float>(GetParam()); } // --gtest_filter=*ModularityCorrectness* INSTANTIATE_TEST_CASE_P(SpectralModularityCorrectnessCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/uk.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/uk.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 5, 5, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 3, 3,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 5, 5,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 7,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) ///// more instances ) ); // --gtest_filter=*ModularityCorner* INSTANTIATE_TEST_CASE_P(SpectralModularityCornerCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 4, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 17, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) // tests cases on coAuthorsDBLP may diverge on some cards (likely due to different normalization operation) //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 4,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 17, 7,NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) ///// more instances ) ); // --gtest_filter=*LanczosBlancedCutCorrectness* INSTANTIATE_TEST_CASE_P(SpectralLanczosBlancedCutCorrectnessCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 2, 2,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 4, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT) ///// more instances ) ); // --gtest_filter=*LanczosBlancedCutCorner* INSTANTIATE_TEST_CASE_P(SpectralLanczosBlancedCutCornerCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 17, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT) // tests cases on coAuthorsDBLP may diverge on some cards (likely due to different normalization operation) //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT), //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 17, 7,NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_EDGE_CUT) ) ); // --gtest_filter=*LobpcgBlancedCutCorrectness* INSTANTIATE_TEST_CASE_P(SpectralLobpcgBlancedCutCorrectnessCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 2, 2,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 4, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT) ///// more instances ) ); // --gtest_filter=*LobpcgBlancedCutCorner* INSTANTIATE_TEST_CASE_P(SpectralLobpcgBlancedCutCornerCheck, NVGraphCAPITests_SpectralClustering, // graph FILE number of clusters # number of eigenvalues # ::testing::Values( SpectralClustering_Usecase("dimacs10/delaunay_n10.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/uk.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/delaunay_n12.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/data.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/cti.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 4, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 17, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT) // tests cases on coAuthorsDBLP may diverge on some cards (likely due to different normalization operation) //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 4,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT), //SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 17, 7,NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_EDGE_CUT) ///// more instances ) ); //Followinf tests were commented becasue they are a bit redundent and quite long to run // previous tests already contain dataset with 1 million edges //// --gtest_filter=*ModularityLargeCorrectness* //INSTANTIATE_TEST_CASE_P(SpectralModularityLargeCorrectnessCheck, // NVGraphCAPITests_SpectralClustering, // // graph FILE number of clusters # number of eigenvalues # // ::testing::Values( // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 5, 5, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 2, 2, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 3, 3, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 5, 5, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 7, NVGRAPH_MODULARITY_MAXIMIZATION, NVGRAPH_MODULARITY) // ///// more instances // ) // ); // //// --gtest_filter=*LanczosBlancedCutLargeCorrectness* //INSTANTIATE_TEST_CASE_P(SpectralLanczosBlancedCutLargeCorrectnessCheck, // NVGraphCAPITests_SpectralClustering, // // graph FILE number of clusters # number of eigenvalues # // ::testing::Values( // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LANCZOS,NVGRAPH_RATIO_CUT) // ) // ); //// --gtest_filter=*LobpcgBlancedCutLargeCorrectness* //INSTANTIATE_TEST_CASE_P(SpectralLobpcgBlancedCutLargeCorrectnessCheck, // NVGraphCAPITests_SpectralClustering, // // graph FILE number of clusters # number of eigenvalues # // ::testing::Values( // //SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/citationCiteseer.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 2, 2, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 3, 3, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 5, 5, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT), // SpectralClustering_Usecase("dimacs10/coAuthorsDBLP.mtx", 7, 7, NVGRAPH_BALANCED_CUT_LOBPCG, NVGRAPH_RATIO_CUT) // ) // ); /**************************** * SELECTOR *****************************/ typedef struct Selector_Usecase_t { std::string graph_file; nvgraphEdgeWeightMatching_t metric; Selector_Usecase_t(const std::string& a, nvgraphEdgeWeightMatching_t b) : metric(b){ graph_file = convert_to_local_path(a);}; Selector_Usecase_t& operator=(const Selector_Usecase_t& rhs) { graph_file = rhs.graph_file; metric = rhs.metric; return *this; } }Selector_Usecase; class NVGraphCAPITests_Selector : public ::testing::TestWithParam<Selector_Usecase> { public: NVGraphCAPITests_Selector() : handle(NULL) {} static void SetupTestCase() {} static void TearDownTestCase() {} virtual void SetUp() { if (handle == NULL) { status = nvgraphCreate(&handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } } virtual void TearDown() { if (handle != NULL) { status = nvgraphDestroy(handle); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); handle = NULL; } } nvgraphStatus_t status; nvgraphHandle_t handle; template <typename T> void run_current_test(const Selector_Usecase& param) { const ::testing::TestInfo* const test_info =::testing::UnitTest::GetInstance()->current_test_info(); std::stringstream ss; ss << param.metric; std::string test_id = std::string(test_info->test_case_name()) + std::string(".") + std::string(test_info->name()) + std::string("_") + getFileName(param.graph_file)+ std::string("_") + ss.str().c_str(); nvgraphStatus_t status; int m, n, nnz; MM_typecode mc; FILE* fpin = fopen(param.graph_file.c_str(),"r"); ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; ASSERT_EQ(mm_properties<int>(fpin, 1, &mc, &m, &n, &nnz),0) << "could not read Matrix Market file properties"<< "\n"; ASSERT_TRUE(mm_is_matrix(mc)); ASSERT_TRUE(mm_is_coordinate(mc)); ASSERT_TRUE(m==n); ASSERT_FALSE(mm_is_complex(mc)); ASSERT_FALSE(mm_is_skew(mc)); // Allocate memory on host std::vector<int> cooRowIndA(nnz); std::vector<int> csrColIndA(nnz); std::vector<int> csrRowPtrA(n+1); std::vector<T> csrValA(nnz); ASSERT_EQ( (mm_to_coo<int,T>(fpin, 1, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL)) , 0)<< "could not read matrix data"<< "\n"; ASSERT_EQ( (coo_to_csr<int,T> (n, n, nnz, &cooRowIndA[0], &csrColIndA[0], &csrValA[0], NULL, &csrRowPtrA[0], NULL, NULL, NULL)), 0) << "could not covert COO to CSR "<< "\n"; ASSERT_EQ(fclose(fpin),0); //ASSERT_TRUE(fpin != NULL) << "Cannot read input graph file: " << param.graph_file << std::endl; if (!enough_device_memory<T>(n, nnz, sizeof(int)*(csrRowPtrA.size() + csrColIndA.size()))) { std::cout << "[ WAIVED ] " << test_info->test_case_name() << "." << test_info->name() << std::endl; return; } //int *aggregates_d; //cudaMalloc((void**)&aggregates_d , n*sizeof(int)); nvgraphGraphDescr_t g1 = NULL; status = nvgraphCreateGraphDescr(handle, &g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); // set up graph nvgraphCSRTopology32I_st topology = {n, nnz, &csrRowPtrA[0], &csrColIndA[0]}; status = nvgraphSetGraphStructure(handle, g1, (void*)&topology, NVGRAPH_CSR_32); // set up graph data size_t numsets = 1; //void* vertexptr[1] = {(void*)&calculated_res[0]}; //cudaDataType_t type_v[1] = {nvgraph_Const<T>::Type}; void* edgeptr[1] = {(void*)&csrValA[0]}; cudaDataType_t type_e[1] = {nvgraph_Const<T>::Type}; //status = nvgraphAllocateVertexData(handle, g1, numsets, type_v); //ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); //status = nvgraphSetVertexData(handle, g1, vertexptr[0], 0, NVGRAPH_CSR_32 ); //ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); status = nvgraphAllocateEdgeData(handle, g1, numsets, type_e ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); status = nvgraphSetEdgeData(handle, g1, (void *)edgeptr[0], 0 ); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); int weight_index = 0; std::vector<int> aggregates_h(n); //std::vector<int> aggregates_global_h(n); size_t num_aggregates; size_t *num_aggregates_ptr = &num_aggregates; status = nvgraphHeavyEdgeMatching(handle, g1, weight_index, param.metric, &aggregates_h[0], num_aggregates_ptr); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); std::cout << "n = " << n << ", num aggregates = " << num_aggregates << std::endl; if (param.metric == NVGRAPH_SCALED_BY_DIAGONAL) EXPECT_EQ(num_aggregates, static_cast<size_t>(166)); // comparing against amgx result on poisson2D.mtx else EXPECT_LE(num_aggregates, static_cast<size_t>(n)); // just make sure the output make sense //for (int i=0; i<n; i++) //{ // printf("%d\n", aggregates_h[i]); //} status = nvgraphDestroyGraphDescr(handle, g1); ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, status); } }; TEST_P(NVGraphCAPITests_Selector, CheckResultDouble) { run_current_test<double>(GetParam()); } TEST_P(NVGraphCAPITests_Selector, CheckResultFloat) { run_current_test<float>(GetParam()); } // --gtest_filter=*Correctness* INSTANTIATE_TEST_CASE_P(SmallCorrectnessCheck, NVGraphCAPITests_Selector, // graph FILE SIMILARITY_METRIC ::testing::Values( Selector_Usecase("Florida/poisson2D.mtx", NVGRAPH_SCALED_BY_DIAGONAL), Selector_Usecase("dimacs10/delaunay_n10.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/delaunay_n10.mtx", NVGRAPH_UNSCALED), Selector_Usecase("dimacs10/uk.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/uk.mtx", NVGRAPH_UNSCALED), Selector_Usecase("dimacs10/data.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/data.mtx", NVGRAPH_UNSCALED), Selector_Usecase("dimacs10/cti.mtx", NVGRAPH_SCALED_BY_ROW_SUM), Selector_Usecase("dimacs10/cti.mtx", NVGRAPH_UNSCALED) ///// more instances ) ); int main(int argc, char **argv) { srand(42); ::testing::InitGoogleTest(&argc, argv); for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "--perf") == 0) PERF = 1; if (strcmp(argv[i], "--stress-iters") == 0) STRESS_MULTIPLIER = atoi(argv[i+1]); if (strcmp(argv[i], "--ref-data-dir") == 0) ref_data_prefix = std::string(argv[i+1]); if (strcmp(argv[i], "--graph-data-dir") == 0) graph_data_prefix = std::string(argv[i+1]); } return RUN_ALL_TESTS(); return 0; }
53.088415
229
0.584822
seunghwak
24c934f081d9ad0d56c6c5ee51ae4f9c7033400e
1,596
hpp
C++
Sources/Audio/SoundBuffer.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Audio/SoundBuffer.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Audio/SoundBuffer.hpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
#pragma once #include "Maths/Vector3.hpp" #include "Resources/Resource.hpp" #include "Audio.hpp" namespace acid { /** * @brief Resource that represents a sound buffer. */ class ACID_EXPORT SoundBuffer : public Resource { public: /** * Creates a new sound buffer, or finds one with the same values. * @param metadata The metadata to decode values from. * @return The sound buffer with the requested values. */ static std::shared_ptr<SoundBuffer> Create(const Metadata &metadata); /** * Creates a new sound buffer, or finds one with the same values. * @param filename The file to load the sound buffer from. * @return The sound buffer with the requested values. */ static std::shared_ptr<SoundBuffer> Create(const std::string &filename); /** * Creates a new sound buffer. * @param filename The file to load the sound buffer from. * @param load If this resource will be loaded immediately, otherwise {@link SoundBuffer#Load} can be called later. */ explicit SoundBuffer(std::string filename, const bool &load = true); ~SoundBuffer(); void Load() override; const std::string &GetFilename() const { return m_filename; }; const uint32_t &GetBuffer() const { return m_buffer; } ACID_EXPORT friend const Metadata &operator>>(const Metadata &metadata, SoundBuffer &soundBuffer); ACID_EXPORT friend Metadata &operator<<(Metadata &metadata, const SoundBuffer &soundBuffer); private: static uint32_t LoadBufferWav(const std::string &filename); static uint32_t LoadBufferOgg(const std::string &filename); std::string m_filename; uint32_t m_buffer; }; }
27.517241
116
0.736842
liuping1997
24cb85e54cd50c9746b27788c67e923e9747c047
1,079
cpp
C++
Excelenta/Problema1.cpp
NegreanV/MyAlgorithms
7dd16d677d537d34280c3858ccf4cbea4b3ddf26
[ "Apache-2.0" ]
1
2015-10-24T10:02:06.000Z
2015-10-24T10:02:06.000Z
Excelenta/Problema1.cpp
NegreanV/MyAlgorithms
7dd16d677d537d34280c3858ccf4cbea4b3ddf26
[ "Apache-2.0" ]
null
null
null
Excelenta/Problema1.cpp
NegreanV/MyAlgorithms
7dd16d677d537d34280c3858ccf4cbea4b3ddf26
[ "Apache-2.0" ]
null
null
null
/*Se considera fisierul BAC.TXT ce contine un sir crescator cu cel mult un milion de numere naturale de cel mult noua cifre fiecare, separate prin câte un spatiu. Sa se scrie un program C/C++ care, folosind un algoritm eficient din punct de vedere al memoriei utilizate si al timpului de executare, citeste din fisier toti termenii sirului si afiseaza pe ecran, pe o singura linie, fiecare termen distinct al sirului urmat de numarul de aparitii ale acestuia în sir. Valorile afisate sunt separate prin câte un spatiu. Exemplu: daca fisierul BAC.TXT are urmatorul continut: 1 1 1 5 5 5 5 9 9 11 20 20 20 programul va afisa: 1 3 5 4 9 2 11 1 20 3 deoarece 1 apare de 3 ori, 5 apare de 4 ori,etc */ #include <fstream> using namespace std; int main() { ifstream f("input.in"); long x, y, n; f >> x; n = 1; while(f >> y) { if(x == y) { n++; } else { cout << x << " " << n << " "; n = 1; } x = y; } cout << x << " " << n; return 0; }
25.690476
86
0.599629
NegreanV
24d0626c3a47f6d399935c90b5edbf5dd7428df0
1,492
cc
C++
src/kernel.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
src/kernel.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
src/kernel.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
#include "kernel.h" cKernel::cKernel(int kernel_radius, double mu, double sigma) : kernel_radius(kernel_radius), mu(mu), sigma(sigma) { this->kernel = new double[this->kernel_radius * 2 + 1]; this->kernel_derivative = new double[this->kernel_radius * 2 + 1]; for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { this->kernel[_i + this->kernel_radius] = 1.0 / (this->sigma * sqrt(2.0 * M_PI)) * exp(-0.5 * pow((_i - this->mu) / this->sigma, 2.0)); this->kernel_derivative[_i + this->kernel_radius] = - (_i - mu) / (pow(this->sigma, 2.0) * sqrt(2.0 * M_PI)) * exp(-0.5 * pow((_i - this->mu) / this->sigma, 2.0)); } double sum0 = 0.0, sum1 = 0.0; for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { sum0 += this->kernel[_i + this->kernel_radius]; sum1 -= _i * this->kernel_derivative[_i + this->kernel_radius]; } for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { this->kernel[_i + this->kernel_radius] /= sum0; this->kernel_derivative[_i + this->kernel_radius] /= sum1; } sum0 = 0.0; sum1 = 0.0; for (int _i = -this->kernel_radius; _i <= this->kernel_radius; _i++) { sum0 += this->kernel[_i + this->kernel_radius]; sum1 -= _i * this->kernel_derivative[_i + this->kernel_radius]; } std::cout << "kernel summation: " << sum0 << std::endl; std::cout << "kernel derivative summation: " << sum1 << std::endl; } cKernel::~cKernel() { delete [] this->kernel; delete [] this->kernel_derivative; }
42.628571
165
0.632708
klantz81
24d4f10e103130563f1b3b21732b8fac57d35c50
8,027
cpp
C++
MIPS/mipsr3000/pi_control.cpp
lovisXII/RISC-V-project
8131f8b2cb2d476ebf80c71d727b1b3831fd6811
[ "MIT" ]
3
2022-02-07T02:15:14.000Z
2022-02-14T09:43:28.000Z
MIPS/mipsr3000/pi_control.cpp
lovisXII/RISC-V-project
8131f8b2cb2d476ebf80c71d727b1b3831fd6811
[ "MIT" ]
null
null
null
MIPS/mipsr3000/pi_control.cpp
lovisXII/RISC-V-project
8131f8b2cb2d476ebf80c71d727b1b3831fd6811
[ "MIT" ]
null
null
null
#include "pi_control.h" void pi_control::processPI_IREQ() { sc_uint<8> pi_ireq; pi_ireq[0]=PI_IREQ0.read(); pi_ireq[1]=PI_IREQ1.read(); pi_ireq[2]=PI_IREQ2.read(); pi_ireq[3]=PI_IREQ3.read(); pi_ireq[4]=PI_IREQ4.read(); pi_ireq[5]=PI_IREQ5.read(); pi_ireq[6]=PI_IREQ6.read(); pi_ireq[7]=PI_IREQ7.read(); PI_IREQ.write(pi_ireq); } void pi_control::processCK_SX() { CK_SX.write(CK.read()); } void pi_control::processREQUEST_SX() { REQUEST_SX.write(PI_IREQ.read()); } void pi_control::processCURPRIO_SX7() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX7.write(prior_rx[7] & (CURPRIO_SX6.read() | request_sx[7])); } void pi_control::processCURPRIO_SX6() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX6.write(prior_rx[6] & (CURPRIO_SX5.read() | request_sx[6])); } void pi_control::processCURPRIO_SX5() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX5.write(prior_rx[5] & (CURPRIO_SX4.read() | request_sx[5])); } void pi_control::processCURPRIO_SX4() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX4.write(prior_rx[4] & (CURPRIO_SX3.read() | request_sx[4])); } void pi_control::processCURPRIO_SX3() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX3.write(prior_rx[3] & (CURPRIO_SX2.read() | request_sx[3])); } void pi_control::processCURPRIO_SX2() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX2.write(prior_rx[2] & (CURPRIO_SX1.read() | request_sx[2])); } void pi_control::processCURPRIO_SX1() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX1.write(prior_rx[1] & (CURPRIO_SX0.read() | request_sx[1])); } void pi_control::processCURPRIO_SX0() { sc_uint<8> prior_rx=PRIOR_RX.read(); sc_uint<8> request_sx=REQUEST_SX.read(); CURPRIO_SX0.write(prior_rx[0] & (CURPRIO_SX7.read() | request_sx[0])); } void pi_control::processCURPRIO_SX() { sc_uint<8> curprio_sx=0x0; curprio_sx[0]=CURPRIO_SX0.read(); curprio_sx[1]=CURPRIO_SX1.read(); curprio_sx[2]=CURPRIO_SX2.read(); curprio_sx[3]=CURPRIO_SX3.read(); curprio_sx[4]=CURPRIO_SX4.read(); curprio_sx[5]=CURPRIO_SX5.read(); curprio_sx[6]=CURPRIO_SX6.read(); curprio_sx[7]=CURPRIO_SX7.read(); CURPRIO_SX.write(curprio_sx); } void pi_control::processGRANT_SX() { sc_uint<8> grant_sx; sc_uint<8> request_sx=REQUEST_SX.read(); sc_uint<8> curprio_sx=CURPRIO_SX.read(); grant_sx[7]=(request_sx[7] & (!curprio_sx[6])); grant_sx[6]=(request_sx[6] & (!curprio_sx[5])); grant_sx[5]=(request_sx[5] & (!curprio_sx[4])); grant_sx[4]=(request_sx[4] & (!curprio_sx[3])); grant_sx[3]=(request_sx[3] & (!curprio_sx[2])); grant_sx[2]=(request_sx[2] & (!curprio_sx[1])); grant_sx[1]=(request_sx[1] & (!curprio_sx[0])); grant_sx[0]=(request_sx[0] & (!curprio_sx[7])); GRANT_SX.write(grant_sx); } void pi_control::processDFLMSTR_SX() { sc_uint<8> dflmstr_sx=0x0; sc_uint<8> prior_rx=PRIOR_RX.read(); dflmstr_sx.range(7,1)=prior_rx.range(7,1) & (~prior_rx.range(6,0)); dflmstr_sx[0]=prior_rx[0] & (!prior_rx[7]); DFLMSTR_SX.write(dflmstr_sx); } void pi_control::processGLBRQST_SX() { GLBRQST_SX.write((REQUEST_SX.read()==0x0)?0:1); } void pi_control::processCMPDFLT_SX() { CMPDFLT_SX.write(DFLMSTR_SX.read() & REQUEST_SX.read()); } void pi_control::processDFLTRQS_SX() { DFLTRQS_SX.write((CMPDFLT_SX.read()==0x0)?0:1); } void pi_control::processSELECT_SX() { sc_uint<32> pi_a=PI_A.read(); sc_uint<32> pi_a_shft=pi_a << 2; if (pi_a_shft.range(31,12)==0x0) SELECT_SX.write(0x1); else if (pi_a_shft.range(31,12)==0x00400) SELECT_SX.write(0x2); else if (pi_a_shft.range(31,12)==0x80000) SELECT_SX.write(0x4); else if (pi_a_shft.range(31,12)==0xBFC00) SELECT_SX.write(0x8); else if (pi_a_shft.range(31,12)==0xC0000) SELECT_SX.write(0x10); else SELECT_SX.write(0x0); } void pi_control::processC_NXTS_SX() { if (RESET_RX.read()==1) C_NXTS_SX.write(c_idle); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==0)) C_NXTS_SX.write(c_idle); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==1) && (GLBRQST_SX.read() ==0)) C_NXTS_SX.write(c_idle); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==0)) C_NXTS_SX.write(c_fadr); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==1)&& (PI_LOCK.read() ==1)) C_NXTS_SX.write(c_fadr); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==1) && (GLBRQST_SX.read() ==1)) C_NXTS_SX.write(c_fadr); else if ((C_STAT_RX.read() == c_fadr) && (PI_LOCK.read() ==1)) C_NXTS_SX.write(c_nadr); else if ((C_STAT_RX.read() == c_nadr) && (PI_LOCK.read() ==1)) C_NXTS_SX.write(c_nadr); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==1)&& (PI_LOCK.read() ==0)) C_NXTS_SX.write(c_ldat); else if ((C_STAT_RX.read() == c_fadr) && (PI_LOCK.read() ==0)) C_NXTS_SX.write(c_ldat); else if ((C_STAT_RX.read() == c_nadr) && (PI_LOCK.read() ==0)) C_NXTS_SX.write(c_ldat); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==0)) C_NXTS_SX.write(c_ldat); else C_NXTS_SX.write(c_idle); } void pi_control::processWRTPRIO_SX() { if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1 )) WRTPRIO_SX.write(1); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read() ==1 )&& (GLBRQST_SX.read() ==1 )) WRTPRIO_SX.write(1); else WRTPRIO_SX.write(0); } void pi_control::processPI_TOUT() { PI_TOUT <= '0'; } void pi_control::processTRANRQS_SX() { if ((PI_OPC.read()==0x0) || (PI_OPC.read()==0x1)) TRANRQS_SX.write(0); else TRANRQS_SX.write(1); } void pi_control::processDATARDY_SX() { if ((PI_ACK.read() == ack_rdy) || (PI_ACK.read() == ack_rdm) | (PI_ACK.read() == ack_spl)) DATARDY_SX.write(1); else DATARDY_SX.write(0); } void pi_control::processPI_SEL() { if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read() ==1) && (DFLTRQS_SX.read() ==1)) PI_SEL.write(SELECT_SX.read()); else if ((C_STAT_RX.read() == c_fadr) && (TRANRQS_SX.read() ==1)) PI_SEL.write(SELECT_SX.read()); else if ((C_STAT_RX.read() == c_nadr) && (TRANRQS_SX.read() ==1) && (DATARDY_SX.read() ==1)) PI_SEL.write(SELECT_SX.read()); else PI_SEL.write(0x0); } void pi_control::processPI_GNT() { if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read()==0)) PI_GNT.write(DFLMSTR_SX.read()); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read()==1)&& (GLBRQST_SX.read()==0)) PI_GNT.write(DFLMSTR_SX.read()); else if ((C_STAT_RX.read() == c_idle) && (GLBRQST_SX.read()==1)&& (DFLTRQS_SX.read()==0)) PI_GNT.write(GRANT_SX.read()); else if ((C_STAT_RX.read() == c_ldat) && (DATARDY_SX.read()==1)&& (GLBRQST_SX.read()==1)) PI_GNT.write(GRANT_SX.read()); else PI_GNT.write(0x0); } void pi_control::processC_STAT_RX() { C_STAT_RX.write(C_NXTS_SX.read()); } void pi_control::processPRIOR_RX() { if (RESET_RX.read()==1) PRIOR_RX.write(0x7F); else if (WRTPRIO_SX.read()==1) PRIOR_RX.write(~GRANT_SX.read()); } void pi_control::processRESET_RX() { RESET_RX.write(!RESET_N.read()); } void pi_control::processGNTS() { sc_uint<8> pi_gnt=PI_GNT.read(); PI_GNT0.write(pi_gnt[0]); PI_GNT1.write(pi_gnt[1]); PI_GNT2.write(pi_gnt[2]); PI_GNT3.write(pi_gnt[3]); PI_GNT4.write(pi_gnt[4]); PI_GNT5.write(pi_gnt[5]); PI_GNT6.write(pi_gnt[6]); PI_GNT7.write(pi_gnt[7]); } void pi_control::processSELS() { sc_uint<8> pi_sel=PI_SEL.read(); PI_SEL0.write(pi_sel[0]); PI_SEL1.write(pi_sel[1]); PI_SEL2.write(pi_sel[2]); PI_SEL3.write(pi_sel[3]); PI_SEL4.write(pi_sel[4]); PI_SEL5.write(pi_sel[5]); PI_SEL6.write(pi_sel[6]); PI_SEL7.write(pi_sel[7]); }
26.57947
117
0.665753
lovisXII
24d7ef2cbedf3c0ca8bdb5bac2609f7477a868fc
13,032
cc
C++
ragel/flat.cc
podsvirov/colm-suite
9d45f0d47982d83141763a9728a4f97d6a06bacd
[ "MIT" ]
3
2018-08-18T16:37:49.000Z
2019-04-30T20:21:50.000Z
ragel/flat.cc
podsvirov/colm-suite
9d45f0d47982d83141763a9728a4f97d6a06bacd
[ "MIT" ]
null
null
null
ragel/flat.cc
podsvirov/colm-suite
9d45f0d47982d83141763a9728a4f97d6a06bacd
[ "MIT" ]
1
2017-08-31T05:45:14.000Z
2017-08-31T05:45:14.000Z
/* * Copyright 2004-2018 Adrian Thurston <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "ragel.h" #include "flat.h" #include "redfsm.h" #include "gendata.h" void Flat::genAnalysis() { redFsm->sortByStateId(); /* Choose default transitions and the single transition. */ redFsm->chooseDefaultSpan(); /* Do flat expand. */ redFsm->makeFlatClass(); /* If any errors have occured in the input file then don't write anything. */ if ( red->id->errorCount > 0 ) return; /* Anlayze Machine will find the final action reference counts, among other * things. We will use these in reporting the usage of fsm directives in * action code. */ red->analyzeMachine(); setKeyType(); /* Run the analysis pass over the table data. */ setTableState( TableArray::AnalyzePass ); tableDataPass(); /* Switch the tables over to the code gen mode. */ setTableState( TableArray::GeneratePass ); } void Flat::tableDataPass() { if ( type == Flat::Loop ) { if ( redFsm->anyActions() ) taActions(); } taKeys(); taCharClass(); taFlatIndexOffset(); taIndicies(); taIndexDefaults(); taTransCondSpaces(); if ( red->condSpaceList.length() > 0 ) taTransOffsets(); taCondTargs(); taCondActions(); taToStateActions(); taFromStateActions(); taEofConds(); taEofActions(); taEofTrans(); taNfaTargs(); taNfaOffsets(); taNfaPushActions(); taNfaPopTrans(); } void Flat::writeData() { if ( type == Flat::Loop ) { /* If there are any transtion functions then output the array. If there * are none, don't bother emitting an empty array that won't be used. */ if ( redFsm->anyActions() ) taActions(); } taKeys(); taCharClass(); taFlatIndexOffset(); taIndicies(); taIndexDefaults(); taTransCondSpaces(); if ( red->condSpaceList.length() > 0 ) taTransOffsets(); taCondTargs(); taCondActions(); if ( redFsm->anyToStateActions() ) taToStateActions(); if ( redFsm->anyFromStateActions() ) taFromStateActions(); taEofConds(); if ( redFsm->anyEofActions() ) taEofActions(); if ( redFsm->anyEofTrans() ) taEofTrans(); taNfaTargs(); taNfaOffsets(); taNfaPushActions(); taNfaPopTrans(); STATE_IDS(); } void Flat::setKeyType() { transKeys.setType( ALPH_TYPE(), alphType->size, alphType->isChar ); transKeys.isSigned = keyOps->isSigned; } void Flat::setTableState( TableArray::State state ) { for ( ArrayVector::Iter i = arrayVector; i.lte(); i++ ) { TableArray *tableArray = *i; tableArray->setState( state ); } } void Flat::taFlatIndexOffset() { flatIndexOffset.start(); int curIndOffset = 0; for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write the index offset. */ flatIndexOffset.value( curIndOffset ); /* Move the index offset ahead. */ if ( st->transList != 0 ) curIndOffset += ( st->high - st->low + 1 ); } flatIndexOffset.finish(); } void Flat::taCharClass() { charClass.start(); if ( redFsm->classMap != 0 ) { long long maxSpan = keyOps->span( redFsm->lowKey, redFsm->highKey ); for ( long long pos = 0; pos < maxSpan; pos++ ) charClass.value( redFsm->classMap[pos] ); } charClass.finish(); } void Flat::taToStateActions() { toStateActions.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write any eof action. */ TO_STATE_ACTION(st); } toStateActions.finish(); } void Flat::taFromStateActions() { fromStateActions.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write any eof action. */ FROM_STATE_ACTION( st ); } fromStateActions.finish(); } void Flat::taEofActions() { eofActions.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* Write any eof action. */ EOF_ACTION( st ); } eofActions.finish(); } void Flat::taEofConds() { /* * EOF Cond Spaces */ eofCondSpaces.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->outCondSpace != 0 ) eofCondSpaces.value( st->outCondSpace->condSpaceId ); else eofCondSpaces.value( -1 ); } eofCondSpaces.finish(); /* * EOF Cond Key Indixes */ eofCondKeyOffs.start(); int curOffset = 0; for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { long off = 0; if ( st->outCondSpace != 0 ) { off = curOffset; curOffset += st->outCondKeys.length(); } eofCondKeyOffs.value( off ); } eofCondKeyOffs.finish(); /* * EOF Cond Key Lengths. */ eofCondKeyLens.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { long len = 0; if ( st->outCondSpace != 0 ) len = st->outCondKeys.length(); eofCondKeyLens.value( len ); } eofCondKeyLens.finish(); /* * EOF Cond Keys */ eofCondKeys.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->outCondSpace != 0 ) { for ( int c = 0; c < st->outCondKeys.length(); c++ ) { CondKey key = st->outCondKeys[c]; eofCondKeys.value( key.getVal() ); } } } eofCondKeys.finish(); } void Flat::taEofTrans() { /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; long *transPos = new long[redFsm->transSet.length()]; for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; transPos[trans->id] = t; } eofTrans.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { long trans = 0; if ( st->eofTrans != 0 ) trans = transPos[st->eofTrans->id] + 1; eofTrans.value( trans ); } eofTrans.finish(); delete[] transPtrs; delete[] transPos; } void Flat::taKeys() { transKeys.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->transList ) { /* Emit just low key and high key. */ transKeys.value( st->low ); transKeys.value( st->high ); } else { /* Emit an impossible range so the driver fails the lookup. */ transKeys.value( 1 ); transKeys.value( 0 ); } } transKeys.finish(); } void Flat::taIndicies() { indicies.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->transList != 0 ) { long long span = st->high - st->low + 1; for ( long long pos = 0; pos < span; pos++ ) indicies.value( st->transList[pos]->id ); } } indicies.finish(); } void Flat::taIndexDefaults() { indexDefaults.start(); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { /* The state's default index goes next. */ if ( st->defTrans != 0 ) indexDefaults.value( st->defTrans->id ); else indexDefaults.value( 0 ); } indexDefaults.finish(); } void Flat::taTransCondSpaces() { transCondSpaces.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) { transPtrs[trans->id] = trans; } /* Keep a count of the num of items in the array written. */ for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; if ( trans->condSpace != 0 ) transCondSpaces.value( trans->condSpace->condSpaceId ); else transCondSpaces.value( -1 ); } delete[] transPtrs; transCondSpaces.finish(); } void Flat::taTransOffsets() { transOffsets.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; /* Keep a count of the num of items in the array written. */ int curOffset = 0; for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; transOffsets.value( curOffset ); curOffset += trans->condFullSize(); } delete[] transPtrs; transOffsets.finish(); } void Flat::taCondTargs() { condTargs.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; /* Keep a count of the num of items in the array written. */ for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; long fullSize = trans->condFullSize(); RedCondPair **fullPairs = new RedCondPair*[fullSize]; for ( long k = 0; k < fullSize; k++ ) fullPairs[k] = trans->errCond(); for ( int c = 0; c < trans->numConds(); c++ ) fullPairs[trans->outCondKey( c ).getVal()] = trans->outCond( c ); for ( int k = 0; k < fullSize; k++ ) { RedCondPair *cond = fullPairs[k]; condTargs.value( cond->targ->id ); } delete[] fullPairs; } delete[] transPtrs; condTargs.finish(); } void Flat::taCondActions() { condActions.start(); /* Transitions must be written ordered by their id. */ RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()]; for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ ) transPtrs[trans->id] = trans; /* Keep a count of the num of items in the array written. */ for ( int t = 0; t < redFsm->transSet.length(); t++ ) { /* Save the position. Needed for eofTargs. */ RedTransAp *trans = transPtrs[t]; long fullSize = trans->condFullSize(); RedCondPair **fullPairs = new RedCondPair*[fullSize]; for ( long k = 0; k < fullSize; k++ ) fullPairs[k] = trans->errCond(); for ( int c = 0; c < trans->numConds(); c++ ) fullPairs[trans->outCondKey( c ).getVal()] = trans->outCond( c ); for ( int k = 0; k < fullSize; k++ ) { RedCondPair *cond = fullPairs[k]; COND_ACTION( cond ); } delete[] fullPairs; } delete[] transPtrs; condActions.finish(); } /* Write out the array of actions. */ void Flat::taActions() { actions.start(); /* Add in the the empty actions array. */ actions.value( 0 ); for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) { /* Length first. */ actions.value( act->key.length() ); for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) actions.value( item->value->actionId ); } actions.finish(); } void Flat::taNfaTargs() { nfaTargs.start(); /* Offset of zero means no NFA targs, put a filler there. */ nfaTargs.value( 0 ); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs != 0 ) { nfaTargs.value( st->nfaTargs->length() ); for ( RedNfaTargs::Iter targ = *st->nfaTargs; targ.lte(); targ++ ) nfaTargs.value( targ->state->id ); } } nfaTargs.finish(); } /* These need to mirror nfa targs. */ void Flat::taNfaPushActions() { nfaPushActions.start(); nfaPushActions.value( 0 ); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs != 0 ) { nfaPushActions.value( 0 ); for ( RedNfaTargs::Iter targ = *st->nfaTargs; targ.lte(); targ++ ) NFA_PUSH_ACTION( targ ); } } nfaPushActions.finish(); } void Flat::taNfaPopTrans() { nfaPopTrans.start(); nfaPopTrans.value( 0 ); for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs != 0 ) { nfaPopTrans.value( 0 ); for ( RedNfaTargs::Iter targ = *st->nfaTargs; targ.lte(); targ++ ) NFA_POP_TEST( targ ); } } nfaPopTrans.finish(); } void Flat::taNfaOffsets() { nfaOffsets.start(); /* Offset of zero means no NFA targs, real targs start at 1. */ long offset = 1; for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) { if ( st->nfaTargs == 0 ) { nfaOffsets.value( 0 ); } else { nfaOffsets.value( offset ); offset += 1 + st->nfaTargs->length(); } } nfaOffsets.finish(); }
22.585789
81
0.651473
podsvirov
24dd44fbc951d9b8039b54dedd592133ae1e0dfc
1,221
hpp
C++
src/libs/asn1/include/keto/asn1/TimeHelper.hpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/libs/asn1/include/keto/asn1/TimeHelper.hpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/libs/asn1/include/keto/asn1/TimeHelper.hpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: TimeHelper.hpp * Author: ubuntu * * Created on January 31, 2018, 8:12 AM */ #ifndef TIMEHELPER_HPP #define TIMEHELPER_HPP #include "UTCTime.h" #include <chrono> namespace keto { namespace asn1 { class TimeHelper { public: TimeHelper(); TimeHelper(const UTCTime_t& time); TimeHelper(const TimeHelper& orig) = default; virtual ~TimeHelper(); TimeHelper& operator =(const UTCTime_t& time); TimeHelper& operator =(const UTCTime_t* time); /** * The internal memory is assumed to be owned by the last person in the row * and thus must be freed by that code. * * @return A utc time copy. */ operator UTCTime_t() const; TimeHelper& operator =(const std::time_t& time); operator std::time_t() const; TimeHelper& operator =(const std::chrono::system_clock::time_point& time); operator std::chrono::system_clock::time_point() const; private: std::chrono::system_clock::time_point time_point; }; } } #endif /* TIMEHELPER_HPP */
22.611111
79
0.674857
burntjam
24e7a91e3bd72cc1198516040aae5562d61e71e6
3,096
hpp
C++
include/more_concepts/base_concepts.hpp
MiSo1289/more_concepts
ee7949691e8d0024b818bc10f3157dcdeb4ed8af
[ "MIT" ]
45
2021-02-01T01:28:27.000Z
2022-03-29T23:48:46.000Z
include/more_concepts/base_concepts.hpp
MiSo1289/more_concepts
ee7949691e8d0024b818bc10f3157dcdeb4ed8af
[ "MIT" ]
1
2021-02-11T12:33:25.000Z
2021-02-11T16:33:05.000Z
include/more_concepts/base_concepts.hpp
MiSo1289/more_concepts
ee7949691e8d0024b818bc10f3157dcdeb4ed8af
[ "MIT" ]
3
2021-02-11T07:25:47.000Z
2021-08-15T16:55:11.000Z
#pragma once #include <concepts> #include <cstddef> #include <system_error> #include <type_traits> #include "more_concepts/detail/type_traits.hpp" namespace more_concepts { /// Types that are non-reference, non-c-array, non-function or function reference, /// non-const and non-volatile. /// /// Assigning an object of this type to an auto variable preserves the type. template <typename T> concept decayed = std::same_as<T, std::decay_t<T>>; /// Types that support aggregate initialization: /// https://en.cppreference.com/w/cpp/language/aggregate_initialization template <typename T> concept aggregate = std::is_aggregate_v<T>; /// Types which can be trivially constructed and destructed (as in without performing /// any (de)initialization at all), and can be trivially copied (as in copying is equivalent /// to calling memcpy). template <typename T> concept trivial = std::is_trivial_v<T>; /// Type is a scoped or unscoped enumeration (enum / enum class). template <typename T> concept enum_type = std::is_enum_v<T>; /// An enum type that represents an error, and can be used to construct a std::error_code /// object. template <typename T> concept error_code_enum = enum_type<T> and std::is_error_code_enum_v<T>; /// An enum type that represents an error, and can be used to construct a std::error_condition /// object. template <typename T> concept error_condition_enum = enum_type<T> and std::is_error_condition_enum_v<T>; /// Types that can be called with std::invoke using one or more function signatures. /// The return type of each signature is only checked for convertibility. template <typename Fn, typename... Signatures> concept invocable_as = requires(Signatures& ... signatures) { ([] <typename Ret, typename... Args>(auto(&)(Args...) -> Ret) requires std::is_invocable_r_v<Ret, Fn, Args> {}(signatures), ...); }; /// Types that can be called with the function call operator using one or more function /// signatures. The return type of each signature must match exactly. template <typename Fn, typename... Signatures> concept callable_as = requires(Signatures& ... signatures) { // Call operator checking is deferred to a type trait; // doing it inline breaks the compiler (GCC 10.2) ([] <typename Ret, typename... Args>(auto(&)(Args...) -> Ret) requires detail::is_callable_r_v<Ret, Fn, Args...> {}(signatures), ...); }; /// From https://en.cppreference.com/w/cpp/named_req/Hash: /// A Hash is a function object for which the output depends only on the input /// and has a very low probability of yielding the same output given different input values. /// /// Used to define the unordered_associative_container concept. template <typename Fn, typename KeyType> concept hash_function = callable_as< Fn const, auto(KeyType&) -> std::size_t, auto(KeyType const&) -> std::size_t>; }
38.7
98
0.674419
MiSo1289
24e811f79451435abe222df6e663d9e41fce8351
232
hpp
C++
book/cpp_templates/tmplbook/meta/pow3const.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/meta/pow3const.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/meta/pow3const.hpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
// primary template to compute 3 to the Nth template<int N> struct Pow3 { static int const value = 3 * Pow3<N-1>::value; }; // full specialization to end the recursion template<> struct Pow3<0> { static int const value = 1; };
19.333333
48
0.689655
houruixiang
00878d1828f82cbcc4f844db2ec01e3607c21e02
1,216
cpp
C++
plugins/mmstd_moldyn/src/io/MMSPDFrameData.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
plugins/mmstd_moldyn/src/io/MMSPDFrameData.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
plugins/mmstd_moldyn/src/io/MMSPDFrameData.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * MMSPDFrameData.cpp * * Copyright (C) 2011 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "io/MMSPDFrameData.h" using namespace megamol::stdplugin::moldyn::io; /****************************************************************************/ /* * MMSPDFrameData::Particles::Particles */ MMSPDFrameData::Particles::Particles(void) : count(0), data(), fieldMap(NULL) { // Intentionally empty } /* * MMSPDFrameData::Particles::~Particles */ MMSPDFrameData::Particles::~Particles(void) { delete[] this->fieldMap; this->fieldMap = NULL; } /* * MMSPDFrameData::Particles::operator== */ bool MMSPDFrameData::Particles::operator==(const MMSPDFrameData::Particles& rhs) { return (this->count == rhs.count) && (&this->data == &rhs.data) // sufficient && (this->fieldMap == rhs.fieldMap); // sufficient } /****************************************************************************/ /* * MMSPDFrameData::MMSPDFrameData */ MMSPDFrameData::MMSPDFrameData(void) : data(), idxRec() { // Intentionally empty } /* * MMSPDFrameData::~MMSPDFrameData */ MMSPDFrameData::~MMSPDFrameData(void) { // Intentionally empty }
20.610169
82
0.583882
azuki-monster
008c68739342faedec38079069043a21980ac6c4
527
hpp
C++
src/font.hpp
ceilors/fb-tetris
5496898443e35e37e374de2e97505a6027d38c30
[ "BSD-3-Clause" ]
null
null
null
src/font.hpp
ceilors/fb-tetris
5496898443e35e37e374de2e97505a6027d38c30
[ "BSD-3-Clause" ]
null
null
null
src/font.hpp
ceilors/fb-tetris
5496898443e35e37e374de2e97505a6027d38c30
[ "BSD-3-Clause" ]
null
null
null
#ifndef __FONT_HPP__ #define __FONT_HPP__ #include <sstream> #include <cstdint> #include <ft2build.h> #include FT_FREETYPE_H #include "framebuffer.hpp" #include "structs.hpp" class Font { FT_Library library; FT_Face face; FT_GlyphSlot slot; const uint16_t font_dpi = 100; uint16_t font_size = 0; public: Font(const char * filename, uint16_t size); ~Font(); void render(FrameBuffer & fb, Point pos, const char * text); void render(FrameBuffer & fb, Point pos, uint32_t value); }; #endif
19.518519
64
0.70019
ceilors
009a69572ae19d08e1621db09756870bd9d81657
2,617
cpp
C++
source/models.cpp
KJ002/Tetris
bf02931628c7b7bd78b4aa46fefca4d219786a65
[ "MIT" ]
null
null
null
source/models.cpp
KJ002/Tetris
bf02931628c7b7bd78b4aa46fefca4d219786a65
[ "MIT" ]
null
null
null
source/models.cpp
KJ002/Tetris
bf02931628c7b7bd78b4aa46fefca4d219786a65
[ "MIT" ]
null
null
null
#include "models.hpp" #include <array> #include <raylib.h> TetrisMeta::TetrisMeta(int x, int y, int shape){ shape = shape % 7; origin = (Vec2){(float)x, (float)y}; if (!shape){ map = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, }; rotationalOrigin = (Vec2){2.5, 1.5}; colour = BLUE; } if (shape == 1){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = DARKBLUE; } if (shape == 2){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = GOLD; } if (shape == 3){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1.5, 1.5}; colour = YELLOW; } if (shape == 4){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = LIME; } if (shape == 5){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = MAGENTA; } if (shape == 6){ map = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, }; rotationalOrigin = (Vec2){1, 1}; colour = RED; } } TetrisMeta::TetrisMeta(){ TetrisMeta(0, 0, 0); } int TetrisMeta::getX() const{ return origin.x; } int TetrisMeta::getY() const{ return origin.y; } Vec2 TetrisMeta::get() const{ return origin; } Rectangle TetrisMeta::getRec() const{ return (Rectangle){origin.x, origin.y, 10., 10.}; } void TetrisMeta::setX(const int x){ origin.x = (float)x; } void TetrisMeta::setY(const int y){ origin.y = (float)y; } void TetrisMeta::setX(const float x){ origin.x = x; } void TetrisMeta::setY(const float y){ origin.y = y; } void TetrisMeta::set(const Vec2 v){ origin = v; } int TetrisMeta::appendX(const int x){ origin.x += x; return origin.x; } int TetrisMeta::appendY(const int y){ origin.y += y; return origin.y; } float TetrisMeta::appendX(const float x){ origin.x += x; return origin.x; } float TetrisMeta::appendY(const float y){ origin.y += y; return origin.y; } Vec2 TetrisMeta::append(const Vec2 v){ origin = origin + v; return origin; }
15.485207
51
0.477264
KJ002
009fe56b1bf529a6710d1c8311e3e9668e6662b1
2,197
cpp
C++
samples/CoreAPI_SpriteRendering/SpriteRendering.cpp
odayibasi/swengine
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
[ "Zlib", "MIT" ]
3
2021-03-01T20:41:13.000Z
2021-07-10T13:45:47.000Z
samples/CoreAPI_SpriteRendering/SpriteRendering.cpp
odayibasi/swengine
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
[ "Zlib", "MIT" ]
null
null
null
samples/CoreAPI_SpriteRendering/SpriteRendering.cpp
odayibasi/swengine
ef07b7c9125d01596837a423a9f3dcbced1f5aa7
[ "Zlib", "MIT" ]
null
null
null
#include "../../include/SWEngine.h" #pragma comment (lib,"../../lib/SWUtil.lib") #pragma comment (lib,"../../lib/SWTypes.lib") #pragma comment (lib,"../../lib/SWCore.lib") #pragma comment (lib,"../../lib/SWGame.lib") #pragma comment (lib,"../../lib/SWGui.lib") #pragma comment (lib,"../../lib/SWEngine.lib") swApplication spriteRenderingApp; int spriteID; int spriteID2; int animatorID=-1; int animatorID2=-1; //Img1 Setting swRect target1={200,200,125,150}; swRect target2={400,200,125,150}; //------------------------------------------------------------------------------------------- void GameLoop(){ swGraphicsBeginScene(); //Background swGraphicsSetBgColor0(0.0f,0.0f,0.6f); //BlendingMode swGraphicsSetBlendingMode(SW_BLENDING_MODE_SOLID); //Draw Image int index=swAnimatorGetIndex(animatorID); swGraphicsSetColor0(1,1,1,1); swGraphicsRenderSprite0(spriteID,index,&target1); index=swAnimatorGetIndex(animatorID2); swGraphicsSetColor0(1,1,1,1); swGraphicsRenderSprite0(spriteID2,index,&target2); swGraphicsEndScene(); } //------------------------------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) { //Application Settings spriteRenderingApp.hInstance=hInstance; spriteRenderingApp.fullScreen=false; spriteRenderingApp.cursor=true; spriteRenderingApp.width=800; spriteRenderingApp.height=600; spriteRenderingApp.title="Sprite Rendering"; spriteRenderingApp.path="\\rsc\\SprRendering\\"; spriteRenderingApp.appRun=GameLoop; //Application Execution swEngineInit(&spriteRenderingApp); //Init My Application //spriteID=swGraphicsCreateSprite("XenRunning\\"); spriteID=swGraphicsCreateSprite("Smurfs\\"); animatorID=swAnimatorCreate(swGraphicsGetCountOfImgInSprite(spriteID),0.1); swAnimatorSetExecutionMode(animatorID, SW_ANIMATOR_EXEC_FORWARD_LOOP); spriteID2=swGraphicsCreateSprite("XenRunning\\"); animatorID2=swAnimatorCreate(swGraphicsGetCountOfImgInSprite(spriteID2),0.1); swAnimatorSetExecutionMode(animatorID2, SW_ANIMATOR_EXEC_FORWARD_LOOP); swEngineRun(); swEngineExit(); return 0; }
24.142857
93
0.699135
odayibasi
00a03f1b75847a8934df7a07051cddbc3a8427e8
7,303
hpp
C++
libraries/app/include/graphene/app/api_objects.hpp
dls-cipher/bitshares-core
feba0cf93f0e442ef5e39f58b469112033cd74d8
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api_objects.hpp
dls-cipher/bitshares-core
feba0cf93f0e442ef5e39f58b469112033cd74d8
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api_objects.hpp
dls-cipher/bitshares-core
feba0cf93f0e442ef5e39f58b469112033cd74d8
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The 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. */ #pragma once #include <graphene/chain/account_object.hpp> #include <graphene/chain/asset_object.hpp> #include <graphene/chain/vesting_balance_object.hpp> #include <graphene/chain/market_object.hpp> #include <graphene/chain/proposal_object.hpp> #include <graphene/chain/withdraw_permission_object.hpp> #include <graphene/chain/htlc_object.hpp> #include <graphene/api_helper_indexes/api_helper_indexes.hpp> #include <graphene/market_history/market_history_plugin.hpp> #include <fc/optional.hpp> namespace graphene { namespace app { using namespace graphene::chain; using namespace graphene::market_history; struct more_data { bool balances = false; bool vesting_balances = false; bool limit_orders = false; bool call_orders = false; bool settle_orders = false; bool proposals = false; bool assets = false; bool withdraws_from = false; bool withdraws_to = false; bool htlcs_from = false; bool htlcs_to = false; }; struct full_account { account_object account; account_statistics_object statistics; string registrar_name; string referrer_name; string lifetime_referrer_name; vector<variant> votes; optional<vesting_balance_object> cashback_balance; vector<account_balance_object> balances; vector<vesting_balance_object> vesting_balances; vector<limit_order_object> limit_orders; vector<call_order_object> call_orders; vector<force_settlement_object> settle_orders; vector<proposal_object> proposals; vector<asset_id_type> assets; vector<withdraw_permission_object> withdraws_from; vector<withdraw_permission_object> withdraws_to; vector<htlc_object> htlcs_from; vector<htlc_object> htlcs_to; more_data more_data_available; }; struct order { string price; string quote; string base; }; struct order_book { string base; string quote; vector< order > bids; vector< order > asks; }; struct market_ticker { time_point_sec time; string base; string quote; string latest; string lowest_ask; string lowest_ask_base_size; string lowest_ask_quote_size; string highest_bid; string highest_bid_base_size; string highest_bid_quote_size; string percent_change; string base_volume; string quote_volume; optional<object_id_type> mto_id; market_ticker() {} market_ticker(const market_ticker_object& mto, const fc::time_point_sec& now, const asset_object& asset_base, const asset_object& asset_quote, const order_book& orders); market_ticker(const fc::time_point_sec& now, const asset_object& asset_base, const asset_object& asset_quote); }; struct market_volume { time_point_sec time; string base; string quote; string base_volume; string quote_volume; }; struct market_trade { int64_t sequence = 0; fc::time_point_sec date; string price; string amount; string value; string type; account_id_type side1_account_id = GRAPHENE_NULL_ACCOUNT; account_id_type side2_account_id = GRAPHENE_NULL_ACCOUNT; }; struct extended_asset_object : asset_object { extended_asset_object() {} explicit extended_asset_object( const asset_object& a ) : asset_object( a ) {} explicit extended_asset_object( asset_object&& a ) : asset_object( std::move(a) ) {} optional<share_type> total_in_collateral; optional<share_type> total_backing_collateral; }; } } FC_REFLECT( graphene::app::more_data, (balances) (vesting_balances) (limit_orders) (call_orders) (settle_orders) (proposals) (assets) (withdraws_from) (withdraws_to) (htlcs_from) (htlcs_to) ) FC_REFLECT( graphene::app::full_account, (account) (statistics) (registrar_name) (referrer_name) (lifetime_referrer_name) (votes) (cashback_balance) (balances) (vesting_balances) (limit_orders) (call_orders) (settle_orders) (proposals) (assets) (withdraws_from) (withdraws_to) (htlcs_from) (htlcs_to) (more_data_available) ) FC_REFLECT( graphene::app::order, (price)(quote)(base) ); FC_REFLECT( graphene::app::order_book, (base)(quote)(bids)(asks) ); FC_REFLECT( graphene::app::market_ticker, (time)(base)(quote)(latest)(lowest_ask)(lowest_ask_base_size)(lowest_ask_quote_size) (highest_bid)(highest_bid_base_size)(highest_bid_quote_size)(percent_change)(base_volume)(quote_volume)(mto_id) ); FC_REFLECT( graphene::app::market_volume, (time)(base)(quote)(base_volume)(quote_volume) ); FC_REFLECT( graphene::app::market_trade, (sequence)(date)(price)(amount)(value)(type) (side1_account_id)(side2_account_id)); FC_REFLECT_DERIVED( graphene::app::extended_asset_object, (graphene::chain::asset_object), (total_in_collateral)(total_backing_collateral) );
37.071066
126
0.606189
dls-cipher
00a13c40be88a9e7bc31cc03d6355162f9d7a23e
3,175
cpp
C++
src/base/tkernel_utils.cpp
Unionfab/mayo
881b81b2b6febe6fb88967e4eef6ef22882e1734
[ "BSD-2-Clause" ]
382
2018-02-24T23:46:02.000Z
2022-03-31T16:08:24.000Z
src/base/tkernel_utils.cpp
Unionfab/mayo
881b81b2b6febe6fb88967e4eef6ef22882e1734
[ "BSD-2-Clause" ]
102
2017-05-18T09:36:26.000Z
2022-03-24T15:24:28.000Z
src/base/tkernel_utils.cpp
Unionfab/mayo
881b81b2b6febe6fb88967e4eef6ef22882e1734
[ "BSD-2-Clause" ]
124
2017-10-22T23:40:13.000Z
2022-03-28T08:57:23.000Z
/**************************************************************************** ** Copyright (c) 2021, Fougue Ltd. <http://www.fougue.pro> ** All rights reserved. ** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt ****************************************************************************/ #include "tkernel_utils.h" #include <Message_ProgressIndicator.hxx> #include <cmath> namespace Mayo { TKernelUtils::ReturnType_StartProgressIndicator TKernelUtils::start(const opencascade::handle<Message_ProgressIndicator>& progress) { #if OCC_VERSION_HEX >= OCC_VERSION_CHECK(7, 5, 0) return Message_ProgressIndicator::Start(progress); #else return progress; #endif } std::string TKernelUtils::colorToHex(const Quantity_Color& color) { //#if OCC_VERSION_HEX >= 0x070400 // constexpr bool hashPrefix = true; // return to_QString(Quantity_Color::ColorToHex(this->value(), hashPrefix)); //#endif // Converts a decimal digit to hexadecimal character auto fnHexDigit = [](uint8_t v) { if (v < 10) return '0' + v; else return 'A' + (v - 10); }; // Adds to 'str' the hexadecimal representation of 'v' belonging to [0, 255] auto fnAddHexColorComponent = [&](std::string& str, double v) { double iv = 0.; // Integral part of 'v' const double fv = std::modf(v / 16., &iv); // Fractional part of 'v' const auto a1 = uint8_t(iv); const auto a0 = uint8_t(fv * 16); str += fnHexDigit(a1); str += fnHexDigit(a0); }; std::string strHex; strHex += '#'; fnAddHexColorComponent(strHex, color.Red() * 255); fnAddHexColorComponent(strHex, color.Green() * 255); fnAddHexColorComponent(strHex, color.Blue() * 255); return strHex; } bool TKernelUtils::colorFromHex(std::string_view strHex, Quantity_Color* color) { //#if OCC_VERSION_HEX >= 0x070400 // Quantity_Color color; // return Quantity_Color::ColorFromHex(strHexHex.c_str(), color); //#else if (!color) return true; if (strHex.empty()) return false; if (strHex.at(0) != '#') return false; if (strHex.size() != 7) return false; // Converts an hexadecimal digit to decimal digit auto fnFromHex = [](char c) { if (c >= '0' && c <= '9') return int(c - '0'); else if (c >= 'A' && c <= 'F') return int(c - 'A' + 10); else if (c >= 'a' && c <= 'f') return int(c - 'a' + 10); else return -1; }; // Decodes a string containing an hexadecimal number to a decimal number auto fnHex2Int = [&](std::string_view str) { int result = 0; for (char c : str) { result = result * 16; const int h = fnFromHex(c); if (h < 0) return -1; result += h; } return result; }; const int r = fnHex2Int(strHex.substr(1, 2)); const int g = fnHex2Int(strHex.substr(3, 2)); const int b = fnHex2Int(strHex.substr(5, 2)); color->SetValues(r / 255., g / 255., b / 255., Quantity_TOC_RGB); return true; } } // namespace Mayo
28.603604
83
0.562835
Unionfab
00a2800fbe8a64fd882eba54a45718b91645985b
827
cpp
C++
Smooth_Game/Source/Component.cpp
Glitch0011/DirectX11-Demo
02b2ff51f4c936696ab25fb34da77cb4997980a9
[ "MIT" ]
null
null
null
Smooth_Game/Source/Component.cpp
Glitch0011/DirectX11-Demo
02b2ff51f4c936696ab25fb34da77cb4997980a9
[ "MIT" ]
null
null
null
Smooth_Game/Source/Component.cpp
Glitch0011/DirectX11-Demo
02b2ff51f4c936696ab25fb34da77cb4997980a9
[ "MIT" ]
null
null
null
#include <Component.h> #include <GameObject.h> using namespace std; using namespace SmoothGame; HRESULT Component::Send(MessageName name, Params param) { return this->GameObject->Send(name, param); } HRESULT Component::RecieveMessage(MessageName functionName, Params parameters) { if (this->functions.size() > 0) { for (auto functionDeclaration : this->functions) { if (functionDeclaration.first == functionName) { return functionDeclaration.second(parameters); } } } return E_NOTIMPL; } HRESULT Component::DelayedSend(MessageName funtionName, Params parameters) { return this->GameObject->DelayedSend(funtionName, parameters); } HRESULT Component::SendAsync(MessageName name, Params param, function<void(HRESULT, Params)> callback) { return this->GameObject->SendAsync(name, param, callback); }
22.972222
102
0.754534
Glitch0011
00a4b6e7228139c55153d0688a42e282e3a86328
1,641
cpp
C++
Source/CoreExtensions/Private/Math/Triangle2D.cpp
TheEmidee/UECoreExtensions
3068a8655509b7ff3d8f3e2fedf345618fdb37a2
[ "MIT" ]
2
2021-08-13T17:45:45.000Z
2021-10-06T14:42:52.000Z
Source/CoreExtensions/Private/Math/Triangle2D.cpp
TheEmidee/UE4CoreExtensions
e904c600d125d2fff737f8e54ea93145c964484d
[ "MIT" ]
1
2022-03-04T13:20:29.000Z
2022-03-04T13:20:29.000Z
Source/CoreExtensions/Private/Math/Triangle2D.cpp
TheEmidee/UECoreExtensions
3068a8655509b7ff3d8f3e2fedf345618fdb37a2
[ "MIT" ]
null
null
null
#include "Math/Triangle2D.h" FTriangle2D::FTriangle2D( const FVector2D & v1, const FVector2D & v2, const FVector2D & v3 ) : PointA( v1 ), PointB( v2 ), PointC( v3 ) {} bool FTriangle2D::ContainsVertex( const FVector2D & v ) const { return PointA.Equals( v ) || PointB.Equals( v ) || PointC.Equals( v ); } // From: https://githuPointB.com/Bl4ckb0ne/delaunay-triangulation bool FTriangle2D::CircumCircleContains( const FVector2D & v ) const { const auto ab = PointA.SizeSquared(); const auto cd = PointB.SizeSquared(); const auto ef = PointC.SizeSquared(); const auto ax = PointA.X; const auto ay = PointA.Y; const auto bx = PointB.X; const auto by = PointB.Y; const auto cx = PointC.X; const auto cy = PointC.Y; const auto circum_x = ( ab * ( cy - by ) + cd * ( ay - cy ) + ef * ( by - ay ) ) / ( ax * ( cy - by ) + bx * ( ay - cy ) + cx * ( by - ay ) ); const auto circum_y = ( ab * ( cx - bx ) + cd * ( ax - cx ) + ef * ( bx - ax ) ) / ( ay * ( cx - bx ) + by * ( ax - cx ) + cy * ( bx - ax ) ); const FVector2D circum( 0.5f * circum_x, 0.5f * circum_y ); const auto circum_radius = FVector2D::DistSquared( PointA, circum ); const auto dist = FVector2D::DistSquared( v, circum ); return dist <= circum_radius; } bool FTriangle2D::operator==( const FTriangle2D & t ) const { return ( PointA == t.PointA || PointA == t.PointB || PointA == t.PointC ) && ( PointB == t.PointA || PointB == t.PointB || PointB == t.PointC ) && ( PointC == t.PointA || PointC == t.PointB || PointC == t.PointC ); }
39.071429
147
0.57465
TheEmidee
00a4f998bf537d09a9fa7d120e7b6d1ff70c23c6
2,635
hpp
C++
lib/util/bitmask.hpp
sparkml/mastermind-strategy
22763672c413c6a73e2c036a9f522b65a0025b68
[ "MIT" ]
null
null
null
lib/util/bitmask.hpp
sparkml/mastermind-strategy
22763672c413c6a73e2c036a9f522b65a0025b68
[ "MIT" ]
null
null
null
lib/util/bitmask.hpp
sparkml/mastermind-strategy
22763672c413c6a73e2c036a9f522b65a0025b68
[ "MIT" ]
null
null
null
/// @defgroup BitMask Bit-Mask of fixed size /// @ingroup util #ifndef UTILITIES_BITMASK_HPP #define UTILITIES_BITMASK_HPP #include <cassert> #include "intrinsic.hpp" namespace util { /** * Represents a bitmask of fixed size. * This class serves as a simpler and faster alternative to * <code>std::bitset<N></code>. * @ingroup BitMask */ template <class T, size_t Bits> class bitmask { public: static_assert(Bits <= sizeof(T)*8, "The storage type does not have enough bits."); typedef T value_type; private: value_type _value; public: /// Creates an empty bitmask. bitmask() : _value(0) { } /// Creates a bitmask using the supplied mask. explicit bitmask(value_type value) : _value(value) { } /// Gets the internal value of the mask. value_type value() const { return _value; } /// Tests a given bit. bool operator [] (size_t bit) const { assert(bit <= Bits); return (_value & ((value_type)1 << bit)) != 0; } /// Resets a given bit to zero. void reset(int bit) { assert(bit >= 0 && bit <= (int)Bits); _value &= ~((value_type)1 << bit); } /// Resets the bits corresponding to the set bits in the given mask. void reset(const bitmask<T,Bits> &m) { _value &= ~ m.value(); } /// Resets all bits to zero. void reset() { _value = 0; } /// Returns @c true if all bits are reset. bool empty() const { return _value == 0; } /// Tests whether the bitmask is empty. bool operator ! () const { return _value == 0; } /// Returns @c true if there is exactly one bit set. bool unique() const { return _value && (_value & (_value - 1)) == 0; } /// Returns @c true if there are no more than one bit set. bool empty_or_unique() const { return (_value & (_value - 1)) == T(0); } /// Returns the index of the least significant bit set. /// If no bit is set, returns @c -1. int smallest() const { return _value == 0 ? -1 : util::intrinsic::bit_scan_forward(_value); } #if 0 int count() const { int n = 0; for (int i = 0; i < MM_MAX_COLORS; ++i) { if (value & (1 << i)) ++n; } return n; } void set_count(int count) { assert(count >= 0 && count <= MM_MAX_COLORS); value = (1 << count) - 1; } #endif /// Returns a bitmask with the least significant @c count bits set. static bitmask<T,Bits> fill(size_t count) { assert(count >= 0 && count <= Bits); return bitmask<T,Bits>(((value_type)1 << count) - 1); } }; template <class T, size_t Bits> inline bitmask<T,Bits> operator & ( const bitmask<T,Bits> &x, const bitmask<T,Bits> &y) { return bitmask<T,Bits>(x.value() & y.value()); } } // namespace util #endif // UTILITIES_BITMASK_HPP
20.585938
83
0.639848
sparkml
00a5389a8939ec667314c40addf56e1b1cb02493
28,558
cpp
C++
src/coreclr/jit/importer_vectorization.cpp
kejxu/runtime
906146aba64a9c14bcc77cffa5f540ead31cd4a7
[ "MIT" ]
null
null
null
src/coreclr/jit/importer_vectorization.cpp
kejxu/runtime
906146aba64a9c14bcc77cffa5f540ead31cd4a7
[ "MIT" ]
null
null
null
src/coreclr/jit/importer_vectorization.cpp
kejxu/runtime
906146aba64a9c14bcc77cffa5f540ead31cd4a7
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif //------------------------------------------------------------------------ // importer_vectorization.cpp // // This file is responsible for various (partial) vectorizations during import phase, // e.g. the following APIs are currently supported: // // 1) String.Equals(string, string) // 2) String.Equals(string, string, StringComparison.Ordinal) // 3) str.Equals(string) // 4) str.Equals(String, StringComparison.Ordinal) // 5) str.StartsWith(string, StringComparison.Ordinal) // 6) MemoryExtensions.SequenceEqual<char>(ROS<char>, ROS<char>) // 7) MemoryExtensions.Equals(ROS<char>, ROS<char>, StringComparison.Ordinal) // 8) MemoryExtensions.StartsWith<char>(ROS<char>, ROS<char>) // 9) MemoryExtensions.StartsWith(ROS<char>, ROS<char>, StringComparison.Ordinal) // // When one of the arguments is a constant string of a [0..32] size so we can inline // a vectorized comparison against it using SWAR or SIMD techniques (e.g. via two V256 vectors) // // We might add these in future: // 1) OrdinalIgnoreCase for everything above // 2) Span.CopyTo // 3) Spans/Arrays of bytes (e.g. UTF8) against a constant RVA data // //------------------------------------------------------------------------ // impExpandHalfConstEqualsSIMD: Attempts to unroll and vectorize // Equals against a constant WCHAR data for Length in [8..32] range // using SIMD instructions. C# equivalent of what this function emits: // // bool IsTestString(ReadOnlySpan<char> span) // { // // Length and Null checks are not handled here // ref char s = ref MemoryMarshal.GetReference(span); // var v1 = Vector128.LoadUnsafe(ref s); // var v1 = Vector128.LoadUnsafe(ref s, span.Length - Vector128<ushort>.Count); // var cns1 = Vector128.Create('T', 'e', 's', 't', 'S', 't', 'r', 'i'); // var cns2 = Vector128.Create('s', 't', 'S', 't', 'r', 'i', 'n', 'g'); // return ((v1 ^ cns1) | (v2 ^ cns2)) == Vector<ushort>.Zero; // // // for: // // return span.SequenceEqual("TestString"); // } // // Arguments: // data - Pointer to a data to vectorize // cns - Constant data (array of 2-byte chars) // len - Number of chars in the cns // dataOffset - Offset for data // // Return Value: // A pointer to the newly created SIMD node or nullptr if unrolling is not // possible or not profitable // // Notes: // This function doesn't check obj for null or its Length, it's just an internal helper // for impExpandHalfConstEquals // GenTree* Compiler::impExpandHalfConstEqualsSIMD(GenTreeLclVar* data, WCHAR* cns, int len, int dataOffset) { assert(len >= 8 && len <= 32); #if defined(FEATURE_HW_INTRINSICS) && defined(TARGET_64BIT) if (!compOpportunisticallyDependsOn(InstructionSet_Vector128)) { // We need SSE2 or ADVSIMD at least return nullptr; } CorInfoType baseType = CORINFO_TYPE_ULONG; int simdSize; var_types simdType; NamedIntrinsic niZero; NamedIntrinsic niEquals; NamedIntrinsic niCreate; GenTree* cnsVec1; GenTree* cnsVec2; // Optimization: don't use two vectors for Length == 8 or 16 bool useSingleVector = false; #if defined(TARGET_XARCH) if (compOpportunisticallyDependsOn(InstructionSet_Vector256) && len >= 16) { // Handle [16..32] inputs via two Vector256 assert(len >= 16 && len <= 32); simdSize = 32; simdType = TYP_SIMD32; niZero = NI_Vector256_get_Zero; niEquals = NI_Vector256_op_Equality; niCreate = NI_Vector256_Create; // Special case: use a single vector for Length == 16 useSingleVector = len == 16; assert(sizeof(ssize_t) == 8); // this code is guarded with TARGET_64BIT GenTree* long1 = gtNewIconNode(*(ssize_t*)(cns + 0), TYP_LONG); GenTree* long2 = gtNewIconNode(*(ssize_t*)(cns + 4), TYP_LONG); GenTree* long3 = gtNewIconNode(*(ssize_t*)(cns + 8), TYP_LONG); GenTree* long4 = gtNewIconNode(*(ssize_t*)(cns + 12), TYP_LONG); cnsVec1 = gtNewSimdHWIntrinsicNode(simdType, long1, long2, long3, long4, niCreate, baseType, simdSize); // cnsVec2 most likely overlaps with cnsVec1: GenTree* long5 = gtNewIconNode(*(ssize_t*)(cns + len - 16), TYP_LONG); GenTree* long6 = gtNewIconNode(*(ssize_t*)(cns + len - 12), TYP_LONG); GenTree* long7 = gtNewIconNode(*(ssize_t*)(cns + len - 8), TYP_LONG); GenTree* long8 = gtNewIconNode(*(ssize_t*)(cns + len - 4), TYP_LONG); cnsVec2 = gtNewSimdHWIntrinsicNode(simdType, long5, long6, long7, long8, niCreate, baseType, simdSize); } else #endif if (len <= 16) { // Handle [8..16] inputs via two Vector128 assert(len >= 8 && len <= 16); simdSize = 16; simdType = TYP_SIMD16; niZero = NI_Vector128_get_Zero; niEquals = NI_Vector128_op_Equality; niCreate = NI_Vector128_Create; // Special case: use a single vector for Length == 8 useSingleVector = len == 8; assert(sizeof(ssize_t) == 8); // this code is guarded with TARGET_64BIT GenTree* long1 = gtNewIconNode(*(ssize_t*)(cns + 0), TYP_LONG); GenTree* long2 = gtNewIconNode(*(ssize_t*)(cns + 4), TYP_LONG); cnsVec1 = gtNewSimdHWIntrinsicNode(simdType, long1, long2, niCreate, baseType, simdSize); // cnsVec2 most likely overlaps with cnsVec1: GenTree* long3 = gtNewIconNode(*(ssize_t*)(cns + len - 8), TYP_LONG); GenTree* long4 = gtNewIconNode(*(ssize_t*)(cns + len - 4), TYP_LONG); cnsVec2 = gtNewSimdHWIntrinsicNode(simdType, long3, long4, niCreate, baseType, simdSize); } else { JITDUMP("impExpandHalfConstEqualsSIMD: No V256 support and data is too big for V128\n"); // NOTE: We might consider using four V128 for ARM64 return nullptr; } GenTree* zero = gtNewSimdHWIntrinsicNode(simdType, niZero, baseType, simdSize); GenTree* offset1 = gtNewIconNode(dataOffset, TYP_I_IMPL); GenTree* offset2 = gtNewIconNode(dataOffset + len * sizeof(USHORT) - simdSize, TYP_I_IMPL); GenTree* dataPtr1 = gtNewOperNode(GT_ADD, TYP_BYREF, data, offset1); GenTree* dataPtr2 = gtNewOperNode(GT_ADD, TYP_BYREF, gtClone(data), offset2); GenTree* vec1 = gtNewIndir(simdType, dataPtr1); GenTree* vec2 = gtNewIndir(simdType, dataPtr2); // TODO-Unroll-CQ: Spill vec1 and vec2 for better pipelining, currently we end up emitting: // // vmovdqu xmm0, xmmword ptr [rcx+12] // vpxor xmm0, xmm0, xmmword ptr[reloc @RWD00] // vmovdqu xmm1, xmmword ptr [rcx+20] // vpxor xmm1, xmm1, xmmword ptr[reloc @RWD16] // // While we should re-order them to be: // // vmovdqu xmm0, xmmword ptr [rcx+12] // vmovdqu xmm1, xmmword ptr [rcx+20] // vpxor xmm0, xmm0, xmmword ptr[reloc @RWD00] // vpxor xmm1, xmm1, xmmword ptr[reloc @RWD16] // // ((v1 ^ cns1) | (v2 ^ cns2)) == zero GenTree* xor1 = gtNewSimdBinOpNode(GT_XOR, simdType, vec1, cnsVec1, baseType, simdSize, false); GenTree* xor2 = gtNewSimdBinOpNode(GT_XOR, simdType, vec2, cnsVec2, baseType, simdSize, false); GenTree* orr = gtNewSimdBinOpNode(GT_OR, simdType, xor1, xor2, baseType, simdSize, false); return gtNewSimdHWIntrinsicNode(TYP_BOOL, useSingleVector ? xor1 : orr, zero, niEquals, baseType, simdSize); #else return nullptr; #endif } //------------------------------------------------------------------------ // impCreateCompareInd: creates the following tree: // // * EQ int // +--* IND <type> // | \--* ADD byref // | +--* <obj> // | \--* CNS_INT <offset> // \--* CNS_INT <value> // // Arguments: // comp - Compiler object // obj - GenTree representing data pointer // type - type for the IND node // offset - offset for the data pointer // value - constant value to compare against // // Return Value: // A tree with indirect load and comparison // static GenTree* impCreateCompareInd(Compiler* comp, GenTreeLclVar* obj, var_types type, ssize_t offset, ssize_t value) { GenTree* offsetTree = comp->gtNewIconNode(offset, TYP_I_IMPL); GenTree* addOffsetTree = comp->gtNewOperNode(GT_ADD, TYP_BYREF, obj, offsetTree); GenTree* indirTree = comp->gtNewIndir(type, addOffsetTree); GenTree* valueTree = comp->gtNewIconNode(value, genActualType(type)); return comp->gtNewOperNode(GT_EQ, TYP_INT, indirTree, valueTree); } //------------------------------------------------------------------------ // impExpandHalfConstEqualsSWAR: Attempts to unroll and vectorize // Equals against a constant WCHAR data for Length in [1..8] range // using SWAR (a sort of SIMD but for GPR registers and instructions) // // Arguments: // data - Pointer to a data to vectorize // cns - Constant data (array of 2-byte chars) // len - Number of chars in the cns // dataOffset - Offset for data // // Return Value: // A pointer to the newly created SWAR node or nullptr if unrolling is not // possible or not profitable // // Notes: // This function doesn't check obj for null or its Length, it's just an internal helper // for impExpandHalfConstEquals // GenTree* Compiler::impExpandHalfConstEqualsSWAR(GenTreeLclVar* data, WCHAR* cns, int len, int dataOffset) { assert(len >= 1 && len <= 8); // Compose Int32 or Int64 values from ushort components #define MAKEINT32(c1, c2) ((UINT64)c2 << 16) | ((UINT64)c1 << 0) #define MAKEINT64(c1, c2, c3, c4) ((UINT64)c4 << 48) | ((UINT64)c3 << 32) | ((UINT64)c2 << 16) | ((UINT64)c1 << 0) if (len == 1) { // [ ch1 ] // [value] // return impCreateCompareInd(this, data, TYP_SHORT, dataOffset, cns[0]); } if (len == 2) { // [ ch1 ][ ch2 ] // [ value ] // const UINT32 value = MAKEINT32(cns[0], cns[1]); return impCreateCompareInd(this, data, TYP_INT, dataOffset, value); } #ifdef TARGET_64BIT if (len == 3) { // handle len = 3 via two Int32 with overlapping: // // [ ch1 ][ ch2 ][ ch3 ] // [ value1 ] // [ value2 ] // // where offset for value2 is 2 bytes (1 char) // UINT32 value1 = MAKEINT32(cns[0], cns[1]); UINT32 value2 = MAKEINT32(cns[1], cns[2]); GenTree* firstIndir = impCreateCompareInd(this, data, TYP_INT, dataOffset, value1); GenTree* secondIndir = impCreateCompareInd(this, gtClone(data)->AsLclVar(), TYP_INT, dataOffset + sizeof(USHORT), value2); // TODO-Unroll-CQ: Consider merging two indirs via XOR instead of QMARK // e.g. gtNewOperNode(GT_XOR, TYP_INT, firstIndir, secondIndir); // but it currently has CQ issues (redundant movs) GenTreeColon* doubleIndirColon = gtNewColonNode(TYP_INT, secondIndir, gtNewFalse()); return gtNewQmarkNode(TYP_INT, firstIndir, doubleIndirColon); } assert(len >= 4 && len <= 8); UINT64 value1 = MAKEINT64(cns[0], cns[1], cns[2], cns[3]); if (len == 4) { // [ ch1 ][ ch2 ][ ch3 ][ ch4 ] // [ value ] // return impCreateCompareInd(this, data, TYP_LONG, dataOffset, value1); } // For 5..7 value2 will overlap with value1, e.g. for Length == 6: // // [ ch1 ][ ch2 ][ ch3 ][ ch4 ][ ch5 ][ ch6 ] // [ value1 ] // [ value2 ] // UINT64 value2 = MAKEINT64(cns[len - 4], cns[len - 3], cns[len - 2], cns[len - 1]); GenTree* firstIndir = impCreateCompareInd(this, data, TYP_LONG, dataOffset, value1); ssize_t offset = dataOffset + len * sizeof(WCHAR) - sizeof(UINT64); GenTree* secondIndir = impCreateCompareInd(this, gtClone(data)->AsLclVar(), TYP_LONG, offset, value2); // TODO-Unroll-CQ: Consider merging two indirs via XOR instead of QMARK GenTreeColon* doubleIndirColon = gtNewColonNode(TYP_INT, secondIndir, gtNewFalse()); return gtNewQmarkNode(TYP_INT, firstIndir, doubleIndirColon); #else // TARGET_64BIT return nullptr; #endif } //------------------------------------------------------------------------ // impExpandHalfConstEquals: Attempts to unroll and vectorize // Equals against a constant WCHAR data for Length in [8..32] range // using either SWAR or SIMD. In a general case it will look like this: // // bool equals = obj != null && obj.Length == len && (SWAR or SIMD) // // Arguments: // data - Pointer (LCL_VAR) to a data to vectorize // lengthFld - Pointer (LCL_VAR or GT_FIELD) to Length field // checkForNull - Check data for null // startsWith - Is it StartsWith or Equals? // cns - Constant data (array of 2-byte chars) // len - Number of 2-byte chars in the cns // dataOffset - Offset for data // // Return Value: // A pointer to the newly created SIMD node or nullptr if unrolling is not // possible or not profitable // GenTree* Compiler::impExpandHalfConstEquals(GenTreeLclVar* data, GenTree* lengthFld, bool checkForNull, bool startsWith, WCHAR* cnsData, int len, int dataOffset) { assert(len >= 0); if (compCurBB->isRunRarely()) { // Not profitable to expand JITDUMP("impExpandHalfConstEquals: block is cold - not profitable to expand.\n"); return nullptr; } if ((compIsForInlining() ? (fgBBcount + impInlineRoot()->fgBBcount) : (fgBBcount)) > 20) { // We don't want to unroll too much and in big methods // TODO-Unroll-CQ: come up with some better heuristic/budget JITDUMP("impExpandHalfConstEquals: method has too many BBs (>20) - not profitable to expand.\n"); return nullptr; } const genTreeOps cmpOp = startsWith ? GT_GE : GT_EQ; GenTree* elementsCount = gtNewIconNode(len); GenTree* lenCheckNode; if (len == 0) { // For zero length we don't need to compare content, the following expression is enough: // // varData != null && lengthFld == 0 // lenCheckNode = gtNewOperNode(cmpOp, TYP_INT, lengthFld, elementsCount); } else { assert(cnsData != nullptr); GenTree* indirCmp = nullptr; if (len < 8) // SWAR impl supports len == 8 but we'd better give it to SIMD { indirCmp = impExpandHalfConstEqualsSWAR(gtClone(data)->AsLclVar(), cnsData, len, dataOffset); } else if (len <= 32) { indirCmp = impExpandHalfConstEqualsSIMD(gtClone(data)->AsLclVar(), cnsData, len, dataOffset); } if (indirCmp == nullptr) { JITDUMP("unable to compose indirCmp\n"); return nullptr; } GenTreeColon* lenCheckColon = gtNewColonNode(TYP_INT, indirCmp, gtNewFalse()); // For StartsWith we use GT_GE, e.g.: `x.Length >= 10` lenCheckNode = gtNewQmarkNode(TYP_INT, gtNewOperNode(cmpOp, TYP_INT, lengthFld, elementsCount), lenCheckColon); } GenTree* rootQmark; if (checkForNull) { // varData == nullptr GenTreeColon* nullCheckColon = gtNewColonNode(TYP_INT, lenCheckNode, gtNewFalse()); rootQmark = gtNewQmarkNode(TYP_INT, gtNewOperNode(GT_NE, TYP_INT, data, gtNewNull()), nullCheckColon); } else { // no nullcheck, just "obj.Length == len && (SWAR or SIMD)" rootQmark = lenCheckNode; } return rootQmark; } //------------------------------------------------------------------------ // impGetStrConFromSpan: Try to obtain string literal out of a span: // var span = "str".AsSpan(); // var span = (ReadOnlySpan<char>)"str" // // Arguments: // span - String_op_Implicit or MemoryExtensions_AsSpan call // with a string literal // // Returns: // GenTreeStrCon node or nullptr // GenTreeStrCon* Compiler::impGetStrConFromSpan(GenTree* span) { GenTreeCall* argCall = nullptr; if (span->OperIs(GT_RET_EXPR)) { // NOTE: we don't support chains of RET_EXPR here GenTree* inlineCandidate = span->AsRetExpr()->gtInlineCandidate; if (inlineCandidate->OperIs(GT_CALL)) { argCall = inlineCandidate->AsCall(); } } else if (span->OperIs(GT_CALL)) { argCall = span->AsCall(); } if ((argCall != nullptr) && ((argCall->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) != 0)) { const NamedIntrinsic ni = lookupNamedIntrinsic(argCall->gtCallMethHnd); if ((ni == NI_System_MemoryExtensions_AsSpan) || (ni == NI_System_String_op_Implicit)) { assert(argCall->gtCallArgs->GetNext() == nullptr); if (argCall->gtCallArgs->GetNode()->OperIs(GT_CNS_STR)) { return argCall->gtCallArgs->GetNode()->AsStrCon(); } } } return nullptr; } //------------------------------------------------------------------------ // impStringEqualsOrStartsWith: The main entry-point for String methods // We're going to unroll & vectorize the following cases: // 1) String.Equals(obj, "cns") // 2) String.Equals(obj, "cns", StringComparison.Ordinal) // 3) String.Equals("cns", obj) // 4) String.Equals("cns", obj, StringComparison.Ordinal) // 5) obj.Equals("cns") // 5) obj.Equals("cns") // 6) obj.Equals("cns", StringComparison.Ordinal) // 7) "cns".Equals(obj) // 8) "cns".Equals(obj, StringComparison.Ordinal) // 9) obj.StartsWith("cns", StringComparison.Ordinal) // 10) "cns".StartsWith(obj, StringComparison.Ordinal) // // For cases 5, 6 and 9 we don't emit "obj != null" // NOTE: String.Equals(object) is not supported currently // // Arguments: // startsWith - Is it StartsWith or Equals? // sig - signature of StartsWith or Equals method // methodFlags - its flags // // Returns: // GenTree representing vectorized comparison or nullptr // GenTree* Compiler::impStringEqualsOrStartsWith(bool startsWith, CORINFO_SIG_INFO* sig, unsigned methodFlags) { const bool isStatic = methodFlags & CORINFO_FLG_STATIC; const int argsCount = sig->numArgs + (isStatic ? 0 : 1); GenTree* op1; GenTree* op2; if (argsCount == 3) // overload with StringComparison { if (!impStackTop(0).val->IsIntegralConst(4)) // StringComparison.Ordinal { // TODO-Unroll-CQ: Unroll & vectorize OrdinalIgnoreCase return nullptr; } op1 = impStackTop(2).val; op2 = impStackTop(1).val; } else { assert(argsCount == 2); op1 = impStackTop(1).val; op2 = impStackTop(0).val; } if (!(op1->OperIs(GT_CNS_STR) ^ op2->OperIs(GT_CNS_STR))) { // either op1 or op2 has to be CNS_STR, but not both - that case is optimized // just fine as is. return nullptr; } GenTree* varStr; GenTreeStrCon* cnsStr; if (op1->OperIs(GT_CNS_STR)) { cnsStr = op1->AsStrCon(); varStr = op2; } else { cnsStr = op2->AsStrCon(); varStr = op1; } bool needsNullcheck = true; if ((op1 != cnsStr) && !isStatic) { // for the following cases we should not check varStr for null: // // obj.Equals("cns") // obj.Equals("cns", StringComparison.Ordinal) // obj.StartsWith("cns", StringComparison.Ordinal) // // instead, it should throw NRE if it's null needsNullcheck = false; } int cnsLength = -1; const char16_t* str = nullptr; if (cnsStr->IsStringEmptyField()) { // check for fake "" first cnsLength = 0; JITDUMP("Trying to unroll String.Equals|StartsWith(op1, \"\")...\n", str) } else { str = info.compCompHnd->getStringLiteral(cnsStr->gtScpHnd, cnsStr->gtSconCPX, &cnsLength); if ((cnsLength < 0) || (str == nullptr)) { // We were unable to get the literal (e.g. dynamic context) return nullptr; } JITDUMP("Trying to unroll String.Equals|StartsWith(op1, \"%ws\")...\n", str) } // Create a temp which is safe to gtClone for varStr // We're not appending it as a statement until we figure out unrolling is profitable (and possible) unsigned varStrTmp = lvaGrabTemp(true DEBUGARG("spilling varStr")); lvaTable[varStrTmp].lvType = varStr->TypeGet(); GenTreeLclVar* varStrLcl = gtNewLclvNode(varStrTmp, varStr->TypeGet()); // Create a tree representing string's Length: // TODO-Unroll-CQ: Consider using ARR_LENGTH here, but we'll have to modify QMARK to propagate BBF_HAS_IDX_LEN int strLenOffset = OFFSETOF__CORINFO_String__stringLen; GenTree* lenOffset = gtNewIconNode(strLenOffset, TYP_I_IMPL); GenTree* lenNode = gtNewIndir(TYP_INT, gtNewOperNode(GT_ADD, TYP_BYREF, varStrLcl, lenOffset)); varStrLcl = gtClone(varStrLcl)->AsLclVar(); GenTree* unrolled = impExpandHalfConstEquals(varStrLcl, lenNode, needsNullcheck, startsWith, (WCHAR*)str, cnsLength, strLenOffset + sizeof(int)); if (unrolled != nullptr) { impAssignTempGen(varStrTmp, varStr); if (unrolled->OperIs(GT_QMARK)) { // QMARK nodes cannot reside on the evaluation stack unsigned rootTmp = lvaGrabTemp(true DEBUGARG("spilling unroll qmark")); impAssignTempGen(rootTmp, unrolled); unrolled = gtNewLclvNode(rootTmp, TYP_INT); } JITDUMP("\n... Successfully unrolled to:\n") DISPTREE(unrolled) for (int i = 0; i < argsCount; i++) { impPopStack(); } } return unrolled; } //------------------------------------------------------------------------ // impSpanEqualsOrStartsWith: The main entry-point for [ReadOnly]Span<char> methods // We're going to unroll & vectorize the following cases: // 1) MemoryExtensions.SequenceEqual<char>(var, "cns") // 2) MemoryExtensions.SequenceEqual<char>("cns", var) // 3) MemoryExtensions.Equals(var, "cns", StringComparison.Ordinal) // 4) MemoryExtensions.Equals("cns", var, StringComparison.Ordinal) // 5) MemoryExtensions.StartsWith<char>("cns", var) // 6) MemoryExtensions.StartsWith<char>(var, "cns") // 7) MemoryExtensions.StartsWith("cns", var, StringComparison.Ordinal) // 8) MemoryExtensions.StartsWith(var, "cns", StringComparison.Ordinal) // // Arguments: // startsWith - Is it StartsWith or Equals? // sig - signature of StartsWith or Equals method // methodFlags - its flags // // Returns: // GenTree representing vectorized comparison or nullptr // GenTree* Compiler::impSpanEqualsOrStartsWith(bool startsWith, CORINFO_SIG_INFO* sig, unsigned methodFlags) { const bool isStatic = methodFlags & CORINFO_FLG_STATIC; const int argsCount = sig->numArgs + (isStatic ? 0 : 1); GenTree* op1; GenTree* op2; if (argsCount == 3) // overload with StringComparison { if (!impStackTop(0).val->IsIntegralConst(4)) // StringComparison.Ordinal { // TODO-Unroll-CQ: Unroll & vectorize OrdinalIgnoreCase return nullptr; } op1 = impStackTop(2).val; op2 = impStackTop(1).val; } else { assert(argsCount == 2); op1 = impStackTop(1).val; op2 = impStackTop(0).val; } // For generic StartsWith and Equals we need to make sure T is char if (sig->sigInst.methInstCount != 0) { assert(sig->sigInst.methInstCount == 1); CORINFO_CLASS_HANDLE targetElemHnd = sig->sigInst.methInst[0]; CorInfoType typ = info.compCompHnd->getTypeForPrimitiveValueClass(targetElemHnd); if ((typ != CORINFO_TYPE_SHORT) && (typ != CORINFO_TYPE_USHORT) && (typ != CORINFO_TYPE_CHAR)) { return nullptr; } } // Try to obtain original string literals out of span arguments GenTreeStrCon* op1Str = impGetStrConFromSpan(op1); GenTreeStrCon* op2Str = impGetStrConFromSpan(op2); if (!((op1Str != nullptr) ^ (op2Str != nullptr))) { // either op1 or op2 has to be '(ReadOnlySpan)"cns"' return nullptr; } GenTree* spanObj; GenTreeStrCon* cnsStr; if (op1Str != nullptr) { cnsStr = op1Str; spanObj = op2; } else { cnsStr = op2Str; spanObj = op1; } int cnsLength = -1; const char16_t* str = nullptr; if (cnsStr->IsStringEmptyField()) { // check for fake "" first cnsLength = 0; JITDUMP("Trying to unroll MemoryExtensions.Equals|SequenceEqual|StartsWith(op1, \"\")...\n", str) } else { str = info.compCompHnd->getStringLiteral(cnsStr->gtScpHnd, cnsStr->gtSconCPX, &cnsLength); if (cnsLength < 0 || str == nullptr) { // We were unable to get the literal (e.g. dynamic context) return nullptr; } JITDUMP("Trying to unroll MemoryExtensions.Equals|SequenceEqual|StartsWith(op1, \"%ws\")...\n", str) } CORINFO_CLASS_HANDLE spanCls = gtGetStructHandle(spanObj); CORINFO_FIELD_HANDLE pointerHnd = info.compCompHnd->getFieldInClass(spanCls, 0); CORINFO_FIELD_HANDLE lengthHnd = info.compCompHnd->getFieldInClass(spanCls, 1); const unsigned lengthOffset = info.compCompHnd->getFieldOffset(lengthHnd); // Create a placeholder for Span object - we're not going to Append it to statements // in advance to avoid redundant spills in case if we fail to vectorize unsigned spanObjRef = lvaGrabTemp(true DEBUGARG("spanObj tmp")); unsigned spanDataTmp = lvaGrabTemp(true DEBUGARG("spanData tmp")); lvaTable[spanObjRef].lvType = TYP_BYREF; lvaTable[spanDataTmp].lvType = TYP_BYREF; GenTreeLclVar* spanObjRefLcl = gtNewLclvNode(spanObjRef, TYP_BYREF); GenTreeLclVar* spanDataTmpLcl = gtNewLclvNode(spanDataTmp, TYP_BYREF); GenTreeField* spanLength = gtNewFieldRef(TYP_INT, lengthHnd, gtClone(spanObjRefLcl), lengthOffset); GenTreeField* spanData = gtNewFieldRef(TYP_BYREF, pointerHnd, spanObjRefLcl); GenTree* unrolled = impExpandHalfConstEquals(spanDataTmpLcl, spanLength, false, startsWith, (WCHAR*)str, cnsLength, 0); if (unrolled != nullptr) { // We succeeded, fill the placeholders: impAssignTempGen(spanObjRef, impGetStructAddr(spanObj, spanCls, (unsigned)CHECK_SPILL_NONE, true)); impAssignTempGen(spanDataTmp, spanData); if (unrolled->OperIs(GT_QMARK)) { // QMARK can't be a root node, spill it to a temp unsigned rootTmp = lvaGrabTemp(true DEBUGARG("spilling unroll qmark")); impAssignTempGen(rootTmp, unrolled); unrolled = gtNewLclvNode(rootTmp, TYP_INT); } JITDUMP("... Successfully unrolled to:\n") DISPTREE(unrolled) for (int i = 0; i < argsCount; i++) { impPopStack(); } // We have to clean up GT_RET_EXPR for String.op_Implicit or MemoryExtensions.AsSpans if ((spanObj != op1) && op1->OperIs(GT_RET_EXPR)) { GenTree* inlineCandidate = op1->AsRetExpr()->gtInlineCandidate; assert(inlineCandidate->IsCall()); inlineCandidate->gtBashToNOP(); } else if ((spanObj != op2) && op2->OperIs(GT_RET_EXPR)) { GenTree* inlineCandidate = op2->AsRetExpr()->gtInlineCandidate; assert(inlineCandidate->IsCall()); inlineCandidate->gtBashToNOP(); } } return unrolled; }
37.925631
120
0.606275
kejxu
00a611b66e97f4d0f3b10198cc4ae33aacdb2caa
724
cpp
C++
sys/fs/util/dirbuf_add.cpp
apexrtos/apex
9538ab2f5b974035ca30ca8750479bdefe153047
[ "0BSD" ]
15
2020-05-08T06:21:58.000Z
2021-12-11T18:10:43.000Z
sys/fs/util/dirbuf_add.cpp
apexrtos/apex
9538ab2f5b974035ca30ca8750479bdefe153047
[ "0BSD" ]
11
2020-05-08T06:46:37.000Z
2021-03-30T05:46:03.000Z
sys/fs/util/dirbuf_add.cpp
apexrtos/apex
9538ab2f5b974035ca30ca8750479bdefe153047
[ "0BSD" ]
5
2020-08-31T17:05:03.000Z
2021-12-08T07:09:00.000Z
#include <fs/util.h> #include <cstddef> #include <cstring> #include <dirent.h> int dirbuf_add(dirent **buf, size_t *remain, ino_t ino, off_t off, unsigned char type, const char *name) { const size_t align = alignof(dirent); const size_t dirent_noname = offsetof(dirent, d_name); const size_t name_max = *remain - dirent_noname; if ((ssize_t)name_max < 2) return -1; const size_t name_len = strlcpy((*buf)->d_name, name, name_max); if (name_len >= name_max) return -1; const size_t reclen = (dirent_noname + name_len + align) & -align; (*buf)->d_ino = ino; (*buf)->d_off = off; (*buf)->d_reclen = reclen; (*buf)->d_type = type; *remain -= reclen; *buf = (dirent *)((char *)*buf + reclen); return 0; }
25.857143
67
0.668508
apexrtos
00a7937a3572efeed6b27e280e09db524b533373
5,692
cpp
C++
openexrid/Mask.cpp
MercenariesEngineering/openidmask
c7b2da1de1fbac8a4362839427bc13fde6a399c0
[ "MIT" ]
120
2016-02-19T10:58:34.000Z
2022-03-20T12:13:28.000Z
openexrid/Mask.cpp
MercenariesEngineering/openexrid
f52e9c3417aab63d6c66e29cf7304d723bd55300
[ "MIT" ]
9
2016-04-15T07:52:12.000Z
2021-06-28T07:41:57.000Z
openexrid/Mask.cpp
MercenariesEngineering/openidmask
c7b2da1de1fbac8a4362839427bc13fde6a399c0
[ "MIT" ]
21
2016-04-13T11:48:09.000Z
2020-01-23T13:38:43.000Z
/* * *** ***** ********************* Mercenaries Engineering SARL ***************** Copyright (C) 2016 ************* ********* http://www.mercenaries-engineering.com *********** **** **** ** ** */ #include "Mask.h" #include "Builder.h" #include <ImfChannelList.h> #include <ImfDeepFrameBuffer.h> #include <ImfDeepScanLineInputFile.h> #include <ImfDeepScanLineOutputFile.h> #include <ImfIntAttribute.h> #include <ImfPartType.h> #include <ImfStringAttribute.h> #include <ImathBox.h> #include <assert.h> #include <stdexcept> using namespace Imf; using namespace Imath; using namespace std; using namespace openexrid; // Compression extern std::string b64decode (const std::string& str); extern std::string inflate (const std::string& str); // *************************************************************************** Mask::Mask () : _Width (0), _Height (0), _A (-1) {} // *************************************************************************** void Mask::read (const char *filename) { DeepScanLineInputFile file (filename); const Header& header = file.header(); const Box2i displayWindow = header.displayWindow(); _Width = displayWindow.max.x - displayWindow.min.x + 1; _Height = displayWindow.max.y - displayWindow.min.y + 1; const Box2i dataWindow = header.dataWindow(); // Check the version const Imf::IntAttribute *version = header.findTypedAttribute<Imf::IntAttribute> ("EXRIdVersion"); if (!version) throw runtime_error ("The EXRIdVersion attribute is missing"); if (version->value () > (int)Version) throw runtime_error ("The file has been created by an unknown version of the library"); // Get the name attribute const Imf::StringAttribute *names = header.findTypedAttribute<Imf::StringAttribute> ("EXRIdNames"); if (!names) throw runtime_error ("The EXRIdNames attribute is missing"); // Copy the names if (version->value() < 3) _Names = inflate (names->value ()); else _Names = inflate (b64decode(names->value ())); // Count the names int namesN = 0; { size_t index = 0; while (index < _Names.size ()) { index += strnlen (&_Names[index], _Names.size ()-index)+1; ++namesN; } } // Build the name indexes _NamesIndexes.clear (); _NamesIndexes.reserve (namesN); { // Current index size_t index = 0; while (index < _Names.size ()) { // Push the index of the current name _NamesIndexes.push_back ((uint32_t)index); index += strnlen (&_Names[index], _Names.size ()-index)+1; } assert (_NamesIndexes.size () == namesN); } // Allocate the pixel indexes _PixelsIndexes.clear (); _PixelsIndexes.resize (_Width*_Height+1, 0); // Initialize the frame buffer DeepFrameBuffer frameBuffer; frameBuffer.insertSampleCountSlice (Imf::Slice (UINT, (char *) (&_PixelsIndexes[0]), sizeof (uint32_t), sizeof (uint32_t)*_Width)); // For each pixel of a single line, the pointer on the id values vector<uint32_t*> id (_Width); frameBuffer.insert ("Id", DeepSlice (UINT, (char *)&id[0], sizeof (uint32_t*), 0, sizeof (uint32_t))); // Read the slices _Slices.clear (); const ChannelList &channels = header.channels (); for (ChannelList::ConstIterator channel = channels.begin (); channel != channels.end (); ++channel) { if (channel.channel ().type == HALF) _Slices.push_back (channel.name()); } // For each pixel of a single line, the pointer on the coverage values vector<vector<half*> > slices (_Slices.size ()); for (size_t s = 0; s < _Slices.size (); ++s) { slices[s].resize (_Width); frameBuffer.insert (_Slices[s], DeepSlice (HALF, (char *)&slices[s][0], sizeof (half*), 0, sizeof (half))); } file.setFrameBuffer(frameBuffer); // Read the whole pixel sample counts file.readPixelSampleCounts(dataWindow.min.y, dataWindow.max.y); // Accumulate the sample counts to get the indexes // The current index uint32_t index = 0; for (int i = 0; i < _Width*_Height+1; ++i) { const uint32_t n = _PixelsIndexes[i]; // Convert from a sample count to a sample index _PixelsIndexes[i] = index; index += n; } // Resize the samples _Ids.clear (); _Ids.resize (index, 0); _SlicesData.resize (_Slices.size ()); for (size_t s = 0; s < _Slices.size (); ++s) { _SlicesData[s].clear (); _SlicesData[s].resize (index, 0.f); } // For each line for (int y = dataWindow.min.y; y <= dataWindow.max.y; y++) { const int lineStart = y*_Width; // For each pixel for (int x = 0; x < _Width; x++) { const int _i = lineStart+x; // The sample id and coverage pointers for this pixel const uint32_t count = _PixelsIndexes[_i+1]-_PixelsIndexes[_i]; // Avoid invalide indexes id[x] = count ? &_Ids[_PixelsIndexes[_i]] : NULL; for (size_t s = 0; s < _Slices.size (); ++s) slices[s][x] = count ? &_SlicesData[s][_PixelsIndexes[_i]] : NULL; } file.readPixels (y); // In version 1, samples are already uncumulated if (version->value () > 1) { const int A = findSlice ("A"); for (int x = 0; x < _Width; x++) { const int _i = lineStart+x; const uint32_t count = _PixelsIndexes[_i+1]-_PixelsIndexes[_i]; if (count == 0) continue; // Uncumulate the pixels value float prevAlpha = 0.f; for (uint32_t s = 0; s < count; ++s) { const int curr = _PixelsIndexes[_i]+s; const float alpha = (float)_SlicesData[A][curr]; for (size_t v = 0; v < _Slices.size (); ++v) _SlicesData[v][curr] = (1.f-prevAlpha)*_SlicesData[v][curr]; prevAlpha += (1.f-prevAlpha)*alpha; } } } } } // ***************************************************************************
28.318408
109
0.617709
MercenariesEngineering
00ad17966b6f2d7a580a642290e68f89253b7ec3
3,712
cpp
C++
module/mpc-be/SRC/src/filters/renderer/VideoRenderers/CPUUsage.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/renderer/VideoRenderers/CPUUsage.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/renderer/VideoRenderers/CPUUsage.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2013-2018 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * use source from http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/ * */ #include "StdAfx.h" #include "CPUUsage.h" CCPUUsage::CCPUUsage() : m_nCPUUsage(0) , m_dwLastRun(0) , m_lRunCount(0) { ZeroMemory(&m_ftPrevSysKernel, sizeof(FILETIME)); ZeroMemory(&m_ftPrevSysUser, sizeof(FILETIME)); ZeroMemory(&m_ftPrevProcKernel, sizeof(FILETIME)); ZeroMemory(&m_ftPrevProcUser, sizeof(FILETIME)); GetUsage(); } /********************************************** * CCPUUsage::GetUsage * returns the percent of the CPU that this process * has used since the last time the method was called. * If there is not enough information, -1 is returned. * If the method is recalled to quickly, the previous value * is returned. ***********************************************/ const short CCPUUsage::GetUsage() { //create a local copy to protect against race conditions in setting the //member variable short nCpuCopy = m_nCPUUsage; if (::InterlockedIncrement(&m_lRunCount) == 1) { /* If this is called too often, the measurement itself will greatly affect the results. */ if (!EnoughTimePassed()) { ::InterlockedDecrement(&m_lRunCount); return nCpuCopy; } FILETIME ftSysIdle, ftSysKernel, ftSysUser; FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser; if (!GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser) || !GetProcessTimes(GetCurrentProcess(), &ftProcCreation, &ftProcExit, &ftProcKernel, &ftProcUser)) { ::InterlockedDecrement(&m_lRunCount); return nCpuCopy; } if (!IsFirstRun()) { /* CPU usage is calculated by getting the total amount of time the system has operated since the last measurement (made up of kernel + user) and the total amount of time the process has run (kernel + user). */ ULONGLONG ftSysKernelDiff = SubtractTimes(ftSysKernel, m_ftPrevSysKernel); ULONGLONG ftSysUserDiff = SubtractTimes(ftSysUser, m_ftPrevSysUser); ULONGLONG ftProcKernelDiff = SubtractTimes(ftProcKernel, m_ftPrevProcKernel); ULONGLONG ftProcUserDiff = SubtractTimes(ftProcUser, m_ftPrevProcUser); ULONGLONG nTotalSys = ftSysKernelDiff + ftSysUserDiff; ULONGLONG nTotalProc = ftProcKernelDiff + ftProcUserDiff; if (nTotalSys > 0) { m_nCPUUsage = (short)((100.0 * nTotalProc) / nTotalSys); } } m_ftPrevSysKernel = ftSysKernel; m_ftPrevSysUser = ftSysUser; m_ftPrevProcKernel = ftProcKernel; m_ftPrevProcUser = ftProcUser; m_dwLastRun = GetTickCount(); nCpuCopy = m_nCPUUsage; } ::InterlockedDecrement(&m_lRunCount); return nCpuCopy; } ULONGLONG CCPUUsage::SubtractTimes(const FILETIME& ftA, const FILETIME& ftB) { LARGE_INTEGER a, b; a.LowPart = ftA.dwLowDateTime; a.HighPart = ftA.dwHighDateTime; b.LowPart = ftB.dwLowDateTime; b.HighPart = ftB.dwHighDateTime; return a.QuadPart - b.QuadPart; } bool CCPUUsage::EnoughTimePassed() { const DWORD minElapsedMS = 1000UL; return (GetTickCount() - m_dwLastRun) >= minElapsedMS; }
29.228346
110
0.717942
1aq
00b2efd06cd56a1f88f29d529b461715f705497b
2,070
hpp
C++
lib/io/Input.hpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
1
2016-11-15T09:04:12.000Z
2016-11-15T09:04:12.000Z
lib/io/Input.hpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
lib/io/Input.hpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 maldicion069 * * Authors: Cristian Rodríguez Bernal <[email protected]> * * This file is part of MonkeyBrushPlusPlus * <https://github.com/maldicion069/monkeybrushplusplus> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3.0 as published * by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __MB_INPUT__ #define __MB_INPUT__ #include <mb/api.h> #include "../Includes.hpp" #include "Mouse.hpp" #include "Keyboard.hpp" namespace mb { class Input { public: MB_API static void initialize(); MB_API static void destroy(); MB_API static mb::Keyboard* Keyboard(); MB_API static mb::Mouse* Mouse(); MB_API static bool isKeyPressed(Keyboard::Key key); MB_API static bool isKeyClicked(Keyboard::Key key); MB_API static bool KeyReleased(Keyboard::Key key); MB_API static int MouseX(); MB_API static int MouseY(); MB_API static Input* instance(); MB_API static int PreviousMouseX(); MB_API static int PreviousMouseY(); MB_API static int MouseWheelX(); MB_API static int MouseWheelY(); MB_API static int DeltaX(int val); MB_API static int DeltaY(int val); MB_API static bool MouseButtonPress(MouseButton button); MB_API static bool MouseButtonSinglePress(MouseButton button); MB_API static bool MouseButtonRelease(MouseButton button); MB_API static void update(); protected: mb::Keyboard* _keyboard; mb::Mouse* _mouse; static Input *_instance; }; } #endif /* __MB_INPUT__ */
23.793103
80
0.729469
maldicion069
00b7e1243aa38f26f5fd456a2a6b9619f3a8d9b9
16,380
cpp
C++
IMa/update_t_RY.cpp
jaredgk/IMgui-electron
b72ce318dcc500664bd264d8c1578723f61aa769
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
IMa/update_t_RY.cpp
jaredgk/IMgui-electron
b72ce318dcc500664bd264d8c1578723f61aa769
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
IMa/update_t_RY.cpp
jaredgk/IMgui-electron
b72ce318dcc500664bd264d8c1578723f61aa769
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
/*IMa2p 2009-2015 Jody Hey, Rasmus Nielsen, Sang Chul Choi, Vitor Sousa, Janeen Pisciotta, and Arun Sethuraman */ #undef GLOBVARS #include "imamp.hpp" #include "update_gtree_common.hpp" #include "updateassignment.hpp" /*********** LOCAL STUFF **********/ static struct genealogy_weights holdallgweight_t_RY; static struct genealogy_weights holdgweight_t_RY[MAXLOCI]; static struct probcalc holdallpcalc_t_RY; static int largestsamp; static int **skipflag; static double beforesplit (int tnode, double oldt, double newt, double tau_u, double ptime); static double aftersplit (int tnode, double oldt, double newt, double tau_d, double ptime); static void storegenealogystats_all_loci (int ci, int mode); static double forwardRY3 (double ptime, /* double oldt, */double r, double t_u_prior); static double backwardRY3 (double ptime, /* double newt, */double r,double t_u_prior); /********* LOCAL FUNCTIONS **************/ void storegenealogystats_all_loci (int ci, int mode) { static double holdlength[MAXLOCI], holdtlength[MAXLOCI]; static double holdroottime[MAXLOCI]; static int holdroot[MAXLOCI]; static int holdmig[MAXLOCI]; int li; if (mode == 0) { for (li = 0; li < nloci; li++) { holdlength[li] = C[ci]->G[li].length; holdtlength[li] = C[ci]->G[li].tlength; holdroottime[li] = C[ci]->G[li].roottime; holdroot[li] = C[ci]->G[li].root; holdmig[li] = C[ci]->G[li].mignum; } } else { for (li = 0; li < nloci; li++) { C[ci]->G[li].length = holdlength[li]; C[ci]->G[li].tlength = holdtlength[li]; C[ci]->G[li].mignum = holdmig[li]; C[ci]->G[li].roottime = holdroottime[li]; C[ci]->G[li].root = holdroot[li]; } } return; } // storegenealogystats double aftersplit (int tnode, double oldt, double newt, double tau_d, double ptime) { if (tnode == lastperiodnumber - 1) { return ptime + newt - oldt; } else { return tau_d - (tau_d - newt) * (tau_d - ptime) / (tau_d - oldt); } } double beforesplit (int tnode, double oldt, double newt, double tau_u, double ptime) { if (tnode == 0) { return ptime * newt / oldt; } else { return tau_u + (ptime - tau_u) * (newt - tau_u) / (oldt - tau_u); } } /*************GLOBAL FUNCTIONS ******************/ void init_t_RY (void) { int li, j; init_genealogy_weights (&holdallgweight_t_RY); for (li = 0; li < nloci; li++) init_genealogy_weights (&holdgweight_t_RY[li]); init_probcalc (&holdallpcalc_t_RY); for (largestsamp = 0, j = 0; j < nloci; j++) if (largestsamp < L[j].numlines) largestsamp = L[j].numlines; skipflag = alloc2Dint (nloci, 2 * largestsamp - 1); } // init_changet_RY void free_t_RY (void) { int li; free_genealogy_weights (&holdallgweight_t_RY); for (li = 0; li < nloci; li++) { free_genealogy_weights (&holdgweight_t_RY[li]); } free_probcalc (&holdallpcalc_t_RY); orig2d_free2D ((void **) skipflag, nloci); } // free_changet_RY /* Notes on changet_RY() implements updating of Rannala and Yang (2003) This application is pretty much the same as theirs - changing times on a species tree that contains a gene tree. The big difference is that IM includes migration. This means that we have to count migration events and change migration times in the same was as we change coalescent times and count how many get changed. R&Y also only change coalescent times in populations affected by a changed t. But because we have migration there is more entanglement between populations. It seems best to change all times within an interval that is affected by a changing t. in R&Y usage u (upper) means older, deeper in the genealogy l (lower) means younger, more recent in the genealogy In R&Y Tu next older split time Tl next more recent split time T - current split time T* - proposed time t - time of some event t* - time of that event after update If Tu> t > T t* = Tu - (Tu-t) (Tu-t*)/(Tu-T) If Tl< t<= T t* = Tl + (t-tl) (T*-Tl)/(T-Tl) nl = number of nodes with Tl< t < T ml = number of migration events with Tl< t < T nu = number of nodes with Tu> t > T mu = number of migration events with Tu> t > T MH criteria p(X|G*,t*)p(G*,t*) (Tu-T*)^(nu+mu) (T*-Tl)^(nl+ml) --------------------------------------------------- p(X|G,t)p(G,t) (Tu-T)^(nu+mu) (T-Tl)^(nl+ml) but this causes confusion with jhey usage in which u means upper - more recent. so here we use u for upper (meaning more recent) use d for down (older) tau current split time tau* new value tau_d - older node time (i.e. time of next oldest node - deeper in the genealogy) tau_u - more recent node time (i.e. time of next youngest node - more recent in time) tau_d > tau > tau_u if tau is the first node, then tau_u = 0. if tau is the last node, then tau_d = infinity for an event at time t where tau_u < t < tau_d if t > tau see aftersplit() t is older than the current split time t* = tau_d - (tau_d - tau*)(tau_d - t)/(tau_d-tau) (A7) if t <= tau see beforesplit() t* = tau_u + (tau* - tau_u)(t - tau_u)/(tau - tau_u) (A8) m is the number of events moved using A7, n is the number moved using A8 then Hastings term for the update is: tau_d - tau* tau* - tau_u (------------)^m (------------)^n tau-u - tau tau - tau_u For IM, we use the same except m and n include both includes migation and coalescent events For edges where downtime < tau_d || uptime > tau_d are not involved in the update For any edge that spends zero time in either splitpop or the ancestral pop, during the tau_u/tau_d interval it is possible to not update the coalescent time or migration times of The difficulty is that it is possible that an uptime for one edge gets moved because the times on one of its daughter edges got moved. This means that for checking about skipping an edge, because it is not involved in any population associated with the splittin time update we need to check entire groups of branches that descend from an edge that crosses the tau_u boundary. use a scoring system for edges -1 to ignore because out of bounds above -2 to ignore because out of bounds below 0 to deal with, edge is relevant 1 to ignore because not in splitpops or ancestral pop set up a recursive function for an edge that crosses the tau_d line, check to see if that edge and all descendent edges that to not cross tau_l are in the populations affected by the splitting time update If all of those edges are not relevant then they all get a skipflag value of 1 If any one of them does spend any time in any of the populations involved int the population split then all of the edges have their skipflag value set to 0 */ /* let u refer to the more recent time and d to the older time */ int changet_RY1 (int ci, int timeperiod) // after Rannala and Yang (2003) - rubberband method { double metropolishastingsterm, newt, oldt; double pdgnew[MAXLOCI + MAXLINKED], pdgnewsum, pdgoldsum, probgnewsum, temppdg; double t_u_hterm, t_d_hterm, tpw; int li, i, j, ecd, ecu, emd, emu, ai, ui; double U; struct genealogy *G; struct edge *gtree; double t_d, t_u, t_u_prior, t_d_prior; double holdt[MAXPERIODS]; if (assignmentoptions[POPULATIONASSIGNMENTCHECKPOINT] == 1) { assertgenealogy (ci); } t_u = (timeperiod == 0) ? 0 : C[ci]->tvals[timeperiod - 1]; t_d = (timeperiod == (lastperiodnumber - 1)) ? TIMEMAX : C[ci]->tvals[timeperiod + 1]; t_d_prior = DMIN (T[timeperiod].pr.max, t_d); t_u_prior = DMAX (T[timeperiod].pr.min, t_u); oldt = C[ci]->tvals[timeperiod]; newt = getnewt (timeperiod, t_u_prior, t_d_prior, oldt, 1); t_u_hterm = (newt - t_u) / (oldt - t_u); if (timeperiod == lastperiodnumber - 1) { t_d_hterm = 1; } else { t_d_hterm = (t_d - newt) / (t_d - oldt); } copy_treeinfo (&holdallgweight_t_RY, &C[ci]->allgweight); // try turning this off and forcing all recalculations copy_probcalc (&holdallpcalc_t_RY, &C[ci]->allpcalc); for (i = 0; i < lastperiodnumber; i++) holdt[i] = C[ci]->tvals[i]; pdgoldsum = C[ci]->allpcalc.pdg; setzero_genealogy_weights (&C[ci]->allgweight); ecd = ecu = emd = emu = 0; pdgnewsum = 0; probgnewsum = 0; storegenealogystats_all_loci (ci, 0); C[ci]->tvals[timeperiod] = newt; for (i = 0; i < nurates; i++) pdgnew[i] = 0; for (li = 0; li < nloci; li++) { G = &(C[ci]->G[li]); gtree = G->gtree; copy_treeinfo (&holdgweight_t_RY[li], &G->gweight); for (i = 0; i < L[li].numlines; i++) { if (gtree[i].down != -1) { if (gtree[i].time <= oldt && gtree[i].time > t_u) { //assert (skipflag[li][i] == 0);turn off 9/19/10 gtree[i].time = beforesplit (timeperiod, oldt, newt, /* t_d, */ t_u, gtree[i].time); assert (gtree[i].time != newt); ecu++; } else { if (gtree[i].time > oldt && gtree[i].time < t_d) { // assert (skipflag[li][i] == 0); turn off 9/19/10 gtree[i].time = aftersplit (timeperiod, oldt, newt, t_d, /* t_u, */ gtree[i].time); assert (gtree[i].time != newt); ecd++; } //else do not change the time } j = 0; while (gtree[i].mig[j].mt > -0.5) { assert (gtree[i].mig[j].mt < C[0]->tvals[lastperiodnumber]); if (gtree[i].mig[j].mt <= oldt && gtree[i].mig[j].mt > t_u) { gtree[i].mig[j].mt = beforesplit (timeperiod, oldt, newt, /* t_d, */ t_u, gtree[i].mig[j].mt); emu++; } else { assert (oldt < C[0]->tvals[lastperiodnumber]); if (gtree[i].mig[j].mt > oldt && gtree[i].mig[j].mt < t_d) { gtree[i].mig[j].mt = aftersplit (timeperiod, oldt, newt, t_d, /* t_u, */ gtree[i].mig[j].mt); emd++; } // else no need to change the time } j++; } } } if (G->roottime <= oldt && G->roottime > t_u /* && skipflag[li][G->root] == 0 turn off 9/19/10*/) G->roottime = beforesplit (timeperiod, oldt, newt, /* t_d, */ t_u, G->roottime); else if (G->roottime > oldt && G->roottime < t_d /* && skipflag[li][G->root] == 0 turn off 9/19/10*/) G->roottime = aftersplit (timeperiod, oldt, newt, t_d, /* t_u, */ G->roottime); setzero_genealogy_weights (&G->gweight); treeweight (ci, li); sum_treeinfo (&C[ci]->allgweight, &G->gweight); ai = 0; ui = L[li].uii[ai]; switch (L[li].model) { assert (pdgnew[ui] == 0); case HKY: if (assignmentoptions[JCMODEL] == 1) { temppdg = pdgnew[ui] = likelihoodJC (ci, li, G->uvals[0]); } else { temppdg = pdgnew[ui] = likelihoodHKY (ci, li, G->uvals[0], G->kappaval, -1, -1, -1, -1); } break; case INFINITESITES: temppdg = pdgnew[ui] = likelihoodIS (ci, li, G->uvals[0]); break; case STEPWISE: temppdg = 0; for (; ai < L[li].nlinked; ai++) { ui = L[li].uii[ai]; assert (pdgnew[ui] == 0); pdgnew[ui] = likelihoodSW (ci, li, ai, G->uvals[ai], 1.0); temppdg += pdgnew[ui]; } break; case JOINT_IS_SW: temppdg = pdgnew[ui] = likelihoodIS (ci, li, G->uvals[0]); for (ai = 1; ai < L[li].nlinked; ai++) { ui = L[li].uii[ai]; assert (pdgnew[ui] == 0); pdgnew[ui] = likelihoodSW (ci, li, ai, G->uvals[ai], 1.0); temppdg += pdgnew[ui]; } break; } pdgnewsum += temppdg; } assert (!ODD (ecd)); assert (!ODD (ecu)); ecd /= 2; ecu /= 2; integrate_tree_prob (ci, &C[ci]->allgweight, &holdallgweight_t_RY, &C[ci]->allpcalc, &holdallpcalc_t_RY, &holdt[0]); // try enforcing full cacullation tpw = gbeta * (pdgnewsum - pdgoldsum); /* 5/19/2011 JH adding thermodynamic integration */ if (calcoptions[CALCMARGINALLIKELIHOOD]) { metropolishastingsterm = beta[ci] * tpw + (C[ci]->allpcalc.probg - holdallpcalc_t_RY.probg) + (ecd + emd) * log (t_d_hterm) + (ecu + emu) * log (t_u_hterm); } else { tpw += C[ci]->allpcalc.probg - holdallpcalc_t_RY.probg; metropolishastingsterm = beta[ci] * tpw + (ecd + emd) * log (t_d_hterm) + (ecu + emu) * log (t_u_hterm); } //assert(metropolishastingsterm >= -1e200 && metropolishastingsterm < 1e200); U = log (uniform ()); if (U < DMIN(1.0, metropolishastingsterm)) //9/13/2010 //if (metropolishastingsterm >= 0.0 || metropolishastingsterm > U) { for (li = 0; li < nloci; li++) { C[ci]->G[li].pdg = 0; for (ai = 0; ai < L[li].nlinked; ai++) { C[ci]->G[li].pdg_a[ai] = pdgnew[L[li].uii[ai]]; C[ci]->G[li].pdg += C[ci]->G[li].pdg_a[ai]; } if (L[li].model == HKY) { storescalefactors (ci, li); copyfraclike (ci, li); } } C[ci]->allpcalc.pdg = pdgnewsum; C[ci]->poptree[C[ci]->droppops[timeperiod + 1][0]].time = C[ci]->poptree[C[ci]->droppops[timeperiod + 1][1]].time = newt; if (assignmentoptions[POPULATIONASSIGNMENTCHECKPOINT] == 1) { assertgenealogy (ci); } return 1; } else { copy_treeinfo (&C[ci]->allgweight, &holdallgweight_t_RY); copy_probcalc (&C[ci]->allpcalc, &holdallpcalc_t_RY); assert (pdgoldsum == C[ci]->allpcalc.pdg); C[ci]->tvals[timeperiod] = oldt; for (li = 0; li < nloci; li++) { G = &(C[ci]->G[li]); gtree = G->gtree; storegenealogystats_all_loci (ci, 1); copy_treeinfo (&G->gweight, &holdgweight_t_RY[li]); for (i = 0; i < L[li].numlines; i++) { if (gtree[i].down != -1) { if (gtree[i].time <= newt && gtree[i].time > t_u) { // assert (skipflag[li][i] == 0); turned off 9/19/10 gtree[i].time = beforesplit (timeperiod, newt, oldt, /* t_d, */ t_u, gtree[i].time); //cecu++; } else { if (gtree[i].time > newt && gtree[i].time < t_d) { //assert (skipflag[li][i] == 0); turned off 9/19/10 gtree[i].time = aftersplit (timeperiod, newt, oldt, t_d, /* t_u, */ gtree[i].time); //cecl++; } } j = 0; while (gtree[i].mig[j].mt > -0.5) { if (gtree[i].mig[j].mt <= newt && gtree[i].mig[j].mt > t_u) { gtree[i].mig[j].mt = beforesplit (timeperiod, newt, oldt, /* t_d, */ t_u, gtree[i].mig[j].mt); //cemu++; } else if (gtree[i].mig[j].mt > newt && gtree[i].mig[j].mt < t_d) { gtree[i].mig[j].mt = aftersplit (timeperiod, newt, oldt, t_d, /* t_u, */ gtree[i].mig[j].mt); //ceml++; } j++; } } } // assert(fabs(C[ci]->G[li].gtree[ C[ci]->G[li].gtree[C[ci]->G[li].root].up[0]].time - C[ci]->G[li].roottime) < 1e-8); } /* assert(ecu==cecu/2); assert(ecd==cecl/2); assert(emu==cemu); assert(emd==ceml); */ for (li = 0; li < nloci; li++) { if (L[li].model == HKY) restorescalefactors (ci, li); /* have to reset the dlikeA values in the genealogies for stepwise model */ if (L[li].model == STEPWISE) for (ai = 0; ai < L[li].nlinked; ai++) likelihoodSW (ci, li, ai, C[ci]->G[li].uvals[ai], 1.0); if (L[li].model == JOINT_IS_SW) for (ai = 1; ai < L[li].nlinked; ai++) likelihoodSW (ci, li, ai, C[ci]->G[li].uvals[ai], 1.0); // assert(fabs(C[ci]->G[li].gtree[ C[ci]->G[li].gtree[C[ci]->G[li].root].up[0]].time - C[ci]->G[li].roottime) < 1e-8); } if (assignmentoptions[POPULATIONASSIGNMENTCHECKPOINT] == 1) { assertgenealogy (ci); } return 0; } } /* changet_RY1 */
31.560694
160
0.573382
jaredgk
00beece22dffd42c0610e574d6e37930fa8dddb0
997
cpp
C++
archive/1/dwa_slowa.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
archive/1/dwa_slowa.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
archive/1/dwa_slowa.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
//#include <iostream> #include <cstdio> #include <string> #include <algorithm> #include <cstring> using namespace std; typedef long long unsigned U; int main() { /* cout.sync_with_stdio(false); U _; cin >> _; string a, b; cin >> a >> b; U n; cin >> n; for(U i = 0; i < n; ++i) { U ai, bi; cin >> ai >> bi; swap(a[ai], b[bi]); int eq = a.compare(b); cout << (eq == 0 ? '0' : eq > 0 ? '1' : '2') << '\n'; }*/ U _; scanf("%llu", &_); const U maxlen = 1e6 + 1; char a[maxlen], b[maxlen]; scanf("%s %s", a, b); U n; scanf("%llu", &n); for(U i = 0; i < n; ++i) { U ai, bi; scanf("%llu %llu", &ai, &bi); U t = a[ai]; a[ai] = b[bi]; b[bi] = t; int eq = strcmp(a, b); printf("%c\n", (eq == 0 ? '0' : eq > 0 ? '1' : '2')); } return 0; }
16.080645
46
0.374122
Aleshkev
00c060f0fe5aca9d5fd8d8c546de0ec4264135c2
14,178
cc
C++
test/bezierSubdivision.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
1
2021-12-02T09:25:32.000Z
2021-12-02T09:25:32.000Z
test/bezierSubdivision.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
test/bezierSubdivision.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
#include <crv.h> #include <crvBezier.h> #include <crvSnap.h> #include <gmi_analytic.h> #include <gmi_null.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apf.h> #include <PCU.h> #include <mth.h> #include <mth_def.h> #include <pcu_util.h> /* * This contains all the tests for bezier subdivision */ void vertFunction(double const p[2], double x[3], void*) { (void)p; (void)x; } // simple quartic edge void edgeFunction(double const p[2], double x[3], void*) { x[0] = p[0]*p[0]*p[0]*p[0]; x[1] = p[0]*p[0]; x[2] = p[0]; } void reparam_zero(double const from[2], double to[2], void*) { (void)from; to[0] = 0; to[1] = 0; } void reparam_one(double const from[2], double to[2], void*) { (void)from; to[0] = 1; to[1] = 0; } agm_bdry add_bdry(gmi_model* m, gmi_ent* e) { return agm_add_bdry(gmi_analytic_topo(m), agm_from_gmi(e)); } agm_use add_adj(gmi_model* m, agm_bdry b, int tag) { agm* topo = gmi_analytic_topo(m); int dim = agm_dim_from_type(agm_bounds(topo, b).type); gmi_ent* de = gmi_find(m, dim - 1, tag); return agm_add_use(topo, b, agm_from_gmi(de)); } gmi_model* makeEdgeModel() { gmi_model* model = gmi_make_analytic(); int edPer = 0; double edRan[2] = {0, 1}; gmi_add_analytic(model, 0, 0, vertFunction, NULL,NULL,NULL); gmi_add_analytic(model, 0, 1, vertFunction, NULL,NULL,NULL); gmi_ent* ed = gmi_add_analytic(model, 1, 0, edgeFunction, &edPer, &edRan, 0); agm_bdry b = add_bdry(model, ed); agm_use u0 = add_adj(model, b, 0); gmi_add_analytic_reparam(model, u0, reparam_zero, 0); agm_use u1 = add_adj(model, b, 1); gmi_add_analytic_reparam(model, u1, reparam_one, 0); return model; } // edges go counter clockwise // face areas are 1/2 and 19/30 void vert0(double const p[2], double x[3], void*) { (void)p; (void)x; } // edges go counter clockwise void edge0(double const p[2], double x[3], void*) { x[0] = p[0]; x[1] = 0.; } void edge1(double const p[2], double x[3], void*) { x[0] = 1.0-p[0]*(p[0]-1.0)*p[0]*(p[0]-1.0); x[1] = p[0]; } void edge2(double const p[2], double x[3], void*) { double u = 1.-p[0]; x[0] = u; x[1] = u; } void face0(double const p[2], double x[3], void*) { (void)p; (void)x; } void make_edge_topo(gmi_model* m, gmi_ent* e, int v0tag, int v1tag) { agm_bdry b = add_bdry(m, e); agm_use u0 = add_adj(m, b, v0tag); gmi_add_analytic_reparam(m, u0, reparam_zero, 0); agm_use u1 = add_adj(m, b, v1tag); gmi_add_analytic_reparam(m, u1, reparam_one, 0); } gmi_model* makeFaceModel() { gmi_model* model = gmi_make_analytic(); int edPer = 0; double edRan[2] = {0, 1}; for(int i = 0; i < 3; ++i) gmi_add_analytic(model, 0, i, vertFunction,NULL,NULL,NULL); gmi_ent* eds[3]; eds[0] = gmi_add_analytic(model, 1, 0, edge0, &edPer, &edRan, 0); eds[1] = gmi_add_analytic(model, 1, 1, edge1, &edPer, &edRan, 0); eds[2] = gmi_add_analytic(model, 1, 2, edge2, &edPer, &edRan, 0); for(int i = 0; i < 3; ++i) make_edge_topo(model, eds[i], i, (i+1) % 3); int faPer[2] = {0, 0}; double faRan[2][2] = {{0,1},{0,1}}; gmi_add_analytic(model, 2, 0, face0, faPer, faRan, 0); return model; } apf::Mesh2* createMesh2D() { gmi_model* model = makeFaceModel(); apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 2, false); apf::MeshEntity* v[3], *edges[3]; apf::Vector3 points2D[3] = {apf::Vector3(0,0,0),apf::Vector3(1,0,0),apf::Vector3(1,1,0)}; for (int i = 0; i < 3; ++i){ v[i] = m->createVertex(m->findModelEntity(0,i),points2D[i],points2D[i]); } for (int i = 0; i < 3; ++i){ apf::ModelEntity* edge = m->findModelEntity(1,i); apf::MeshEntity* ved[2] = {v[i],v[(i+1) % 3]}; edges[i] = m->createEntity(apf::Mesh::EDGE,edge,ved); } apf::ModelEntity* faceModel = m->findModelEntity(2,0); m->createEntity(apf::Mesh::TRIANGLE,faceModel,edges); m->acceptChanges(); m->verify(); return m; } static apf::Vector3 points3D[4] = {apf::Vector3(0,0,0), apf::Vector3(1,0,0), apf::Vector3(0,1,0), apf::Vector3(0,0,1)}; apf::Mesh2* createMesh3D() { gmi_model* model = gmi_load(".null"); apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false); apf::buildOneElement(m,0,apf::Mesh::TET,points3D); apf::deriveMdsModel(m); m->acceptChanges(); m->verify(); return m; } /* * Create a mesh with a single edge, * Create two edges as an even subdivision, * and keep all three around, using the original one * to compare correctness of the split. * */ void testEdgeSubdivision() { for (int o = 1; o <= 6; ++o){ gmi_model* model = makeEdgeModel(); apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 1, false); apf::ModelEntity* edgeModel = m->findModelEntity(1,0); apf::Vector3 points[2] = {apf::Vector3(0,0,0),apf::Vector3(1,1,1)}; apf::MeshEntity* v[2]; for (int i = 0; i < 2; ++i) v[i] = m->createVertex(m->findModelEntity(0,i),points[i],points[i]); apf::MeshEntity* edge = m->createEntity(apf::Mesh::EDGE,edgeModel, v); m->acceptChanges(); m->verify(); // curve the mesh crv::BezierCurver bc(m,o,0); bc.run(); apf::Element* elem = apf::createElement(m->getCoordinateField(),edge); apf::NewArray<apf::Vector3> nodes; apf::NewArray<apf::Vector3> subNodes[2]; subNodes[0].allocate(o+1); subNodes[1].allocate(o+1); apf::getVectorNodes(elem,nodes); // subdivide the edge's nodes crv::subdivideBezierEdge(o,1./4,nodes,subNodes); // create the two new edges apf::Vector3 p; crv::transferParametricOnEdgeSplit(m,edge,1./4,p); apf::MeshEntity* v2 = m->createVertex(edgeModel,subNodes[0][o],p); apf::MeshEntity* vE[2][2] = {{v[0],v2},{v2,v[1]}}; apf::MeshEntity* e[2]; for (int i = 0; i < 2; ++i){ e[i] = m->createEntity(apf::Mesh::EDGE,edgeModel,vE[i]); for (int j = 1; j < o; ++j) m->setPoint(e[i],j-1,subNodes[i][j]); } // compare the two curves to the original one apf::Element* elem0 = apf::createElement(m->getCoordinateField(),e[0]); apf::Element* elem1 = apf::createElement(m->getCoordinateField(),e[1]); apf::Vector3 pt1, pt2, p1, p2; for (int i = 0; i <= 100; ++i){ p1[0] = 0.02*i-1.; p2[0] = 0.005*i-1.; apf::getVector(elem0,p1,pt1); apf::getVector(elem,p2,pt2); PCU_ALWAYS_ASSERT(std::abs((pt2-pt1).getLength()) < 1e-15); p2[0] = 0.015*i-0.5; apf::getVector(elem1,p1,pt1); apf::getVector(elem,p2,pt2); PCU_ALWAYS_ASSERT(std::abs((pt2-pt1).getLength()) < 1e-15); } apf::destroyElement(elem); apf::destroyElement(elem0); apf::destroyElement(elem1); m->destroyNative(); apf::destroyMesh(m); } } /* Create a single triangle, split it, and make sure each triangle * exactly replicates its part of the old one * */ void testTriSubdivision1() { for(int o = 1; o <= 6; ++o){ apf::Mesh2* m = createMesh2D(); crv::BezierCurver bc(m,o,0); bc.run(); apf::MeshIterator* it = m->begin(2); apf::MeshEntity* e = m->iterate(it); m->end(it); apf::Element* elem = apf::createElement(m->getCoordinateField(),e); apf::MeshEntity* verts[3],* edges[3]; m->getDownward(e,0,verts); m->getDownward(e,1,edges); apf::NewArray<apf::Vector3> nodes; apf::NewArray<apf::Vector3> subNodes[3]; for (int t = 0; t < 3; ++t) subNodes[t].allocate((o+1)*(o+2)/2); apf::getVectorNodes(elem,nodes); apf::Vector3 splitpt(0,0.5,0.5); crv::subdivideBezierTriangle(o,splitpt,nodes,subNodes); apf::MeshEntity* v3 = m->createVertex(m->findModelEntity(2,0), subNodes[0][2],splitpt); apf::MeshEntity* newFaces[3],* newEdges[3]; for (int i = 0; i < 3; ++i){ apf::MeshEntity* vE[2] = {v3,verts[i]}; newEdges[i] = m->createEntity(apf::Mesh::EDGE,m->findModelEntity(1,i), vE); for (int j = 0; j < o-1; ++j){ m->setPoint(newEdges[i],j,subNodes[i][3+2*(o-1)+j]); } } for (int i = 0; i < 3; ++i){ apf::MeshEntity* eF[3] = {edges[i],newEdges[(i+1) % 3], newEdges[i]}; newFaces[i] = m->createEntity(apf::Mesh::TRIANGLE,m->findModelEntity(2,0), eF); for (int j = 0; j < (o-1)*(o-2)/2; ++j){ m->setPoint(newFaces[i],j,subNodes[i][3+3*(o-1)+j]); } } // compare the three faces to the original one apf::Element* elems[3] = {apf::createElement(m->getCoordinateField(),newFaces[0]), apf::createElement(m->getCoordinateField(),newFaces[1]), apf::createElement(m->getCoordinateField(),newFaces[2])}; apf::Vector3 p,pOld,pt,ptOld; for (int j = 0; j <= 10; ++j){ p[1] = 1.*j/10; for (int i = 0; i <= 10-j; ++i){ p[0] = 1.*i/10; p[2] = 1.-p[0]-p[1]; // p[1] is the new split point, rescale from new to old for (int t = 0; t < 3; ++t){ apf::getVector(elems[t],p,pt); for (int pi = 0; pi < 3; ++pi) pOld[pi] = splitpt[(pi+2) % 3]*p[1]; pOld[t] += p[0]; pOld[(t+2) % 3] += p[2]; apf::getVector(elem,pOld,ptOld); PCU_ALWAYS_ASSERT(std::abs((ptOld-pt).getLength()) < 1e-15); } } } apf::destroyElement(elem); m->destroy(e); for(int t = 0; t < 3; ++t) apf::destroyElement(elems[t]); m->destroyNative(); apf::destroyMesh(m); } } /* Create a single triangle, split it into 4, and try not to crash * */ void testTriSubdivision4() { for(int o = 2; o <= 2; ++o){ apf::Mesh2* m = createMesh2D(); crv::BezierCurver bc(m,o,0); bc.run(); apf::MeshIterator* it = m->begin(2); apf::MeshEntity* e = m->iterate(it); m->end(it); apf::Element* elem = apf::createElement(m->getCoordinateField(),e); apf::NewArray<apf::Vector3> nodes; apf::NewArray<apf::Vector3> subNodes[4]; for (int t = 0; t < 4; ++t) subNodes[t].allocate((o+1)*(o+2)/2); apf::getVectorNodes(elem,nodes); apf::Vector3 splitpt(0,0.5,0.5); crv::subdivideBezierTriangle(o,nodes,subNodes); apf::destroyElement(elem); m->destroyNative(); apf::destroyMesh(m); } } /* Create a single tet, split it, and make sure each tet * exactly replicates its part of the old one * */ void testTetSubdivision1() { gmi_register_null(); for (int order = 1; order <= 4; ++order){ apf::Mesh2* m = createMesh3D(); crv::BezierCurver bc(m,order,0); bc.run(); apf::MeshIterator* it = m->begin(3); apf::MeshEntity* tet = m->iterate(it); m->end(it); apf::MeshEntity* verts[4],* edges[6],* faces[4]; m->getDownward(tet,0,verts); m->getDownward(tet,1,edges); m->getDownward(tet,2,faces); apf::Element* elem = apf::createElement(m->getCoordinateField(),tet); apf::NewArray<apf::Vector3> nodes; apf::NewArray<apf::Vector3> subNodes[4]; for (int t = 0; t < 4; ++t) subNodes[t].allocate(crv::getNumControlPoints(apf::Mesh::TET,order)); apf::getVectorNodes(elem,nodes); apf::Vector3 splitpt(0.25,0.35,0.25); crv::subdivideBezierTet(order,splitpt,nodes,subNodes); apf::MeshEntity* v4 = m->createVertex(m->findModelEntity(2,0), subNodes[0][3],splitpt); apf::MeshEntity* newFaces[6],* newEdges[4],* newTets[4]; for (int i = 0; i < 4; ++i){ apf::MeshEntity* vE[2] = {verts[i],v4}; newEdges[i] = m->createEntity(apf::Mesh::EDGE,m->findModelEntity(1,i), vE); for (int j = 0; j < order-1; ++j){ m->setPoint(newEdges[i],j,subNodes[i][4+3*(order-1)+j]); } } int const tet_tri[6][2] = {{0,1},{0,2},{2,3},{3,1},{1,3},{2,1}}; int nE = (order-1); int nF = (order-1)*(order-2)/2; // this compensates for alignment issues for (int f = 0; f < 6; ++f){ apf::MeshEntity* eF[3] = {edges[f],newEdges[apf::tet_edge_verts[f][1]], newEdges[apf::tet_edge_verts[f][0]]}; newFaces[f] = m->createEntity(apf::Mesh::TRIANGLE,m->findModelEntity(2,0), eF); for (int j = 0; j < nF; ++j){ m->setPoint(newFaces[f],j,subNodes[tet_tri[f][0]][4+6*nE+tet_tri[f][1]*nF+j]); if(f == 3 && order == 4){ int o[3] = {1,0,2}; m->setPoint(newFaces[f],j,subNodes[tet_tri[f][0]][4+6*nE+tet_tri[f][1]*nF+o[j]]); } } } apf::MeshEntity* fT0[4] = {faces[0],newFaces[0],newFaces[1],newFaces[2]}; newTets[0] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT0); apf::MeshEntity* fT1[4] = {faces[1],newFaces[0],newFaces[3],newFaces[4]}; newTets[1] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT1); apf::MeshEntity* fT2[4] = {faces[2],newFaces[1],newFaces[4],newFaces[5]}; newTets[2] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT2); apf::MeshEntity* fT3[4] = {faces[3],newFaces[2],newFaces[5],newFaces[3]}; newTets[3] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT3); if(order == 4){ for (int t = 0; t < 4; ++t){ apf::Vector3 pt = (points3D[apf::tet_tri_verts[t][0]] + points3D[apf::tet_tri_verts[t][1]] + points3D[apf::tet_tri_verts[t][2]] + splitpt)*0.25; m->setPoint(newTets[t],0,pt); } } apf::Element* elems[4] = {apf::createElement(m->getCoordinateField(),newTets[0]), apf::createElement(m->getCoordinateField(),newTets[1]), apf::createElement(m->getCoordinateField(),newTets[2]), apf::createElement(m->getCoordinateField(),newTets[3])}; double totalVolume = apf::measure((apf::MeshElement*)elem); double volumeSum = apf::measure((apf::MeshElement*)elems[0]) + apf::measure((apf::MeshElement*)elems[1]) + apf::measure((apf::MeshElement*)elems[2]) + apf::measure((apf::MeshElement*)elems[3]); PCU_ALWAYS_ASSERT(fabs(totalVolume - volumeSum) < 1e-15); apf::destroyElement(elem); m->destroy(tet); for(int t = 0; t < 4; ++t) apf::destroyElement(elems[t]); m->destroyNative(); apf::destroyMesh(m); } } int main(int argc, char** argv) { MPI_Init(&argc,&argv); PCU_Comm_Init(); testEdgeSubdivision(); testTriSubdivision1(); testTriSubdivision4(); testTetSubdivision1(); PCU_Comm_Free(); MPI_Finalize(); }
28.817073
91
0.59543
cwsmith
00c360bb1f1401d970e227967685e6fa65092e5f
6,023
cc
C++
src/main.cc
FlyAlCode/FlightSim
800b46ebf87449408cc908c59cb5e18bea5863c3
[ "Apache-2.0" ]
null
null
null
src/main.cc
FlyAlCode/FlightSim
800b46ebf87449408cc908c59cb5e18bea5863c3
[ "Apache-2.0" ]
null
null
null
src/main.cc
FlyAlCode/FlightSim
800b46ebf87449408cc908c59cb5e18bea5863c3
[ "Apache-2.0" ]
null
null
null
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <fstream> #include <string> #include <memory> #include "camera.h" #include "ground.h" #include <stdio.h> #include <stdlib.h> double const PI = 3.1415926; void DrawMask(const cv::Mat &src, const cv::Mat &mask, cv::Mat &result){ CV_Assert(mask.rows==src.rows && mask.cols == mask.rows); if(mask.channels()!=1) cv::cvtColor(mask, mask, CV_RGB2GRAY); src.copyTo(result); for(int i=0; i<mask.rows; i++){ for(int j=0; j<mask.cols; j++){ if(mask.at<uchar>(i,j)!=0) result.at<cv::Vec3b>(i,j) = cv::Vec3b(0,255,0); } } } int main(int argc, char *argv[]){ if(argc<22){ std::cout<<"Usage: flight_sim [acc_error_model_file] [gro_error_model_file][sat_file_name] [road_file_name] \ \n [save_path] [angle_x angle_y angle_z] [position_x position_y position_z] [v_x v_y v_z] \ [a_mean_x a_mean_y a_mean_z] [w_mean_x w_mean_y w_mean_z] [max_image_num]"<<std::endl; exit(-1); } std::shared_ptr<flight_sim::Ground> ground (new flight_sim::Ground ); if(!ground->Init(argv[3],argv[4], 1.2)){ std::cout<<"Fail to load ground file"<<std::endl; return -1; } ground->Print(); // init camera flight_sim::Camera::IMUParam imu_params; imu_params.acc_error_model_file_ = std::string(argv[1]); imu_params.gro_error_model_file_ = std::string(argv[2]); for(int i=0; i<3; i++){ // imu_params.a_mean_[i] = 0; imu_params.a_std_[i] = 0.5; // imu_params.w_mean_[i] = 0; imu_params.w_std_[i] = 0.0; } imu_params.a_mean_[0] = atof(argv[15]); imu_params.a_mean_[1] = atof(argv[16]); imu_params.a_mean_[2] = atof(argv[17]); imu_params.w_mean_[0] = atof(argv[18]); imu_params.w_mean_[1] = atof(argv[19]); imu_params.w_mean_[2] = atof(argv[20]); for(int i=0; i<3; ++i){ std::cout<<imu_params.a_mean_[i]<<" "; } std::cout<<std::endl; for(int i=0; i<3; ++i){ std::cout<<imu_params.w_mean_[i]<<" "; } std::cout<<std::endl; flight_sim::Camera camera; double K_data[9] = {450, 0, 400, 0, 450, 400, 0, 0, 1}; cv::Mat K(3, 3, CV_64F, K_data); camera.Init(imu_params,K, ground); // set initial pose of the camera double init_pose[9]/* = {0,20/180*PI,0,355000,4659000,1000,-200,300,0} */; // angle, position, v // get initial pose from params { init_pose[0] = atof(argv[6])/* /180*PI */; init_pose[1] = atof(argv[7])/* /180*PI */; init_pose[2] = atof(argv[8])/* /180*PI */; init_pose[3] = atof(argv[9]); init_pose[4] = atof(argv[10]); init_pose[5] = atof(argv[11]); init_pose[6] = atof(argv[12]); init_pose[7] = atof(argv[13]); init_pose[8] = atof(argv[14]); } // double init_pose[9]; // std::cout<<"Please input initial_angle_x:"<<std::endl; // std::cin>>init_pose[0]; // std::cout<<"Please input initial_angle_y:"<<std::endl; // std::cin>>init_pose[1]; // std::cout<<"Please input initial_angle_z:"<<std::endl; // std::cin>>init_pose[2]; // std::cout<<"Please input initial_position_x:"<<std::endl; // std::cin>>init_pose[3]; // std::cout<<"Please input initial_position_y:"<<std::endl; // std::cin>>init_pose[4]; // std::cout<<"Please input initial_position_z:"<<std::endl; // std::cin>>init_pose[5]; // std::cout<<"Please input initial_v_x:"<<std::endl; // std::cin>>init_pose[6]; // std::cout<<"Please input initial_v_y:"<<std::endl; // std::cin>>init_pose[7]; // std::cout<<"Please input initial_v_z:"<<std::endl; // std::cin>>init_pose[8]; camera.SetInitPose(init_pose); std::cout<<"************ Start fly!!! *************"<<std::endl; cv::Mat current_sat_img, current_road_img; // cv::namedWindow("sat"); // cv::namedWindow("road"); int img_count = 0; std::ofstream fout(std::string(argv[5]) + "H_c2g.txt"); std::ofstream fout_R(std::string(argv[5]) + "R.txt"); std::ofstream fout_T(std::string(argv[5]) + "t.txt"); fout.precision(7); fout_R.precision(7); fout_T.precision(7); int max_img_num = atoi(argv[21]); while(cv::waitKey(1)!='q' && img_count<max_img_num){ camera.UpdatePose(); if(!camera.GetCurrentImage(current_sat_img, current_road_img)) break; // cv::imshow("sat", current_sat_img); // cv::imshow("road", current_road_img); cv::Mat add_img; DrawMask(current_sat_img, current_road_img, add_img); cv::imshow("add img", add_img); std::cout<<"img number: "<<img_count<<std::endl; // write image char tmp[20]; sprintf(tmp, "%.3d", img_count); std::string sat_save_name = std::string(argv[5]) + "sat/" + tmp + ".jpg"; std::string road_save_name = std::string(argv[5]) + "road/" + tmp + ".png"; // std::cout<<road_save_name<<std::endl; cv::imwrite(sat_save_name, current_sat_img); cv::imwrite(road_save_name, current_road_img); // print pose cv::Mat H_c2g = camera.get_H_c_2_g(); for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ fout<<H_c2g.at<double>(i,j)<<" "; } } fout<<std::endl; cv::Mat R_tmp = camera.get_R(); for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ fout_R<<R_tmp.at<double>(i,j)<<" "; } } fout_R<<std::endl; cv::Mat t_tmp = camera.get_t(); // t_tmp 为相机中心在世界坐标系下的坐标 t_tmp = -R_tmp.t() * t_tmp; // std::cout<<t_tmp.t()<<std::endl; for(int i=0; i<3; i++){ fout_T<<t_tmp.at<double>(i,0)<<" "; } fout_T<<std::endl; ++img_count; } fout.close(); fout_R.close(); fout_T.close(); return 0; }
32.912568
117
0.560518
FlyAlCode
00c39216be647d3b43936243cec4a03200425647
565
cpp
C++
src/mango/core/wire/request/SnippetTextRequest.cpp
vero-zhang/mango
0cc8d34a8b729151953df41a7e9cd26324345d44
[ "MIT" ]
null
null
null
src/mango/core/wire/request/SnippetTextRequest.cpp
vero-zhang/mango
0cc8d34a8b729151953df41a7e9cd26324345d44
[ "MIT" ]
null
null
null
src/mango/core/wire/request/SnippetTextRequest.cpp
vero-zhang/mango
0cc8d34a8b729151953df41a7e9cd26324345d44
[ "MIT" ]
null
null
null
#include <mango/core/runtime/Runner.h> #include "mango/core/wire/request/SnippetTextRequest.h" #include "mango/core/wire/response/SnippetTextResponse.h" MANGO_NS_BEGIN SnippetTextRequest::SnippetTextRequest ( const std::string& keyword , const std::string& name , const std::string& multilineArg) : keyword(keyword) , name(name) , multilineArg(multilineArg) { } WireResponse* SnippetTextRequest::run(Runner& runner) const { return new SnippetTextResponse (runner.snippetText(keyword, name, multilineArg)); } MANGO_NS_END
23.541667
62
0.734513
vero-zhang
00c4ed79dcdef2a8be7c6512041002de0f26323e
5,857
cpp
C++
2022_CONTROL WORK 1/Project1/Fraction.cpp
Leonchik1945/spbu_homework_2021-2022
84139157b40c5864531e8275c97eaadef9619378
[ "Apache-2.0" ]
null
null
null
2022_CONTROL WORK 1/Project1/Fraction.cpp
Leonchik1945/spbu_homework_2021-2022
84139157b40c5864531e8275c97eaadef9619378
[ "Apache-2.0" ]
null
null
null
2022_CONTROL WORK 1/Project1/Fraction.cpp
Leonchik1945/spbu_homework_2021-2022
84139157b40c5864531e8275c97eaadef9619378
[ "Apache-2.0" ]
null
null
null
#include "Fraction.h" long long Nod(long long a, long long b) { if (b == 0) { return (a); } else { return (Nod(b, a % b)); } } Fraction::Fraction(long long numerator, long long denominator) : numerator(numerator), denominator(denominator) {} Fraction::Fraction(const Fraction& f) : numerator(f.numerator), denominator(f.denominator) {} Fraction::~Fraction() { this->numerator = 0; this->denominator = 0; } int Fraction::getnumerator() { return this->numerator; } void Fraction::setnumerator(int numerator) { this->numerator = numerator; } int Fraction::getdenominator() { return this->denominator; } void Fraction::setdenominatorr(int denominator) { this->denominator = denominator; } void Fraction::set(int numerator, int denominator) { this->numerator = numerator; this->denominator = denominator; } void Fraction::operator=(const Fraction& f) { this->numerator = f.numerator; this->denominator = f.denominator; } long long Fraction::Nok() { return ((this->numerator * this->denominator) / Nod(this->numerator, this->denominator)); } Fraction Fraction::reverse() { return Fraction((this->numerator - (this->numerator - 1)) * this->denominator, (this->denominator - (this->denominator - 1)) * this->numerator); } Fraction Fraction::abs(Fraction& f) { if (f.numerator == 0) { return 0; } else if (f.numerator > 0) { if (f.denominator < 0) { return Fraction(f.numerator, f.denominator * (-1)); } else if (f.denominator > 0) { return Fraction(f.numerator, f.denominator); } else if (f.denominator == 0) { return false; } } else if (f.numerator < 0) { if (f.denominator < 0) { return Fraction(f.numerator * (-1), f.denominator * (-1)); } else if (f.denominator > 0) { return Fraction(f.numerator * (-1), f.denominator); } else if (f.denominator == 0) { return false; } } } bool Fraction::operator==(Fraction& f) { if ((this->Nok() / Nod(this->numerator, this->denominator)) == (f.Nok() / Nod(f.numerator, f.denominator))) { return true; } else { return false; } } bool Fraction::operator<(Fraction& f) { if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) < (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator)) { return true; } else { return false; } } bool Fraction::operator<=(Fraction& f) { if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) <= (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator)) { return true; } else { return false; } } bool Fraction::operator>(Fraction& f) { if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) > (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator)) { return true; } else { return false; } } bool Fraction::operator>=(Fraction& f) { if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) >= (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator)) { return true; } else { return false; } } Fraction operator+(const double t, const Fraction& f) { return Fraction(f.numerator + (t * f.denominator), f.denominator); } Fraction operator+(const Fraction& f, const double t) { return Fraction(f.numerator + (t * f.denominator), f.denominator); } Fraction operator+(const Fraction& f1, const Fraction& f2) { return Fraction((f1.numerator * f2.denominator) + (f2.numerator * f1.denominator), f1.denominator * f2.denominator); } Fraction operator-(const double t, const Fraction& f) { return Fraction((t * f.denominator) - f.numerator, f.denominator); } Fraction operator-(const Fraction& f, const double t) { return Fraction((t * f.denominator) - f.numerator, f.denominator); } Fraction operator-(const Fraction& f1, const Fraction& f2) { return Fraction((f1.numerator * f2.denominator) - (f2.numerator * f1.denominator), f1.denominator * f2.denominator); } Fraction operator*(const double t, const Fraction& f) { return Fraction(f.numerator * t, f.denominator); } Fraction operator*(const Fraction& f, const double t) { return Fraction(f.numerator * t, f.denominator); } Fraction operator*(const Fraction& f1, const Fraction& f2) { return Fraction(f1.numerator * f2.numerator, f1.denominator * f2.denominator); } Fraction operator/(const double t, const Fraction& f) { return Fraction(f.denominator * t, f.numerator); } Fraction operator/(const Fraction& f, const double t) { return Fraction(f.denominator * t, f.numerator); } Fraction operator/(const Fraction& f1, const Fraction& f2) { return Fraction(f1.numerator * f2.denominator, f1.denominator * f2.numerator); } std::ostream& operator<<(std::ostream& stream, const Fraction& f) { if (f.numerator == 0) { stream << "0"; } else { if (f.numerator > 0) { if (f.denominator == 1) { stream << f.numerator; } else if (f.denominator < 0) { stream << "-" << f.numerator << "/" << f.denominator * (-1); } else if (f.denominator > 0) { stream << f.numerator << "/" << f.denominator; } else { stream << "The denominator is zero!" } } else { if (f.denominator == 1) { stream << f.numerator; } else if (f.denominator < 0) { stream << f.numerator * (-1) << "/" << f.denominator * (-1); } else if (f.denominator > 0) { stream << f.numerator << "/" << f.denominator; } else { stream << "The denominator is zero!" } } } return stream; // TODO: insert return statement here }
21.221014
236
0.656138
Leonchik1945
00c739e3f434cbe007a216b58205ac579c72c9bf
4,872
hh
C++
scipy/special/ellint_carlson_cpp_lite/_rg.hh
lorentzenchr/scipy
393a05ee927883ad6316b7092c851afea8f16816
[ "BSD-3-Clause" ]
9,095
2015-01-02T18:24:23.000Z
2022-03-31T20:35:31.000Z
scipy/special/ellint_carlson_cpp_lite/_rg.hh
lorentzenchr/scipy
393a05ee927883ad6316b7092c851afea8f16816
[ "BSD-3-Clause" ]
11,500
2015-01-01T01:15:30.000Z
2022-03-31T23:07:35.000Z
scipy/special/ellint_carlson_cpp_lite/_rg.hh
lorentzenchr/scipy
393a05ee927883ad6316b7092c851afea8f16816
[ "BSD-3-Clause" ]
5,838
2015-01-05T11:56:42.000Z
2022-03-31T23:21:19.000Z
#ifndef ELLINT_RG_GENERIC_GUARD #define ELLINT_RG_GENERIC_GUARD #include <algorithm> #include <iterator> #include <complex> #include "ellint_typing.hh" #include "ellint_argcheck.hh" #include "ellint_common.hh" #include "ellint_carlson.hh" #define CHECK_STATUS_OR_FAIL() \ do { \ if ( status_tmp != ExitStatus::success ) \ { \ status = status_tmp; \ } \ if ( is_horrible(status) ) \ { \ res = typing::nan<T>(); \ return status; \ } \ } while ( 0 ) /* References * [1] B. C. Carlson, "Numerical computation of real or complex elliptic * integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995. * https://arxiv.org/abs/math/9409227 * https://doi.org/10.1007/BF02198293 * [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical * Functions," NIST, US Dept. of Commerce. * https://dlmf.nist.gov/19.16.E1 * https://dlmf.nist.gov/19.20.ii */ /* Forward declaration */ /* See the file _rf.hh for the definition of agm_update */ namespace ellint_carlson { template<typename T> inline void agm_update(T& x, T& y); } namespace ellint_carlson { namespace arithmetic { namespace aux { template<typename T> static inline typing::real_only<T, void> rg_dot2_acc(const T& fac, const T& term, T& acc, T& cor) { fdot2_acc(fac, term, acc, cor); } template<typename CT> static inline typing::cplx_only<CT, void> rg_dot2_acc(const typing::decplx_t<CT>& fac, const CT& term, CT& acc, CT& cor) { typedef typing::decplx_t<CT> RT; RT ar, cr, ai, ci; CT p, q; eft_prod(fac, term.real(), ar, cr); eft_prod(fac, term.imag(), ai, ci); eft_sum(acc, CT{ar, ai}, p, q); acc = p; cor += q + CT{cr, ci}; } }} /* namespace ellint_carlson::arithmetic::aux */ template<typename T> static ExitStatus rg0(const T& x, const T& y, const double& rerr, T& res) { typedef typing::decplx_t<T> RT; ExitStatus status = ExitStatus::success; double rsq = 2.0 * std::sqrt(rerr); RT fac(0.25); T xm = std::sqrt(x); T ym = std::sqrt(y); T dm = (xm + ym) * (RT)0.5; T sum = -dm * dm; T cor(0.0); dm = xm - ym; unsigned int m = 0; while ( std::abs(dm) >= rsq * std::fmin(std::abs(xm), std::abs(ym)) ) { if ( m > config::max_iter ) { status = ExitStatus::n_iter; break; } agm_update(xm, ym); /* Ref[1], Eq. 2.39 or Eq. (46) in the arXiv preprint */ fac *= (RT)2.0; dm = xm - ym; arithmetic::aux::rg_dot2_acc(fac, dm * dm, sum, cor); ++m; } res = (RT)(constants::pi) / (xm + ym); res *= -(RT)0.5 * (sum + cor); return status; } template<typename T> ExitStatus rg(const T& x, const T& y, const T& z, const double& rerr, T& res) { typedef typing::decplx_t<T> RT; ExitStatus status = ExitStatus::success; #ifndef ELLINT_NO_VALIDATE_RELATIVE_ERROR_BOUND if ( argcheck::invalid_rerr(rerr, 1.0e-4) ) { res = typing::nan<T>(); return ExitStatus::bad_rerr; } #endif T cct[3] = {x, y, z}; std::sort(std::begin(cct), std::end(cct), util::abscmp<T>); if ( (argcheck::isinf(cct[0]) || argcheck::isinf(cct[1]) || argcheck::isinf(cct[2])) && argcheck::ph_good(cct[0]) && argcheck::ph_good(cct[1]) && argcheck::ph_good(cct[2]) ) { res = typing::huge<T>(); return ExitStatus::singular; } if ( argcheck::too_small(cct[0]) ) { if ( argcheck::too_small(cct[1]) ) { /* Special case -- also covers the case of z ~ zero. */ res = std::sqrt(cct[2]) * (RT)0.5; return status; } else { /* Special case -- use the AGM algorithm. */ status = rg0(cct[1], cct[2], rerr, res); return status; } } /* Ref[2], Eq. 19.21.11 (second identity) <https://dlmf.nist.gov/19.21.E11> * i.e. 6R_G() = sum of [ x * (y + z) * R_D() ] over cyclic permutations of * (x, y, z). * This cyclic form is manifestly symmetric and is preferred over * Eq. 19.21.10 ibid. * Here we put the three R_D terms in the buffer cct2, and the * x * (y + z) = dot({x, x}, {y, z}) terms in cct1. */ T cct1[3]; T cct2[3]; ExitStatus status_tmp; status_tmp = rd(y, z, x, rerr, cct2[0]); CHECK_STATUS_OR_FAIL(); status_tmp = rd(z, x, y, rerr, cct2[1]); CHECK_STATUS_OR_FAIL(); status_tmp = rd(x, y, z, rerr, cct2[2]); CHECK_STATUS_OR_FAIL(); /* Fill the cct1 buffer via the intermediate buffers tm1, tm2 * that are dotted together (using the compensation algorithm). */ T tm1[2] = {x, x}; T tm2[2] = {y, z}; cct1[0] = arithmetic::dot2(tm1, tm2); tm1[0] = tm1[1] = y; tm2[0] = x; cct1[1] = arithmetic::dot2(tm1, tm2); tm1[0] = tm1[1] = z; tm2[1] = y; cct1[2] = arithmetic::dot2(tm1, tm2); res = arithmetic::dot2(cct1, cct2) / (RT)6.0; return status; } } /* namespace ellint_carlson */ #endif /* ELLINT_RG_GENERIC_GUARD */
24.730964
79
0.59688
lorentzenchr
00c8fca2829018f992225203c6cb298cfdadfb92
6,943
hpp
C++
libraries/wasm/wasm_context.hpp
chenxinhua2018/nchain
9c694d91dc48fc548b88a0016497c34c9a1cbaaa
[ "MIT" ]
1
2020-10-22T23:03:50.000Z
2020-10-22T23:03:50.000Z
src/vm/wasm/wasm_context.hpp
linnbenton/WaykiChain
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
[ "MIT" ]
null
null
null
src/vm/wasm/wasm_context.hpp
linnbenton/WaykiChain
91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #include <string> #include <vector> #include <queue> #include <map> #include <chrono> #include "tx/universaltx.h" #include "wasm/types/inline_transaction.hpp" #include "wasm/wasm_interface.hpp" #include "wasm/datastream.hpp" #include "wasm/wasm_trace.hpp" #include "eosio/vm/allocator.hpp" #include "persistence/cachewrapper.h" #include "entities/receipt.h" #include "wasm/exception/exceptions.hpp" using namespace std; using namespace wasm; namespace wasm { class wasm_context : public wasm_context_interface { public: wasm_context(CUniversalTx &ctrl, inline_transaction &t, CCacheWrapper &cw, vector <CReceipt> &receipts_in, vector <transaction_log>& logs, bool mining, uint32_t depth = 0) : trx_cord(ctrl.txCord), trx(t), control_trx(ctrl), database(cw), receipts(receipts_in), trx_logs(logs), recurse_depth(depth) { reset_console(); }; ~wasm_context() { wasm_alloc.free(); }; public: void initialize(); void execute(inline_transaction_trace &trace); void execute_one(inline_transaction_trace &trace); bool has_permission_from_inline_transaction(const permission &p); bool get_code(const uint64_t& contract, std::vector <uint8_t> &code, uint256 &hash); uint64_t get_runcost(); void check_authorization(const inline_transaction& t); //fixme:V4 void call_one(inline_transaction_trace &trace); int64_t call_one_with_return(inline_transaction_trace &trace); // Console methods: public: void reset_console(); std::ostringstream& get_console_stream() { return _pending_console_output; } const std::ostringstream& get_console_stream() const { return _pending_console_output; } //virtual public: void execute_inline (const inline_transaction& t); void notify_recipient (const uint64_t& recipient ); bool has_recipient (const uint64_t& account ) const; uint64_t receiver() { return _receiver; } uint64_t contract() { return trx.contract; } uint64_t action() { return trx.action; } const char* get_action_data() { return trx.data.data(); } uint32_t get_action_data_size() { return trx.data.size(); } bool is_account (const uint64_t& account) const; void require_auth (const uint64_t& account) const; void require_auth2(const uint64_t& account, const uint64_t& permission) const {} bool has_authorization(const uint64_t& account) const; uint64_t pending_block_time() { return control_trx.pending_block_time; } TxID get_txid() { return control_trx.GetHash(); } uint64_t get_maintainer(const uint64_t& contract); void exit () { wasmif.exit(); } bool get_system_asset_price(uint64_t base, uint64_t quote, std::vector<char>& price); bool set_data( const uint64_t& contract, const string& k, const string& v ) { CUniversalContractStore contractStore; CHAIN_ASSERT( database.contractCache.GetContract(CRegID(contract), contractStore), contract_exception, "contract '%s' does not exist", wasm::regid(contract).to_string()) return database.contractCache.SetContractData(CRegID(contract), k, v); } bool get_data( const uint64_t& contract, const string& k, string &v ) { CUniversalContractStore contractStore; CHAIN_ASSERT( database.contractCache.GetContract(CRegID(contract), contractStore), contract_exception, "contract '%s' does not exist", wasm::regid(contract).to_string()) return database.contractCache.GetContractData(CRegID(contract), k, v); } bool erase_data( const uint64_t& contract, const string& k ) { CUniversalContractStore contractStore; CHAIN_ASSERT( database.contractCache.GetContract(CRegID(contract), contractStore), contract_exception, "contract '%s' does not exist", wasm::regid(contract).to_string()) return database.contractCache.EraseContractData(CRegID(contract), k); } std::vector<uint64_t> get_active_producers(); bool contracts_console() { return SysCfg().GetBoolArg("-contracts_console", false) && control_trx.context_type == TxExecuteContextType::VALIDATE_MEMPOOL; } void console_append(const string& val) { _pending_console_output << val; } vm::wasm_allocator* get_wasm_allocator() { return &wasm_alloc; } bool is_memory_in_wasm_allocator ( const uint64_t& p ) { return wasm_alloc.is_in_range(reinterpret_cast<const char*>(p)); } std::chrono::milliseconds get_max_transaction_duration() { return control_trx.get_max_transaction_duration(); } void update_storage_usage( const uint64_t& account, const int64_t& size_in_bytes); void pause_billing_timer () { control_trx.pause_billing_timer(); }; void resume_billing_timer() { control_trx.resume_billing_timer(); }; void emit_result(const string_view &name, const string_view &type, const string_view &value) override { CHAIN_ASSERT( false, contract_exception, "%s() only used for rpc", __func__) } int64_t call_with_return(inline_transaction& t); uint64_t call(inline_transaction &inline_trx);//return with size void set_return(void *data, uint32_t data_len); std::vector<uint8_t> get_return(); void append_log(uint64_t payer, uint64_t receiver, const string& topic, const string& data); public: CTxCord& trx_cord; inline_transaction& trx; CUniversalTx& control_trx; CCacheWrapper& database; vector<CReceipt>& receipts; vector<transaction_log>& trx_logs; uint32_t recurse_depth; vector<uint64_t> notified; vector<inline_transaction> inline_transactions; wasm::wasm_interface wasmif; vm::wasm_allocator wasm_alloc; uint64_t _receiver; vector<vector<uint8_t>> return_values; vector<uint8_t> the_last_return_buffer; //inline_transaction_trace *trace_ptr = nullptr; private: std::ostringstream _pending_console_output; }; }
41.08284
143
0.620913
chenxinhua2018
00ca8fc4349e9be6e22e0fa6a1e3f11e64cc7555
2,666
cpp
C++
tests/contraction_test.cpp
vaidehi8913/VieCut
f4bd2b468689cb8e5e11f18f1bb21468a119083d
[ "MIT" ]
22
2020-06-12T07:26:45.000Z
2022-03-03T17:03:08.000Z
tests/contraction_test.cpp
vaidehi8913/VieCut
f4bd2b468689cb8e5e11f18f1bb21468a119083d
[ "MIT" ]
4
2019-09-04T10:39:39.000Z
2020-05-26T05:25:35.000Z
tests/contraction_test.cpp
vaidehi8913/VieCut
f4bd2b468689cb8e5e11f18f1bb21468a119083d
[ "MIT" ]
3
2020-12-11T13:43:45.000Z
2021-11-09T15:08:58.000Z
/****************************************************************************** * contraction_test.h * * Source of VieCut. * ****************************************************************************** * Copyright (C) 2018 Alexander Noe <[email protected]> * * Published under the MIT license in the LICENSE file. *****************************************************************************/ #include <omp.h> #include <algorithm> #include <memory> #include <string> #include <vector> #ifdef PARALLEL #include "parallel/coarsening/contract_graph.h" #else #include "coarsening/contract_graph.h" #endif #include "common/definitions.h" #include "data_structure/graph_access.h" #include "gtest/gtest_pred_impl.h" #include "io/graph_io.h" TEST(ContractionTest, NoContr) { #ifdef PARALLEL omp_set_num_threads(4); #endif graphAccessPtr G = graph_io::readGraphWeighted( std::string(VIECUT_PATH) + "/graphs/small.metis"); std::vector<NodeID> mapping; std::vector<std::vector<NodeID> > reverse_mapping; for (NodeID n : G->nodes()) { mapping.push_back(n); reverse_mapping.emplace_back(); reverse_mapping.back().emplace_back(n); } graphAccessPtr cntr = contraction::contractGraph( G, mapping, reverse_mapping); ASSERT_EQ(G->number_of_nodes(), cntr->number_of_nodes()); ASSERT_EQ(G->number_of_edges(), cntr->number_of_edges()); } TEST(ContractionTest, ContrBlock) { #ifdef PARALLEL omp_set_num_threads(4); #endif std::vector<std::string> graphs = { "", "-wgt" }; for (std::string graph : graphs) { graphAccessPtr G = graph_io::readGraphWeighted( std::string(VIECUT_PATH) + "/graphs/small" + graph + ".metis"); std::vector<NodeID> mapping; std::vector<std::vector<NodeID> > reverse_mapping; reverse_mapping.emplace_back(); reverse_mapping.emplace_back(); for (NodeID n : G->nodes()) { mapping.push_back(n / 4); reverse_mapping[n / 4].emplace_back(n); } graphAccessPtr cntr = contraction::contractGraph( G, mapping, reverse_mapping); ASSERT_EQ(cntr->number_of_edges(), 2); ASSERT_EQ(cntr->number_of_nodes(), 2); ASSERT_EQ(cntr->getEdgeTarget(0), 1); ASSERT_EQ(cntr->getEdgeTarget(1), 0); // in weighted graph edge weight is 3, in unweighted 2 if (graph == "") { ASSERT_EQ(cntr->getEdgeWeight(0), 2); ASSERT_EQ(cntr->getEdgeWeight(1), 2); } else { ASSERT_EQ(cntr->getEdgeWeight(0), 3); ASSERT_EQ(cntr->getEdgeWeight(1), 3); } } }
29.296703
79
0.582521
vaidehi8913
00ccaaa47e8e6d3f55574562e5c9701d58674fd7
1,318
cpp
C++
Crimsonite/Crimsonite/source/render/MatrixMaths.cpp
Fletcher-Morris/Crimsonite-Engine
515e6bd8994a324380fe831e6e568509695153f3
[ "MIT" ]
null
null
null
Crimsonite/Crimsonite/source/render/MatrixMaths.cpp
Fletcher-Morris/Crimsonite-Engine
515e6bd8994a324380fe831e6e568509695153f3
[ "MIT" ]
null
null
null
Crimsonite/Crimsonite/source/render/MatrixMaths.cpp
Fletcher-Morris/Crimsonite-Engine
515e6bd8994a324380fe831e6e568509695153f3
[ "MIT" ]
null
null
null
#include "MatrixMaths.h" #include "../ecs/Transform.h" #include "../ecs/components/Camera.h" glm::mat4 CreateModelMatrix(Transform * _transform) { glm::mat4 matrix = glm::mat4(1.0f); glm::vec3 rot = _transform->GetWorldRotation(); matrix = glm::translate(matrix, _transform->GetWorldPosition()); matrix = glm::rotate(matrix, glm::radians(rot.x), { 1,0,0 }); matrix = glm::rotate(matrix, glm::radians(rot.y), { 0,1,0 }); matrix = glm::rotate(matrix, glm::radians(rot.z), { 0,0,1 }); matrix = glm::scale(matrix, _transform->GetScale()); return matrix; } glm::mat4 CreateViewMatrix(const Camera & _camera) { return glm::lookAt(_camera.entity->transform.GetWorldPosition(), _camera.entity->transform.GetWorldPosition() + _camera.entity->transform.Forward(), -_camera.entity->transform.Up()); } glm::mat4 CreateProjectionMatrix(const CameraSettings & _settings) { float safeWidth = _settings.width; float safeHeight = _settings.height; if (safeHeight == 0.0f) { safeWidth = 1.0f; safeHeight = 1.0f; } return CreateProjectionMatrix(_settings.fov, (float)(safeWidth / safeHeight), _settings.nearClip, _settings.farClip); } glm::mat4 CreateProjectionMatrix(const float _fov, const float _ratio, const float _near, const float _far) { return glm::perspective(glm::radians(_fov), _ratio, _near, _far); }
34.684211
183
0.725341
Fletcher-Morris
00d3ba54f6f408ee1baccdd0d66ce4fd57e7dab5
1,703
cpp
C++
Semantic/SymbolTable/SymbolTable.cpp
mori-ahk/Sky
b8b27a3d5e63905c95d2305ee931821737a56d12
[ "MIT" ]
1
2020-04-29T02:11:42.000Z
2020-04-29T02:11:42.000Z
Semantic/SymbolTable/SymbolTable.cpp
mori-ahk/Sky
b8b27a3d5e63905c95d2305ee931821737a56d12
[ "MIT" ]
null
null
null
Semantic/SymbolTable/SymbolTable.cpp
mori-ahk/Sky
b8b27a3d5e63905c95d2305ee931821737a56d12
[ "MIT" ]
null
null
null
// // Created by Morteza Ahmadi on 2020-03-05. // #include "SymbolTable.h" #include "../Error/Error.h" void Semantic::SymbolTable::addClass(std::string &className, Class *_class) { if (classes.find(className) != classes.end()) throw Semantic::Err::DuplicateClassDecl(className); classes[className] = _class; } void Semantic::SymbolTable::addFunction(std::string &funcName, Function *function) { if (freeFunctions.find(funcName) != freeFunctions.end()) { int tag = freeFunctions.at(funcName).size(); function->setTag(funcName + "_" + std::to_string(tag)); freeFunctions.at(funcName).push_back(function); } else { function->setTag(funcName + "_" + std::to_string(0)); freeFunctions[funcName].push_back(function); } } Function* Semantic::SymbolTable::getFreeFunction(const std::string &funcName, Function *function) const { if (freeFunctions.find(funcName) == freeFunctions.end()) throw Semantic::Err::UndeclaredFunction(funcName, function->getPosition()); for (auto &f : freeFunctions.at(funcName)) { if (*f == *function) return f; } throw Semantic::Err::UndeclaredFunction(funcName, function->getPosition()); } const std::vector<Function *> &Semantic::SymbolTable::getFreeFunction(const std::string &funcName) const { if (freeFunctions.find(funcName) == freeFunctions.end()) throw Semantic::Err::UndeclaredFunction(funcName, 0); return freeFunctions.at(funcName); } Class *Semantic::SymbolTable::getClass(const std::string &className) { if (classes.find(className) == classes.end()) throw Semantic::Err::UndeclaredClass(className); return classes.at(className); }
36.234043
106
0.688784
mori-ahk
00d53e351dd5743ebcd117c09543e6a7dec9989b
1,165
cpp
C++
115_DistinctSubsequences.cpp
kun2012/Leetcode
fa6bbe3f559176911ebb12c9b911b969c6ec85fb
[ "MIT" ]
null
null
null
115_DistinctSubsequences.cpp
kun2012/Leetcode
fa6bbe3f559176911ebb12c9b911b969c6ec85fb
[ "MIT" ]
null
null
null
115_DistinctSubsequences.cpp
kun2012/Leetcode
fa6bbe3f559176911ebb12c9b911b969c6ec85fb
[ "MIT" ]
null
null
null
/**************************************************************** Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). Here is an example: S = "rabbbit", T = "rabbit" Return 3. ****************************************************************/ class Solution { public: int numDistinct(string s, string t) { int n = s.size(); int m = t.size(); if (n == 0 || m == 0) return 0; if (n < m) return 0; vector<vector<int> > f(n, vector<int>(m, 0)); if (s[0] == t[0]) f[0][0] = 1; for (int i = 1; i < n; i++) { f[i][0] = f[i - 1][0] + (s[i] == t[0]); } for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { f[i][j] = f[i - 1][j]; if (s[i] == t[j]) f[i][j] += f[i - 1][j - 1]; } } return f[n - 1][m - 1]; } };
41.607143
262
0.438627
kun2012
00d76b16befd0c5f779e45bf3df994a109fdf6af
4,940
cpp
C++
src/messages/serializer.cpp
jaspersong/Project_CS-4500
eba9ca138a2845d457c72562d6792bb72c4fe99c
[ "MIT" ]
null
null
null
src/messages/serializer.cpp
jaspersong/Project_CS-4500
eba9ca138a2845d457c72562d6792bb72c4fe99c
[ "MIT" ]
null
null
null
src/messages/serializer.cpp
jaspersong/Project_CS-4500
eba9ca138a2845d457c72562d6792bb72c4fe99c
[ "MIT" ]
null
null
null
/** * Name: Snowy Chen, Joe Song * Date: 22 March 2020 * Section: Jason Hemann, MR 11:45-1:25 * Email: [email protected], [email protected] */ // Lang::Cpp #include <cassert> #include <cstring> #include "serializer.h" Serializer::Serializer(size_t starting_size) { this->buffer = new unsigned char[starting_size]; this->buffer_size = starting_size; this->offset = 0; this->owns_buffer = true; } Serializer::~Serializer() { if (this->owns_buffer) { delete[] this->buffer; } this->buffer = nullptr; this->buffer_size = 0; this->offset = 0; } bool Serializer::grow_buffer() { if (this->owns_buffer) { // Reallocate the buffer size_t new_size = this->buffer_size * this->buffer_size; auto *new_buffer = new unsigned char[new_size]; // Copy the previous data into memcpy(static_cast<void *>(new_buffer), static_cast<void *>(this->buffer), this->offset); // Now replace the old buffer with the new one delete[] this->buffer; this->buffer = new_buffer; this->buffer_size = new_size; return true; } else { return false; } } bool Serializer::set_generic(unsigned char *value, size_t num_bytes) { assert(value != nullptr); // Make sure there's enough space in the buffer for this value bool ret_value = (this->buffer_size - this->offset) >= num_bytes; // Make sure that we own the buffer as well ret_value = this->owns_buffer && ret_value; // Grow the buffer if necessary if (!ret_value && this->owns_buffer) { ret_value = this->grow_buffer(); } // Set the value if possible if (ret_value) { auto *value_buffer = static_cast<unsigned char *>(value); memcpy(this->buffer + this->offset, value_buffer, num_bytes); // Move the offset this->offset += num_bytes; ret_value = true; } return ret_value; } unsigned char *Serializer::get_serialized_buffer() { this->owns_buffer = false; return this->buffer; } Deserializer::Deserializer(unsigned char *buffer, size_t num_bytes, bool steal) { assert(buffer != nullptr); if (steal) { this->buffer = buffer; this->num_bytes = num_bytes; this->offset = 0; } else { this->num_bytes = num_bytes; this->offset = 0; this->buffer = new unsigned char[this->num_bytes]; memcpy(this->buffer, reinterpret_cast<const void *>(buffer), this->num_bytes); } this->own_buffer = true; } Deserializer::Deserializer(unsigned char *buffer, size_t num_bytes) { assert(buffer != nullptr); this->buffer = buffer; this->num_bytes = num_bytes; this->offset = 0; this->own_buffer = false; } Deserializer::~Deserializer() { if (this->own_buffer) { delete[] this->buffer; } this->buffer = nullptr; this->num_bytes = 0; this->offset = 0; } size_t Deserializer::get_num_bytes_left() { if (this->offset <= this->num_bytes) { return this->num_bytes - this->offset; } else { return 0; } } unsigned char Deserializer::get_byte() { assert(this->get_num_bytes_left() >= sizeof(unsigned char)); unsigned char ret_value = this->buffer[this->offset]; // Move to the next pointer this->offset += sizeof(unsigned char); return ret_value; } bool Deserializer::get_bool() { assert(this->get_num_bytes_left() >= sizeof(bool)); // Cast the buffer into an array of bool in order to grab the binary of // the bool for the next few bytes bool *interpreted_buffer = reinterpret_cast<bool *>(this->buffer + this->offset); bool ret_value = interpreted_buffer[0]; // Update the offset to a new offset based off the string this->offset += sizeof(bool); return ret_value; } size_t Deserializer::get_size_t() { assert(this->get_num_bytes_left() >= sizeof(size_t)); // Get the size of the string auto *size_t_buffer = reinterpret_cast<size_t *>(this->buffer + this->offset); size_t ret_value = size_t_buffer[0]; // Update the offset to a new offset based off the string this->offset += sizeof(size_t); return ret_value; } int Deserializer::get_int() { assert(this->get_num_bytes_left() >= sizeof(int)); // Cast the buffer into an array of bool in order to grab the binary of // the bool for the next few bytes int *interpreted_buffer = reinterpret_cast<int *>(this->buffer + this->offset); int ret_value = interpreted_buffer[0]; // Update the offset to a new offset based off the string this->offset += sizeof(int); return ret_value; } double Deserializer::get_double() { assert(this->get_num_bytes_left() >= sizeof(double)); // Cast the buffer into an array of bool in order to grab the binary of // the bool for the next few bytes auto *interpreted_buffer = reinterpret_cast<double *>(this->buffer + this->offset); double ret_value = interpreted_buffer[0]; // Update the offset to a new offset based off the string this->offset += sizeof(double); return ret_value; }
24.949495
80
0.674696
jaspersong
00e0433befdba7565f18b0f2fb23b4261b581b4a
974
cpp
C++
software/src/master/src/kernel/Vca_IPeek.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
[ "BSD-3-Clause" ]
30
2016-10-07T15:23:35.000Z
2020-03-25T20:01:30.000Z
src/kernel/Vca_IPeek.cpp
MichaelJCaruso/vision-software-src-master
12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92
[ "BSD-3-Clause" ]
30
2016-10-31T19:48:08.000Z
2021-04-28T01:31:53.000Z
software/src/master/src/kernel/Vca_IPeek.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
[ "BSD-3-Clause" ]
15
2016-10-07T16:44:13.000Z
2021-06-21T18:47:55.000Z
/** * @file * Provides definition for IPeek interface. */ #define Vca_IPeek /************************ ************************ ***** Interfaces ***** ************************ ************************/ /******************** ***** System ***** ********************/ #include "Vk.h" /****************** ***** Self ***** ******************/ #include "Vca_IPeek.h" /************************ ***** Supporting ***** ************************/ #include "Vca_CompilerHappyPill.h" /************************ ************************ ***** ***** ***** Vca::IPeek ***** ***** ***** ************************ ************************/ VINTERFACE_TEMPLATE_EXPORTS (Vca::IPeek) namespace Vca { // {0B933950-2E07-44ed-9496-59D576836DC0} VINTERFACE_TYPEINFO_DEFINITION ( IPeek, 0xb933950, 0x2e07, 0x44ed, 0x94, 0x96, 0x59, 0xd5, 0x76, 0x83, 0x6d, 0xc0 ); VINTERFACE_MEMBERINFO_DEFINITION (IPeek, GetValue, 0); }
19.098039
74
0.370637
c-kuhlman
00e7418a63eea90d4710d80b149e5ec02ce5a367
594
hpp
C++
callgraph/detail/from_to_connector.hpp
anthony-arnold/callgraph
1d7fede6c31b9d9a0fc7f1b2358cb7204aff4e94
[ "BSD-2-Clause" ]
2
2020-12-04T11:20:44.000Z
2022-01-08T10:24:49.000Z
callgraph/detail/from_to_connector.hpp
anthony-arnold/callgraph
1d7fede6c31b9d9a0fc7f1b2358cb7204aff4e94
[ "BSD-2-Clause" ]
null
null
null
callgraph/detail/from_to_connector.hpp
anthony-arnold/callgraph
1d7fede6c31b9d9a0fc7f1b2358cb7204aff4e94
[ "BSD-2-Clause" ]
null
null
null
// callgraph/detail/from_to_connector.hpp // License: BSD-2-Clause #ifndef CALLGRAPH_DETAIL_FROM_TO_CONNECTOR_HPP #define CALLGRAPH_DETAIL_FROM_TO_CONNECTOR_HPP #include <callgraph/detail/base_connector.hpp> #ifndef NO_DOC namespace callgraph { namespace detail { template <typename T, size_t From, size_t To> class from_to_connector : public base_connector<T> { public: constexpr from_to_connector(T&& v) : base_connector<T>(std::forward<T>(v)) {} }; } } #endif // NO_DOC #endif // CALLGRAPH_DETAIL_FROM_TO_CONNECTOR_HPP
25.826087
60
0.70202
anthony-arnold
00e8912ce9cbe1f9011e3074d95b341886d6cebb
3,613
cpp
C++
lib/Transforms/BlockSeparator.cpp
compor/Atrox
d6e893f0c91764c58e198ccf316096b0ec9f7d90
[ "MIT" ]
null
null
null
lib/Transforms/BlockSeparator.cpp
compor/Atrox
d6e893f0c91764c58e198ccf316096b0ec9f7d90
[ "MIT" ]
null
null
null
lib/Transforms/BlockSeparator.cpp
compor/Atrox
d6e893f0c91764c58e198ccf316096b0ec9f7d90
[ "MIT" ]
null
null
null
// // // #include "Atrox/Transforms/BlockSeparator.hpp" #include "IteratorRecognition/Analysis/IteratorRecognition.hpp" #include "llvm/IR/BasicBlock.h" // using llvm::BasicBlock #include "llvm/IR/Instructions.h" // using llvm::BranchInst #include "llvm/IR/Dominators.h" // using llvm::DominatorTree #include "llvm/Analysis/LoopInfo.h" // using llvm::Loop // using llvm::LoopInfo #include "llvm/Transforms/Utils/BasicBlockUtils.h" // using llvm::SplitBlock #include "llvm/Support/Debug.h" // using LLVM_DEBUG macro // using llvm::dbgs #include <algorithm> // using std::reverse #include <iterator> // using std::prev #define DEBUG_TYPE "atrox-separator" namespace atrox { Mode GetMode(const llvm::Instruction &Inst, const llvm::Loop &CurLoop, const iteratorrecognition::IteratorInfo &Info) { return Info.isIterator(&Inst) ? Mode::Iterator : Mode::Payload; } bool FindPartitionPoints(const llvm::Loop &CurLoop, const iteratorrecognition::IteratorInfo &Info, BlockModeMapTy &Modes, BlockModeChangePointMapTy &Points) { for (auto bi = CurLoop.block_begin(), be = CurLoop.block_end(); bi != be; ++bi) { auto *bb = *bi; // auto firstI = bb->getFirstInsertionPt(); // auto lastSeenMode = InvertMode(GetMode(*firstI, CurLoop, Info)); bool hasAllSameModeInstructions = true; auto phisMode = GetMode(*bb->begin(), CurLoop, Info); for (auto &e : bb->phis()) { auto mode = GetMode(e, CurLoop, Info); if (phisMode != mode) { hasAllSameModeInstructions = false; break; } phisMode = mode; } // these are just for auto type deduction auto firstI = bb->getFirstInsertionPt(); auto lastSeenMode = GetMode(*firstI, CurLoop, Info); if (hasAllSameModeInstructions) { firstI = bb->begin(); lastSeenMode = GetMode(*firstI, CurLoop, Info); } else { firstI = bb->getFirstInsertionPt(); lastSeenMode = GetMode(*firstI, CurLoop, Info); auto modeChangePt = std::make_pair(&*firstI, InvertMode(lastSeenMode)); if (Points.find(bb) == Points.end()) Points.emplace(bb, std::vector<BlockModeChangePointTy>{}); Points.at(bb).push_back(modeChangePt); } hasAllSameModeInstructions = true; for (auto ii = firstI, ie = bb->end(); ii != ie; ++ii) { auto &inst = *ii; auto *br = llvm::dyn_cast<llvm::BranchInst>(&inst); bool isUncondBr = br && br->isUnconditional(); auto curMode = GetMode(inst, CurLoop, Info); if (lastSeenMode != curMode && !isUncondBr) { hasAllSameModeInstructions = false; auto modeChangePt = std::make_pair(&inst, curMode); if (Points.find(bb) == Points.end()) Points.emplace(bb, std::vector<BlockModeChangePointTy>{}); Points.at(bb).push_back(modeChangePt); lastSeenMode = curMode; } } if (hasAllSameModeInstructions) Modes.emplace(bb, lastSeenMode); } return !Points.empty(); } void SplitAtPartitionPoints(BlockModeChangePointMapTy &Points, BlockModeMapTy &Modes, llvm::DominatorTree *DT, llvm::LoopInfo *LI) { for (auto &e : Points) { auto *oldBB = e.first; Mode lastMode; std::reverse(e.second.begin(), e.second.end()); for (auto &k : e.second) { auto *splitI = k.first; lastMode = k.second; Modes.emplace(llvm::SplitBlock(oldBB, splitI, DT, LI), lastMode); } Modes.emplace(oldBB, InvertMode(lastMode)); } return; } } // namespace atrox
27.165414
77
0.634376
compor
00f3236832c39fe11d14eba4cc6a3c4ef88d8ce1
106
cpp
C++
InlineFunction/inline_functions.cpp
clemaitre58/LessonsCpp
a385b30c9ca970f0be68a781a55cfe409058aa05
[ "MIT" ]
null
null
null
InlineFunction/inline_functions.cpp
clemaitre58/LessonsCpp
a385b30c9ca970f0be68a781a55cfe409058aa05
[ "MIT" ]
null
null
null
InlineFunction/inline_functions.cpp
clemaitre58/LessonsCpp
a385b30c9ca970f0be68a781a55cfe409058aa05
[ "MIT" ]
5
2020-04-11T20:19:27.000Z
2020-04-14T04:20:19.000Z
#include "inline_function.h" namespace inline_function { int f2(const int & b) { return b + 2; } }
10.6
28
0.650943
clemaitre58
00f37d7fcff45d0055be0dcd39b51c78b43f1bff
2,645
hpp
C++
irob_utils/include/irob_utils/pose.hpp
BenGab/irob-saf
3a0fee98239bd935aa99c9d9526eb9b4cfc8963c
[ "MIT" ]
null
null
null
irob_utils/include/irob_utils/pose.hpp
BenGab/irob-saf
3a0fee98239bd935aa99c9d9526eb9b4cfc8963c
[ "MIT" ]
null
null
null
irob_utils/include/irob_utils/pose.hpp
BenGab/irob-saf
3a0fee98239bd935aa99c9d9526eb9b4cfc8963c
[ "MIT" ]
null
null
null
/* * pose.hpp * * Author(s): Tamas D. Nagy * Created on: 2016-10-27 * * Class to store and make calculations on a robot arm, * including the angle of the grippers. * */ #ifndef IROB_POSE_HPP_ #define IROB_POSE_HPP_ #include <iostream> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Transform.h> #include <std_msgs/Float32.h> #include <sensor_msgs/JointState.h> #include <Eigen/Dense> #include <Eigen/Geometry> #include <cmath> #include <irob_msgs/ToolPose.h> #include <irob_msgs/ToolPoseStamped.h> namespace saf { class Pose { public: struct Distance { double cartesian; double angle; double jaw; Distance operator*=(double); Distance operator/=(double); Distance operator*(double) const; Distance operator/(double) const; friend std::ostream& operator<<(std::ostream&, const Distance&); }; Eigen::Vector3d position; Eigen::Quaternion<double> orientation; double jaw; Pose(); Pose(double, double, double, double, double, double, double, double); Pose(const Pose&); Pose(const irob_msgs::ToolPose&); Pose(const irob_msgs::ToolPoseStamped&); Pose(const geometry_msgs::Pose&, double jaw); Pose(const geometry_msgs::PoseStamped&, double jaw); Pose(const Eigen::Vector3d&, const Eigen::Quaternion<double>&, double); Pose(const geometry_msgs::Point&, const Eigen::Quaternion<double>&, double); void swap(Pose&); Pose operator=(const Pose&); Pose operator+=(const Eigen::Vector3d&); Pose operator-=(const Eigen::Vector3d&); Pose operator+(const Eigen::Vector3d&) const; Pose operator-(const Eigen::Vector3d&) const; Pose interpolate(double, const Pose&) const; Pose rotate(const Eigen::Matrix3d&) const; Pose transform(const Eigen::Matrix3d&, const Eigen::Vector3d&, double = 1.0); Pose invTransform(const Eigen::Matrix3d&, const Eigen::Vector3d&, double = 1.0); Pose transform(const geometry_msgs::Transform&, double = 1.0); Pose invTransform(const geometry_msgs::Transform&, double = 1.0); bool isNaN() const; Distance dist(const Pose&) const; Distance dist(const Eigen::Vector3d&) const; Distance dist(const Eigen::Quaternion<double>&) const; Distance dist(double) const; irob_msgs::ToolPose toRosToolPose() const; geometry_msgs::Pose toRosPose() const; sensor_msgs::JointState toRosJaw() const; friend std::ostream& operator<<(std::ostream&, const Pose&); friend std::istream& operator>>(std::istream&, Pose&); }; } #endif
27.552083
84
0.675992
BenGab
00f8ee486d4ba99bb23fafc09b7e6bf10f4165f7
23,401
cc
C++
gazebo/common/Mesh.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
gazebo/common/Mesh.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
gazebo/common/Mesh.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <float.h> #include <string.h> #include <algorithm> #include "gazebo/math/Helpers.hh" #include "gazebo/common/Material.hh" #include "gazebo/common/Exception.hh" #include "gazebo/common/Console.hh" #include "gazebo/common/Mesh.hh" #include "gazebo/common/Skeleton.hh" #include "gazebo/gazebo_config.h" using namespace gazebo; using namespace common; ////////////////////////////////////////////////// Mesh::Mesh() { this->name = "unknown"; this->skeleton = NULL; } ////////////////////////////////////////////////// Mesh::~Mesh() { for (std::vector<SubMesh*>::iterator iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { delete *iter; } this->submeshes.clear(); for (std::vector<Material*>::iterator iter = this->materials.begin(); iter != this->materials.end(); ++iter) { delete *iter; } this->materials.clear(); delete this->skeleton; } ////////////////////////////////////////////////// void Mesh::SetPath(const std::string &_path) { this->path = _path; } ////////////////////////////////////////////////// std::string Mesh::GetPath() const { return this->path; } ////////////////////////////////////////////////// void Mesh::SetName(const std::string &_n) { this->name = _n; } ////////////////////////////////////////////////// std::string Mesh::GetName() const { return this->name; } ////////////////////////////////////////////////// ignition::math::Vector3d Mesh::Max() const { ignition::math::Vector3d max; std::vector<SubMesh*>::const_iterator iter; max.X(-FLT_MAX); max.Y(-FLT_MAX); max.Z(-FLT_MAX); for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; ignition::math::Vector3d smax = (*iter)->Max(); max.X(std::max(max.X(), smax.X())); max.Y(std::max(max.Y(), smax.Y())); max.Z(std::max(max.Z(), smax.Z())); } return max; } ////////////////////////////////////////////////// ignition::math::Vector3d Mesh::Min() const { ignition::math::Vector3d min; std::vector<SubMesh *>::const_iterator iter; min.X(FLT_MAX); min.Y(FLT_MAX); min.Z(FLT_MAX); for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; ignition::math::Vector3d smin = (*iter)->Min(); min.X(std::min(min.X(), smin.X())); min.Y(std::min(min.Y(), smin.Y())); min.Z(std::min(min.Z(), smin.Z())); } return min; } ////////////////////////////////////////////////// unsigned int Mesh::GetVertexCount() const { unsigned int sum = 0; std::vector<SubMesh *>::const_iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; sum += (*iter)->GetVertexCount(); } return sum; } ////////////////////////////////////////////////// unsigned int Mesh::GetNormalCount() const { unsigned int sum = 0; std::vector<SubMesh *>::const_iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; sum += (*iter)->GetNormalCount(); } return sum; } ////////////////////////////////////////////////// unsigned int Mesh::GetIndexCount() const { unsigned int sum = 0; std::vector<SubMesh *>::const_iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; sum += (*iter)->GetIndexCount(); } return sum; } ////////////////////////////////////////////////// unsigned int Mesh::GetTexCoordCount() const { unsigned int sum = 0; std::vector<SubMesh *>::const_iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; sum += (*iter)->GetTexCoordCount(); } return sum; } ////////////////////////////////////////////////// void Mesh::AddSubMesh(SubMesh *_sub) { this->submeshes.push_back(_sub); } ////////////////////////////////////////////////// unsigned int Mesh::GetSubMeshCount() const { return this->submeshes.size(); } ////////////////////////////////////////////////// const SubMesh *Mesh::GetSubMesh(unsigned int i) const { if (i < this->submeshes.size()) return this->submeshes[i]; else gzthrow("Invalid index: " << i << " >= " << this->submeshes.size() << "\n"); } ////////////////////////////////////////////////// const SubMesh *Mesh::GetSubMesh(const std::string &_name) const { // Find the submesh with the provided name. for (std::vector<SubMesh *>::const_iterator iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetName() == _name) return *iter; } return NULL; } ////////////////////////////////////////////////// int Mesh::AddMaterial(Material *_mat) { int result = -1; if (_mat) { this->materials.push_back(_mat); result = this->materials.size()-1; } return result; } ////////////////////////////////////////////////// unsigned int Mesh::GetMaterialCount() const { return this->materials.size(); } ////////////////////////////////////////////////// const Material *Mesh::GetMaterial(int index) const { if (index >= 0 && index < static_cast<int>(this->materials.size())) return this->materials[index]; return NULL; } ////////////////////////////////////////////////// int Mesh::GetMaterialIndex(const Material *_mat) const { for (unsigned int i = 0; i < this->materials.size(); ++i) { if (this->materials[i] == _mat) return i; } return -1; } ////////////////////////////////////////////////// void Mesh::FillArrays(float **_vertArr, int **_indArr) const { std::vector<SubMesh *>::const_iterator iter; unsigned int vertCount = 0; unsigned int indCount = 0; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; vertCount += (*iter)->GetVertexCount(); indCount += (*iter)->GetIndexCount(); } if (*_vertArr) delete [] *_vertArr; if (*_indArr) delete [] *_indArr; *_vertArr = new float[vertCount * 3]; *_indArr = new int[indCount]; float *vPtr = *_vertArr; unsigned int index = 0; unsigned int offset = 0; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; float *vertTmp = NULL; int *indTmp = NULL; (*iter)->FillArrays(&vertTmp, &indTmp); memcpy(vPtr, vertTmp, sizeof(vertTmp[0])*(*iter)->GetVertexCount()*3); for (unsigned int i = 0; i < (*iter)->GetIndexCount(); ++i) { (*_indArr)[index++] = (*iter)->GetIndex(i) + offset; } offset = offset + (*iter)->GetMaxIndex() + 1; vPtr += (*iter)->GetVertexCount()*3; delete [] vertTmp; delete [] indTmp; } } ////////////////////////////////////////////////// void Mesh::RecalculateNormals() { std::vector<SubMesh*>::iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) (*iter)->RecalculateNormals(); } ////////////////////////////////////////////////// void Mesh::SetSkeleton(Skeleton* _skel) { this->skeleton = _skel; } ////////////////////////////////////////////////// Skeleton* Mesh::GetSkeleton() const { return this->skeleton; } ////////////////////////////////////////////////// bool Mesh::HasSkeleton() const { if (this->skeleton) return true; else return false; } ////////////////////////////////////////////////// void Mesh::Scale(double _factor) { std::vector<SubMesh*>::iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) (*iter)->Scale(_factor); } ////////////////////////////////////////////////// void Mesh::SetScale(const ignition::math::Vector3d &_factor) { std::vector<SubMesh*>::iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) (*iter)->SetScale(_factor); } ////////////////////////////////////////////////// void Mesh::GenSphericalTexCoord(const ignition::math::Vector3d &_center) { std::vector<SubMesh*>::iterator siter; for (siter = this->submeshes.begin(); siter != this->submeshes.end(); ++siter) (*siter)->GenSphericalTexCoord(_center); } ////////////////////////////////////////////////// void Mesh::Center(const ignition::math::Vector3d &_center) { ignition::math::Vector3d min, max, half; min = this->Min(); max = this->Max(); half = (max - min) * 0.5; this->Translate(_center - (min + half)); } ////////////////////////////////////////////////// void Mesh::Translate(const ignition::math::Vector3d &_vec) { std::vector<SubMesh*>::iterator iter; for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter) { if ((*iter)->GetVertexCount() <= 2) continue; (*iter)->Translate(_vec); } } ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// SubMesh::SubMesh() { this->materialIndex = -1; this->primitiveType = TRIANGLES; } ////////////////////////////////////////////////// SubMesh::SubMesh(const SubMesh *_mesh) { if (!_mesh) { gzerr << "Submesh is NULL." << std::endl; return; } this->name = _mesh->name; this->materialIndex = _mesh->materialIndex; this->primitiveType = _mesh->primitiveType; std::copy(_mesh->nodeAssignments.begin(), _mesh->nodeAssignments.end(), std::back_inserter(this->nodeAssignments)); std::copy(_mesh->indices.begin(), _mesh->indices.end(), std::back_inserter(this->indices)); std::copy(_mesh->normals.begin(), _mesh->normals.end(), std::back_inserter(this->normals)); std::copy(_mesh->texCoords.begin(), _mesh->texCoords.end(), std::back_inserter(this->texCoords)); std::copy(_mesh->vertices.begin(), _mesh->vertices.end(), std::back_inserter(this->vertices)); } ////////////////////////////////////////////////// SubMesh::~SubMesh() { this->vertices.clear(); this->indices.clear(); this->nodeAssignments.clear(); } ////////////////////////////////////////////////// void SubMesh::SetPrimitiveType(PrimitiveType _type) { this->primitiveType = _type; } ////////////////////////////////////////////////// SubMesh::PrimitiveType SubMesh::GetPrimitiveType() const { return this->primitiveType; } ////////////////////////////////////////////////// void SubMesh::CopyVertices(const std::vector<ignition::math::Vector3d> &_verts) { this->vertices.clear(); this->vertices.resize(_verts.size()); std::copy(_verts.begin(), _verts.end(), this->vertices.begin()); } ////////////////////////////////////////////////// void SubMesh::CopyNormals(const std::vector<ignition::math::Vector3d> &_norms) { this->normals.clear(); this->normals.resize(_norms.size()); for (unsigned int i = 0; i < _norms.size(); ++i) { this->normals[i] = _norms[i]; this->normals[i].Normalize(); if (ignition::math::equal(this->normals[i].Length(), 0.0)) { this->normals[i].Set(0, 0, 1); } } } ////////////////////////////////////////////////// void SubMesh::SetVertexCount(unsigned int _count) { this->vertices.resize(_count); } ////////////////////////////////////////////////// void SubMesh::SetIndexCount(unsigned int _count) { this->indices.resize(_count); } ////////////////////////////////////////////////// void SubMesh::SetNormalCount(unsigned int _count) { this->normals.resize(_count); } ////////////////////////////////////////////////// void SubMesh::SetTexCoordCount(unsigned int _count) { this->texCoords.resize(_count); } ////////////////////////////////////////////////// void SubMesh::AddIndex(unsigned int _i) { this->indices.push_back(_i); } ////////////////////////////////////////////////// void SubMesh::AddVertex(const ignition::math::Vector3d &_v) { this->vertices.push_back(_v); } ////////////////////////////////////////////////// void SubMesh::AddVertex(double _x, double _y, double _z) { this->AddVertex(ignition::math::Vector3d(_x, _y, _z)); } ////////////////////////////////////////////////// void SubMesh::AddNormal(const ignition::math::Vector3d &_n) { this->normals.push_back(_n); } ////////////////////////////////////////////////// void SubMesh::AddNormal(double _x, double _y, double _z) { this->AddNormal(ignition::math::Vector3d(_x, _y, _z)); } ////////////////////////////////////////////////// void SubMesh::AddTexCoord(double _u, double _v) { this->texCoords.push_back(ignition::math::Vector2d(_u, _v)); } ////////////////////////////////////////////////// void SubMesh::AddNodeAssignment(unsigned int _vertex, unsigned int _node, float _weight) { NodeAssignment na; na.vertexIndex = _vertex; na.nodeIndex = _node; na.weight = _weight; this->nodeAssignments.push_back(na); } ////////////////////////////////////////////////// ignition::math::Vector3d SubMesh::Vertex(unsigned int _i) const { if (_i >= this->vertices.size()) gzthrow("Index too large"); return this->vertices[_i]; } ////////////////////////////////////////////////// void SubMesh::SetVertex(unsigned int _i, const ignition::math::Vector3d &_v) { if (_i >= this->vertices.size()) gzthrow("Index too large"); this->vertices[_i] = _v; } ////////////////////////////////////////////////// ignition::math::Vector3d SubMesh::Normal(unsigned int _i) const { if (_i >= this->normals.size()) gzthrow("Index too large"); return this->normals[_i]; } ////////////////////////////////////////////////// void SubMesh::SetNormal(unsigned int _i, const ignition::math::Vector3d &_n) { if (_i >= this->normals.size()) gzthrow("Index too large"); this->normals[_i] = _n; } ////////////////////////////////////////////////// ignition::math::Vector2d SubMesh::TexCoord(unsigned int _i) const { if (_i >= this->texCoords.size()) gzthrow("Index too large"); return this->texCoords[_i]; } ////////////////////////////////////////////////// NodeAssignment SubMesh::GetNodeAssignment(unsigned int _i) const { if (_i >= this->nodeAssignments.size()) gzthrow("Index too large"); return this->nodeAssignments[_i]; } ////////////////////////////////////////////////// void SubMesh::SetTexCoord(unsigned int _i, const ignition::math::Vector2d &_t) { if (_i >= this->texCoords.size()) gzthrow("Index too large"); this->texCoords[_i] = _t; } ////////////////////////////////////////////////// unsigned int SubMesh::GetIndex(unsigned int _i) const { if (_i > this->indices.size()) gzthrow("Index too large"); return this->indices[_i]; } ////////////////////////////////////////////////// ignition::math::Vector3d SubMesh::Max() const { ignition::math::Vector3d max; std::vector<ignition::math::Vector3d>::const_iterator iter; max.X(-FLT_MAX); max.Y(-FLT_MAX); max.Z(-FLT_MAX); for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter) { max.X(std::max(max.X(), (*iter).X())); max.Y(std::max(max.Y(), (*iter).Y())); max.Z(std::max(max.Z(), (*iter).Z())); } return max; } ////////////////////////////////////////////////// ignition::math::Vector3d SubMesh::Min() const { ignition::math::Vector3d min; std::vector<ignition::math::Vector3d>::const_iterator iter; min.X(FLT_MAX); min.Y(FLT_MAX); min.Z(FLT_MAX); for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter) { min.X(std::min(min.X(), (*iter).X())); min.Y(std::min(min.Y(), (*iter).Y())); min.Z(std::min(min.Z(), (*iter).Z())); } return min; } ////////////////////////////////////////////////// unsigned int SubMesh::GetVertexCount() const { return this->vertices.size(); } ////////////////////////////////////////////////// unsigned int SubMesh::GetNormalCount() const { return this->normals.size(); } ////////////////////////////////////////////////// unsigned int SubMesh::GetIndexCount() const { return this->indices.size(); } ////////////////////////////////////////////////// unsigned int SubMesh::GetTexCoordCount() const { return this->texCoords.size(); } ////////////////////////////////////////////////// unsigned int SubMesh::GetNodeAssignmentsCount() const { return this->nodeAssignments.size(); } ////////////////////////////////////////////////// unsigned int SubMesh::GetMaxIndex() const { std::vector<unsigned int>::const_iterator maxIter; maxIter = std::max_element(this->indices.begin(), this->indices.end()); if (maxIter != this->indices.end()) return *maxIter; return 0; } ////////////////////////////////////////////////// void SubMesh::SetMaterialIndex(unsigned int _index) { this->materialIndex = _index; } ////////////////////////////////////////////////// unsigned int SubMesh::GetMaterialIndex() const { return this->materialIndex; } ////////////////////////////////////////////////// bool SubMesh::HasVertex(const ignition::math::Vector3d &_v) const { std::vector< ignition::math::Vector3d >::const_iterator iter; for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter) if (_v.Equal(*iter)) return true; return false; } ////////////////////////////////////////////////// unsigned int SubMesh::GetVertexIndex(const ignition::math::Vector3d &_v) const { std::vector< ignition::math::Vector3d >::const_iterator iter; for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter) if (_v.Equal(*iter)) return iter - this->vertices.begin(); return 0; } ////////////////////////////////////////////////// void SubMesh::FillArrays(float **_vertArr, int **_indArr) const { if (this->vertices.empty() || this->indices.empty()) gzerr << "No vertices or indices\n"; std::vector<ignition::math::Vector3d>::const_iterator viter; std::vector<unsigned int>::const_iterator iiter; unsigned int i; if (*_vertArr) delete [] *_vertArr; if (*_indArr) delete [] *_indArr; *_vertArr = new float[this->vertices.size() * 3]; *_indArr = new int[this->indices.size()]; for (viter = this->vertices.begin(), i = 0; viter != this->vertices.end(); ++viter) { (*_vertArr)[i++] = static_cast<float>((*viter).X()); (*_vertArr)[i++] = static_cast<float>((*viter).Y()); (*_vertArr)[i++] = static_cast<float>((*viter).Z()); } for (iiter = this->indices.begin(), i = 0; iiter != this->indices.end(); ++iiter) { (*_indArr)[i++] = (*iiter); } } ////////////////////////////////////////////////// void SubMesh::RecalculateNormals() { unsigned int i; if (normals.size() < 3) return; // Reset all the normals for (i = 0; i < this->normals.size(); ++i) this->normals[i].Set(0, 0, 0); if (this->normals.size() != this->vertices.size()) this->normals.resize(this->vertices.size()); // For each face, which is defined by three indices, calculate the normals for (i = 0; i < this->indices.size(); i+= 3) { ignition::math::Vector3d v1 = this->vertices[this->indices[i]]; ignition::math::Vector3d v2 = this->vertices[this->indices[i+1]]; ignition::math::Vector3d v3 = this->vertices[this->indices[i+2]]; ignition::math::Vector3d n = ignition::math::Vector3d::Normal(v1, v2, v3); for (unsigned int j = 0; j< this->vertices.size(); ++j) { if (this->vertices[j] == v1 || this->vertices[j] == v2 || this->vertices[j] == v3) { this->normals[j] += n; } } } // Normalize the results for (i = 0; i < this->normals.size(); ++i) { this->normals[i].Normalize(); } } ////////////////////////////////////////////////// void Mesh::GetAABB(ignition::math::Vector3d &_center, ignition::math::Vector3d &_minXYZ, ignition::math::Vector3d &_maxXYZ) const { // find aabb center _minXYZ.X(1e15); _maxXYZ.X(-1e15); _minXYZ.Y(1e15); _maxXYZ.Y(-1e15); _minXYZ.Z(1e15); _maxXYZ.Z(-1e15); _center.X(0); _center.Y(0); _center.Z(0); std::vector<SubMesh*>::const_iterator siter; for (siter = this->submeshes.begin(); siter != this->submeshes.end(); ++siter) { ignition::math::Vector3d max = (*siter)->Max(); ignition::math::Vector3d min = (*siter)->Min(); _minXYZ.X(std::min(_minXYZ.X(), min.X())); _maxXYZ.X(std::max(_maxXYZ.X(), max.X())); _minXYZ.Y(std::min(_minXYZ.Y(), min.Y())); _maxXYZ.Y(std::max(_maxXYZ.Y(), max.Y())); _minXYZ.Z(std::min(_minXYZ.Z(), min.Z())); _maxXYZ.Z(std::max(_maxXYZ.Z(), max.Z())); } _center.X(0.5 * (_minXYZ.X() + _maxXYZ.X())); _center.Y(0.5 * (_minXYZ.Y() + _maxXYZ.Y())); _center.Z(0.5 * (_minXYZ.Z() + _maxXYZ.Z())); } ////////////////////////////////////////////////// void SubMesh::GenSphericalTexCoord(const ignition::math::Vector3d &_center) { std::vector<ignition::math::Vector3d>::const_iterator viter; for (viter = this->vertices.begin(); viter != this->vertices.end(); ++viter) { // generate projected texture coordinates, projected from center // get x, y, z for computing texture coordinate projections double x = (*viter).X() - _center.X(); double y = (*viter).Y() - _center.Y(); double z = (*viter).Z() - _center.Z(); double r = std::max(0.000001, sqrt(x*x+y*y+z*z)); double s = std::min(1.0, std::max(-1.0, z/r)); double t = std::min(1.0, std::max(-1.0, y/r)); double u = acos(s) / M_PI; double v = acos(t) / M_PI; this->AddTexCoord(u, v); } } ////////////////////////////////////////////////// void SubMesh::Scale(double _factor) { for (auto &vert : this->vertices) vert *= _factor; } ////////////////////////////////////////////////// void SubMesh::SetScale(const ignition::math::Vector3d &_factor) { for (auto &vert : this->vertices) vert *= _factor; } ////////////////////////////////////////////////// void SubMesh::Center(const ignition::math::Vector3d &_center) { ignition::math::Vector3d min, max, half; min = this->Min(); max = this->Max(); half = (max - min) * 0.5; this->Translate(_center - (min + half)); } ////////////////////////////////////////////////// void SubMesh::Translate(const ignition::math::Vector3d &_vec) { for (auto &vert : this->vertices) vert += _vec; } ////////////////////////////////////////////////// void SubMesh::SetName(const std::string &_n) { this->name = _n; } ////////////////////////////////////////////////// std::string SubMesh::GetName() const { return this->name; } ////////////////////////////////////////////////// NodeAssignment::NodeAssignment() : vertexIndex(0), nodeIndex(0), weight(0.0) { }
25.271058
80
0.524465
otamachan
00fed53ddd8627733c2a7af5922dfb3cd3de868e
4,491
cpp
C++
CsPlayback/Source/CsPlayback/Public/Managers/Playback/CsConsoleCommand_Manager_Playback.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlayback/Source/CsPlayback/Public/Managers/Playback/CsConsoleCommand_Manager_Playback.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlayback/Source/CsPlayback/Public/Managers/Playback/CsConsoleCommand_Manager_Playback.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, Inc. All rights reserved. #include "Managers/Playback/CsConsoleCommand_Manager_Playback.h" #include "CsPlayback.h" // Library #include "Library/CsLibrary_String.h" #include "ConsoleCommand/CsLibrary_ConsoleCommand.h" #include "Library/CsLibrary_Valid.h" #include "Managers/Playback/CsLibrary_Manager_Playback.h" // Utility #include "Utility/CsPlaybackLog.h" // Coordinators #include "Coordinators/ConsoleCommand/CsCoordinator_ConsoleCommand.h" namespace NCsPlayback { namespace NManager { namespace NConsoleCommand { namespace NCached { namespace Str { CSPLAYBACK_API const FString CategoryName = TEXT("Manager_Playback"); CS_DEFINE_FUNCTION_NAME_AS_STRING(NCsPlayback::NManager::FConsoleCommand, Exec_PlayLatest); } } } // Enum #pragma region // FConsoleCommand::ECommand #define CS_TEMP_ADD_TO_ENUM_MAP(EnumElementName) const FConsoleCommand::ECommand FConsoleCommand::NCommand::EnumElementName = FConsoleCommand::EMCommand::Get().Add(FConsoleCommand::ECommand::EnumElementName, #EnumElementName) CS_TEMP_ADD_TO_ENUM_MAP(PlayLatest); #undef CS_TEMP_ADD_TO_ENUM_MAP #pragma endregion Enum FConsoleCommand::FConsoleCommand(UObject* InRoot) { MyRoot = InRoot; UCsCoordinator_ConsoleCommand* Coordinator_ConsoleCommand = UCsCoordinator_ConsoleCommand::Get(MyRoot->GetWorld()->GetGameInstance()); Handle = Coordinator_ConsoleCommand->AddManager(this); OnDeconstruct_Event.BindUObject(Coordinator_ConsoleCommand, &UCsCoordinator_ConsoleCommand::OnDeconstructManager); typedef NCsConsoleCommand::FInfo InfoType; CommandInfos.Reset(); // Populate CommandInfos { const int32& Count = EMCommand::Get().Num(); CommandInfos.Reserve(Count); // Play Latest { CommandInfos.AddDefaulted(); InfoType& Info = CommandInfos.Last(); Info.PrimaryDefinitionIndex = 0; TArray<FString> Base; Base.Add(TEXT("ManagerPlaybackPlayLatest")); Base.Add(TEXT("ManagerPlayback PlayLatest")); Base.Add(TEXT("ManagerPlayback Play Latest")); Base.Add(TEXT("Manager Playback PlayLatest")); Base.Add(TEXT("Manager Playback Play Latest")); // Commands { TArray<FString>& Commands = Info.Commands; Commands.Reset(Base.Num()); for (FString& Str : Base) { Commands.Add(Str.ToLower()); } } // Definitions { TArray<FString>& Definitions = Info.Definitions; Definitions.Reset(Base.Num()); for (FString& Str : Base) { Definitions.Add(Str); } } // Description { FString& Description = Info.Description; Description += TEXT("Call the command Spawn.\n"); Description += TEXT("- Checks for the following console commands:\n"); for (FString& Str : Info.Definitions) { Description += TEXT("-- ") + Str + TEXT("\n"); } } } } } FConsoleCommand::~FConsoleCommand() { OnDeconstruct_Event.Execute(this, Handle); } // ConsoleCommandManagerType (NCsConsoleCommand::NManager::IManager) #pragma region bool FConsoleCommand::Exec(UWorld* InWorld, const TCHAR* Cmd, FOutputDevice& Out /*=*GLog*/) { // ManagerPlaybackPlayLatest // ManagerPlayback PlayLatest // ManagerPlayback Play Latest // Manager Playback PlayLatest // Manager Playback Play Latest if (Exec_PlayLatest(Cmd)) return true; return false; } #pragma endregion ConsoleCommandManagerType (NCsConsoleCommand::NManager::IManager) bool FConsoleCommand::Exec_PlayLatest(const TCHAR* Cmd) { using namespace NConsoleCommand::NCached; const FString& Context = Str::Exec_PlayLatest; void(*Log)(const FString&) = &NCsPlayback::FLog::Warning; FString OutString; FParse::Line(&Cmd, OutString, true); OutString.ToLower(); const TArray<FString>& Commands = CommandInfos[(uint8)ECommand::PlayLatest].Commands; const TArray<FString>& Definitions = CommandInfos[(uint8)ECommand::PlayLatest].Definitions; const int32 Count = Commands.Num(); for (int32 I = 0; I < Count; ++I) { const FString& Command = Commands[I]; const FString& Definition = Definitions[I]; if (OutString.RemoveFromStart(Command)) { CS_IS_PTR_NULL(MyRoot) typedef NCsPlayback::NManager::NPlayback::FLibrary PlaybackLibrary; PlaybackLibrary::SafePlayLatest(Context, MyRoot); return true; } } return false; } } }
26.263158
227
0.701403
closedsum
2e0291cdbfd04525931fa716a2d277b6793cab84
17,411
cpp
C++
JHSeng's work/report/src/USBCore.cpp
JHSeng/ros_experiment
d5ec652e8f2d79e76b896b69757090d953ff6653
[ "MIT" ]
null
null
null
JHSeng's work/report/src/USBCore.cpp
JHSeng/ros_experiment
d5ec652e8f2d79e76b896b69757090d953ff6653
[ "MIT" ]
null
null
null
JHSeng's work/report/src/USBCore.cpp
JHSeng/ros_experiment
d5ec652e8f2d79e76b896b69757090d953ff6653
[ "MIT" ]
null
null
null
#include "USBAPI.h" #include "PluggableUSB.h" #include <stdlib.h> #if defined(USBCON) /**脉冲生成计数器,用于跟踪每种脉冲类型剩余的毫秒数*/ #define TX_RX_LED_PULSE_MS 100 volatile u8 TxLEDPulse; /** <数据Tx LED脉冲剩余的毫秒数*/ volatile u8 RxLEDPulse; /** <剩余的毫秒数用于数据接收LED脉冲*/ extern const u16 STRING_LANGUAGE[] PROGMEM; extern const u8 STRING_PRODUCT[] PROGMEM; extern const u8 STRING_MANUFACTURER[] PROGMEM; extern const DeviceDescriptor USB_DeviceDescriptorIAD PROGMEM; const u16 STRING_LANGUAGE[2] = { (3 << 8) | (2 + 2), 0x0409 // English }; #ifndef USB_PRODUCT // 如果未提供产品,使用USB IO板 #define USB_PRODUCT "USB IO Board" #endif const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT; #if USB_VID == 0x2341 # if defined(USB_MANUFACTURER) # undef USB_MANUFACTURER # endif # define USB_MANUFACTURER "Arduino LLC" #elif USB_VID == 0x1b4f # if defined(USB_MANUFACTURER) # undef USB_MANUFACTURER # endif # define USB_MANUFACTURER "SparkFun" #elif !defined(USB_MANUFACTURER) // 如果宏中未提供制造商名称,则失败 # define USB_MANUFACTURER "Unknown" #endif const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER; #define DEVICE_CLASS 0x02 // 设备描述器 const DeviceDescriptor USB_DeviceDescriptorIAD = D_DEVICE(0xEF, 0x02, 0x01, 64, USB_VID, USB_PID, 0x100, IMANUFACTURER, IPRODUCT, ISERIAL, 1); volatile u8 _usbConfiguration = 0; volatile u8 _usbCurrentStatus = 0; // 由GetStatus()请求返回到设备的信息 volatile u8 _usbSuspendState = 0; // UDINT的副本以检查SUSPI和WAKEUPI位 static inline void WaitIN(void) { while (!(UEINTX & (1 << TXINI))); } static inline void ClearIN(void) { UEINTX = ~(1 << TXINI); } static inline void WaitOUT(void) { while (!(UEINTX & (1 << RXOUTI))); } static inline u8 WaitForINOrOUT() { while (!(UEINTX & ((1 << TXINI) | (1 << RXOUTI)))); return (UEINTX & (1 << RXOUTI)) == 0; } static inline void ClearOUT(void) { UEINTX = ~(1 << RXOUTI); } static inline void Recv(volatile u8 *data, u8 count) { while (count--) *data++ = UEDATX; RXLED1; // 点亮RX LED RxLEDPulse = TX_RX_LED_PULSE_MS; } static inline u8 Recv8() { RXLED1; // 点亮RX LED RxLEDPulse = TX_RX_LED_PULSE_MS; return UEDATX; } static inline void Send8(u8 d) { UEDATX = d; } static inline void SetEP(u8 ep) { UENUM = ep; } static inline u8 FifoByteCount() { return UEBCLX; } static inline u8 ReceivedSetupInt() { return UEINTX & (1 << RXSTPI); } static inline void ClearSetupInt() { UEINTX = ~((1 << RXSTPI) | (1 << RXOUTI) | (1 << TXINI)); } static inline void Stall() { UECONX = (1 << STALLRQ) | (1 << EPEN); } static inline u8 ReadWriteAllowed() { return UEINTX & (1 << RWAL); } static inline u8 Stalled() { return UEINTX & (1 << STALLEDI); } static inline u8 FifoFree() { return UEINTX & (1 << FIFOCON); } static inline void ReleaseRX() { UEINTX = 0x6B; // FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1 } static inline void ReleaseTX() { UEINTX = 0x3A; // FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0 } static inline u8 FrameNumber() { return UDFNUML; } u8 USBGetConfiguration(void) { return _usbConfiguration; } #define USB_RECV_TIMEOUT class LockEP { u8 _sreg; public: LockEP(u8 ep) : _sreg(SREG) { cli(); SetEP(ep & 7); } ~LockEP() { SREG = _sreg; } }; // 字节数(假设为RX端点) u8 USB_Available(u8 ep) { LockEP lock(ep); return FifoByteCount(); } // 非阻塞接收 // 返回读取的字节数 int USB_Recv(u8 ep, void *d, int len) { if (!_usbConfiguration || len < 0) return -1; LockEP lock(ep); u8 n = FifoByteCount(); len = min(n, len); n = len; u8 *dst = (u8 *)d; while (n--) *dst++ = Recv8(); // 释放空缓冲区 if (len && !FifoByteCount()) ReleaseRX(); return len; } // 如果准备好,接收1byte int USB_Recv(u8 ep) { u8 c; if (USB_Recv(ep, &c, 1) != 1) return -1; return c; } // 发送EP的空间 u8 USB_SendSpace(u8 ep) { LockEP lock(ep); if (!ReadWriteAllowed()) return 0; return USB_EP_SIZE - FifoByteCount(); } // 禁止向端点发送数据 int USB_Send(u8 ep, const void *d, int len) { if (!_usbConfiguration) return -1; if (_usbSuspendState & (1 << SUSPI)) { // 发送远程唤醒 UDCON |= (1 << RMWKUP); } int r = len; const u8 *data = (const u8 *)d; u8 timeout = 250; // 250ms超时则再次发送 bool sendZlp = false; while (len || sendZlp) { u8 n = USB_SendSpace(ep); if (n == 0) { if (!(--timeout)) return -1; delay(1); continue; } if (n > len) n = len; { LockEP lock(ep); // SOF中断处理程序可能已释放帧 if (!ReadWriteAllowed()) continue; len -= n; if (ep & TRANSFER_ZERO) { while (n--) Send8(0); } else if (ep & TRANSFER_PGM) { while (n--) Send8(pgm_read_byte(data++)); } else { while (n--) Send8(*data++); } if (sendZlp) { ReleaseTX(); sendZlp = false; } else if (!ReadWriteAllowed()) { // 如果缓冲区满,释放之 ReleaseTX(); if (len == 0) sendZlp = true; } else if ((len == 0) && (ep & TRANSFER_RELEASE)) { // 用TRANSFER_RELEASE强行释放 // 从未使用过TRANSFER_RELEASE,是否可以删除? ReleaseTX(); } } } TXLED1; // 点亮TX LED TxLEDPulse = TX_RX_LED_PULSE_MS; return r; } u8 _initEndpoints[USB_ENDPOINTS] = { 0, // 控制端点 EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN // 接下来的端点都被初始化为0 }; #define EP_SINGLE_64 0x32 // EP0 #define EP_DOUBLE_64 0x36 // 其他端点 #define EP_SINGLE_16 0x12 static void InitEP(u8 index, u8 type, u8 size) { UENUM = index; UECONX = (1 << EPEN); UECFG0X = type; UECFG1X = size; } static void InitEndpoints() { for (u8 i = 1; i < sizeof(_initEndpoints) && _initEndpoints[i] != 0; i++) { UENUM = i; UECONX = (1 << EPEN); UECFG0X = _initEndpoints[i]; #if USB_EP_SIZE == 16 UECFG1X = EP_SINGLE_16; #elif USB_EP_SIZE == 64 UECFG1X = EP_DOUBLE_64; #else #error Unsupported value for USB_EP_SIZE #endif } UERST = 0x7E; // 重置它们 UERST = 0; } // 处理CLASS_INTERFACE请求 static bool ClassInterfaceRequest(USBSetup &setup) { u8 i = setup.wIndex; if (CDC_ACM_INTERFACE == i) return CDC_Setup(setup); #ifdef PLUGGABLE_USB_ENABLED return PluggableUSB().setup(setup); #endif return false; } static int _cmark; static int _cend; void InitControl(int end) { SetEP(0); _cmark = 0; _cend = end; } static bool SendControl(u8 d) { if (_cmark < _cend) { if (!WaitForINOrOUT()) return false; Send8(d); if (!((_cmark + 1) & 0x3F)) ClearIN(); // fifo满,释放之 } _cmark++; return true; } // 被_cmark / _cend裁剪 int USB_SendControl(u8 flags, const void *d, int len) { int sent = len; const u8 *data = (const u8 *)d; bool pgm = flags & TRANSFER_PGM; while (len--) { u8 c = pgm ? pgm_read_byte(data++) : *data++; if (!SendControl(c)) return -1; } return sent; } // 发送USB描述符字符串。该字符串作为一个纯ASCII字符串存储在PROGMEM中,以正确的2字节作为UTF-16发送字首 static bool USB_SendStringDescriptor(const u8 *string_P, u8 string_len, uint8_t flags) { SendControl(2 + string_len * 2); SendControl(3); bool pgm = flags & TRANSFER_PGM; for (u8 i = 0; i < string_len; i++) { bool r = SendControl(pgm ? pgm_read_byte(&string_P[i]) : string_P[i]); r &= SendControl(0); // 高位 if (!r) return false; } return true; } // 不会超时或跨越FIFO边界 int USB_RecvControl(void *d, int len) { auto length = len; while (length) { // 收到的收益不超过USB Control EP所能提供的。使用固定的64,因为控制EP即使在16u2上也始终具有64个字节。 auto recvLength = length; if (recvLength > 64) recvLength = 64; // 写入数据以适合数组的结尾(而不是开头) WaitOUT(); Recv((u8 *)d + len - length, recvLength); ClearOUT(); length -= recvLength; } return len; } static u8 SendInterfaces() { u8 interfaces = 0; CDC_GetInterface(&interfaces); #ifdef PLUGGABLE_USB_ENABLED PluggableUSB().getInterface(&interfaces); #endif return interfaces; } // 构造动态配置描述符,需要动态的端点分配等 static bool SendConfiguration(int maxlen) { // 计数和度量接口 InitControl(0); u8 interfaces = SendInterfaces(); ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor), interfaces); // 发送数据 InitControl(maxlen); USB_SendControl(0, &config, sizeof(ConfigDescriptor)); SendInterfaces(); return true; } static bool SendDescriptor(USBSetup &setup) { int ret; u8 t = setup.wValueH; if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t) return SendConfiguration(setup.wLength); InitControl(setup.wLength); #ifdef PLUGGABLE_USB_ENABLED ret = PluggableUSB().getDescriptor(setup); if (ret != 0) return (ret > 0 ? true : false); #endif const u8 *desc_addr = 0; if (USB_DEVICE_DESCRIPTOR_TYPE == t) { desc_addr = (const u8 *)&USB_DeviceDescriptorIAD; } else if (USB_STRING_DESCRIPTOR_TYPE == t) { if (setup.wValueL == 0) { desc_addr = (const u8 *)&STRING_LANGUAGE; } else if (setup.wValueL == IPRODUCT) { return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT), TRANSFER_PGM); } else if (setup.wValueL == IMANUFACTURER) { return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER), TRANSFER_PGM); } else if (setup.wValueL == ISERIAL) { #ifdef PLUGGABLE_USB_ENABLED char name[ISERIAL_MAX_LEN]; PluggableUSB().getShortName(name); return USB_SendStringDescriptor((uint8_t *)name, strlen(name), 0); #endif } else return false; } if (desc_addr == 0) return false; u8 desc_length = pgm_read_byte(desc_addr); USB_SendControl(TRANSFER_PGM, desc_addr, desc_length); return true; } // 端点0中断 ISR(USB_COM_vect) { SetEP(0); if (!ReceivedSetupInt()) return; USBSetup setup; Recv((u8 *)&setup, 8); ClearSetupInt(); u8 requestType = setup.bmRequestType; if (requestType & REQUEST_DEVICETOHOST) WaitIN(); else ClearIN(); bool ok = true; if (REQUEST_STANDARD == (requestType & REQUEST_TYPE)) { // 标准请求 u8 r = setup.bRequest; u16 wValue = setup.wValueL | (setup.wValueH << 8); if (GET_STATUS == r) { if (requestType == (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_DEVICE)) { Send8(_usbCurrentStatus); Send8(0); } else { // TODO:在此处处理端点的HALT状态 Send8(0); Send8(0); } } else if (CLEAR_FEATURE == r) { if ((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE)) && (wValue == DEVICE_REMOTE_WAKEUP)) { _usbCurrentStatus &= ~FEATURE_REMOTE_WAKEUP_ENABLED; } } else if (SET_FEATURE == r) { if ((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE)) && (wValue == DEVICE_REMOTE_WAKEUP)) { _usbCurrentStatus |= FEATURE_REMOTE_WAKEUP_ENABLED; } } else if (SET_ADDRESS == r) { WaitIN(); UDADDR = setup.wValueL | (1 << ADDEN); } else if (GET_DESCRIPTOR == r) { ok = SendDescriptor(setup); } else if (SET_DESCRIPTOR == r) { ok = false; } else if (GET_CONFIGURATION == r) { Send8(1); } else if (SET_CONFIGURATION == r) { if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT)) { InitEndpoints(); _usbConfiguration = setup.wValueL; } else ok = false; } else if (GET_INTERFACE == r) { } else if (SET_INTERFACE == r) { } } else { InitControl(setup.wLength); // 传输的最大容量 ok = ClassInterfaceRequest(setup); } if (ok) ClearIN(); else Stall(); } void USB_Flush(u8 ep) { SetEP(ep); if (FifoByteCount()) ReleaseTX(); } static inline void USB_ClockDisable() { #if defined(OTGPADE) USBCON = (USBCON & ~(1 << OTGPADE)) | (1 << FRZCLK); // 冻结时钟并禁用VBUS Pad #else // u2系列 USBCON = (1 << FRZCLK); // 冻结时钟 #endif PLLCSR &= ~(1 << PLLE); // 停止PLL } static inline void USB_ClockEnable() { #if defined(UHWCON) UHWCON |= (1 << UVREGE); // 电源内部寄存器 #endif USBCON = (1 << USBE) | (1 << FRZCLK); // 时钟冻结,USB启用 // ATmega32U4 #if defined(PINDIV) #if F_CPU == 16000000UL PLLCSR |= (1 << PINDIV); // 需要 16 MHz xtal #elif F_CPU == 8000000UL PLLCSR &= ~(1 << PINDIV); // 需要 8 MHz xtal #else #error "Clock rate of F_CPU not supported" #endif #elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__) || defined(__AVR_ATmega32U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega8U2__) // 对于u2系列,数据表令人困惑。 在第40页上称为PINDIV,在第290页上称为PLLP0 #if F_CPU == 16000000UL // 需要 16 MHz xtal PLLCSR |= (1 << PLLP0); #elif F_CPU == 8000000UL // 需要 8 MHz xtal PLLCSR &= ~(1 << PLLP0); #endif // AT90USB646, AT90USB647, AT90USB1286, AT90USB1287 #elif defined(PLLP2) #if F_CPU == 16000000UL #if defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__) // 用于Atmel AT90USB128x. 不要用于 Atmel AT90USB64x. PLLCSR = (PLLCSR & ~(1 << PLLP1)) | ((1 << PLLP2) | (1 << PLLP0)); // 需要 16 MHz xtal #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__) // 用于AT90USB64x. 不要用于 AT90USB128x. PLLCSR = (PLLCSR & ~(1 << PLLP0)) | ((1 << PLLP2) | (1 << PLLP1)); // 需要 16 MHz xtal #else #error "USB Chip not supported, please defined method of USB PLL initialization" #endif #elif F_CPU == 8000000UL // 用于Atmel AT90USB128x and AT90USB64x PLLCSR = (PLLCSR & ~(1 << PLLP2)) | ((1 << PLLP1) | (1 << PLLP0)); // 需要 8 MHz xtal #else #error "Clock rate of F_CPU not supported" #endif #else #error "USB Chip not supported, please defined method of USB PLL initialization" #endif PLLCSR |= (1 << PLLE); while (!(PLLCSR & (1 << PLOCK))) {} // 等待锁定 // 在特定版本的macosx(10.7.3)上进行了一些测试,报告了一些使用串行重置板时的奇怪行为 // 通过端口触摸速度为1200 bps。 此延迟可以解决此问题。 delay(1); #if defined(OTGPADE) USBCON = (USBCON & ~(1 << FRZCLK)) | (1 << OTGPADE); // 启动USB clock, enable VBUS Pad #else USBCON &= ~(1 << FRZCLK); // 启动USB clock #endif #if defined(RSTCPU) #if defined(LSM) UDCON &= ~((1 << RSTCPU) | (1 << LSM) | (1 << RMWKUP) | (1 << DETACH)); // 启用连接电阻,设置全速模式 #else // u2 Series UDCON &= ~((1 << RSTCPU) | (1 << RMWKUP) | (1 << DETACH)); // 启用连接电阻,设置全速模式 #endif #else // AT90USB64x和AT90USB128x没有RSTCPU UDCON &= ~((1 << LSM) | (1 << RMWKUP) | (1 << DETACH)); // 启用连接电阻,设置全速模式 #endif } // 普通中断 ISR(USB_GEN_vect) { u8 udint = UDINT; UDINT &= ~((1 << EORSTI) | (1 << SOFI)); // 清除此处要处理的IRQ的IRQ标志,WAKEUPI和SUSPI除外 // 重置 if (udint & (1 << EORSTI)) { InitEP(0, EP_TYPE_CONTROL, EP_SINGLE_64); // 初始化ep0 _usbConfiguration = 0; // 没有设置 UEIENX = 1 << RXSTPE; // 为ep0启用中断 } // 启动Frame。每毫秒发生一次,因此我们也将其用于TX和RX LED一次触发时序 if (udint & (1 << SOFI)) { USB_Flush(CDC_TX); // 如果找到,发送一个tx帧 // 检查一次捕获是否已经过去。 如果是这样,请关闭LED if (TxLEDPulse && !(--TxLEDPulse)) TXLED0; if (RxLEDPulse && !(--RxLEDPulse)) RXLED0; } // 一旦数据上出现非空闲模式,就会触发WAKEUPI中断行。 因此,即使控制器未处于“挂起”模式,也可能发生WAKEUPI中断。 // 因此,我们仅在USB挂起时才启用它。 if (udint & (1 << WAKEUPI)) { UDIEN = (UDIEN & ~(1 << WAKEUPE)) | (1 << SUSPE); // 禁用WAKEUP中断,并允许SUSPEND中断 // WAKEUPI应通过软件清除(必须先启用USB时钟输入)。 // USB_ClockEnable(); UDINT &= ~(1 << WAKEUPI); _usbSuspendState = (_usbSuspendState & ~(1 << SUSPI)) | (1 << WAKEUPI); } else if (udint & (1 << SUSPI)) { // WAKEUPI / SUSPI位中只有一个可以同时激活 UDIEN = (UDIEN & ~(1 << SUSPE)) | (1 << WAKEUPE); // 禁用SUSPEND中断并启用WAKEUP中断 //USB_ClockDisable(); UDINT &= ~((1 << WAKEUPI) | (1 << SUSPI)); // 清除所有已经挂起的WAKEUP IRQ和SUSPI请求 _usbSuspendState = (_usbSuspendState & ~(1 << WAKEUPI)) | (1 << SUSPI); } } // VBUS或计数帧 u8 USBConnected() { u8 f = UDFNUML; delay(3); return f != UDFNUML; } USBDevice_ USBDevice; USBDevice_::USBDevice_() {} void USBDevice_::attach() { _usbConfiguration = 0; _usbCurrentStatus = 0; _usbSuspendState = 0; USB_ClockEnable(); UDINT &= ~((1 << WAKEUPI) | (1 << SUSPI)); // 清除已经挂起的WAKEUP / SUSPEND请求 UDIEN = (1 << EORSTE) | (1 << SOFE) | (1 << SUSPE); // 启用EOR(复位结束),SOF(帧启动)和SUSPEND中断 TX_RX_LED_INIT; } void USBDevice_::detach() {} // 检查中断。需要完成VBUS检测 bool USBDevice_::configured() { return _usbConfiguration; } void USBDevice_::poll() {} bool USBDevice_::wakeupHost() { // 清除所有先前已设置但可以在该时间处理的唤醒请求。例如因为当时主机尚未暂停。 UDCON &= ~(1 << RMWKUP); if (!(UDCON & (1 << RMWKUP)) && (_usbSuspendState & (1 << SUSPI)) && (_usbCurrentStatus & FEATURE_REMOTE_WAKEUP_ENABLED)) { // 此简短版本仅在尚未暂停设备时起作用。 目前Arduino核心根本不处理SUSPEND,所以没关系。 USB_ClockEnable(); UDCON |= (1 << RMWKUP); // 发送唤醒请求 return true; } return false; } bool USBDevice_::isSuspended() { return (_usbSuspendState & (1 << SUSPI)); } #endif /* if defined(USBCON) */
31.035651
155
0.60031
JHSeng
2e04d61885cdbc57fa7a44e574ed97f4826d3f4f
3,063
cpp
C++
VVGL/src/GLContextWindowBacking.cpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
24
2019-01-17T17:56:18.000Z
2022-02-27T19:57:13.000Z
VVGL/src/GLContextWindowBacking.cpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
6
2019-01-17T17:17:12.000Z
2020-06-19T11:27:50.000Z
VVGL/src/GLContextWindowBacking.cpp
mrRay/VVISF-GL
96b00da11e4497da304041ea2a5ffc6e3a8c9454
[ "BSD-3-Clause" ]
2
2020-12-25T04:57:31.000Z
2021-03-02T22:05:31.000Z
#include "GLContextWindowBacking.hpp" #if defined(VVGL_SDK_WIN) namespace VVGL { const TCHAR* GLCONTEXTWINDOWBACKING_WNDCLASSNAME = _T("GLCONTEXTWINDOWBACKING_WNDCLASSNAME"); static const TCHAR* GLCONTEXTWINDOWBACKING_PROPERTY = _T("GLCONTEXTWINDOWBACKING_PROPERTY"); static bool GLContextWindowBackingClassRegistered = false; LRESULT CALLBACK GLContextWindowBacking_wndProc(HWND Wnd, UINT Msg, WPARAM wParam, LPARAM lParam); GLContextWindowBacking::GLContextWindowBacking(const VVGL::Rect & inRect) { //cout << __PRETTY_FUNCTION__ << endl; // register the window class if we haven't already if (!GLContextWindowBackingClassRegistered) { WNDCLASSEX WndClass; memset(&WndClass, 0, sizeof(WNDCLASSEX)); WndClass.cbSize = sizeof(WNDCLASSEX); //WndClass.style = CS_OWNDC; // Class styles WndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; WndClass.lpfnWndProc = GLContextWindowBacking_wndProc; WndClass.cbClsExtra = 0; // No extra class data WndClass.cbWndExtra = 0; // No extra window data WndClass.hInstance = GetModuleHandle(NULL); WndClass.hIcon = LoadIcon(0, IDI_APPLICATION); WndClass.hCursor = LoadCursor(0, IDC_ARROW); WndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); WndClass.lpszMenuName = NULL; WndClass.lpszClassName = GLCONTEXTWINDOWBACKING_WNDCLASSNAME; RegisterClassEx(&WndClass); GLContextWindowBackingClassRegistered = true; } // create the window, get its device context //DWORD tmpFlag = WS_OVERLAPPEDWINDOW | WS_CHILD; //DWORD tmpFlag = WS_OVERLAPPEDWINDOW; //DWORD tmpFlag = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; //tmpFlag = tmpFlag | WS_VISIBLE; DWORD tmpFlag = 0; tmpFlag |= WS_CLIPSIBLINGS; tmpFlag |= WS_CLIPCHILDREN; //tmpFlag |= WS_POPUP; //tmpFlag |= WS_EX_APPWINDOW; //tmpFlag |= WS_EX_TOPMOST; //tmpFlag |= WS_VISIBLE; //tmpFlag |= WS_MAXIMIZEBOX; //tmpFlag |= WS_THICKFRAME; //tmpFlag |= WS_EX_WINDOWEDGE; tmpFlag |= WS_OVERLAPPEDWINDOW; _wnd = CreateWindowEx( 0, GLCONTEXTWINDOWBACKING_WNDCLASSNAME, _T("VVGL Test App"), tmpFlag, int(inRect.botLeft().x), int(inRect.botLeft().y), int(inRect.size.width), int(inRect.size.height), //int(inRect.topLeft().x), int(inRect.topLeft().y), int(inRect.botRight().x), int(inRect.botRight().y), 0, 0, NULL, NULL); SetProp(_wnd, GLCONTEXTWINDOWBACKING_PROPERTY, (HANDLE)this); _dc = GetDC(_wnd); // configure the window's pixel format ConfigDeviceContextPixelFormat(_dc); } GLContextWindowBacking::~GLContextWindowBacking() { ReleaseDC(_wnd, _dc); DestroyWindow(_wnd); } LRESULT CALLBACK GLContextWindowBacking_wndProc(HWND Wnd, UINT Msg, WPARAM wParam, LPARAM lParam) { //if (Msg == WM_CREATE) // cout << "GLContextWindowBacking received WM_CREATE and is clear to create a GL ctx" << endl; return DefWindowProc(Wnd, Msg, wParam, lParam); }; } #endif // VVGL_SDK_WIN
31.90625
107
0.711721
mrRay
2e07012b6ccf4565ad0591026233b490894a32b9
2,318
cpp
C++
esp32/airpapyrus/CCS811Sensor.cpp
ciffelia/airpapyrus
4e6642025d6b1e81210c63f3cae46e4e361804ea
[ "MIT" ]
null
null
null
esp32/airpapyrus/CCS811Sensor.cpp
ciffelia/airpapyrus
4e6642025d6b1e81210c63f3cae46e4e361804ea
[ "MIT" ]
null
null
null
esp32/airpapyrus/CCS811Sensor.cpp
ciffelia/airpapyrus
4e6642025d6b1e81210c63f3cae46e4e361804ea
[ "MIT" ]
null
null
null
#include "CCS811Sensor.hpp" #include "Constants.hpp" #include "Logger.hpp" CCS811Sensor::CCS811Sensor() : ccs811(Constants::GPIO::Address::CCS811) { } void CCS811Sensor::reset() { pinMode(Constants::GPIO::Pin::CCS811_RESET, OUTPUT); digitalWrite(Constants::GPIO::Pin::CCS811_RESET, 0); delay(10); digitalWrite(Constants::GPIO::Pin::CCS811_RESET, 1); delay(10); } void CCS811Sensor::wake() { pinMode(Constants::GPIO::Pin::CCS811_WAKE, OUTPUT); digitalWrite(Constants::GPIO::Pin::CCS811_WAKE, 0); delay(10); } void CCS811Sensor::sleep() { pinMode(Constants::GPIO::Pin::CCS811_WAKE, OUTPUT); digitalWrite(Constants::GPIO::Pin::CCS811_WAKE, 1); delay(10); } bool CCS811Sensor::waitForDataAvailable(const int timeout) { for (int elapsed = 0; elapsed < timeout * 10 && !ccs811.dataAvailable(); elapsed++) { delay(100); } return ccs811.dataAvailable(); } bool CCS811Sensor::initialize() { this->reset(); this->wake(); const auto beginStatus = ccs811.beginWithStatus(); if (beginStatus != CCS811::CCS811_Stat_SUCCESS) { Printf("ccs811.begin() failed. Error: %s.", ccs811.statusString(beginStatus)); return false; } // Mode 1: measurement every second const auto setModeStatus = ccs811.setDriveMode(1); if (setModeStatus != CCS811::CCS811_Stat_SUCCESS) { Printf("ccs811.setDriveMode() failed. Error: %s.", ccs811.statusString(setModeStatus)); return false; } // 600秒待ってもデータを読み出せなければ諦める if (!this->waitForDataAvailable(600)) { Println("waitForDataAvailable() timed out. (600s)"); return false; } return true; } bool CCS811Sensor::setEnvironmentalData(const BME280Data bme280Data) { const auto status = ccs811.setEnvironmentalData(bme280Data.humidity, bme280Data.temperature); if (status != CCS811::CCS811_Stat_SUCCESS) { Printf("ccs811.setEnvironmentalData() failed. Error: %s.", ccs811.statusString(status)); return false; } return true; } CCS811Data CCS811Sensor::read() { // 15秒待ってもデータを読み出せなければ諦める if (!this->waitForDataAvailable(15)) { Println("waitForDataAvailable() timed out. (15s)"); Println("Resetting CCS811..."); this->initialize(); return this->read(); } ccs811.readAlgorithmResults(); return CCS811Data( ccs811.getCO2(), ccs811.getTVOC() ); }
22.950495
95
0.694133
ciffelia
2e08233eba05439eed938035df117b2cf5280ae8
462
cpp
C++
519_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
519_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
519_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int vec_sum=0; int temp1_sum=0; int temp2_sum=0; for(int i=0;i<n;i++) { int x; cin>>x; vec_sum+=x; } for(int i=0;i<n-1;i++) { int x; cin>>x; temp1_sum+=x; } for(int i=0;i<n-2;i++) { int x; cin>>x; temp2_sum+=x; } cout<<vec_sum-temp1_sum<<endl; cout<<temp1_sum-temp2_sum<<endl; }
14.903226
37
0.480519
onexmaster
2e0b8c9b9baa9cd6501e2376d31757d25d948f27
6,650
cpp
C++
src/caffe/layers/softmax_noisy_label_loss_layer.cpp
gnina/caffe
59b3451cd54ae106de3335876ba25f68b9553098
[ "Intel", "BSD-2-Clause" ]
1
2016-06-09T16:44:58.000Z
2016-06-09T16:44:58.000Z
src/caffe/layers/softmax_noisy_label_loss_layer.cpp
gnina/caffe
59b3451cd54ae106de3335876ba25f68b9553098
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/layers/softmax_noisy_label_loss_layer.cpp
gnina/caffe
59b3451cd54ae106de3335876ba25f68b9553098
[ "Intel", "BSD-2-Clause" ]
3
2016-02-10T17:38:44.000Z
2018-10-14T07:44:19.000Z
#include <algorithm> #include <functional> #include <cfloat> #include <vector> #include <iostream> #include <utility> #include "caffe/layers/softmax_noisy_label_loss_layer.hpp" #include "caffe/filler.hpp" namespace caffe { template <typename Dtype> void SoftmaxWithNoisyLabelLossLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { if (this->layer_param_.loss_weight_size() == 0) { this->layer_param_.add_loss_weight(Dtype(1)); for (int i = 1; i < top.size(); ++i) { this->layer_param_.add_loss_weight(0); } } softmax_bottom_vec_y_.clear(); softmax_bottom_vec_z_.clear(); softmax_top_vec_y_.clear(); softmax_top_vec_z_.clear(); softmax_bottom_vec_y_.push_back(bottom[0]); softmax_bottom_vec_z_.push_back(bottom[1]); softmax_top_vec_y_.push_back(&prob_y_); softmax_top_vec_z_.push_back(&prob_z_); softmax_layer_y_->SetUp(softmax_bottom_vec_y_, softmax_top_vec_y_); softmax_layer_z_->SetUp(softmax_bottom_vec_z_, softmax_top_vec_z_); N_ = bottom[0]->channels(); this->blobs_.resize(1); this->blobs_[0].reset(new Blob<Dtype>(1, 1, N_, N_)); shared_ptr<Filler<Dtype> > c_filler(GetFiller<Dtype>( this->layer_param_.softmax_noisy_label_loss_param().matrix_c_filler())); c_filler->Fill(this->blobs_[0].get()); CHECK_EQ(this->blobs_[0]->num(), 1); CHECK_EQ(this->blobs_[0]->channels(), 1); CHECK_EQ(this->blobs_[0]->height(), N_); CHECK_EQ(this->blobs_[0]->width(), N_); lr_z_ = this->layer_param_.softmax_noisy_label_loss_param().update_noise_lr(); } template <typename Dtype> void SoftmaxWithNoisyLabelLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); softmax_layer_y_->Reshape(softmax_bottom_vec_y_, softmax_top_vec_y_); softmax_layer_z_->Reshape(softmax_bottom_vec_z_, softmax_top_vec_z_); M_ = bottom[0]->num(); CHECK_EQ(bottom[0]->channels(), N_); posterior_.Reshape(M_, N_, NumNoiseType, 1); if (top.size() >= 2) top[1]->ReshapeLike(prob_y_); if (top.size() >= 3) top[2]->ReshapeLike(prob_z_); if (top.size() >= 4) top[3]->ReshapeLike(posterior_); } template <typename Dtype> void SoftmaxWithNoisyLabelLossLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // Compute conditional probability of p(y|x) and p(z|x) softmax_layer_y_->Forward(softmax_bottom_vec_y_, softmax_top_vec_y_); softmax_layer_z_->Forward(softmax_bottom_vec_z_, softmax_top_vec_z_); // Compute posterior const Dtype* C = this->blobs_[0]->cpu_data(); const Dtype* noisy_label = bottom[2]->cpu_data(); const Dtype* p_y_given_x = prob_y_.cpu_data(); const Dtype* p_z_given_x = prob_z_.cpu_data(); const Dtype uniform = Dtype(1.0) / (N_ - 1); const int dim_yz = N_ * NumNoiseType; Dtype* posterior_data = posterior_.mutable_cpu_data(); Dtype loss = 0; for (int i = 0; i < M_; ++i) { if (noisy_label[i] == -1) { // Unlabeled caffe_memset(dim_yz * sizeof(Dtype), 0, posterior_data + i * dim_yz); continue; } for (int y = 0; y < N_; ++y) { int offset = posterior_.offset(i, y); Dtype py = p_y_given_x[i * N_ + y]; for (int z = 0; z < NumNoiseType; ++z) { Dtype pz = p_z_given_x[i * NumNoiseType + z]; switch (NoiseType(z)) { case NoiseFree: posterior_data[offset + z] = (y == noisy_label[i]); break; case RandomNoise: posterior_data[offset + z] = uniform * (y != noisy_label[i]); break; case ConfusingNoise: posterior_data[offset + z] = C[static_cast<int>(noisy_label[i] * N_ + y)]; break; default: break; } posterior_data[offset + z] *= py * pz; } } // Compute loss Dtype sum = 0; Dtype weighted_loss = 0; for (int y = 0; y < N_; ++y) { for (int z = 0; z < NumNoiseType; ++z) { Dtype p = posterior_.data_at(i, y, z, 0); sum += p; weighted_loss -= p * log(std::max(p, Dtype(FLT_MIN))); } } if (sum > 0) { loss += weighted_loss / sum; caffe_scal(dim_yz, Dtype(1.0) / sum, posterior_data + i * dim_yz); } } top[0]->mutable_cpu_data()[0] = loss / M_; if (top.size() >= 2) top[1]->ShareData(prob_y_); if (top.size() >= 3) top[2]->ShareData(prob_z_); if (top.size() >= 4) top[3]->ShareData(posterior_); } template <typename Dtype> void SoftmaxWithNoisyLabelLossLayer<Dtype>::Backward_cpu( const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[2]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { // Back prop: y Blob<Dtype> true_prob(M_, N_, 1, 1); Dtype* p = true_prob.mutable_cpu_data(); const Dtype* p_yz = posterior_.cpu_data(); for (int i = 0; i < M_; ++i) { for (int y = 0; y < N_; ++y) { int offset = posterior_.offset(i, y); Dtype sum = 0; for (int z = 0; z < NumNoiseType; ++z) sum += p_yz[offset + z]; p[i * N_ + y] = sum; } } BackProp(prob_y_, true_prob, top[0]->cpu_diff()[0], bottom[0]); } if (propagate_down[1]) { // Back prop: z Blob<Dtype> true_prob(M_, NumNoiseType, 1, 1); Dtype* p = true_prob.mutable_cpu_data(); const Dtype* p_yz = posterior_.cpu_data(); for (int i = 0; i < M_; ++i) { for (int z = 0; z < NumNoiseType; ++z) { Dtype sum = 0; for (int y = 0; y < N_; ++y) sum += p_yz[i * N_ * NumNoiseType + y * NumNoiseType + z]; p[i * NumNoiseType + z] = sum; } } BackProp(prob_z_, true_prob, top[0]->cpu_diff()[0] * lr_z_, bottom[1]); } } template <typename Dtype> void SoftmaxWithNoisyLabelLossLayer<Dtype>::BackProp(const Blob<Dtype>& prob, const Blob<Dtype>& true_prob, Dtype lr, Blob<Dtype>* diff) { const Dtype* prob_data = prob.cpu_data(); const Dtype* true_prob_data = true_prob.cpu_data(); Dtype* diff_data = diff->mutable_cpu_diff(); caffe_sub(diff->count(), prob_data, true_prob_data, diff_data); // set diff of unlabeled samples to 0 const int N = prob.channels(); for (int i = 0; i < M_; ++i) { Dtype sum = 0; for (int j = 0; j < N; ++j) sum += true_prob_data[i * N + j]; for (int j = 0; j < N; ++j) diff_data[i * N + j] *= sum; } caffe_scal(diff->count(), lr / M_, diff_data); } INSTANTIATE_CLASS(SoftmaxWithNoisyLabelLossLayer); REGISTER_LAYER_CLASS(SoftmaxWithNoisyLabelLoss); }
35.185185
80
0.633233
gnina
2e1139f3fd96af61c9eb61cbbc0eea294d26f404
4,661
hh
C++
include/snow/types/slot_mask.hh
nilium/libsnow-common
dff60ce529cdbe13ccf1f94756a78214c8f9d09d
[ "BSL-1.0" ]
1
2015-10-01T20:10:05.000Z
2015-10-01T20:10:05.000Z
include/snow/types/slot_mask.hh
nilium/libsnow-common
dff60ce529cdbe13ccf1f94756a78214c8f9d09d
[ "BSL-1.0" ]
null
null
null
include/snow/types/slot_mask.hh
nilium/libsnow-common
dff60ce529cdbe13ccf1f94756a78214c8f9d09d
[ "BSL-1.0" ]
null
null
null
/* * Copyright Noel Cower 2013. * * 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) */ #pragma once #include <cstdint> #include <iostream> #include <vector> namespace snow { template <typename HT, typename CT> struct slot_mask_t; template <typename HT, typename CT> std::ostream &operator << (std::ostream &out, const slot_mask_t<HT, CT> &in); template <typename HT = int, typename CT = unsigned int> struct slot_mask_t { using handle_t = HT; using count_t = CT; static const handle_t NO_HANDLE = 0; slot_mask_t(size_t size = 1); ~slot_mask_t() = default; slot_mask_t(const slot_mask_t &) = default; slot_mask_t &operator = (const slot_mask_t &) = default; slot_mask_t(slot_mask_t &&other) : slots_(std::move(other.slots_)) {} slot_mask_t &operator = (slot_mask_t &&other) { if (&other != this) { slots_ = std::move(other.slots_); } return *this; } inline size_t size() const { return slots_.size(); } void resize(size_t new_size); size_t slots_free_at(size_t index) const; bool index_is_free(size_t index, size_t slots) const; std::pair<bool, size_t> find_free_index(size_t slots, size_t from = 0) const; // Handle may not be NO_HANDLE (0) void consume_index(size_t index, size_t slots, handle_t handle); // Must pass same handle for slots otherwise the consumed slots // cannot be released. void release_index(size_t index, size_t slots, handle_t handle); private: friend std::ostream &operator << <> (std::ostream &out, const slot_mask_t<HT, CT> &in); void join_same(size_t from); struct slot_t { handle_t handle; // 0 = unused count_t count; // number to right, counting self }; std::vector<slot_t> slots_; }; template <typename HT, typename CT> std::ostream &operator << (std::ostream &out, const slot_mask_t<HT, CT> &in) { out << '{'; for (const auto &slot : in.slots_) out << ((slot.handle == 0) ? '-' : '+'); return (out << '}'); } template <typename HT, typename CT> slot_mask_t<HT, CT>::slot_mask_t(size_t size) { resize(size); } template <typename HT, typename CT> void slot_mask_t<HT, CT>::resize(size_t new_size) { slots_.resize(new_size, { NO_HANDLE, 1 }); if (new_size == 0) { return; } join_same(new_size - 1); } template <typename HT, typename CT> size_t slot_mask_t<HT, CT>::slots_free_at(size_t index) const { if (index >= slots_.size()) return 0; return slots_[index].count; } template <typename HT, typename CT> bool slot_mask_t<HT, CT>::index_is_free(size_t index, size_t slots) const { if (index + slots > slots_.size()) return false; const slot_t &slot = slots_[index]; return slot.count >= slots && slot.handle == NO_HANDLE; } template <typename HT, typename CT> std::pair<bool, size_t> slot_mask_t<HT, CT>::find_free_index(size_t slots, size_t from) const { if (slots == 0) { return { false, 0 }; } const size_t length = slots_.size() - (slots - 1); size_t index = from; for (; index < length; ++index) { const slot_t &slot = slots_[index]; if (slot.handle == 0 && slots <= slot.count) { return { true, index }; } else { index += slot.count - 1; } } return { false, 0 }; } template <typename HT, typename CT> void slot_mask_t<HT, CT>::consume_index(size_t index, size_t slots, handle_t handle) { size_t from = index; while (slots) { slot_t &slot = slots_[index]; slot.handle = handle; slot.count = slots; index += 1; slots -= 1; } if (from > 0) { join_same(from - 1); } } template <typename HT, typename CT> void slot_mask_t<HT, CT>::release_index(size_t index, size_t slots, handle_t handle) { size_t from = index; while (slots) { slot_t &slot = slots_[index]; if (slot.handle != handle) { if (index > 0 && index != from) { join_same(index - 1); } return; } slot.handle = NO_HANDLE; slot.count = slots; index += 1; slots -= 1; } if (from > 0) { join_same(from - 1); } } template <typename HT, typename CT> void slot_mask_t<HT, CT>::join_same(size_t from) { const int handle = slots_[from].handle; int counter = 1; { const size_t right = from + 1; if (right < slots_.size() && handle == slots_[right].handle) { counter += slots_[right].count; } } for (;;) { slot_t &slot = slots_[from]; if (slot.handle != handle) { return; } slot.count = counter; if (from == 0) { return; } counter += 1; from -= 1; } } } // namespace snow
21.186364
93
0.636344
nilium
2e1323cd5ce50e74e5e7c7a739c17bf7001f5cda
3,882
cpp
C++
PhotosConsigne/src/Widgets/PhotoW.cpp
FlorianLance/PhotosConsigne
8ea3a68dc3db36bf054c3759d909f9af44647660
[ "MIT" ]
2
2018-05-06T20:59:09.000Z
2021-02-25T11:00:14.000Z
PhotosConsigne/src/Widgets/PhotoW.cpp
FlorianLance/PhotosConsigne
8ea3a68dc3db36bf054c3759d909f9af44647660
[ "MIT" ]
null
null
null
PhotosConsigne/src/Widgets/PhotoW.cpp
FlorianLance/PhotosConsigne
8ea3a68dc3db36bf054c3759d909f9af44647660
[ "MIT" ]
1
2021-02-01T14:57:04.000Z
2021-02-01T14:57:04.000Z
/******************************************************************************* ** PhotosConsigne ** ** MIT License ** ** Copyright (c) [2016] [Florian Lance] ** ** ** ** 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. ** ** ** ********************************************************************************/ /** * \file PhotoW.cpp * \brief defines PhotoW * \author Florian Lance * \date 01/11/15 */ // local #include "PhotoW.hpp" // Qt #include <QPainter> PhotoW::PhotoW(QWidget *parent) : QWidget(parent) { connect(&m_doubleClickTimer, &QTimer::timeout, this, [&]{ m_doubleClickTimer.stop(); }); } void PhotoW::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); if (m_image.isNull()) return; QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); QSize widgetSize = event->rect().size(); QSize imageSize = m_image.size(); // imageSize.scale(event->rect().size(), Qt::KeepAspectRatio); imageSize.scale(QSize(widgetSize.width()-2, widgetSize.height()-2), Qt::KeepAspectRatio); QImage scaledImage = m_image.scaled(imageSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); m_imageRect = QRectF(width()*0.5-scaledImage.size().width()*0.5,height()*0.5-scaledImage.size().height()*0.5, scaledImage.width(), scaledImage.height()); QPen pen; pen.setWidth(1); pen.setColor(Qt::black); painter.setPen(pen); painter.drawImage(static_cast<int>(m_imageRect.x()), static_cast<int>(m_imageRect.y()), scaledImage); painter.drawRect(QRectF(m_imageRect.x()-1, m_imageRect.y(), scaledImage.width()+1, scaledImage.height()+1)); } const QImage* PhotoW::Image() const { return &m_image; } void PhotoW::set_image (QImage image){ m_image = image; } void PhotoW::mousePressEvent(QMouseEvent *ev){ bool inside = m_imageRect.contains(ev->pos()); if(inside){ QPointF pos((ev->pos().x()-m_imageRect.x())/m_imageRect.width(), (ev->pos().y()-m_imageRect.y())/m_imageRect.height()); emit click_inside_signal(pos); if(m_doubleClickTimer.isActive()){ emit double_click_signal(); }else{ m_doubleClickTimer.start(300); } } }
38.058824
127
0.548171
FlorianLance
2e14073384a0c7faed9ffc4535640188330bef5f
1,392
hpp
C++
src/Errors.hpp
evanova/libdgmpp
867dc081b8dc474b396481ae1b92283affc858d3
[ "MIT" ]
4
2018-05-07T16:47:27.000Z
2021-05-17T13:38:18.000Z
src/Errors.hpp
evanova/libdgmpp
867dc081b8dc474b396481ae1b92283affc858d3
[ "MIT" ]
null
null
null
src/Errors.hpp
evanova/libdgmpp
867dc081b8dc474b396481ae1b92283affc858d3
[ "MIT" ]
null
null
null
// // Errors.hpp // dgmpp // // Created by Artem Shimanski on 24.11.2017. // #pragma once #include <stdexcept> #include "Utility.hpp" namespace dgmpp { template <typename T> struct CannotFit: public std::logic_error { CannotFit(std::unique_ptr<T> type): type(std::move(type)), std::logic_error("Cannot fit") {} std::unique_ptr<T> type; }; struct InvalidSkillLevel: std::invalid_argument { InvalidSkillLevel(): std::invalid_argument("Skill level should be in [0...5] range") {} }; template<typename T> class NotFound: public std::out_of_range { public: NotFound (T identifier) : std::out_of_range("id = " + std::to_string(static_cast<int>(identifier))) {}; }; struct NotEnoughCommodities: public std::logic_error { NotEnoughCommodities(std::size_t quantity) : std::logic_error(std::to_string(quantity)) {} }; struct InvalidRoute: public std::invalid_argument { InvalidRoute() : std::invalid_argument("Missing source or destination") {} }; struct InvalidCategoryID: public std::logic_error { InvalidCategoryID(CategoryID categoryID): categoryID(categoryID), std::logic_error("Invalid categoryID") {}; CategoryID categoryID; }; // struct DifferentCommodities: public std::runtime_error { // DifferentCommodities(TypeID a, TypeID b) : std::runtime_error(std::to_string(static_cast<int>(a)) + " != " + std::to_string(static_cast<int>(b))) {} // } }
29
152
0.713362
evanova
2e19873f0e039a428ed40c8bde870a8aa988e0ce
449
cpp
C++
src/digital_clock.cpp
imharris24/Digital-Clock
dbca263357f4fed182e278e8133dba07471583d8
[ "CC0-1.0" ]
null
null
null
src/digital_clock.cpp
imharris24/Digital-Clock
dbca263357f4fed182e278e8133dba07471583d8
[ "CC0-1.0" ]
null
null
null
src/digital_clock.cpp
imharris24/Digital-Clock
dbca263357f4fed182e278e8133dba07471583d8
[ "CC0-1.0" ]
null
null
null
#include "digital_clock.h" #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<chrono> #include<ctime> #include<Windows.h> using namespace std; void DisplayTime() { auto CurrentTime = chrono::system_clock::now(); while (true) { system("cls"); CurrentTime = chrono::system_clock::now(); time_t Current_T = chrono::system_clock::to_time_t(CurrentTime); cout << "\n\tDate & Time : " << ctime(&Current_T) << "\n"; Sleep(999); } }
21.380952
66
0.697105
imharris24
2e1c505128c9453740642d5763549d151330ed78
5,570
cpp
C++
commands.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
1
2018-10-08T13:28:32.000Z
2018-10-08T13:28:32.000Z
commands.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
9
2019-08-21T18:07:49.000Z
2019-09-30T19:48:28.000Z
commands.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
null
null
null
#include <Arduino.h> #include <Time.h> #include <DS1307RTC.h> #include <SdFat.h> #include "common.h" #include "sd_log.h" #include "timers.h" static int scan_time(char *date, char *time, unsigned short *y, tmElements_t *tm) { uint16_t numbers[3]; char *c; int i = 0; c = strtok(date, "-"); while (c && (i < 3)) { numbers[i] = atoi(c); c = strtok(NULL, "-"); i++; } if (i != 3) return 1; *y = numbers[0]; tm->Month = numbers[1]; tm->Day = numbers[2]; i = 0; c = strtok(time, ":"); while (c && (i < 3)) { numbers[i] = atoi(c); c = strtok(NULL, ":"); i++; } if (i != 3) return 1; tm->Hour = numbers[0]; tm->Minute = numbers[1]; tm->Second = numbers[2]; return 0; } static char cmd_time(char argc, char *argv[]) { unsigned short int y; tmElements_t tm; if (argc == 0) { printTime(now()); return 0; } if (argc != 2) { Serial.println(F("Usage: time YYYY-MM-DD HH:MM:SS")); return 1; } if (scan_time(argv[0], argv[1], &y, &tm)) { Serial.println(F("Cannot parse time")); return 1; } tm.Year = y - 1970; if (!RTC.write(tm)) Serial.println(F("RTC error")); setTime(makeTime(tm)); if (!RTC.read(tm)) Serial.println(F("RTC error")); printTime(now()); return 0; } static char cmd_ls(char, char *[]) { if (!isSdReady()) return 1; root.ls(LS_SIZE); return 0; } static SdFile file; static char filename[13]; static char cmd_dumpall(char, char *[]) { if (!isSdReady()) return 1; root.close(); root.open(sd_counter_dir, O_READ); while (file.openNext(&root, O_RDONLY)) { if (file.isDir()) goto next_file; if (!file.getName(filename, sizeof(filename))) goto next_file; if (!strstr(filename, ".CSV")) goto next_file; Serial.println(filename); dumpSdLog(filename); next_file: file.close(); } return 0; } static char cmd_dump(char argc, char *argv[]) { if (argc == 1) return dumpSdLog(argv[0]); else return dumpSdLog(NULL); return 0; } static char cmd_raw(char, char *[]) { raw_measuring = !raw_measuring; if (raw_measuring) { if (raw_measuring) stop_timer(IDLE_TIMEOUT_TIMER); else schedule_timer(IDLE_TIMEOUT_TIMER, IDLE_TIMEOUT_MS); } return 0; } static char cmd_batt(char, char *[]) { Serial.println(readBattery_mV()); return 0; } static char cmd_poff(char, char *[]) { digitalWrite(LED_PIN, 1); digitalWrite(PWR_ON_PIN, 0); return 0; } static char cmd_bt(char argc, char *argv[]) { if (argc != 1) { Serial.print(F("Bluetooth ")); if (bluetooth_mode == BT_PERMANENT) Serial.println(F("ON")); else Serial.println(F("AUTO")); } else { if (!strcmp(argv[0], "on")) { set_bluetooth_mode(BT_PERMANENT); } else if (!strcmp(argv[0], "auto")) { set_bluetooth_mode(BT_AUTO); } } return 0; } static char cmd_ver(char, char *[]) { Serial.println(F("Build: " __DATE__ " " __TIME__)); return 0; } static char cmd_help(char, char *[]) { puts_P(PSTR( "Commands:\n" " time [yyyy-mm-dd HH:MM:SS] \t - get/set time\n" " raw\t\t\t\t - toggle raw dump\n" " ls\t\t\t\t - list files on SD\n" " dump [file]\t\t\t - dump file content\n" " dumpall [file]\t\t\t - dump all logs content\n" " batt\t\t\t\t - show battery voltage\n" " bt [on|auto]\t\t\t - bluetooth enabled permanently/on demand (by magnet)\n" " ver \t\t\t\t – show firmware version\n" )); return 0; } typedef char (*cmd_handler_t)(char argc, char *argv[]); struct cmd_table_entry { PGM_P cmd; cmd_handler_t handler; }; static const char cmd_time_name[] PROGMEM = "time"; static const char cmd_ls_name[] PROGMEM = "ls"; static const char cmd_dump_name[] PROGMEM = "dump"; static const char cmd_dumpall_name[] PROGMEM = "dumpall"; static const char cmd_raw_name[] PROGMEM = "raw"; static const char cmd_poff_name[] PROGMEM = "poff"; static const char cmd_batt_name[] PROGMEM = "batt"; static const char cmd_bt_name[] PROGMEM = "bt"; static const char cmd_ver_name[] PROGMEM = "ver"; static const char cmd_help_name[] PROGMEM = "help"; #define CMD(name) {cmd_ ## name ## _name, cmd_ ## name} static PROGMEM const struct cmd_table_entry cmd_table[] = { CMD(time), CMD(ls), CMD(dump), CMD(dumpall), CMD(raw), CMD(poff), CMD(batt), CMD(bt), CMD(ver), CMD(help), }; #define MAX_CMD_ARGS 3 void parse_cmdline(char *buf, uint8_t) { char *cmd = strtok(buf, " "); struct cmd_table_entry cmd_entry; char *argv[MAX_CMD_ARGS]; uint8_t argc = 0; unsigned char i; char ret = 1; if (!cmd) return; while (argc < MAX_CMD_ARGS) { argv[argc] = strtok(NULL, " "); if (argv[argc]) argc++; else break; } for (i = 0; i < ARRAY_SIZE(cmd_table); i++) { memcpy_P(&cmd_entry, &cmd_table[i], sizeof(cmd_entry)); if (!strcmp_P(cmd, cmd_entry.cmd)) { ret = cmd_entry.handler(argc, argv); break; } } if (ret) Serial.println("ERROR"); } #define SERIAL_BUF_LEN 60 static char serial_buf[SERIAL_BUF_LEN]; static uint8_t serial_buf_level = 0; void processSerial() { char c; while (Serial.available()) { idle_sleep_mode = SLEEP_MODE_IDLE; // digitalWrite(LED_PIN, 1); schedule_timer(IDLE_TIMEOUT_TIMER, IDLE_TIMEOUT_MS); c = Serial.read(); Serial.write(c); // digitalWrite(LED_PIN, 1); if ((c == '\r') || (c == '\n')) { if (c == '\r') Serial.write('\n'); serial_buf[serial_buf_level] = '\0'; serial_buf_level++; parse_cmdline(serial_buf, serial_buf_level); serial_buf_level = 0; Serial.write("> "); } else { if (serial_buf_level < SERIAL_BUF_LEN - 1) { serial_buf[serial_buf_level] = c; serial_buf_level++; } } } // digitalWrite(LED_PIN, 0); }
18.262295
78
0.63842
jekhor
2e1e311a60c2b658b683d9387bd1803c5c401c37
366
hpp
C++
include/amcl_3d/time.hpp
yukkysaito/amcl_3d
3284678ee2f184fb704a44c2affc8d398ece5863
[ "BSD-3-Clause" ]
10
2019-08-16T05:17:38.000Z
2022-03-09T07:59:03.000Z
include/amcl_3d/time.hpp
rsasaki0109/amcl_3d
584d49a94666b6ee4aab9652d2142274b96e7c6c
[ "BSD-3-Clause" ]
2
2018-10-10T06:59:23.000Z
2019-06-04T01:09:55.000Z
include/amcl_3d/time.hpp
yukkysaito/amcl_3d
3284678ee2f184fb704a44c2affc8d398ece5863
[ "BSD-3-Clause" ]
6
2018-10-10T06:57:56.000Z
2020-07-19T11:58:08.000Z
#pragma once #include <ros/ros.h> namespace amcl_3d { struct Time { Time(const ros::Time &ros_time); Time(); ros::Time toROSTime(); static Time fromROSTime(const ros::Time &ros_time); static double getDiff(const Time &start, const Time &end); static Time getTimeNow(); unsigned int sec; unsigned int nsec; }; } // namespace amcl_3d
19.263158
62
0.669399
yukkysaito
2e202efccdb33bbe69ac1aad6b1e464c2568882d
329
cpp
C++
chap15/Exer15_39/Exer15_39_Query.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap15/Exer15_39/Exer15_39_Query.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap15/Exer15_39/Exer15_39_Query.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
#include "Exer15_39_Query.h" // constructor of Query that takes a string parameter // inline Query::Query(const std::string &s) : q(new WordQuery(s)) {} std::ostream& operator<<(std::ostream &os, const Query &query) { // Query::rep makes a virtual call through its Query_base pointer to rep() return os << query.rep(); }
36.555556
78
0.696049
sjbarigye
2e2523e00203352c8b7d1cc80284af8205793086
2,390
cc
C++
util/src/stringutil.cc
robert-mijakovic/readex-ptf
5514b0545721ef27de0426a7fa0116d2e0bb5eef
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
util/src/stringutil.cc
robert-mijakovic/readex-ptf
5514b0545721ef27de0426a7fa0116d2e0bb5eef
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
util/src/stringutil.cc
robert-mijakovic/readex-ptf
5514b0545721ef27de0426a7fa0116d2e0bb5eef
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** @file stringutil.cc @brief String manipulation routines @author Karl Fuerlinger @verbatim Revision: $Revision$ Revision date: $Date$ Committed by: $Author$ This file is part of the Periscope performance measurement tool. See http://www.lrr.in.tum.de/periscope for details. Copyright (c) 2005-2011, Technische Universitaet Muenchen, Germany See the COPYING file in the base directory of the package for details. @endverbatim */ #include <string> #include <iostream> #include <algorithm> #include "strutil.h" using std::string; using std::cout; using std::endl; using std::pair; size_t strskip_ws( std::string str, int pos ) { return str.find_first_not_of( "\t ", pos ); } size_t get_token( std::string str, int pos, std::string delim, std::string& tok ) { std::string::size_type p1, p2; p1 = str.find_first_not_of( delim, pos ); if( p1 == std::string::npos ) { tok = ""; return std::string::npos; } p2 = str.find_first_of( delim, p1 ); if( p2 == std::string::npos ) { tok = str.substr( p1, str.size() - p1 ); return std::string::npos; } tok = str.substr( p1, p2 - p1 ); return p2; } // list< pair<std::string, std::string> >& kvpairs size_t get_key_value_pair( std::string str, int pos, std::pair< std::string, std::string >& kvpair ) { std::string key, value; std::string::size_type p1; // get the key p1 = get_token( str, pos, " =", key ); if( p1 == std::string::npos ) { kvpair.first = ""; kvpair.second = ""; return std::string::npos; } // expect '=' next p1 = strskip_ws( str, p1 ); if( p1 == std::string::npos || str[ p1 ] != '=' ) { kvpair.first = ""; kvpair.second = ""; return std::string::npos; } p1 = strskip_ws( str, p1 + 1 ); if( p1 == std::string::npos ) { kvpair.first = ""; kvpair.second = ""; return std::string::npos; } // value could be enclosed in double quotes if( str[ p1 ] == '"' ) { p1 = get_token( str, p1, "\"", value ); } else { p1 = get_token( str, p1, " ", value ); } if( p1 != std::string::npos ) { p1++; } kvpair.first = key; kvpair.second = value; return p1; }
22.980769
83
0.551046
robert-mijakovic
2e276f26c03d408e1680e5d90f56447f611f65c5
4,316
hpp
C++
libs/boost_1_72_0/boost/smart_ptr/enable_shared_from_raw.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/smart_ptr/enable_shared_from_raw.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/smart_ptr/enable_shared_from_raw.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
#ifndef BOOST_ENABLE_SHARED_FROM_RAW_HPP_INCLUDED #define BOOST_ENABLE_SHARED_FROM_RAW_HPP_INCLUDED // // enable_shared_from_raw.hpp // // Copyright 2002, 2009, 2014 Peter Dimov // Copyright 2008-2009 Frank Mori Hess // // 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 <boost/assert.hpp> #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> namespace boost { template <typename T> boost::shared_ptr<T> shared_from_raw(T *); template <typename T> boost::weak_ptr<T> weak_from_raw(T *); namespace detail { template <class X, class Y> inline void sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py, boost::enable_shared_from_raw const *pe); } // namespace detail class enable_shared_from_raw { protected: enable_shared_from_raw() {} enable_shared_from_raw(enable_shared_from_raw const &) {} enable_shared_from_raw &operator=(enable_shared_from_raw const &) { return *this; } ~enable_shared_from_raw() { BOOST_ASSERT(shared_this_.use_count() <= 1); // make sure no dangling shared_ptr objects exist } private: void init_if_expired() const { if (weak_this_.expired()) { shared_this_.reset(static_cast<void *>(0), detail::esft2_deleter_wrapper()); weak_this_ = shared_this_; } } void init_if_empty() const { if (weak_this_._empty()) { shared_this_.reset(static_cast<void *>(0), detail::esft2_deleter_wrapper()); weak_this_ = shared_this_; } } #ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS public: #else private: template <class Y> friend class shared_ptr; template <typename T> friend boost::shared_ptr<T> shared_from_raw(T *); template <typename T> friend boost::weak_ptr<T> weak_from_raw(T *); template <class X, class Y> friend inline void detail::sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py, boost::enable_shared_from_raw const *pe); #endif shared_ptr<void const volatile> shared_from_this() const { init_if_expired(); return shared_ptr<void const volatile>(weak_this_); } shared_ptr<void const volatile> shared_from_this() const volatile { return const_cast<enable_shared_from_raw const *>(this)->shared_from_this(); } weak_ptr<void const volatile> weak_from_this() const { init_if_empty(); return weak_this_; } weak_ptr<void const volatile> weak_from_this() const volatile { return const_cast<enable_shared_from_raw const *>(this)->weak_from_this(); } // Note: invoked automatically by shared_ptr; do not call template <class X, class Y> void _internal_accept_owner(shared_ptr<X> *ppx, Y *) const { BOOST_ASSERT(ppx != 0); if (weak_this_.expired()) { weak_this_ = *ppx; } else if (shared_this_.use_count() != 0) { BOOST_ASSERT(ppx->unique()); // no weak_ptrs should exist either, but // there's no way to check that detail::esft2_deleter_wrapper *pd = boost::get_deleter<detail::esft2_deleter_wrapper>(shared_this_); BOOST_ASSERT(pd != 0); pd->set_deleter(*ppx); ppx->reset(shared_this_, ppx->get()); shared_this_.reset(); } } mutable weak_ptr<void const volatile> weak_this_; private: mutable shared_ptr<void const volatile> shared_this_; }; template <typename T> boost::shared_ptr<T> shared_from_raw(T *p) { BOOST_ASSERT(p != 0); return boost::shared_ptr<T>(p->enable_shared_from_raw::shared_from_this(), p); } template <typename T> boost::weak_ptr<T> weak_from_raw(T *p) { BOOST_ASSERT(p != 0); boost::weak_ptr<T> result(p->enable_shared_from_raw::weak_from_this(), p); return result; } namespace detail { template <class X, class Y> inline void sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py, boost::enable_shared_from_raw const *pe) { if (pe != 0) { pe->_internal_accept_owner(ppx, const_cast<Y *>(py)); } } } // namespace detail } // namespace boost #endif // #ifndef BOOST_ENABLE_SHARED_FROM_RAW_HPP_INCLUDED
29.162162
80
0.68721
henrywarhurst
2e2c633559616dc04e63ed1a91844008a24a9354
32,857
cpp
C++
SU2-Quantum/SU2_CFD/src/output/CFlowIncOutput.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/output/CFlowIncOutput.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/src/output/CFlowIncOutput.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file output_flow_inc.cpp * \brief Main subroutines for incompressible flow output * \author R. Sanchez * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #include "../../include/output/CFlowIncOutput.hpp" #include "../../../Common/include/geometry/CGeometry.hpp" #include "../../include/solvers/CSolver.hpp" CFlowIncOutput::CFlowIncOutput(CConfig *config, unsigned short nDim) : CFlowOutput(config, nDim, false) { turb_model = config->GetKind_Turb_Model(); heat = config->GetEnergy_Equation(); weakly_coupled_heat = config->GetWeakly_Coupled_Heat(); /*--- Set the default history fields if nothing is set in the config file ---*/ if (nRequestedHistoryFields == 0){ requestedHistoryFields.emplace_back("ITER"); requestedHistoryFields.emplace_back("RMS_RES"); nRequestedHistoryFields = requestedHistoryFields.size(); } if (nRequestedScreenFields == 0){ if (multiZone) requestedScreenFields.emplace_back("OUTER_ITER"); requestedScreenFields.emplace_back("INNER_ITER"); requestedScreenFields.emplace_back("RMS_PRESSURE"); requestedScreenFields.emplace_back("RMS_VELOCITY-X"); requestedScreenFields.emplace_back("RMS_VELOCITY-Y"); nRequestedScreenFields = requestedScreenFields.size(); } if (nRequestedVolumeFields == 0){ requestedVolumeFields.emplace_back("COORDINATES"); requestedVolumeFields.emplace_back("SOLUTION"); requestedVolumeFields.emplace_back("PRIMITIVE"); if (config->GetGrid_Movement()) requestedVolumeFields.emplace_back("GRID_VELOCITY"); nRequestedVolumeFields = requestedVolumeFields.size(); } stringstream ss; ss << "Zone " << config->GetiZone() << " (Incomp. Fluid)"; multiZoneHeaderString = ss.str(); /*--- Set the volume filename --- */ volumeFilename = config->GetVolume_FileName(); /*--- Set the surface filename --- */ surfaceFilename = config->GetSurfCoeff_FileName(); /*--- Set the restart filename --- */ restartFilename = config->GetRestart_FileName(); /*--- Set the default convergence field --- */ if (convFields.empty() ) convFields.emplace_back("RMS_PRESSURE"); } CFlowIncOutput::~CFlowIncOutput(void) {} void CFlowIncOutput::SetHistoryOutputFields(CConfig *config){ /// BEGIN_GROUP: RMS_RES, DESCRIPTION: The root-mean-square residuals of the SOLUTION variables. /// DESCRIPTION: Root-mean square residual of the pressure. AddHistoryOutput("RMS_PRESSURE", "rms[P]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the pressure.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Root-mean square residual of the velocity x-component. AddHistoryOutput("RMS_VELOCITY-X", "rms[U]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the velocity x-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Root-mean square residual of the velocity y-component. AddHistoryOutput("RMS_VELOCITY-Y", "rms[V]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the velocity y-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Root-mean square residual of the velocity z-component. if (nDim == 3) AddHistoryOutput("RMS_VELOCITY-Z", "rms[W]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the velocity z-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the temperature. if (heat || weakly_coupled_heat) AddHistoryOutput("RMS_TEMPERATURE", "rms[T]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the temperature.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Root-mean square residual of the radiative energy (P1 model). if (config->AddRadiation()) AddHistoryOutput("RMS_RAD_ENERGY", "rms[E_Rad]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the radiative energy.", HistoryFieldType::RESIDUAL); switch(turb_model){ case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP: /// DESCRIPTION: Root-mean square residual of nu tilde (SA model). AddHistoryOutput("RMS_NU_TILDE", "rms[nu]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of nu tilde (SA model).", HistoryFieldType::RESIDUAL); break; case SST: case SST_SUST: /// DESCRIPTION: Root-mean square residual of kinetic energy (SST model). AddHistoryOutput("RMS_TKE", "rms[k]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of kinetic energy (SST model).", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Root-mean square residual of the dissipation (SST model). AddHistoryOutput("RMS_DISSIPATION", "rms[w]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of dissipation (SST model).", HistoryFieldType::RESIDUAL); break; default: break; } /// END_GROUP /// BEGIN_GROUP: MAX_RES, DESCRIPTION: The maximum residuals of the SOLUTION variables. /// DESCRIPTION: Maximum residual of the pressure. AddHistoryOutput("MAX_PRESSURE", "max[P]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the pressure.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the velocity x-component. AddHistoryOutput("MAX_VELOCITY-X", "max[U]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the velocity x-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the velocity y-component. AddHistoryOutput("MAX_VELOCITY-Y", "max[V]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the velocity y-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the velocity z-component. if (nDim == 3) AddHistoryOutput("MAX_VELOCITY-Z", "max[W]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the velocity z-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the temperature. if (heat || weakly_coupled_heat) AddHistoryOutput("MAX_TEMPERATURE", "max[T]", ScreenOutputFormat::FIXED, "MAX_RES", "Root-mean square residual of the temperature.", HistoryFieldType::RESIDUAL); switch(turb_model){ case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP: /// DESCRIPTION: Maximum residual of nu tilde (SA model). AddHistoryOutput("MAX_NU_TILDE", "max[nu]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of nu tilde (SA model).", HistoryFieldType::RESIDUAL); break; case SST: case SST_SUST: /// DESCRIPTION: Maximum residual of kinetic energy (SST model). AddHistoryOutput("MAX_TKE", "max[k]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of kinetic energy (SST model).", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the dissipation (SST model). AddHistoryOutput("MAX_DISSIPATION", "max[w]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of dissipation (SST model).", HistoryFieldType::RESIDUAL); break; default: break; } /// END_GROUP /// BEGIN_GROUP: BGS_RES, DESCRIPTION: The block-gauss seidel residuals of the SOLUTION variables. /// DESCRIPTION: Maximum residual of the pressure. AddHistoryOutput("BGS_PRESSURE", "bgs[P]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the pressure.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the velocity x-component. AddHistoryOutput("BGS_VELOCITY-X", "bgs[U]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the velocity x-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the velocity y-component. AddHistoryOutput("BGS_VELOCITY-Y", "bgs[V]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the velocity y-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the velocity z-component. if (nDim == 3) AddHistoryOutput("BGS_VELOCITY-Z", "bgs[W]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the velocity z-component.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the temperature. if (heat || weakly_coupled_heat) AddHistoryOutput("BGS_TEMPERATURE", "bgs[T]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the temperature.", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Multizone residual of the radiative energy (P1 model). if (config->AddRadiation()) AddHistoryOutput("BGS_RAD_ENERGY", "bgs[E_Rad]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the radiative energy.", HistoryFieldType::RESIDUAL); switch(turb_model){ case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP: /// DESCRIPTION: Maximum residual of nu tilde (SA model). AddHistoryOutput("BGS_NU_TILDE", "bgs[nu]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of nu tilde (SA model).", HistoryFieldType::RESIDUAL); break; case SST: case SST_SUST: /// DESCRIPTION: Maximum residual of kinetic energy (SST model). AddHistoryOutput("BGS_TKE", "bgs[k]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of kinetic energy (SST model).", HistoryFieldType::RESIDUAL); /// DESCRIPTION: Maximum residual of the dissipation (SST model). AddHistoryOutput("BGS_DISSIPATION", "bgs[w]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of dissipation (SST model).", HistoryFieldType::RESIDUAL); break; default: break; } /// END_GROUP /// BEGIN_GROUP: ROTATING_FRAME, DESCRIPTION: Coefficients related to a rotating frame of reference. /// DESCRIPTION: Merit AddHistoryOutput("MERIT", "CMerit", ScreenOutputFormat::SCIENTIFIC, "ROTATING_FRAME", "Merit", HistoryFieldType::COEFFICIENT); /// DESCRIPTION: CT AddHistoryOutput("CT", "CT", ScreenOutputFormat::SCIENTIFIC, "ROTATING_FRAME", "CT", HistoryFieldType::COEFFICIENT); /// DESCRIPTION: CQ AddHistoryOutput("CQ", "CQ", ScreenOutputFormat::SCIENTIFIC, "ROTATING_FRAME", "CQ", HistoryFieldType::COEFFICIENT); /// END_GROUP /// BEGIN_GROUP: HEAT_COEFF, DESCRIPTION: Heat coefficients on all surfaces set with MARKER_MONITORING. /// DESCRIPTION: Total heatflux AddHistoryOutput("TOTAL_HEATFLUX", "HF", ScreenOutputFormat::SCIENTIFIC, "HEAT", "Total heatflux on all surfaces set with MARKER_MONITORING.", HistoryFieldType::COEFFICIENT); /// DESCRIPTION: Maximal heatflux AddHistoryOutput("HEATFLUX_MAX", "maxHF", ScreenOutputFormat::SCIENTIFIC, "HEAT", "Total maximum heatflux on all surfaces set with MARKER_MONITORING.", HistoryFieldType::COEFFICIENT); /// DESCRIPTION: Temperature AddHistoryOutput("TEMPERATURE", "Temp", ScreenOutputFormat::SCIENTIFIC, "HEAT", "Total avg. temperature on all surfaces set with MARKER_MONITORING.", HistoryFieldType::COEFFICIENT); /// END_GROUP /// DESCRIPTION: Angle of attack AddHistoryOutput("AOA", "AoA", ScreenOutputFormat::SCIENTIFIC,"AOA", "Angle of attack"); /// DESCRIPTION: Linear solver iterations AddHistoryOutput("LINSOL_ITER", "LinSolIter", ScreenOutputFormat::INTEGER, "LINSOL", "Number of iterations of the linear solver."); AddHistoryOutput("LINSOL_RESIDUAL", "LinSolRes", ScreenOutputFormat::FIXED, "LINSOL", "Residual of the linear solver."); AddHistoryOutput("MIN_DELTA_TIME", "Min DT", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current minimum local time step"); AddHistoryOutput("MAX_DELTA_TIME", "Max DT", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current maximum local time step"); AddHistoryOutput("MIN_CFL", "Min CFL", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current minimum of the local CFL numbers"); AddHistoryOutput("MAX_CFL", "Max CFL", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current maximum of the local CFL numbers"); AddHistoryOutput("AVG_CFL", "Avg CFL", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current average of the local CFL numbers"); if (config->GetDeform_Mesh()){ AddHistoryOutput("DEFORM_MIN_VOLUME", "MinVolume", ScreenOutputFormat::SCIENTIFIC, "DEFORM", "Minimum volume in the mesh"); AddHistoryOutput("DEFORM_MAX_VOLUME", "MaxVolume", ScreenOutputFormat::SCIENTIFIC, "DEFORM", "Maximum volume in the mesh"); AddHistoryOutput("DEFORM_ITER", "DeformIter", ScreenOutputFormat::INTEGER, "DEFORM", "Linear solver iterations for the mesh deformation"); AddHistoryOutput("DEFORM_RESIDUAL", "DeformRes", ScreenOutputFormat::FIXED, "DEFORM", "Residual of the linear solver for the mesh deformation"); } /*--- Add analyze surface history fields --- */ AddAnalyzeSurfaceOutput(config); /*--- Add aerodynamic coefficients fields --- */ AddAerodynamicCoefficients(config); } void CFlowIncOutput::LoadHistoryData(CConfig *config, CGeometry *geometry, CSolver **solver) { CSolver* flow_solver = solver[FLOW_SOL]; CSolver* turb_solver = solver[TURB_SOL]; CSolver* heat_solver = solver[HEAT_SOL]; CSolver* rad_solver = solver[RAD_SOL]; CSolver* mesh_solver = solver[MESH_SOL]; SetHistoryOutputValue("RMS_PRESSURE", log10(flow_solver->GetRes_RMS(0))); SetHistoryOutputValue("RMS_VELOCITY-X", log10(flow_solver->GetRes_RMS(1))); SetHistoryOutputValue("RMS_VELOCITY-Y", log10(flow_solver->GetRes_RMS(2))); if (nDim == 3) SetHistoryOutputValue("RMS_VELOCITY-Z", log10(flow_solver->GetRes_RMS(3))); switch(turb_model){ case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP: SetHistoryOutputValue("RMS_NU_TILDE", log10(turb_solver->GetRes_RMS(0))); break; case SST: case SST_SUST: SetHistoryOutputValue("RMS_TKE", log10(turb_solver->GetRes_RMS(0))); SetHistoryOutputValue("RMS_DISSIPATION", log10(turb_solver->GetRes_RMS(1))); break; } if (config->AddRadiation()) SetHistoryOutputValue("RMS_RAD_ENERGY", log10(rad_solver->GetRes_RMS(0))); SetHistoryOutputValue("MAX_PRESSURE", log10(flow_solver->GetRes_Max(0))); SetHistoryOutputValue("MAX_VELOCITY-X", log10(flow_solver->GetRes_Max(1))); SetHistoryOutputValue("MAX_VELOCITY-Y", log10(flow_solver->GetRes_Max(2))); if (nDim == 3) SetHistoryOutputValue("RMS_VELOCITY-Z", log10(flow_solver->GetRes_Max(3))); switch(turb_model){ case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP: SetHistoryOutputValue("MAX_NU_TILDE", log10(turb_solver->GetRes_Max(0))); break; case SST: case SST_SUST: SetHistoryOutputValue("MAX_TKE", log10(turb_solver->GetRes_Max(0))); SetHistoryOutputValue("MAX_DISSIPATION", log10(turb_solver->GetRes_Max(1))); break; } if (multiZone){ SetHistoryOutputValue("BGS_PRESSURE", log10(flow_solver->GetRes_BGS(0))); SetHistoryOutputValue("BGS_VELOCITY-X", log10(flow_solver->GetRes_BGS(1))); SetHistoryOutputValue("BGS_VELOCITY-Y", log10(flow_solver->GetRes_BGS(2))); if (nDim == 3) SetHistoryOutputValue("BGS_VELOCITY-Z", log10(flow_solver->GetRes_BGS(3))); switch(turb_model){ case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP: SetHistoryOutputValue("BGS_NU_TILDE", log10(turb_solver->GetRes_BGS(0))); break; case SST: SetHistoryOutputValue("BGS_TKE", log10(turb_solver->GetRes_BGS(0))); SetHistoryOutputValue("BGS_DISSIPATION", log10(turb_solver->GetRes_BGS(1))); break; } if (config->AddRadiation()) SetHistoryOutputValue("BGS_RAD_ENERGY", log10(rad_solver->GetRes_BGS(0))); } if (weakly_coupled_heat){ SetHistoryOutputValue("TOTAL_HEATFLUX", heat_solver->GetTotal_HeatFlux()); SetHistoryOutputValue("HEATFLUX_MAX", heat_solver->GetTotal_MaxHeatFlux()); SetHistoryOutputValue("TEMPERATURE", heat_solver->GetTotal_AvgTemperature()); SetHistoryOutputValue("RMS_TEMPERATURE", log10(heat_solver->GetRes_RMS(0))); SetHistoryOutputValue("MAX_TEMPERATURE", log10(heat_solver->GetRes_Max(0))); if (multiZone) SetHistoryOutputValue("BGS_TEMPERATURE", log10(heat_solver->GetRes_BGS(0))); } if (heat){ SetHistoryOutputValue("TOTAL_HEATFLUX", flow_solver->GetTotal_HeatFlux()); SetHistoryOutputValue("HEATFLUX_MAX", flow_solver->GetTotal_MaxHeatFlux()); SetHistoryOutputValue("TEMPERATURE", flow_solver->GetTotal_AvgTemperature()); if (nDim == 3) SetHistoryOutputValue("RMS_TEMPERATURE", log10(flow_solver->GetRes_RMS(4))); else SetHistoryOutputValue("RMS_TEMPERATURE", log10(flow_solver->GetRes_RMS(3))); if (nDim == 3) SetHistoryOutputValue("MAX_TEMPERATURE", log10(flow_solver->GetRes_Max(4))); else SetHistoryOutputValue("MAX_TEMPERATURE", log10(flow_solver->GetRes_Max(3))); if (multiZone){ if (nDim == 3) SetHistoryOutputValue("BGS_TEMPERATURE", log10(flow_solver->GetRes_BGS(4))); else SetHistoryOutputValue("BGS_TEMPERATURE", log10(flow_solver->GetRes_BGS(3))); } } SetHistoryOutputValue("LINSOL_ITER", flow_solver->GetIterLinSolver()); SetHistoryOutputValue("LINSOL_RESIDUAL", log10(flow_solver->GetResLinSolver())); if (config->GetDeform_Mesh()){ SetHistoryOutputValue("DEFORM_MIN_VOLUME", mesh_solver->GetMinimum_Volume()); SetHistoryOutputValue("DEFORM_MAX_VOLUME", mesh_solver->GetMaximum_Volume()); SetHistoryOutputValue("DEFORM_ITER", mesh_solver->GetIterLinSolver()); SetHistoryOutputValue("DEFORM_RESIDUAL", log10(mesh_solver->GetResLinSolver())); } SetHistoryOutputValue("MIN_DELTA_TIME", flow_solver->GetMin_Delta_Time()); SetHistoryOutputValue("MAX_DELTA_TIME", flow_solver->GetMax_Delta_Time()); SetHistoryOutputValue("MIN_CFL", flow_solver->GetMin_CFL_Local()); SetHistoryOutputValue("MAX_CFL", flow_solver->GetMax_CFL_Local()); SetHistoryOutputValue("AVG_CFL", flow_solver->GetAvg_CFL_Local()); /*--- Set the analyse surface history values --- */ SetAnalyzeSurface(flow_solver, geometry, config, false); /*--- Set aeroydnamic coefficients --- */ SetAerodynamicCoefficients(config, flow_solver); /*--- Set rotating frame coefficients --- */ SetRotatingFrameCoefficients(config, flow_solver); } void CFlowIncOutput::SetVolumeOutputFields(CConfig *config){ // Grid coordinates AddVolumeOutput("COORD-X", "x", "COORDINATES", "x-component of the coordinate vector"); AddVolumeOutput("COORD-Y", "y", "COORDINATES", "y-component of the coordinate vector"); if (nDim == 3) AddVolumeOutput("COORD-Z", "z", "COORDINATES", "z-component of the coordinate vector"); // SOLUTION variables AddVolumeOutput("PRESSURE", "Pressure", "SOLUTION", "Pressure"); AddVolumeOutput("VELOCITY-X", "Velocity_x", "SOLUTION", "x-component of the velocity vector"); AddVolumeOutput("VELOCITY-Y", "Velocity_y", "SOLUTION", "y-component of the velocity vector"); if (nDim == 3) AddVolumeOutput("VELOCITY-Z", "Velocity_z", "SOLUTION", "z-component of the velocity vector"); if (heat || weakly_coupled_heat) AddVolumeOutput("TEMPERATURE", "Temperature","SOLUTION", "Temperature"); switch(config->GetKind_Turb_Model()){ case SST: case SST_SUST: AddVolumeOutput("TKE", "Turb_Kin_Energy", "SOLUTION", "Turbulent kinetic energy"); AddVolumeOutput("DISSIPATION", "Omega", "SOLUTION", "Rate of dissipation"); break; case SA: case SA_COMP: case SA_E: case SA_E_COMP: case SA_NEG: AddVolumeOutput("NU_TILDE", "Nu_Tilde", "SOLUTION", "Spalart–Allmaras variable"); break; case NONE: break; } // Radiation variables if (config->AddRadiation()) AddVolumeOutput("P1-RAD", "Radiative_Energy(P1)", "SOLUTION", "Radiative Energy"); // Grid velocity if (config->GetGrid_Movement()){ AddVolumeOutput("GRID_VELOCITY-X", "Grid_Velocity_x", "GRID_VELOCITY", "x-component of the grid velocity vector"); AddVolumeOutput("GRID_VELOCITY-Y", "Grid_Velocity_y", "GRID_VELOCITY", "y-component of the grid velocity vector"); if (nDim == 3 ) AddVolumeOutput("GRID_VELOCITY-Z", "Grid_Velocity_z", "GRID_VELOCITY", "z-component of the grid velocity vector"); } // Primitive variables AddVolumeOutput("PRESSURE_COEFF", "Pressure_Coefficient", "PRIMITIVE", "Pressure coefficient"); AddVolumeOutput("DENSITY", "Density", "PRIMITIVE", "Density"); if (config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){ AddVolumeOutput("LAMINAR_VISCOSITY", "Laminar_Viscosity", "PRIMITIVE", "Laminar viscosity"); AddVolumeOutput("SKIN_FRICTION-X", "Skin_Friction_Coefficient_x", "PRIMITIVE", "x-component of the skin friction vector"); AddVolumeOutput("SKIN_FRICTION-Y", "Skin_Friction_Coefficient_y", "PRIMITIVE", "y-component of the skin friction vector"); if (nDim == 3) AddVolumeOutput("SKIN_FRICTION-Z", "Skin_Friction_Coefficient_z", "PRIMITIVE", "z-component of the skin friction vector"); AddVolumeOutput("HEAT_FLUX", "Heat_Flux", "PRIMITIVE", "Heat-flux"); AddVolumeOutput("Y_PLUS", "Y_Plus", "PRIMITIVE", "Non-dim. wall distance (Y-Plus)"); } if (config->GetKind_Solver() == INC_RANS) { AddVolumeOutput("EDDY_VISCOSITY", "Eddy_Viscosity", "PRIMITIVE", "Turbulent eddy viscosity"); } if (config->GetKind_Trans_Model() == BC){ AddVolumeOutput("INTERMITTENCY", "gamma_BC", "INTERMITTENCY", "Intermittency"); } //Residuals AddVolumeOutput("RES_PRESSURE", "Residual_Pressure", "RESIDUAL", "Residual of the pressure"); AddVolumeOutput("RES_VELOCITY-X", "Residual_Velocity_x", "RESIDUAL", "Residual of the x-velocity component"); AddVolumeOutput("RES_VELOCITY-Y", "Residual_Velocity_y", "RESIDUAL", "Residual of the y-velocity component"); if (nDim == 3) AddVolumeOutput("RES_VELOCITY-Z", "Residual_Velocity_z", "RESIDUAL", "Residual of the z-velocity component"); AddVolumeOutput("RES_TEMPERATURE", "Residual_Temperature", "RESIDUAL", "Residual of the temperature"); switch(config->GetKind_Turb_Model()){ case SST: case SST_SUST: AddVolumeOutput("RES_TKE", "Residual_TKE", "RESIDUAL", "Residual of turbulent kinetic energy"); AddVolumeOutput("RES_DISSIPATION", "Residual_Omega", "RESIDUAL", "Residual of the rate of dissipation."); break; case SA: case SA_COMP: case SA_E: case SA_E_COMP: case SA_NEG: AddVolumeOutput("RES_NU_TILDE", "Residual_Nu_Tilde", "RESIDUAL", "Residual of the Spalart–Allmaras variable"); break; case NONE: break; } // Limiter values AddVolumeOutput("LIMITER_PRESSURE", "Limiter_Pressure", "LIMITER", "Limiter value of the pressure"); AddVolumeOutput("LIMITER_VELOCITY-X", "Limiter_Velocity_x", "LIMITER", "Limiter value of the x-velocity"); AddVolumeOutput("LIMITER_VELOCITY-Y", "Limiter_Velocity_y", "LIMITER", "Limiter value of the y-velocity"); if (nDim == 3) AddVolumeOutput("LIMITER_VELOCITY-Z", "Limiter_Velocity_z", "LIMITER", "Limiter value of the z-velocity"); AddVolumeOutput("LIMITER_TEMPERATURE", "Limiter_Temperature", "LIMITER", "Limiter value of the temperature"); switch(config->GetKind_Turb_Model()){ case SST: case SST_SUST: AddVolumeOutput("LIMITER_TKE", "Limiter_TKE", "LIMITER", "Limiter value of turb. kinetic energy."); AddVolumeOutput("LIMITER_DISSIPATION", "Limiter_Omega", "LIMITER", "Limiter value of dissipation rate."); break; case SA: case SA_COMP: case SA_E: case SA_E_COMP: case SA_NEG: AddVolumeOutput("LIMITER_NU_TILDE", "Limiter_Nu_Tilde", "LIMITER", "Limiter value of Spalart–Allmaras variable."); break; case NONE: break; } // Hybrid RANS-LES if (config->GetKind_HybridRANSLES() != NO_HYBRIDRANSLES){ AddVolumeOutput("DES_LENGTHSCALE", "DES_LengthScale", "DDES", "DES length scale value"); AddVolumeOutput("WALL_DISTANCE", "Wall_Distance", "DDES", "Wall distance value"); } // Roe Low Dissipation if (config->GetKind_RoeLowDiss() != NO_ROELOWDISS){ AddVolumeOutput("ROE_DISSIPATION", "Roe_Dissipation", "ROE_DISSIPATION", "Value of the Roe dissipation"); } if(config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){ if (nDim == 3){ AddVolumeOutput("VORTICITY_X", "Vorticity_x", "VORTEX_IDENTIFICATION", "x-component of the vorticity vector"); AddVolumeOutput("VORTICITY_Y", "Vorticity_y", "VORTEX_IDENTIFICATION", "y-component of the vorticity vector"); AddVolumeOutput("VORTICITY_Z", "Vorticity_z", "VORTEX_IDENTIFICATION", "z-component of the vorticity vector"); } else { AddVolumeOutput("VORTICITY", "Vorticity", "VORTEX_IDENTIFICATION", "Value of the vorticity"); } AddVolumeOutput("Q_CRITERION", "Q_Criterion", "VORTEX_IDENTIFICATION", "Value of the Q-Criterion"); } } void CFlowIncOutput::LoadVolumeData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint){ CVariable* Node_Flow = solver[FLOW_SOL]->GetNodes(); CVariable* Node_Heat = nullptr; CVariable* Node_Turb = nullptr; CVariable* Node_Rad = nullptr; if (config->GetKind_Turb_Model() != NONE){ Node_Turb = solver[TURB_SOL]->GetNodes(); } if (weakly_coupled_heat){ Node_Heat = solver[HEAT_SOL]->GetNodes(); } CPoint* Node_Geo = geometry->nodes; SetVolumeOutputValue("COORD-X", iPoint, Node_Geo->GetCoord(iPoint, 0)); SetVolumeOutputValue("COORD-Y", iPoint, Node_Geo->GetCoord(iPoint, 1)); if (nDim == 3) SetVolumeOutputValue("COORD-Z", iPoint, Node_Geo->GetCoord(iPoint, 2)); SetVolumeOutputValue("PRESSURE", iPoint, Node_Flow->GetSolution(iPoint, 0)); SetVolumeOutputValue("VELOCITY-X", iPoint, Node_Flow->GetSolution(iPoint, 1)); SetVolumeOutputValue("VELOCITY-Y", iPoint, Node_Flow->GetSolution(iPoint, 2)); if (nDim == 3){ SetVolumeOutputValue("VELOCITY-Z", iPoint, Node_Flow->GetSolution(iPoint, 3)); if (heat) SetVolumeOutputValue("TEMPERATURE", iPoint, Node_Flow->GetSolution(iPoint, 4)); } else { if (heat) SetVolumeOutputValue("TEMPERATURE", iPoint, Node_Flow->GetSolution(iPoint, 3)); } if (weakly_coupled_heat) SetVolumeOutputValue("TEMPERATURE", iPoint, Node_Heat->GetSolution(iPoint, 0)); switch(config->GetKind_Turb_Model()){ case SST: case SST_SUST: SetVolumeOutputValue("TKE", iPoint, Node_Turb->GetSolution(iPoint, 0)); SetVolumeOutputValue("DISSIPATION", iPoint, Node_Turb->GetSolution(iPoint, 1)); break; case SA: case SA_COMP: case SA_E: case SA_E_COMP: case SA_NEG: SetVolumeOutputValue("NU_TILDE", iPoint, Node_Turb->GetSolution(iPoint, 0)); break; case NONE: break; } // Radiation solver if (config->AddRadiation()){ Node_Rad = solver[RAD_SOL]->GetNodes(); SetVolumeOutputValue("P1-RAD", iPoint, Node_Rad->GetSolution(iPoint,0)); } if (config->GetGrid_Movement()){ SetVolumeOutputValue("GRID_VELOCITY-X", iPoint, Node_Geo->GetGridVel(iPoint)[0]); SetVolumeOutputValue("GRID_VELOCITY-Y", iPoint, Node_Geo->GetGridVel(iPoint)[1]); if (nDim == 3) SetVolumeOutputValue("GRID_VELOCITY-Z", iPoint, Node_Geo->GetGridVel(iPoint)[2]); } su2double VelMag = 0.0; for (unsigned short iDim = 0; iDim < nDim; iDim++){ VelMag += pow(solver[FLOW_SOL]->GetVelocity_Inf(iDim),2.0); } su2double factor = 1.0/(0.5*solver[FLOW_SOL]->GetDensity_Inf()*VelMag); SetVolumeOutputValue("PRESSURE_COEFF", iPoint, (Node_Flow->GetPressure(iPoint) - config->GetPressure_FreeStreamND())*factor); SetVolumeOutputValue("DENSITY", iPoint, Node_Flow->GetDensity(iPoint)); if (config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){ SetVolumeOutputValue("LAMINAR_VISCOSITY", iPoint, Node_Flow->GetLaminarViscosity(iPoint)); } if (config->GetKind_Solver() == INC_RANS) { SetVolumeOutputValue("EDDY_VISCOSITY", iPoint, Node_Flow->GetEddyViscosity(iPoint)); } if (config->GetKind_Trans_Model() == BC){ SetVolumeOutputValue("INTERMITTENCY", iPoint, Node_Turb->GetGammaBC(iPoint)); } SetVolumeOutputValue("RES_PRESSURE", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 0)); SetVolumeOutputValue("RES_VELOCITY-X", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 1)); SetVolumeOutputValue("RES_VELOCITY-Y", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 2)); if (nDim == 3){ SetVolumeOutputValue("RES_VELOCITY-Z", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 3)); SetVolumeOutputValue("RES_TEMPERATURE", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 4)); } else { SetVolumeOutputValue("RES_TEMPERATURE", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 3)); } switch(config->GetKind_Turb_Model()){ case SST: case SST_SUST: SetVolumeOutputValue("RES_TKE", iPoint, solver[TURB_SOL]->LinSysRes(iPoint, 0)); SetVolumeOutputValue("RES_DISSIPATION", iPoint, solver[TURB_SOL]->LinSysRes(iPoint, 1)); break; case SA: case SA_COMP: case SA_E: case SA_E_COMP: case SA_NEG: SetVolumeOutputValue("RES_NU_TILDE", iPoint, solver[TURB_SOL]->LinSysRes(iPoint, 0)); break; case NONE: break; } SetVolumeOutputValue("LIMITER_PRESSURE", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 0)); SetVolumeOutputValue("LIMITER_VELOCITY-X", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 1)); SetVolumeOutputValue("LIMITER_VELOCITY-Y", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 2)); if (nDim == 3){ SetVolumeOutputValue("LIMITER_VELOCITY-Z", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 3)); SetVolumeOutputValue("LIMITER_TEMPERATURE", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 4)); } else { SetVolumeOutputValue("LIMITER_TEMPERATURE", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 3)); } switch(config->GetKind_Turb_Model()){ case SST: case SST_SUST: SetVolumeOutputValue("LIMITER_TKE", iPoint, Node_Turb->GetLimiter_Primitive(iPoint, 0)); SetVolumeOutputValue("LIMITER_DISSIPATION", iPoint, Node_Turb->GetLimiter_Primitive(iPoint, 1)); break; case SA: case SA_COMP: case SA_E: case SA_E_COMP: case SA_NEG: SetVolumeOutputValue("LIMITER_NU_TILDE", iPoint, Node_Turb->GetLimiter_Primitive(iPoint, 0)); break; case NONE: break; } if (config->GetKind_HybridRANSLES() != NO_HYBRIDRANSLES){ SetVolumeOutputValue("DES_LENGTHSCALE", iPoint, Node_Flow->GetDES_LengthScale(iPoint)); SetVolumeOutputValue("WALL_DISTANCE", iPoint, Node_Geo->GetWall_Distance(iPoint)); } if (config->GetKind_RoeLowDiss() != NO_ROELOWDISS){ SetVolumeOutputValue("ROE_DISSIPATION", iPoint, Node_Flow->GetRoe_Dissipation(iPoint)); } if(config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){ if (nDim == 3){ SetVolumeOutputValue("VORTICITY_X", iPoint, Node_Flow->GetVorticity(iPoint)[0]); SetVolumeOutputValue("VORTICITY_Y", iPoint, Node_Flow->GetVorticity(iPoint)[1]); SetVolumeOutputValue("VORTICITY_Z", iPoint, Node_Flow->GetVorticity(iPoint)[2]); } else { SetVolumeOutputValue("VORTICITY", iPoint, Node_Flow->GetVorticity(iPoint)[2]); } SetVolumeOutputValue("Q_CRITERION", iPoint, GetQ_Criterion(&(Node_Flow->GetGradient_Primitive(iPoint)[1]))); } } void CFlowIncOutput::LoadSurfaceData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint, unsigned short iMarker, unsigned long iVertex){ if ((config->GetKind_Solver() == INC_NAVIER_STOKES) || (config->GetKind_Solver() == INC_RANS)) { SetVolumeOutputValue("SKIN_FRICTION-X", iPoint, solver[FLOW_SOL]->GetCSkinFriction(iMarker, iVertex, 0)); SetVolumeOutputValue("SKIN_FRICTION-Y", iPoint, solver[FLOW_SOL]->GetCSkinFriction(iMarker, iVertex, 1)); if (nDim == 3) SetVolumeOutputValue("SKIN_FRICTION-Z", iPoint, solver[FLOW_SOL]->GetCSkinFriction(iMarker, iVertex, 2)); if (weakly_coupled_heat) SetVolumeOutputValue("HEAT_FLUX", iPoint, solver[HEAT_SOL]->GetHeatFlux(iMarker, iVertex)); else { SetVolumeOutputValue("HEAT_FLUX", iPoint, solver[FLOW_SOL]->GetHeatFlux(iMarker, iVertex)); } SetVolumeOutputValue("Y_PLUS", iPoint, solver[FLOW_SOL]->GetYPlus(iMarker, iVertex)); } } bool CFlowIncOutput::SetInit_Residuals(CConfig *config){ return (config->GetTime_Marching() != STEADY && (curInnerIter == 0))|| (config->GetTime_Marching() == STEADY && (curInnerIter < 2)); } bool CFlowIncOutput::SetUpdate_Averages(CConfig *config){ return (config->GetTime_Marching() != STEADY && (curInnerIter == config->GetnInner_Iter() - 1 || convergence)); }
49.93465
200
0.728916
Agony5757
2e302fc270d22b89db1aede75e0c47b29168bfd8
6,559
cpp
C++
wws_lua/extras/Lua.Utilities/luawrapper.cpp
ViseEngine/SLED
7815ee6feb656d43f70edba8280caa8a69d0983b
[ "Apache-2.0" ]
158
2015-03-03T00:11:56.000Z
2022-02-08T18:43:11.000Z
wws_lua/extras/Lua.Utilities/luawrapper.cpp
mcanthony/SLED
7815ee6feb656d43f70edba8280caa8a69d0983b
[ "Apache-2.0" ]
3
2015-04-30T13:00:43.000Z
2015-07-07T22:58:35.000Z
wws_lua/extras/Lua.Utilities/luawrapper.cpp
mcanthony/SLED
7815ee6feb656d43f70edba8280caa8a69d0983b
[ "Apache-2.0" ]
48
2015-03-05T05:30:45.000Z
2021-10-18T02:09:02.000Z
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ #include "stdafx.h" #include "luawrapper.h" #include <msclr\marshal_cppstd.h> #include <string> namespace Unmanaged { StackReconciler::StackReconciler(lua_State* luaState) : m_luaState(luaState) , m_count(LuaInterface::GetTop(luaState)) { } StackReconciler::~StackReconciler() { const int count = LuaInterface::GetTop(m_luaState); if ((count != m_count) && (count > m_count)) LuaInterface::Pop(m_luaState, count - m_count); } LuaWrapper::LuaWrapper() : m_luaState(NULL) { m_luaState = LuaInterface::Open(); LuaInterface::OpenLibs(m_luaState); } LuaWrapper::~LuaWrapper() { LuaInterface::Close(m_luaState); } LuaInterface::Errors::Enum LuaWrapper::LoadFile(System::String^ scriptFile) { const std::string str = msclr::interop::marshal_as<std::string>(scriptFile); return LuaInterface::TranslateLuaError(LuaInterface::LoadFile(m_luaState, str.c_str())); } LuaInterface::Errors::Enum LuaWrapper::LoadFile(System::String^ scriptFile, Sce::Lua::Utilities::ParserVariableDelegate^ globalCb, Sce::Lua::Utilities::ParserVariableDelegate^ localCb, Sce::Lua::Utilities::ParserVariableDelegate^ upvalueCb, Sce::Lua::Utilities::ParserFunctionDelegate^ funcCb, Sce::Lua::Utilities::ParserBreakpointDelegate^ bpCb, Sce::Lua::Utilities::ParserLogDelegate^ logCb) { System::IntPtr ipGlobalCb = globalCb == nullptr ? System::IntPtr::Zero : System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(globalCb); System::IntPtr ipLocalCb = localCb == nullptr ? System::IntPtr::Zero : System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(localCb); System::IntPtr ipUpvalueCb = upvalueCb == nullptr ? System::IntPtr::Zero : System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(upvalueCb); System::IntPtr ipFuncCb = funcCb == nullptr ? System::IntPtr::Zero : System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(funcCb); System::IntPtr ipBpCb = bpCb == nullptr ? System::IntPtr::Zero : System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(bpCb); System::IntPtr ipLogCb = logCb == nullptr ? System::IntPtr::Zero : System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(logCb); // Tell Lua about the function pointers { lparser_callbacks::VariableCallback nativeGlobalCb = static_cast<lparser_callbacks::VariableCallback>(ipGlobalCb.ToPointer()); lparser_callbacks::VariableCallback nativeLocalCb = static_cast<lparser_callbacks::VariableCallback>(ipLocalCb.ToPointer()); lparser_callbacks::VariableCallback nativeUpvalueCb = static_cast<lparser_callbacks::VariableCallback>(ipUpvalueCb.ToPointer()); lparser_callbacks::FunctionCallback nativeFuncCb = static_cast<lparser_callbacks::FunctionCallback>(ipFuncCb.ToPointer()); lparser_callbacks::BreakpointCallback nativeBpCb = static_cast<lparser_callbacks::BreakpointCallback>(ipBpCb.ToPointer()); lparser_callbacks::LogCallback nativeLogCb = static_cast<lparser_callbacks::LogCallback>(ipLogCb.ToPointer()); const Unmanaged::StackReconciler recon(m_luaState); LuaInterface::GetGlobal(m_luaState, LUA_PARSER_DEBUG_TABLE); if (LuaInterface::IsNil(m_luaState, -1)) { LuaInterface::Pop(m_luaState, 1); // Create parser debug table LuaInterface::NewTable(m_luaState); LuaInterface::SetGlobal(m_luaState, LUA_PARSER_DEBUG_TABLE); // Get parser debug table on top of stack LuaInterface::GetGlobal(m_luaState, LUA_PARSER_DEBUG_TABLE); // Set function pointers LuaInterface::PushLightUserdata(m_luaState, nativeGlobalCb); LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_VAR_GLOBAL); LuaInterface::PushLightUserdata(m_luaState, nativeLocalCb); LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_VAR_LOCAL); LuaInterface::PushLightUserdata(m_luaState, nativeUpvalueCb); LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_VAR_UPVALUE); LuaInterface::PushLightUserdata(m_luaState, nativeFuncCb); LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_FUNC); LuaInterface::PushLightUserdata(m_luaState, nativeBpCb); LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_BREAKPOINT); LuaInterface::PushLightUserdata(m_luaState, nativeLogCb); LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_LOG); } } const LuaInterface::Errors::Enum retval = LuaInterface::TranslateLuaError(LoadFile(scriptFile)); { ipGlobalCb = System::IntPtr::Zero; ipLocalCb = System::IntPtr::Zero; ipUpvalueCb = System::IntPtr::Zero; ipFuncCb = System::IntPtr::Zero; ipBpCb = System::IntPtr::Zero; ipLogCb = System::IntPtr::Zero; } return retval; } LuaInterface::Errors::Enum LuaWrapper::LoadBuffer(System::String^ scriptBuffer) { const std::string buffer = msclr::interop::marshal_as<std::string>(scriptBuffer); return LuaInterface::TranslateLuaError(LuaInterface::LoadBuffer(m_luaState, buffer.c_str(), buffer.length(), "buffer")); } int LuaWrapper::Compile_Writer(lua_State* L, const void* pData, size_t size, void* pFile) { (void)L; return ((fwrite(pData, size, 1, (FILE *)pFile) != 1) && (size != 0)); } LuaInterface::Errors::Enum LuaWrapper::Compile(System::String^ scriptAbsFilePath, System::String^ scriptAbsDumpFilePath, Sce::Lua::Utilities::LuaCompilerConfig^ config) { // Load script into Lua state { const std::string strInFile = msclr::interop::marshal_as<std::string>(scriptAbsFilePath); const LuaInterface::Errors::Enum err = LuaInterface::TranslateLuaError(LuaInterface::LoadFile(m_luaState, strInFile.c_str())); if (err != LuaInterface::Errors::Ok) return err; } // Create and open the dump file FILE* pDumpFile = 0; { const std::string strOutFile = msclr::interop::marshal_as<std::string>(scriptAbsDumpFilePath); if (fopen_s(&pDumpFile, strOutFile.c_str(), "wb") != 0) return LuaInterface::Errors::ErrOutputFile; } // Dump script to file { LuaInterface::DumpConfig dumpConfig; dumpConfig.endianness = (int)config->Endianness; dumpConfig.sizeof_int = config->SizeOfInt; dumpConfig.sizeof_size_t = config->SizeOfSizeT; dumpConfig.sizeof_lua_Number = config->SizeOfLuaNumber; const LuaInterface::Errors::Enum err = LuaInterface::TranslateLuaError( LuaInterface::DumpEx(m_luaState, Compile_Writer, pDumpFile, (config->StripDebugInfo ? 1 : 0), dumpConfig)); // Close dump file fclose(pDumpFile); return err; } } }
33.984456
168
0.751944
ViseEngine
2e304d5d162ee27191532c7d630113bd7e7998de
12,063
hpp
C++
sources/middle_layer/src/partial_completion.hpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
sources/middle_layer/src/partial_completion.hpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
sources/middle_layer/src/partial_completion.hpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
1
2022-03-28T07:52:21.000Z
2022-03-28T07:52:21.000Z
/******************************************************************************* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #ifndef DML_ML_OWN_PARTIAL_COMPLETION_HPP #define DML_ML_OWN_PARTIAL_COMPLETION_HPP #include <core/descriptor_views.hpp> #include <dml/detail/ml/impl/make_descriptor.hpp> namespace dml::detail::ml { static void update_mem_move_for_continuation(descriptor& dsc) noexcept; static void update_fill_for_continuation(descriptor& dsc) noexcept; static void update_compare_for_continuation(descriptor& dsc) noexcept; static void update_compare_pattern_for_continuation(descriptor& dsc) noexcept; static void update_create_delta_for_continuation(descriptor& dsc) noexcept; static void update_apply_delta_for_continuation(descriptor& dsc) noexcept; static void update_dualcast_for_continuation(descriptor& dsc) noexcept; static void update_crc_for_continuation(descriptor& dsc) noexcept; static void update_copy_crc_for_continuation(descriptor& dsc) noexcept; static void update_dif_check_for_continuation(descriptor& dsc) noexcept; static void update_dif_insert_for_continuation(descriptor& dsc) noexcept; static void update_dif_strip_for_continuation(descriptor& dsc) noexcept; static void update_dif_update_for_continuation(descriptor& dsc) noexcept; static void update_cache_flush_for_continuation(descriptor& dsc) noexcept; static void update_for_continuation(descriptor& dsc) noexcept { auto record = core::get_completion_record(dsc); for (auto& byte : record.bytes) { byte = 0; } auto operation = static_cast<core::operation>(core::any_descriptor(dsc).operation()); switch (operation) { case core::operation::nop: break; case core::operation::drain: break; case core::operation::batch: break; case core::operation::mem_move: update_mem_move_for_continuation(dsc); break; case core::operation::fill: update_fill_for_continuation(dsc); break; case core::operation::compare: update_compare_for_continuation(dsc); break; case core::operation::compare_pattern: update_compare_pattern_for_continuation(dsc); break; case core::operation::create_delta: update_create_delta_for_continuation(dsc); break; case core::operation::apply_delta: update_apply_delta_for_continuation(dsc); break; case core::operation::dualcast: update_dualcast_for_continuation(dsc); break; case core::operation::crc: update_crc_for_continuation(dsc); break; case core::operation::copy_crc: update_copy_crc_for_continuation(dsc); break; case core::operation::dif_check: update_dif_check_for_continuation(dsc); break; case core::operation::dif_insert: update_dif_insert_for_continuation(dsc); break; case core::operation::dif_strip: update_dif_strip_for_continuation(dsc); break; case core::operation::dif_update: update_dif_update_for_continuation(dsc); break; case core::operation::cache_flush: update_cache_flush_for_continuation(dsc); break; } } static void update_mem_move_for_continuation(descriptor& dsc) noexcept { auto mem_move_dsc = core::make_view<core::operation::mem_move>(dsc); auto mem_move_record = core::make_view<core::operation::mem_move>(core::get_completion_record(dsc)); if (0 == mem_move_record.result()) { mem_move_dsc.source_address() += mem_move_record.bytes_completed(); mem_move_dsc.destination_address() += mem_move_record.bytes_completed(); } mem_move_dsc.transfer_size() -= mem_move_record.bytes_completed(); } static void update_fill_for_continuation(descriptor& dsc) noexcept { auto fill_dsc = core::make_view<core::operation::fill>(dsc); auto fill_record = core::make_view<core::operation::fill>(core::get_completion_record(dsc)); fill_dsc.transfer_size() -= fill_record.bytes_completed(); fill_dsc.destination_address() += fill_record.bytes_completed(); } static void update_compare_for_continuation(descriptor& dsc) noexcept { auto compare_dsc = core::make_view<core::operation::compare>(dsc); auto compare_record = core::make_view<core::operation::compare>(core::get_completion_record(dsc)); compare_dsc.transfer_size() -= compare_record.bytes_completed(); compare_dsc.source_1_address() += compare_record.bytes_completed(); compare_dsc.source_2_address() += compare_record.bytes_completed(); } static void update_compare_pattern_for_continuation(descriptor& dsc) noexcept { auto compare_pattern_dsc = core::make_view<core::operation::compare_pattern>(dsc); auto compare_pattern_record = core::make_view<core::operation::compare_pattern>(core::get_completion_record(dsc)); compare_pattern_dsc.transfer_size() -= compare_pattern_record.bytes_completed(); compare_pattern_dsc.source_address() += compare_pattern_record.bytes_completed(); } static void update_create_delta_for_continuation(descriptor& dsc) noexcept { auto create_delta_dsc = core::make_view<core::operation::create_delta>(dsc); auto create_delta_record = core::make_view<core::operation::create_delta>(core::get_completion_record(dsc)); create_delta_dsc.transfer_size() -= create_delta_record.bytes_completed(); create_delta_dsc.source_1_address() += create_delta_record.bytes_completed(); create_delta_dsc.source_2_address() += create_delta_record.bytes_completed(); create_delta_dsc.maximum_delta_record_size() -= create_delta_record.delta_record_size(); create_delta_dsc.delta_record_address() += create_delta_record.delta_record_size(); } static void update_apply_delta_for_continuation(descriptor& dsc) noexcept { auto apply_delta_dsc = core::make_view<core::operation::apply_delta>(dsc); auto apply_delta_record = core::make_view<core::operation::apply_delta>(core::get_completion_record(dsc)); apply_delta_dsc.delta_record_size() -= apply_delta_record.bytes_completed(); apply_delta_dsc.delta_record_address() += apply_delta_record.bytes_completed(); } static void update_dualcast_for_continuation(descriptor& dsc) noexcept { auto dualcast_dsc = core::make_view<core::operation::dualcast>(dsc); auto dualcast_record = core::make_view<core::operation::dualcast>(core::get_completion_record(dsc)); dualcast_dsc.destination_1_address() += dualcast_record.bytes_completed(); dualcast_dsc.destination_2_address() += dualcast_record.bytes_completed(); dualcast_dsc.source_address() += dualcast_record.bytes_completed(); dualcast_dsc.transfer_size() -= dualcast_record.bytes_completed(); } static void update_crc_for_continuation(descriptor& dsc) noexcept { auto crc_dsc = core::make_view<core::operation::crc>(dsc); auto crc_record = core::make_view<core::operation::crc>(core::get_completion_record(dsc)); crc_dsc.crc_seed() = crc_record.crc_value(); crc_dsc.source_address() += crc_record.bytes_completed(); crc_dsc.transfer_size() -= crc_record.bytes_completed(); } static void update_copy_crc_for_continuation(descriptor& dsc) noexcept { auto copy_crc_dsc = core::make_view<core::operation::copy_crc>(dsc); auto copy_crc_record = core::make_view<core::operation::copy_crc>(core::get_completion_record(dsc)); copy_crc_dsc.crc_seed() = copy_crc_record.crc_value(); copy_crc_dsc.source_address() += copy_crc_record.bytes_completed(); copy_crc_dsc.destination_address() += copy_crc_record.bytes_completed(); copy_crc_dsc.transfer_size() -= copy_crc_record.bytes_completed(); } static void update_dif_check_for_continuation(descriptor& dsc) noexcept { auto dif_check_dsc = core::make_view<core::operation::dif_check>(dsc); auto dif_check_record = core::make_view<core::operation::dif_check>(core::get_completion_record(dsc)); dif_check_dsc.source_app_tag() = dif_check_record.source_app_tag(); dif_check_dsc.source_ref_tag() = dif_check_record.source_ref_tag(); dif_check_dsc.source_address() += dif_check_record.bytes_completed(); dif_check_dsc.transfer_size() -= dif_check_record.bytes_completed(); } static void update_dif_insert_for_continuation(descriptor& dsc) noexcept { auto dif_insert_dsc = core::make_view<core::operation::dif_insert>(dsc); auto dif_insert_record = core::make_view<core::operation::dif_insert>(core::get_completion_record(dsc)); dif_insert_dsc.destination_app_tag() = dif_insert_record.destination_app_tag(); dif_insert_dsc.destination_ref_tag() = dif_insert_record.destination_ref_tag(); dif_insert_dsc.source_address() += dif_insert_record.bytes_completed(); dif_insert_dsc.destination_address() += dif_insert_record.bytes_completed(); dif_insert_dsc.transfer_size() -= dif_insert_record.bytes_completed(); } static void update_dif_strip_for_continuation(descriptor& dsc) noexcept { auto dif_strip_dsc = core::make_view<core::operation::dif_strip>(dsc); auto dif_strip_record = core::make_view<core::operation::dif_strip>(core::get_completion_record(dsc)); dif_strip_dsc.source_app_tag() = dif_strip_record.source_app_tag(); dif_strip_dsc.source_ref_tag() = dif_strip_record.source_ref_tag(); dif_strip_dsc.source_address() += dif_strip_record.bytes_completed(); dif_strip_dsc.destination_address() += dif_strip_record.bytes_completed(); dif_strip_dsc.transfer_size() -= dif_strip_record.bytes_completed(); } static void update_dif_update_for_continuation(descriptor& dsc) noexcept { auto dif_update_dsc = core::make_view<core::operation::dif_update>(dsc); auto dif_update_record = core::make_view<core::operation::dif_update>(core::get_completion_record(dsc)); dif_update_dsc.source_app_tag() = dif_update_record.source_app_tag(); dif_update_dsc.source_app_tag() = dif_update_record.source_app_tag(); dif_update_dsc.destination_app_tag() = dif_update_record.destination_app_tag(); dif_update_dsc.destination_ref_tag() = dif_update_record.destination_ref_tag(); dif_update_dsc.source_ref_tag() = dif_update_record.source_ref_tag(); dif_update_dsc.source_address() += dif_update_record.bytes_completed(); dif_update_dsc.destination_address() += dif_update_record.bytes_completed(); dif_update_dsc.transfer_size() -= dif_update_record.bytes_completed(); } static void update_cache_flush_for_continuation(descriptor& dsc) noexcept { auto cache_flush_dsc = core::make_view<core::operation::cache_flush>(dsc); auto cache_flush_record = core::make_view<core::operation::cache_flush>(core::get_completion_record(dsc)); cache_flush_dsc.destination_address() += cache_flush_record.bytes_completed(); cache_flush_dsc.transfer_size() -= cache_flush_record.bytes_completed(); } } // namespace dml::detail::ml #endif // DML_ML_OWN_PARTIAL_COMPLETION_HPP
46.041985
122
0.691287
hhb584520
2e3152e88bacc8c8fe68107e3ee51ff9b01532fa
93
cpp
C++
gamelib/source/util/json_array.cpp
brodiequinlan/game-framework
4243d9b011e0d17da66874fa77b3b6d7a6c5e440
[ "Apache-2.0" ]
1
2021-11-20T02:36:28.000Z
2021-11-20T02:36:28.000Z
gamelib/source/util/json_array.cpp
Bobsaggetismine/game-framework
4243d9b011e0d17da66874fa77b3b6d7a6c5e440
[ "Apache-2.0" ]
1
2019-06-11T01:45:11.000Z
2019-06-11T01:47:43.000Z
gamelib/source/util/json_array.cpp
Bobsaggetismine/game-framework
4243d9b011e0d17da66874fa77b3b6d7a6c5e440
[ "Apache-2.0" ]
null
null
null
#include "bqpch.h" bq::json bq::json_array::get_o(int index){ return m_objects[index]; }
18.6
42
0.688172
brodiequinlan
2e3245b199e5b94f173ed2a4d3f4939a8207c722
913
hpp
C++
include/inet/Url.hpp
bander9289/StratifyAPI
9b45091aa71a4e5718047438ea4044c1fdc814a3
[ "MIT" ]
2
2016-05-21T03:09:19.000Z
2016-08-27T03:40:51.000Z
include/inet/Url.hpp
bander9289/StratifyAPI
9b45091aa71a4e5718047438ea4044c1fdc814a3
[ "MIT" ]
75
2017-10-08T22:21:19.000Z
2020-03-30T21:13:20.000Z
include/inet/Url.hpp
StratifyLabs/StratifyLib
975a5c25a84296fd0dec64fe4dc579cf7027abe6
[ "MIT" ]
5
2018-03-27T16:44:09.000Z
2020-07-08T16:45:55.000Z
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights. #ifndef SAPI_INET_URL_HPP_ #define SAPI_INET_URL_HPP_ #include "../api/InetObject.hpp" #include "../var/String.hpp" namespace inet { class Url : public api::InfoObject { public: enum protocol { protocol_https, protocol_http }; Url(const var::String & url = ""); int set(const var::String & url); var::String to_string() const; u16 port() const { return m_port; } u8 protocol() const { return m_protocol; } const var::String & domain_name() const { return m_domain_name; } const var::String & path() const { return m_path; } static var::String encode(const var::String & input); static var::String decode(const var::String & input); private: /*! \cond */ var::String m_domain_name; var::String m_path; u8 m_protocol; u16 m_port; /*! \endcond */ }; } #endif // SAPI_INET_URL_HPP_
20.288889
100
0.691128
bander9289
2e381dee7d809dea721d1c0484c45caa8d3a8bf9
4,681
cpp
C++
src/plugin.cpp
hhornbacher/mosquitto-auth-plugin
a44586940bd6c7aca9f00b7b4996e3405bef50aa
[ "MIT" ]
2
2020-06-18T13:21:31.000Z
2021-04-20T23:29:31.000Z
src/plugin.cpp
hhornbacher/mosquitto-auth-plugin
a44586940bd6c7aca9f00b7b4996e3405bef50aa
[ "MIT" ]
null
null
null
src/plugin.cpp
hhornbacher/mosquitto-auth-plugin
a44586940bd6c7aca9f00b7b4996e3405bef50aa
[ "MIT" ]
null
null
null
#include "plugin.h" #include <cstdio> #include <cstring> #include <algorithm> #include <libscrypt.h> #include <mosquitto.h> extern "C" { #include <mosquitto_broker.h> } int MosquittoAuthPlugin::security_init(const PluginOptions opts, const bool reload) { mosquitto_log_printf(MOSQ_LOG_DEBUG, "security_init"); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Options:"); for (auto opt : opts) { mosquitto_log_printf(MOSQ_LOG_DEBUG, " %s=%s", opt.first.c_str(), opt.second.c_str()); } mosquitto_log_printf(MOSQ_LOG_DEBUG, " Reload: %d", reload); if (!m_repo->init(opts)) { return MOSQ_ERR_NOT_SUPPORTED; } return MOSQ_ERR_SUCCESS; } int MosquittoAuthPlugin::security_cleanup(const PluginOptions opts, const bool reload) { mosquitto_log_printf(MOSQ_LOG_DEBUG, "security_cleanup"); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Options:"); for (auto opt : opts) { mosquitto_log_printf(MOSQ_LOG_DEBUG, " %s=%s", opt.first.c_str(), opt.second.c_str()); } mosquitto_log_printf(MOSQ_LOG_DEBUG, " Reload: %d", reload); m_repo->cleanup(); return MOSQ_ERR_SUCCESS; } int MosquittoAuthPlugin::acl_check(int access, mosquitto *client, const mosquitto_acl_msg *msg) { const char *username = mosquitto_client_username(client); mosquitto_log_printf(MOSQ_LOG_DEBUG, "acl_check"); if (username == NULL) { mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL failed for empty username!"); return MOSQ_ERR_ACL_DENIED; } mosquitto_log_printf(MOSQ_LOG_DEBUG, " Access: %d", access); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Address: %s", mosquitto_client_address(client)); mosquitto_log_printf(MOSQ_LOG_DEBUG, " ID: %s", mosquitto_client_id(client)); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Username: %s", username); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Topic: %s", msg->topic); User user; if (m_repo->get_user(username, user)) { std::vector<AclRule> rules; m_repo->get_acl_rules(rules); for (auto rule : rules) { std::string topic = rule.topic; if (topic.find("{client_id}") != std::string::npos) { std::string key("{client_id}"); topic = rule.topic.replace(rule.topic.find(key), key.length(), mosquitto_client_id(client)); } mosquitto_log_printf(MOSQ_LOG_DEBUG, " Rule Topic: %s", topic.c_str()); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Rule Access: %d", rule.access); if (msg->topic == topic) { if ( (access == MOSQ_ACL_SUBSCRIBE && rule.access & AclAccess::Subscribe) || (access == MOSQ_ACL_READ && rule.access & AclAccess::Read) || (access == MOSQ_ACL_WRITE && rule.access & AclAccess::Write)) { if (std::find(user.groups.begin(), user.groups.end(), rule.group) != user.groups.end()) { mosquitto_log_printf(MOSQ_LOG_DEBUG, "ACL success for user: %s", user.name.c_str()); return MOSQ_ERR_SUCCESS; } mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL failed for user: %s G", user.name.c_str()); return MOSQ_ERR_ACL_DENIED; } } } mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL failed for user: %s R", user.name.c_str()); return MOSQ_ERR_ACL_DENIED; } mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL Unknown user: %s", username); return MOSQ_ERR_ACL_DENIED; } int MosquittoAuthPlugin::unpwd_check(mosquitto *client, const char *username, const char *password) { mosquitto_log_printf(MOSQ_LOG_DEBUG, "unpwd_check"); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Address: %s", mosquitto_client_address(client)); mosquitto_log_printf(MOSQ_LOG_DEBUG, " ID: %s", mosquitto_client_id(client)); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Username: %s", username); mosquitto_log_printf(MOSQ_LOG_DEBUG, " Password: %s", password); User user; if (m_repo->get_user(username, user)) { if (libscrypt_check(&user.password_hash[0], password)) { mosquitto_log_printf(MOSQ_LOG_DEBUG, "User authorized: %s", user.name.c_str()); return MOSQ_ERR_SUCCESS; } mosquitto_log_printf(MOSQ_LOG_WARNING, "User NOT authorized: %s", user.name.c_str()); return MOSQ_ERR_AUTH; } mosquitto_log_printf(MOSQ_LOG_WARNING, "Unknown user: %s", username); return MOSQ_ERR_AUTH; }
37.448
108
0.631916
hhornbacher
aa319d3f4cf5178e057bf66cd2dc7b73c6bb81a7
14,240
cxx
C++
EVGEN/AliGenSlowNucleons.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
EVGEN/AliGenSlowNucleons.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
2
2016-11-25T08:40:56.000Z
2019-10-11T12:29:29.000Z
EVGEN/AliGenSlowNucleons.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // // Generator for slow nucleons in pA interactions. // Source is modelled by a relativistic Maxwell distributions. // This class cooparates with AliCollisionGeometry if used inside AliGenCocktail. // In this case the number of slow nucleons is determined from the number of wounded nuclei // using a realisation of AliSlowNucleonModel. // Original code by Ferenc Sikler <[email protected]> // #include <TDatabasePDG.h> #include <TPDGCode.h> #include <TH2F.h> #include <TH1F.h> #include <TF1.h> #include <TCanvas.h> #include <TParticle.h> #include "AliConst.h" #include "AliCollisionGeometry.h" #include "AliStack.h" #include "AliRun.h" #include "AliMC.h" #include "AliGenSlowNucleons.h" #include "AliSlowNucleonModel.h" ClassImp(AliGenSlowNucleons) AliGenSlowNucleons::AliGenSlowNucleons() :AliGenerator(-1), fCMS(0.), fMomentum(0.), fBeta(0.), fPmax (0.), fCharge(0), fProtonDirection(1.), fTemperatureG(0.), fBetaSourceG(0.), fTemperatureB(0.), fBetaSourceB(0.), fNgp(0), fNgn(0), fNbp(0), fNbn(0), fDebug(0), fDebugHist1(0), fDebugHist2(0), fThetaDistribution(), fCosThetaGrayHist(), fCosTheta(), fBeamCrossingAngle(0.), fBeamDivergence(0.), fBeamDivEvent(0.), fSmearMode(2), fSlowNucleonModel(0) { // Default constructor fCollisionGeometry = 0; } AliGenSlowNucleons::AliGenSlowNucleons(Int_t npart) :AliGenerator(npart), fCMS(14000.), fMomentum(0.), fBeta(0.), fPmax (10.), fCharge(1), fProtonDirection(1.), fTemperatureG(0.05), fBetaSourceG(0.05), fTemperatureB(0.005), fBetaSourceB(0.), fNgp(0), fNgn(0), fNbp(0), fNbn(0), fDebug(0), fDebugHist1(0), fDebugHist2(0), fThetaDistribution(), fCosThetaGrayHist(), fCosTheta(), fBeamCrossingAngle(0.), fBeamDivergence(0.), fBeamDivEvent(0.), fSmearMode(2), fSlowNucleonModel(new AliSlowNucleonModel()) { // Constructor fName = "SlowNucleons"; fTitle = "Generator for gray particles in pA collisions"; fCollisionGeometry = 0; } //____________________________________________________________ AliGenSlowNucleons::~AliGenSlowNucleons() { // Destructor delete fSlowNucleonModel; } void AliGenSlowNucleons::SetProtonDirection(Float_t dir) { // Set direction of the proton to change between pA (1) and Ap (-1) fProtonDirection = dir / TMath::Abs(dir); } void AliGenSlowNucleons::Init() { // // Initialization // Double_t kMass = TDatabasePDG::Instance()->GetParticle(kProton)->Mass(); fMomentum = fCMS/2. * Float_t(fZTarget) / Float_t(fATarget); fBeta = fMomentum / TMath::Sqrt(kMass * kMass + fMomentum * fMomentum); //printf(" fMomentum %f fBeta %1.10f\n",fMomentum, fBeta); if (fDebug) { fDebugHist1 = new TH2F("DebugHist1", "nu vs N_slow", 100, 0., 100., 20, 0., 20.); fDebugHist2 = new TH2F("DebugHist2", "b vs N_slow", 100, 0., 100., 15, 0., 15.); fCosThetaGrayHist = new TH1F("fCosThetaGrayHist", "Gray particles angle", 100, -1., 1.); } // // non-uniform cos(theta) distribution // if(fThetaDistribution != 0) { fCosTheta = new TF1("fCosTheta", "(2./3.14159265358979312)/(exp(2./3.14159265358979312)-exp(-2./3.14159265358979312))*exp(2.*x/3.14159265358979312)", -1., 1.); } printf("\n AliGenSlowNucleons: applying crossing angle %f mrad to slow nucleons\n",fBeamCrossingAngle*1000.); } void AliGenSlowNucleons::FinishRun() { // End of run action // Show histogram for debugging if requested. if (fDebug) { TCanvas *c = new TCanvas("c","Canvas 1",400,10,600,700); c->Divide(2,1); c->cd(1); fDebugHist1->Draw("colz"); c->cd(2); fDebugHist2->Draw(); c->cd(3); fCosThetaGrayHist->Draw(); } } void AliGenSlowNucleons::Generate() { // // Generate one event // // // Communication with Gray Particle Model // if (fCollisionGeometry) { Float_t b = fCollisionGeometry->ImpactParameter(); // Int_t nn = fCollisionGeometry->NN(); // Int_t nwn = fCollisionGeometry->NwN(); // Int_t nnw = fCollisionGeometry->NNw(); // Int_t nwnw = fCollisionGeometry->NwNw(); // (1) Sikler' model if(fSmearMode==0) fSlowNucleonModel->GetNumberOfSlowNucleons(fCollisionGeometry, fNgp, fNgn, fNbp, fNbn); // (2) Model inspired on exp. data at lower energy (Gallio-Oppedisano) // --- smearing the Ncoll fron generator used as input else if(fSmearMode==1) fSlowNucleonModel->GetNumberOfSlowNucleons2(fCollisionGeometry, fNgp, fNgn, fNbp, fNbn); // --- smearing directly Nslow else if(fSmearMode==2) fSlowNucleonModel->GetNumberOfSlowNucleons2s(fCollisionGeometry, fNgp, fNgn, fNbp, fNbn); if (fDebug) { //printf("Collision Geometry %f %d %d %d %d\n", b, nn, nwn, nnw, nwnw); printf("Slow nucleons: %d grayp %d grayn %d blackp %d blackn \n", fNgp, fNgn, fNbp, fNbn); fDebugHist1->Fill(Float_t(fNgp + fNgn + fNbp + fNbn), fCollisionGeometry->NNw(), 1.); fDebugHist2->Fill(Float_t(fNgp + fNgn + fNbp + fNbn), b, 1.); } } // Float_t p[3] = {0., 0., 0.}, theta=0; Float_t origin[3] = {0., 0., 0.}; Float_t time = 0.; Float_t polar [3] = {0., 0., 0.}; Int_t nt, i, j; Int_t kf; // Extracting 1 value per event for the divergence angle Double_t rvec = gRandom->Gaus(0.0, 1.0); fBeamDivEvent = fBeamDivergence * TMath::Abs(rvec); printf("\n AliGenSlowNucleons: applying beam divergence %f mrad to slow nucleons\n",fBeamDivEvent*1000.); if(fVertexSmear == kPerEvent) { Vertex(); for (j=0; j < 3; j++) origin[j] = fVertex[j]; time = fTime; } // if kPerEvent // // Gray protons // fCharge = 1; kf = kProton; for(i = 0; i < fNgp; i++) { GenerateSlow(fCharge, fTemperatureG, fBetaSourceG, p, theta); if (fDebug) fCosThetaGrayHist->Fill(TMath::Cos(theta)); PushTrack(fTrackIt, -1, kf, p, origin, polar, time, kPNoProcess, nt, 1.,-2); KeepTrack(nt); SetProcessID(nt,kGrayProcess); } // // Gray neutrons // fCharge = 0; kf = kNeutron; for(i = 0; i < fNgn; i++) { GenerateSlow(fCharge, fTemperatureG, fBetaSourceG, p, theta); if (fDebug) fCosThetaGrayHist->Fill(TMath::Cos(theta)); PushTrack(fTrackIt, -1, kf, p, origin, polar, time, kPNoProcess, nt, 1.,-2); KeepTrack(nt); SetProcessID(nt,kGrayProcess); } // // Black protons // fCharge = 1; kf = kProton; for(i = 0; i < fNbp; i++) { GenerateSlow(fCharge, fTemperatureB, fBetaSourceB, p, theta); PushTrack(fTrackIt, -1, kf, p, origin, polar, time, kPNoProcess, nt, 1.,-1); KeepTrack(nt); SetProcessID(nt,kBlackProcess); } // // Black neutrons // fCharge = 0; kf = kNeutron; for(i = 0; i < fNbn; i++) { GenerateSlow(fCharge, fTemperatureB, fBetaSourceB, p, theta); PushTrack(fTrackIt, -1, kf, p, origin, polar, time, kPNoProcess, nt, 1.,-1); KeepTrack(nt); SetProcessID(nt,kBlackProcess); } } void AliGenSlowNucleons::GenerateSlow(Int_t charge, Double_t T, Double_t beta, Float_t* q, Float_t &theta) { /* Emit a slow nucleon with "temperature" T [GeV], from a source moving with velocity beta Three-momentum [GeV/c] is given back in q[3] */ //printf("Generating slow nuc. with: charge %d. temp. %1.4f, beta %f \n",charge,T,beta); Double_t m, pmax, p, f, phi; TDatabasePDG * pdg = TDatabasePDG::Instance(); const Double_t kMassProton = pdg->GetParticle(kProton) ->Mass(); const Double_t kMassNeutron = pdg->GetParticle(kNeutron)->Mass(); /* Select nucleon type */ if(charge == 0) m = kMassNeutron; else m = kMassProton; /* Momentum at maximum of Maxwell-distribution */ pmax = TMath::Sqrt(2*T*(T+TMath::Sqrt(T*T+m*m))); /* Try until proper momentum */ /* for lack of primitive function of the Maxwell-distribution */ /* a brute force trial-accept loop, normalized at pmax */ do { p = Rndm() * fPmax; f = Maxwell(m, p, T) / Maxwell(m , pmax, T); } while(f < Rndm()); /* Spherical symmetric emission for black particles (beta=0)*/ if(beta==0 || fThetaDistribution==0) theta = TMath::ACos(2. * Rndm() - 1.); /* cos theta distributed according to experimental results for gray particles (beta=0.05)*/ else if(fThetaDistribution!=0){ Double_t costheta = fCosTheta->GetRandom(); theta = TMath::ACos(costheta); } // phi = 2. * TMath::Pi() * Rndm(); /* Determine momentum components in system of the moving source */ q[0] = p * TMath::Sin(theta) * TMath::Cos(phi); q[1] = p * TMath::Sin(theta) * TMath::Sin(phi); q[2] = p * TMath::Cos(theta); //if(fDebug==1) printf("\n Momentum in RS of the moving source: p = (%f, %f, %f)\n",q[0],q[1],q[2]); /* Transform to system of the target nucleus */ /* beta is passed as negative, because the gray nucleons are slowed down */ Lorentz(m, -beta, q); //if(fDebug==1) printf(" Momentum in RS of the target nucleus: p = (%f, %f, %f)\n",q[0],q[1],q[2]); /* Transform to laboratory system */ Lorentz(m, fBeta, q); q[2] *= fProtonDirection; if(fDebug==1)printf("\n Momentum after LHC boost: p = (%f, %f, %f)\n",q[0],q[1],q[2]); if(fBeamCrossingAngle>0.) BeamCrossDivergence(1, q); // applying crossing angle if(fBeamDivergence>0.) BeamCrossDivergence(2, q); // applying divergence } Double_t AliGenSlowNucleons::Maxwell(Double_t m, Double_t p, Double_t T) { /* Relativistic Maxwell-distribution */ Double_t ekin; ekin = TMath::Sqrt(p*p+m*m)-m; return (p*p * exp(-ekin/T)); } //_____________________________________________________________________________ void AliGenSlowNucleons::Lorentz(Double_t m, Double_t beta, Float_t* q) { /* Lorentz transform in the direction of q[2] */ Double_t gamma = 1./TMath::Sqrt((1.-beta)*(1.+beta)); Double_t energy = TMath::Sqrt(m*m + q[0]*q[0] + q[1]*q[1] + q[2]*q[2]); q[2] = gamma * (q[2] + beta*energy); //printf(" \t beta %1.10f gamma %f energy %f -> p_z = %f\n",beta, gamma, energy,q[2]); } //_____________________________________________________________________________ void AliGenSlowNucleons::BeamCrossDivergence(Int_t iwhat, Float_t *pLab) { // Applying beam divergence and crossing angle // Double_t pmod = TMath::Sqrt(pLab[0]*pLab[0]+pLab[1]*pLab[1]+pLab[2]*pLab[2]); Double_t tetdiv = 0.; Double_t fidiv = 0.; if(iwhat==1){ tetdiv = fBeamCrossingAngle; fidiv = k2PI/4.; } else if(iwhat==2){ tetdiv = fBeamDivEvent; fidiv = (gRandom->Rndm())*k2PI; } Double_t tetpart = TMath::ATan2(TMath::Sqrt(pLab[0]*pLab[0]+pLab[1]*pLab[1]), pLab[2]); Double_t fipart=0.; if(TMath::Abs(pLab[1])>0. || TMath::Abs(pLab[0])>0.) fipart = TMath::ATan2(pLab[1], pLab[0]); if(fipart<0.) {fipart = fipart+k2PI;} tetdiv = tetdiv*kRaddeg; fidiv = fidiv*kRaddeg; tetpart = tetpart*kRaddeg; fipart = fipart*kRaddeg; Double_t angleSum[2]={0., 0.}; AddAngle(tetpart,fipart,tetdiv,fidiv,angleSum); Double_t tetsum = angleSum[0]; Double_t fisum = angleSum[1]; //printf("tetpart %f fipart %f tetdiv %f fidiv %f angleSum %f %f\n",tetpart,fipart,tetdiv,fidiv,angleSum[0],angleSum[1]); tetsum = tetsum*kDegrad; fisum = fisum*kDegrad; pLab[0] = pmod*TMath::Sin(tetsum)*TMath::Cos(fisum); pLab[1] = pmod*TMath::Sin(tetsum)*TMath::Sin(fisum); pLab[2] = pmod*TMath::Cos(tetsum); if(fDebug==1){ if(iwhat==1) printf(" Beam crossing angle %f mrad ", fBeamCrossingAngle*1000.); else if(iwhat==2) printf(" Beam divergence %f mrad ", fBeamDivEvent*1000.); printf(" p = (%f, %f, %f)\n",pLab[0],pLab[1],pLab[2]); } } //_____________________________________________________________________________ void AliGenSlowNucleons::AddAngle(Double_t theta1, Double_t phi1, Double_t theta2, Double_t phi2, Double_t *angleSum) { // Calculating the sum of 2 angles Double_t temp = -1.; Double_t conv = 180./TMath::ACos(temp); Double_t ct1 = TMath::Cos(theta1/conv); Double_t st1 = TMath::Sin(theta1/conv); Double_t cp1 = TMath::Cos(phi1/conv); Double_t sp1 = TMath::Sin(phi1/conv); Double_t ct2 = TMath::Cos(theta2/conv); Double_t st2 = TMath::Sin(theta2/conv); Double_t cp2 = TMath::Cos(phi2/conv); Double_t sp2 = TMath::Sin(phi2/conv); Double_t cx = ct1*cp1*st2*cp2+st1*cp1*ct2-sp1*st2*sp2; Double_t cy = ct1*sp1*st2*cp2+st1*sp1*ct2+cp1*st2*sp2; Double_t cz = ct1*ct2-st1*st2*cp2; Double_t rtetsum = TMath::ACos(cz); Double_t tetsum = conv*rtetsum; if(TMath::Abs(tetsum)<1e-4 || tetsum==180.) return; temp = cx/TMath::Sin(rtetsum); if(temp>1.) temp=1.; if(temp<-1.) temp=-1.; Double_t fisum = conv*TMath::ACos(temp); if(cy<0) {fisum = 360.-fisum;} angleSum[0] = tetsum; angleSum[1] = fisum; } //_____________________________________________________________________________ void AliGenSlowNucleons::SetProcessID(Int_t nt, UInt_t process) { // Tag the particle as // gray or black if (fStack) fStack->Particle(nt)->SetUniqueID(process); else gAlice->GetMCApp()->Particle(nt)->SetUniqueID(process); }
31.574279
123
0.63743
AllaMaevskaya
aa32fa4dedb60252d53d59c2ba0403520506e623
943
cpp
C++
Rumble3D/src/RigidBodyEngine/CollisionPrimitive.cpp
Nelaty/Rumble3D
801b9feec27ceeea91db3b759083f6351634e062
[ "MIT" ]
1
2020-01-21T16:01:53.000Z
2020-01-21T16:01:53.000Z
Rumble3D/src/RigidBodyEngine/CollisionPrimitive.cpp
Nelaty/Rumble3D
801b9feec27ceeea91db3b759083f6351634e062
[ "MIT" ]
1
2019-10-08T08:25:33.000Z
2019-10-09T06:39:06.000Z
Rumble3D/src/RigidBodyEngine/CollisionPrimitive.cpp
Nelaty/Rumble3D
801b9feec27ceeea91db3b759083f6351634e062
[ "MIT" ]
1
2019-05-14T13:48:16.000Z
2019-05-14T13:48:16.000Z
#include "R3D/RigidBodyEngine/CollisionPrimitive.h" #include "R3D/RigidBodyEngine/RigidBody.h" #include <glm/gtc/matrix_transform.inl> #include <cassert> namespace r3 { void CollisionPrimitive::calculateInternals() { /// \todo use new transform! const auto& transform = m_body->getTransform(); glm::mat4 mat = glm::mat4(transform.getRotationMat()); mat[3] = glm::vec4(transform.getPosition(), 1.0f); m_transform = mat * m_offset; } glm::vec3 CollisionPrimitive::getAxis(const unsigned index) const { assert(index >= 0 && index <= 3); return glm::vec3(m_transform[index]); } const glm::mat4& CollisionPrimitive::getTransform() const { return m_transform; } RigidBody* CollisionPrimitive::getBody() const { return m_body; } CollisionPrimitiveType CollisionPrimitive::getType() const { return m_type; } CollisionPrimitive::CollisionPrimitive(const CollisionPrimitiveType type) : m_type(type) { } }
20.955556
74
0.726405
Nelaty
aa37654983151cb040081ee3a660a55f0b2e958f
1,836
hpp
C++
MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/hal/GPIO.hpp
rshane960/TouchGFX
1f1465f1aa1215d52264ae0199dafa821939de64
[ "MIT" ]
null
null
null
MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/hal/GPIO.hpp
rshane960/TouchGFX
1f1465f1aa1215d52264ae0199dafa821939de64
[ "MIT" ]
null
null
null
MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/hal/GPIO.hpp
rshane960/TouchGFX
1f1465f1aa1215d52264ae0199dafa821939de64
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright (c) 2018(-2021) STMicroelectronics. * All rights reserved. * * This file is part of the TouchGFX 4.18.1 distribution. * * This software is licensed under terms that can be found in the LICENSE file in * the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * *******************************************************************************/ /** * @file touchgfx/hal/GPIO.hpp * * Declares the touchgfx::GPIO class. */ #ifndef TOUCHGFX_GPIO_HPP #define TOUCHGFX_GPIO_HPP namespace touchgfx { /** * Interface class for manipulating GPIOs in order to do performance measurements on target. Not * used on the PC simulator. */ class GPIO { public: /** Enum for the GPIOs used. */ enum GPIO_ID { VSYNC_FREQ, /// Pin is toggled at each VSYNC RENDER_TIME, /// Pin is high when frame rendering begins, low when finished FRAME_RATE, /// Pin is toggled when the framebuffers are swapped. MCU_ACTIVE /// Pin is high when the MCU is doing work (i.e. not in idle task). }; /** Perform configuration of IO pins. */ static void init(); /** * Sets a pin high. * * @param id the pin to set. */ static void set(GPIO_ID id); /** * Sets a pin low. * * @param id the pin to set. */ static void clear(GPIO_ID id); /** * Toggles a pin. * * @param id the pin to toggle. */ static void toggle(GPIO_ID id); /** * Gets the state of a pin. * * @param id the pin to get. * * @return true if the pin is high, false otherwise. */ static bool get(GPIO_ID id); }; } // namespace touchgfx #endif // TOUCHGFX_GPIO_HPP
24.157895
96
0.569172
rshane960
aa3abe536e9e4f269ada3a833dc1c969697575f3
14,401
cpp
C++
Numerical-Methods/Task-9/main.cpp
Maissae/University-Projects
86ef0583760742c0e45be33d3fac3689587d0c76
[ "MIT" ]
null
null
null
Numerical-Methods/Task-9/main.cpp
Maissae/University-Projects
86ef0583760742c0e45be33d3fac3689587d0c76
[ "MIT" ]
null
null
null
Numerical-Methods/Task-9/main.cpp
Maissae/University-Projects
86ef0583760742c0e45be33d3fac3689587d0c76
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> #include<bitset> #include<iostream> #include<iomanip> #include<math.h> #include<string.h> #pragma region Array/Matrix Functions double** CreateMatrix(int n) { double** matrix = new double* [n]; for(int i = 0; i < n; i++) { matrix[i] = new double[n]; } for(int i = 0; i < n; i++) { for(int j = 0; i < n; i++) { matrix[i][j] = 0; } } return matrix; } double** CreateMatrix(int n, int m) { double** matrix = new double* [n]; for(int i = 0; i < n; i++) { matrix[i] = new double[m]; } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { matrix[i][j] = 0; } } return matrix; } double* CreateArray(int n) { double* array = new double[n]; for(int i = 0; i < n; i++) { array[i] = 0; } return array; } double** CopyMatrix(int n, double** matrix) { double** matrix_copy = CreateMatrix(n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { matrix_copy[i][j] = matrix[i][j]; } } return matrix_copy; } double* CopyArray(int n, double* array) { double* array_copy = CreateArray(n); for(int i = 0; i < n; i++) { array_copy[i] = array[i]; } return array_copy; } void Dispose(int n, double** matrix) { for(int i = 0; i < n; i++) { delete[] matrix[i]; } delete[] matrix; } void Dispose(double* array) { delete[] array; } double** InsertMatrix(int n, std::string name = "Matrix") { double** matrix = CreateMatrix(n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { double value; std::cout << "Put value for " << name << "[" << i << "]" << "[" << j << "]: "; std::cin >> value; matrix[i][j] = value; } } return matrix; } double* InsertArray(int n, std::string name = "Array") { double* array = CreateArray(n); for(int i = 0; i < n; i++) { double value; std::cout << "Put value for " << name << "[" << i << "]: "; std::cin >> value; array[i] = value; } return array; } void PrintMatrix(double** matrix, int n, int m, std::string name = "") { std::cout << name << ":" << std::endl; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { printf("%.4f ", matrix[i][j]); } printf("\n"); } printf("\n"); } void PrintMatrix(double* matrix, int n, std::string name = "") { std::cout << name << ":" << std::endl; for(int i = 0; i < n; i++) { printf("%.8e\n", matrix[i]); } printf("\n"); } double** Multiply(double** matrix1, double** matrix2, int n) { double** result = CreateMatrix(n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { for(int k = 0; k < n; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return result; } double* Multiply(double** matrix1, double* matrix2, int n) { double* result = CreateArray(n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { for(int k = 0; k < n; k++) { result[i] += matrix1[i][k] * matrix2[k]; } } } return result; } double* Multiply(double** matrix1, int n, int m, double* matrix2) { double* result = CreateArray(n); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { result[i] += matrix1[i][j] * matrix2[j]; } } return result; } double** Multiply(double** matrix1, int n1, int m1, double** matrix2, int n2, int m2) { double** result = CreateMatrix(n1, m2); for(int i = 0; i < n1; ++i) { for(int j = 0; j < m2; ++j) { for(int k = 0; k < m1; ++k) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return result; } double** Multiply(double** matrix, int n, int m, double scalar) { double** result = CreateMatrix(n,m); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { result[i][j] = matrix[i][j] * scalar; } } return result; } double** Subtract(double** matrix1, double** matrix2, int n, int m) { double** result = CreateMatrix(n,m); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { double value = matrix1[i][j] - matrix2[i][j]; result[i][j] = value; } } return result; } bool Equals(double a, double b) { return (abs(a) - abs(b)) < __DBL_EPSILON__; } bool Equals(double** matrix1, double** matrix2, int n, int m) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(Equals(matrix1[i][j], matrix2[i][j]) == false) { return false; } } } return true; } void Clear(double** matrix, int n, int m) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { matrix[i][j] = 0; } } } void Clear(double* array, int n) { for(int i = 0; i < n; i++) { array[i] = 0; } } void SwapRow(double** matrix, int row1, int row2, int n) { for(int i = 0; i < n; i++) { double temp = matrix[row1][i]; matrix[row1][i] = matrix[row2][i]; matrix[row2][i] = temp; } } void SwapColumn(double** matrix, int col1, int col2, int n) { for(int i = 0; i < n; i++) { double temp = matrix[i][col1]; matrix[i][col1] = matrix[i][col2]; matrix[i][col2] = temp; } } #pragma endregion #pragma region Array/Matrix Math Functions double** Transpose(double** matrix, int n) { double** result = CreateMatrix(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { result[i][j] = matrix[j][i]; } } return result; } double** Transpose(double** matrix, int n, int m) { double** result = CreateMatrix(m, n); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { result[j][i] = matrix[i][j]; } } return result; } void DooLittleDecomposition(int n, double** A, double** L, double** U, double** P) { //Doolittle for(int k = 0; k < n; k++) { //Rows for U for(int j = k; j < n; j++) { double sum = 0; for(int p = 0; p < k; p++) { sum += L[k][p] * U[p][j]; } U[k][j] = A[k][j] - sum; } //Search for max Ukj double ukj_max = 0; int j_max = 0; for(int j = k; j < n; j++) { if(abs(U[k][j]) > abs(ukj_max)) { ukj_max = U[k][j]; j_max = j; } } if(k != j_max) { //Swapping columns SwapColumn(A, k, j_max, n); SwapColumn(U, k, j_max, n); SwapColumn(P, k, j_max, n); } //Columns for L for(int i = k; i < n; i++) { if(k != i) { double sum = 0; for(int p = 0; p < k; p++) { sum += L[i][p] * U[p][k]; } L[i][k] = (A[i][k] - sum) / U[k][k]; } } } } void SolveLinearEquation(int n, double** L, double** U, double** P, double* B, double* y, double* x, double* x_prim) { //Forward substitution for(int i = 0; i < n; i++) { double sum = 0; for(int j = 0; j < i; j++) { sum += L[i][j]*y[j]; } y[i] = (B[i] - sum)/L[i][i]; } //Back substitution for(int i = n - 1; i >= 0; i--) { double sum = 0; for(int j = i + 1; j < n; j++) { sum += U[i][j]*x_prim[j]; } x_prim[i] = (y[i] - sum)/U[i][i]; } //Matrix multiplication for final x for(int i = 0; i < n; i++) { double sum = 0; for(int j = 0; j < n; j++) { sum += P[i][j] * x_prim[j]; } x[i] = sum; } } double FindMax(int n, double* array) { double max = -__DBL_MAX__; for(int i = 0; i < n; i++) { if(max < array[i]) { max = array[i]; } } return max; } void ScaleMatrix(int n, double** A, double* B) { for(int i = 0; i < n; i++) { double max = FindMax(n, A[i]); for(int j = 0; j < n; j++) { A[i][j] /= max; } B[i] /= max; } } double** InverseL(int n, double** L) { double** L_inv = CreateMatrix(n); for(int k = 0; k < n; k++) { double* e = CreateArray(n); double* y = CreateArray(n); e[k] = 1; //Forward substitution for(int i = 0; i < n; i++) { double sum = 0; for(int j = 0; j < i; j++) { sum += L[i][j]*y[j]; } y[i] = (e[i] - sum)/L[i][i]; } //Assigning column to L for(int i = 0; i < n; i++) { L_inv[i][k] = y[i]; } delete[] e; delete[] y; } return L_inv; } double** InverseU(int n, double** U) { double** U_inv = CreateMatrix(n); for(int k = 0; k < n; k++) { double* e = CreateArray(n); double* z = CreateArray(n); e[k] = 1; //Back substitution for(int i = n - 1; i >= 0; i--) { double sum = 0; for(int j = i + 1; j < n; j++) { sum += U[i][j]*z[j]; } z[i] = (e[i] - sum)/U[i][i]; } //Assigning column to U for(int i = 0; i < n; i++) { U_inv[i][k] = z[i]; } delete[] e; delete[] z; } return U_inv; } double Matrix1Form(int n, double** matrix) { double max = 0; for(int i = 0; i < n; i++) { double sum = 0; for(int j = 0; j < n; j++) { sum += abs(matrix[j][i]); } if(sum > max) { max = sum; } } return max; } double MatrixInfForm(int n, double** matrix) { double max = 0; for(int i = 0; i < n; i++) { double sum = 0; for(int j = 0; j < n; j++) { sum += abs(matrix[i][j]); } if(sum > max) { max = sum; } } return max; } double Array1Form(int n, double* array) { double sum = 0; for(int i = 0; i < n; i++) { sum += abs(array[i]); } return sum; } double ArrayInfForm(int n, double* array) { return FindMax(n, array); } double VectorLength(double** vector, int n) { double sum = 0; for(int i = 0; i < n; i++) { sum += pow(vector[i][0], 2); } return sqrt(sum); } double** NormalizeVector(double** vector, int n) { double len = VectorLength(vector, n); double** result = CreateMatrix(n, 1); for(int i = 0; i < n; i++) { result[i][0] = vector[i][0] / len; } return result; } #pragma endregion int sign(double value) { if(value > 0) { return 1; } else if(value < 0) { return -1; } else { return 0; } } int main() { int n; // std::cout << "Enter n: "; // std::cin >> n; //? Testing n = 4; double** A = CreateMatrix(n, n); double** I = CreateMatrix(n, n); double** lambda = CreateMatrix(n, 1); //?Testing A[0] = new double[4] {2, 13, -14, 3}; A[1] = new double[4] {-2, 25, -22, 4}; A[2] = new double[4] {-3, 31, -27, 5}; A[2] = new double[4] {-2, 34, -32, 7}; //A[0] = new double[3] {1,1,1}; //A[1] = new double[3] {2,-2,2}; //A[2] = new double[3] {3,3,-3}; // lambda[0] = 2.76300328661375; // lambda[1] = -1.723685894982085; //lambda[2] = -5.03931739163167; lambda[0][0] = 3; lambda[1][0] = 2; lambda[2][0] = 1; lambda[3][0] = 1; for(int i = 0; i < n; i++) { I[i][i] = 1; } PrintMatrix(A, n, n, "A"); PrintMatrix(I, n, n, "I"); // double** A = InsertMatrix(n, "A"); // std::cout << "Inserted matrix:" << std::endl; PrintMatrix(lambda, n, 1, "lambda"); for(int i = 0; i < n; i++) { printf("============> i = %d <============\n\n", i); //Calculating λ * I double** I_lambda = Multiply(I, n, n, lambda[i][0]); //Subtracting A - Iλ double** A_lambda = Subtract(A, I_lambda, n, n); PrintMatrix(I_lambda, n, n, "I_lambda"); PrintMatrix(A_lambda, n, n, "A_lambda"); double** L = CreateMatrix(n, n); double** U = CreateMatrix(n, n); double** P = CreateMatrix(n, n); //? Setting up L and P for(int j = 0; j < n; j++) { L[j][j] = 1; P[j][j] = 1; } DooLittleDecomposition(n, A_lambda, L, U, P); PrintMatrix(L, n, n, "L"); PrintMatrix(U, n, n, "U"); PrintMatrix(P, n, n, "P"); //Solving Ux'_i = 0 double** x_prim = CreateMatrix(n, 1); //Setting last value to 1 x_prim[n-1][0] = 1; for(int j = n - 2; j >= 0; j--) { double sum = 0; for(int k = j + 1; k < n; k++) { sum += U[j][k]*x_prim[k][0]; } x_prim[j][0] = (0 - sum)/U[j][j]; } //Getting final vector PrintMatrix(x_prim, n, 1, "x_prim_i"); //double** P_Tr = Transpose(P, n, n); double** x = Multiply(P, n, n, x_prim, n, 1); PrintMatrix(x, n, 1, "x_i"); //Normalization double** x_norm = NormalizeVector(x, n); PrintMatrix(x_norm, n, 1, "x_norm"); //A*xi double** A_xi = Multiply(A, n, n, x, n, 1); PrintMatrix(A_xi, n, 1, "A_xi"); //λ*xi double** lambda_xi = Multiply(lambda, n, 1, x, n, 1); PrintMatrix(lambda_xi, n, 1, "lambda_xi"); Dispose(n, A_lambda); Dispose(n, I_lambda); Dispose(n, L); Dispose(n, U); Dispose(n, P); Dispose(n, x_prim); Dispose(n, x); Dispose(n, x_norm); Dispose(n, A_xi); Dispose(n, lambda_xi); } Dispose(n, A); Dispose(n, lambda); return 0; }
21.786687
116
0.43122
Maissae
aa3faf9aaafb9459939c59f788180810b68a1915
5,899
cc
C++
A1/Main/BufferMgr/source/MyDB_BufferManager.cc
JiweiYe/DB_implementation
5f3b043ea2ceffa8a84ef90f1127c8b4d5a83d98
[ "MIT" ]
null
null
null
A1/Main/BufferMgr/source/MyDB_BufferManager.cc
JiweiYe/DB_implementation
5f3b043ea2ceffa8a84ef90f1127c8b4d5a83d98
[ "MIT" ]
null
null
null
A1/Main/BufferMgr/source/MyDB_BufferManager.cc
JiweiYe/DB_implementation
5f3b043ea2ceffa8a84ef90f1127c8b4d5a83d98
[ "MIT" ]
null
null
null
#ifndef BUFFER_MGR_C #define BUFFER_MGR_C #include "MyDB_BufferManager.h" #include <string> using namespace std; MyDB_PageHandle MyDB_BufferManager :: getPage (MyDB_TablePtr whichTable, long i) { string targetPage = pageIdGenerator(whichTable, i); //page already in the buffer if(inbuffer(targetPage)){ MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(page_map[targetPage]); this->LRU_table.erase(page_map[targetPage]); this->page_map[targetPage]->setLruNumber(++currentLRU); this->LRU_table.insert(page_map[targetPage]); return handle; } //page not in the buffer else{ shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,false,false,whichTable,i,this->pageSize,this); string page_id = pageIdGenerator(newPage->table, newPage->pagePos); //buffer is not filled if(this->LRU_table.size() < this->pageNum){ newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize; newPage->loadFromFile(); } //buffer is filled; else{ evict(newPage); } this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage)); this->LRU_table.insert(newPage); MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage); return handle; } } MyDB_PageHandle MyDB_BufferManager :: getPage () { long tmpPagePos; if(tmp_avail.size() <= 0){ tmpPagePos = ++tmpFileCount; } else{ tmpPagePos = *(tmp_avail.begin()); tmp_avail.erase(tmpPagePos); } string page_id = pageIdGenerator(tmp_table, tmpPagePos); shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,false,true,this->tmp_table,tmpFileCount,this->pageSize,this); //buffer is not filled if(this->LRU_table.size() < this->pageNum){ newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize; newPage->loadFromFile(); } //buffer is filled; else{ evict(newPage); } this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage)); this->LRU_table.insert(newPage); MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage); return handle; } MyDB_PageHandle MyDB_BufferManager :: getPinnedPage (MyDB_TablePtr whichTable, long i) { string targetPage = pageIdGenerator(whichTable, i); //page already in the buffer if(inbuffer(targetPage)){ MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(page_map[targetPage]); this->page_map[targetPage]->setPinned(); this->LRU_table.erase(page_map[targetPage]); this->page_map[targetPage]->setLruNumber(++currentLRU); this->LRU_table.insert(page_map[targetPage]); return handle; } //page not in the buffer else{ shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,true,false,whichTable,i,this->pageSize,this); string page_id = pageIdGenerator(newPage->table, newPage->pagePos); //buffer is not filled if(this->LRU_table.size() < this->pageNum){ newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize; newPage->loadFromFile(); } //buffer is filled; else{ evict(newPage); } this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage)); this->LRU_table.insert(newPage); MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage); return handle; } } MyDB_PageHandle MyDB_BufferManager :: getPinnedPage () { long tmpPagePos; if(tmp_avail.size() <= 0){ tmpPagePos = ++tmpFileCount; } else{ tmpPagePos = *(tmp_avail.begin()); tmp_avail.erase(tmpPagePos); } string page_id = pageIdGenerator(tmp_table, tmpPagePos); shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,true,true,this->tmp_table,tmpFileCount,this->pageSize,this); //buffer is not filled if(this->LRU_table.size() < this->pageNum){ newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize; newPage->loadFromFile(); } //buffer is filled; else{ evict(newPage); } this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage)); this->LRU_table.insert(newPage); MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage); return handle; } void MyDB_BufferManager :: evict(shared_ptr <MyDB_Page> newPage){ //find the page to be evicted LRUtable::iterator it; for(it=LRU_table.begin();it!=LRU_table.end();it++){ if((*it)->pinned == false){ break; } } //set the status inbuffer to false (*it)->inBuffer = false; //evict from look up map string evict_page = pageIdGenerator((*it)->table, (*it)->pagePos); page_map.erase(evict_page); //write the data back to disk if dirty && change the data in the buffer if((*it)->dirty){ (*it)->writeToFile(); (*it)->dirty = false; } newPage->bufferInfo = (*it)->bufferInfo; newPage->loadFromFile(); //evict from LRU set LRU_table.erase(*it); } void MyDB_BufferManager :: unpin (MyDB_PageHandle unpinMe) { unpinMe->pageObject->pinned = false; } MyDB_BufferManager :: MyDB_BufferManager (size_t pageSize, size_t numPages, string tempFile) { this->pageSize = pageSize; this->pageNum = numPages; this->tmpFile = tempFile; buffer = (char*) malloc(sizeof(char)*(pageSize*numPages)); this->currentLRU = 0; this->tmpFileCount = 0; tmp_table = make_shared <MyDB_Table> ("temporary_table", this->tmpFile); } MyDB_BufferManager :: ~MyDB_BufferManager () { LRUtable::iterator it; for(it=LRU_table.begin();it!=LRU_table.end();it++){ if((*it)->dirty){ (*it)->writeToFile(); (*it)->dirty = false; } } delete(this->buffer); remove(tmpFile.c_str()); } bool MyDB_BufferManager ::inbuffer(string target){ PageMap::iterator it = this->page_map.find(target); if(it == this->page_map.end()){ return false; } else{ return true; } } string MyDB_BufferManager :: pageIdGenerator(MyDB_TablePtr whichTable, long i){ string table_name = whichTable-> getName(); string pageId = table_name + to_string(i); return pageId; } #endif
29.944162
132
0.712494
JiweiYe
aa419cee82e2fed3f4197a8f654d2e7b6184edbe
12,044
cpp
C++
src/Transform/ONNX/ConstPropHelper.cpp
juan561999/Onnx-mlir
f8554660dd98b5bb911320aa4f22823573c9b0fb
[ "Apache-2.0" ]
null
null
null
src/Transform/ONNX/ConstPropHelper.cpp
juan561999/Onnx-mlir
f8554660dd98b5bb911320aa4f22823573c9b0fb
[ "Apache-2.0" ]
null
null
null
src/Transform/ONNX/ConstPropHelper.cpp
juan561999/Onnx-mlir
f8554660dd98b5bb911320aa4f22823573c9b0fb
[ "Apache-2.0" ]
null
null
null
/* * SPDX-License-Identifier: Apache-2.0 */ //===----------- ONNXConstProp.cpp - ONNX High Level Rewriting ------------===// // // Copyright 2019-2020 The IBM Research Authors. // // ============================================================================= // // This file implements a set of rewriters to constprop an ONNX operation into // composition of other ONNX operations. // // This pass is applied before any other pass so that there is no need to // implement shape inference for the constpropd operation. Hence, it is expected // that there is no knowledge about tensor shape at this point // //===----------------------------------------------------------------------===// #include "src/Transform/ONNX/ConstPropHelper.hpp" using namespace mlir; /// Get the element size in bytes. Use the biggest size to avoid loss in /// casting. int64_t getEltSizeInBytes(Type ty) { auto elementType = ty.cast<ShapedType>().getElementType(); int64_t sizeInBits; if (elementType.isIntOrFloat()) { sizeInBits = elementType.getIntOrFloatBitWidth(); } else { auto vectorType = elementType.cast<VectorType>(); sizeInBits = vectorType.getElementTypeBitWidth() * vectorType.getNumElements(); } return llvm::divideCeil(sizeInBits, 8); } /// Get the number of elements. int64_t getNumberOfElements(ArrayRef<int64_t> shape) { int64_t count = 1; for (unsigned int i = 0; i < shape.size(); ++i) { count *= shape[i]; } return count; } /// Get the size of a tensor from its ranked type in bytes. int64_t getSizeInBytes(Type ty) { ShapedType shapedType = ty.dyn_cast<ShapedType>(); auto shape = shapedType.getShape(); return getNumberOfElements(shape) * getEltSizeInBytes(shapedType); } /// Get the size of a tensor from its ranked type in bytes, using the largest /// precision. int64_t getMaxSizeInBytes(Type ty) { auto shape = ty.dyn_cast<ShapedType>().getShape(); return getNumberOfElements(shape) * 8; } /// Compute strides for a given shape. std::vector<int64_t> getStrides(ArrayRef<int64_t> shape) { int rank = shape.size(); std::vector<int64_t> strides; int64_t count = 1; for (int i = rank - 1; i >= 0; i--) { strides.insert(strides.begin(), count); count *= shape[i]; } return strides; } /// Compute the linear access index. int64_t getLinearAccessIndex( ArrayRef<int64_t> indices, ArrayRef<int64_t> strides) { int64_t index = 0; for (unsigned int i = 0; i < strides.size(); ++i) index += indices[i] * strides[i]; return index; } // Compute the tensor access index from a linear index. std::vector<int64_t> getAccessIndex( int64_t linearIndex, ArrayRef<int64_t> strides) { std::vector<int64_t> res; for (unsigned int i = 0; i < strides.size(); ++i) { int64_t s = strides[i]; if (linearIndex < s) { res.emplace_back(0); } else { res.emplace_back(floor(linearIndex / s)); linearIndex = linearIndex % s; } } return res; } /// Allocate a buffer whose size is getting from a given Value's type. char *allocateBufferFor(Type type, bool useMaxSize) { assert(type.isa<ShapedType>() && "Not a shaped type"); int64_t sizeInBytes; if (useMaxSize) sizeInBytes = getMaxSizeInBytes(type.cast<ShapedType>()); else sizeInBytes = getSizeInBytes(type.cast<ShapedType>()); char *res = (char *)malloc(sizeInBytes); return res; } /// Get a data array from a given ONNXConstantOp. char *createArrayFromDenseElementsAttr(DenseElementsAttr dataAttr) { Type elementType = dataAttr.getType().getElementType(); int64_t numElements = getNumberOfElements(dataAttr.getType().getShape()); char *res = allocateBufferFor(dataAttr.getType(), /*useMaxSize=*/true); if (elementType.isa<FloatType>()) { // Use double to avoid the precision loss during computation. double *resArr = (double *)res; auto valueIt = dataAttr.getFloatValues().begin(); for (int64_t i = 0; i < numElements; ++i) { double val = (double)(*valueIt++).convertToFloat(); *(resArr + i) = val; } } else if (elementType.isa<IntegerType>()) { // Use int64_t to avoid the precision loss during computation. int64_t *resArr = (int64_t *)res; auto valueIt = dataAttr.getIntValues().begin(); for (int64_t i = 0; i < numElements; ++i) { int64_t val = (*valueIt++).getSExtValue(); *(resArr + i) = val; } } else llvm_unreachable("Unknown data type"); return res; } /// A helper function to construct a DenseElementsAttr from an array. DenseElementsAttr createDenseElementsAttrFromArray(char *arr, Type outputType) { int64_t sizeInBytes = getSizeInBytes(outputType); RankedTensorType resType = constructRankedTensorType(outputType.cast<ShapedType>()); return DenseElementsAttr::getFromRawBuffer( resType, ArrayRef<char>(arr, sizeInBytes), /*isSplat=*/false); } /// Create a dense ONNXConstantOp from a byte array. ONNXConstantOp createDenseONNXConstantOp(PatternRewriter &rewriter, Location loc, ShapedType resultType, char *array) { char *resArray = allocateBufferFor(resultType); convertDoubleInt64ToExactType(resultType, array, resArray); DenseElementsAttr denseAttr = createDenseElementsAttrFromArray(resArray, resultType); free(resArray); return rewriter.create<ONNXConstantOp>(loc, resultType, Attribute(), denseAttr, FloatAttr(), ArrayAttr(), IntegerAttr(), ArrayAttr(), StringAttr(), ArrayAttr()); } /// Convert an array whose element type is double or int_64 to an array whose /// element type is the one of 'outType' (smaller precision). It does not /// support converting from floating point to integer and vise versa. void convertDoubleInt64ToExactType(Type outType, char *inArr, char *outArr) { ShapedType shapedType = outType.cast<ShapedType>(); int64_t maxSizeInBytes = getMaxSizeInBytes(shapedType); int64_t numElements = getNumberOfElements(shapedType.getShape()); Type elementType = shapedType.getElementType(); if (elementType.isa<FloatType>()) { FloatType floatTy = elementType.cast<FloatType>(); if (floatTy.getWidth() == 32) { double *inArrDouble = (double *)inArr; float *inArrFloat = (float *)outArr; for (int64_t i = 0; i < numElements; ++i) *(inArrFloat + i) = (float)*(inArrDouble + i); } else if (floatTy.getWidth() == 64) { std::copy(inArr, inArr + maxSizeInBytes, outArr); } else llvm_unreachable("Unknown data type"); } else if (elementType.isa<IntegerType>()) { IntegerType intTy = elementType.cast<IntegerType>(); if (intTy.getWidth() == 32) { int64_t *inArrInt64 = (int64_t *)inArr; int32_t *inArrInt32 = (int32_t *)outArr; for (int64_t i = 0; i < numElements; ++i) *(inArrInt32 + i) = (int32_t)(*(inArrInt64 + i)); } else if (intTy.getWidth() == 64) { std::copy(inArr, inArr + maxSizeInBytes, outArr); } else llvm_unreachable("Unknown data type"); } else llvm_unreachable("Unknown data type"); } /// A helper function to contruct a RankedTensorType from a ShapedType. RankedTensorType constructRankedTensorType(ShapedType type) { assert(type.hasRank() && "Not a ranked type"); return RankedTensorType::get(type.getShape(), type.getElementType()); } //===----------------------------------------------------------------------===// // Code to perform constant propagation for split. //===----------------------------------------------------------------------===// template <typename T> void IterateConstPropSplit(char *constArray, ArrayRef<int64_t> constShape, uint64_t splitAxis, ArrayRef<int64_t> splitOffsets, ArrayRef<Type> replacingTypes, std::vector<char *> &resBuffers) { // Basic info. unsigned int rank = constShape.size(); unsigned int numOfResults = replacingTypes.size(); // Data pointers. T *constArrayT = reinterpret_cast<T *>(constArray); // Strides info. std::vector<int64_t> constStrides = getStrides(constShape); // Allocate temporary buffers. for (unsigned int i = 0; i < numOfResults; ++i) { // Use maximum size (double or int64_t) to avoid the precision loss. char *resArray = allocateBufferFor(replacingTypes[i], /*useMaxSize=*/true); resBuffers.emplace_back(resArray); } // Do splitting for (int64_t i = 0; i < getNumberOfElements(constShape); ++i) { // Input indices. std::vector<int64_t> constIndices = getAccessIndex(i, constStrides); // Find the corresponding output and compute access indices. int toResult = numOfResults - 1; SmallVector<int64_t, 4> resIndices(rank, 0); for (unsigned int r = 0; r < rank; ++r) { if (r == splitAxis) { for (int k = 0; k < (int)numOfResults - 1; ++k) if (constIndices[r] >= splitOffsets[k] && constIndices[r] < splitOffsets[k + 1]) { toResult = k; break; } resIndices[r] = constIndices[r] - splitOffsets[toResult]; } else { resIndices[r] = constIndices[r]; } } // Get linear access indices. std::vector<int64_t> resStrides = getStrides(replacingTypes[toResult].cast<ShapedType>().getShape()); int64_t resOffset = getLinearAccessIndex(resIndices, resStrides); // Copy data. T *resArrayT = reinterpret_cast<T *>(resBuffers[toResult]); *(resArrayT + resOffset) = *(constArrayT + i); } } void ConstPropSplitImpl(Type elementType, char *constArray, llvm::ArrayRef<int64_t> constShape, uint64_t splitAxis, llvm::ArrayRef<int64_t> splitOffsets, llvm::ArrayRef<mlir::Type> replacingTypes, std::vector<char *> &resBuffers) { if (elementType.isa<FloatType>()) { IterateConstPropSplit<double>(constArray, constShape, splitAxis, splitOffsets, replacingTypes, resBuffers); } else if (elementType.isa<IntegerType>()) { IterateConstPropSplit<int64_t>(constArray, constShape, splitAxis, splitOffsets, replacingTypes, resBuffers); } else llvm_unreachable("Unknown data type"); } //===----------------------------------------------------------------------===// // Code to perform constant propagation for transpose. //===----------------------------------------------------------------------===// template <typename T> void IterateConstPropTranspose(char *constArray, ArrayRef<int64_t> constShape, ArrayRef<uint64_t> perm, ArrayRef<int64_t> resShape, char *resArray) { // Data pointers. T *constArrayT = reinterpret_cast<T *>(constArray); T *resArrayT = reinterpret_cast<T *>(resArray); // Get a reversed perm. SmallVector<uint64_t, 4> reversedPerm(perm.size(), 0); for (unsigned int i = 0; i < perm.size(); ++i) reversedPerm[perm[i]] = i; // Strides info. std::vector<int64_t> constStrides = getStrides(constShape); std::vector<int64_t> resStrides = getStrides(resShape); // Calculate transpose result. for (int64_t i = 0; i < getNumberOfElements(resShape); ++i) { // Indices. std::vector<int64_t> resIndices = getAccessIndex(i, resStrides); SmallVector<int64_t, 4> constIndices(perm.size(), 0); for (unsigned int j = 0; j < constIndices.size(); ++j) constIndices[j] = resIndices[reversedPerm[j]]; // Transpose. int64_t constOffset = getLinearAccessIndex(constIndices, constStrides); int64_t resOffset = getLinearAccessIndex(resIndices, resStrides); *(resArrayT + resOffset) = *(constArrayT + constOffset); } } void ConstPropTransposeImpl(Type elementType, char *constArray, llvm::ArrayRef<int64_t> constShape, llvm::ArrayRef<uint64_t> perm, llvm::ArrayRef<int64_t> resShape, char *resArray) { if (elementType.isa<FloatType>()) { // Use double to avoid the precision loss during computation. IterateConstPropTranspose<double>( constArray, constShape, perm, resShape, resArray); } else if (elementType.isa<IntegerType>()) { // Use int64_t to avoid the precision loss during computation. IterateConstPropTranspose<int64_t>( constArray, constShape, perm, resShape, resArray); } else llvm_unreachable("Unknown data type"); }
37.520249
80
0.663982
juan561999
aa4638abefaaaef7eaa7a21b3fadd3dec9691266
506
cpp
C++
mod/wrc/flag/flags/fileFlag.cpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/wrc/flag/flags/fileFlag.cpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/wrc/flag/flags/fileFlag.cpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#include "fileFlag.hpp" #include <fstream> #include <sstream> namespace wrd { WRD_DEF_ME(fileFlag) wbool me::_onTake(const args& tray, cli& c, interpreter& ip) const { std::vector<string> buf; for(const auto& filePath : tray) { std::ifstream fout(filePath); std::stringstream buffer; buffer << fout.rdbuf(); buf.push_back(buffer.str()); } ip.setSrcSupply(*new bufferSrcSupply(buf)); return true; }; }
22
72
0.577075
kniz
aa47ac68b7c4044e40b7ee7cd94a7d62514ad36e
1,106
hpp
C++
include/LoopKeybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
include/LoopKeybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
include/LoopKeybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
#ifndef H_AW_LOOPKEYBINDING #define H_AW_LOOPKEYBINDING #include <vector> #include <functional> #include <SFML/Window.hpp> namespace aw { class LoopKeybinding { public: typedef std::function<void()> LoopKeybindingCallback; LoopKeybinding (const LoopKeybindingCallback&, sf::Keyboard::Key); LoopKeybinding (const LoopKeybindingCallback&, const std::vector<sf::Keyboard::Key>&); ~ LoopKeybinding () = default; LoopKeybinding (LoopKeybinding&&) = default; LoopKeybinding& operator = (LoopKeybinding&&) = default; LoopKeybinding (const LoopKeybinding&) = default; LoopKeybinding& operator = (const LoopKeybinding&) = default; bool check (const std::vector<sf::Keyboard::Key>&); void process (const std::vector<sf::Keyboard::Key>&); const LoopKeybindingCallback& getCallback () const; std::vector<sf::Keyboard::Key> getKeys () const; void setCallback (const LoopKeybindingCallback&); void setKeys (const std::vector<sf::Keyboard::Key>&); private: LoopKeybindingCallback m_callback; std::vector<sf::Keyboard::Key> m_keys; }; } #endif
25.72093
90
0.716094
DangerInteractive
aa601fdffefd00d331af042807bf638a48712c6b
596
cpp
C++
copy_constructor.cpp
Devilshree123/Object-oriented-programming-in-CPP
d5059b1c4f394417235ade5a0794d368d1c13b60
[ "Apache-2.0" ]
null
null
null
copy_constructor.cpp
Devilshree123/Object-oriented-programming-in-CPP
d5059b1c4f394417235ade5a0794d368d1c13b60
[ "Apache-2.0" ]
null
null
null
copy_constructor.cpp
Devilshree123/Object-oriented-programming-in-CPP
d5059b1c4f394417235ade5a0794d368d1c13b60
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; class number { int a ; public: number(){ a=0; } number(int num) { a = num; } number(number &obj) { cout<<"copy constructor is called "<<endl; a = obj.a; } void display(); }; void number :: display() { cout<<"the number is "<<a<<endl; } int main() { number x, y, z(45); x.display(); y.display(); z.display(); number z1(z); z1.display(); return 0; }
14.190476
55
0.407718
Devilshree123
aa62ad93ab34bbbdb4e009f0ef5397bea16621e1
423
cpp
C++
6. Trees/09. Convert BST to Greater Tree.cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
6. Trees/09. Convert BST to Greater Tree.cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
6. Trees/09. Convert BST to Greater Tree.cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
https://leetcode.com/problems/convert-bst-to-greater-tree/ convert bst such that BST is changed to the original key plus the sum of all keys greater than the original key in BST. TreeNode* convertBST(TreeNode* root) { if(root!=NULL){ convertBST(root->right); sum+=root->val; root->val=sum; convertBST(root->left); } return root; }
30.214286
72
0.588652
thekalyan001
aa663493041898051a0fef9fdcb937a0f156ab9c
665
cpp
C++
cppfun/main.cpp
selvakumarjawahar/myexperiments
8d04a38e992bb717c792d198dda1d221b749a375
[ "MIT" ]
null
null
null
cppfun/main.cpp
selvakumarjawahar/myexperiments
8d04a38e992bb717c792d198dda1d221b749a375
[ "MIT" ]
4
2021-09-02T01:23:47.000Z
2022-02-26T19:35:28.000Z
cppfun/main.cpp
selvakumarjawahar/myexperiments
8d04a38e992bb717c792d198dda1d221b749a375
[ "MIT" ]
null
null
null
#include <iostream> #include "StaticMapGenerator.h" #include <cstdlib> Fruits FruitGenerator(){ auto fruit = rand() % 3; return static_cast<Fruits>(fruit); } using DefaultFruitMap = DefaultValueMap<Fruits,Season,Season::AllYear>; int main() { std::cout << "Default = " << (int) FruitMap<Fruits::Grapes>::val << '\n'; std::cout << "Mango Season = " << (int) FruitMap<Fruits::Mango>::val << '\n'; DefaultFruitMap dfmap{{Fruits::Mango,Season::Summer}}; std::cout << "Mango Season = " << (int) dfmap.getValue(Fruits::Mango) << '\n'; std::cout << "Random Fruit Season = " << (int) dfmap.getValue(FruitGenerator()) << '\n'; return 0; }
33.25
92
0.631579
selvakumarjawahar
aa68187c169675cc4c51c365350ab05887d971c1
6,595
cpp
C++
source/app/rendering/device.cpp
mattwamboldt/rasterizer
a571c9350d448f71e991f145cb0264abb2002d4d
[ "MIT" ]
null
null
null
source/app/rendering/device.cpp
mattwamboldt/rasterizer
a571c9350d448f71e991f145cb0264abb2002d4d
[ "MIT" ]
null
null
null
source/app/rendering/device.cpp
mattwamboldt/rasterizer
a571c9350d448f71e991f145cb0264abb2002d4d
[ "MIT" ]
null
null
null
#include "device.h" #include <float.h> Device::Device(SDL_Surface* _screen) :screen(_screen), renderWidth(screen->w), renderHeight(screen->h) { depthBuffer = new float[renderWidth * renderHeight]; } Device::~Device() { if (depthBuffer) { delete[] depthBuffer; } } // Clears the screen buffer to the given color void Device::Clear(Color color) { Uint32* pixels = (Uint32 *)screen->pixels; Uint32 screenColor = SDL_MapRGBA(screen->format, color.r, color.g, color.b, color.a); for (int i = 0; i < renderWidth * renderHeight; ++i) { pixels[i] = screenColor; depthBuffer[i] = FLT_MAX; } } Color Device::GetPixel(int x, int y) { Uint32 index = x + y * renderWidth; Uint32* pixels = (Uint32 *)screen->pixels; Color ret; SDL_GetRGBA(pixels[index], screen->format, &(ret.r), &(ret.g), &(ret.b), &(ret.a)); return ret; } // Draws a pixel to the screen ignoring the depthbuffer void Device::PutPixel(int x, int y, Color c) { Uint32* pixels = (Uint32 *)screen->pixels; Uint32 index = x + y * renderWidth; pixels[index] = SDL_MapRGBA(screen->format, c.r, c.g, c.b, c.a); } // Draws a pixel to the screen only if it passes our depth buffer test void Device::PutPixel(int x, int y, float z, Color c) { Uint32* pixels = (Uint32 *)screen->pixels; Uint32 index = x + y * renderWidth; if (depthBuffer[index] < z) { return; } depthBuffer[index] = z; pixels[index] = SDL_MapRGBA(screen->format, c.r, c.g, c.b, c.a); } // Draws a point to the screen if it is within the viewport void Device::DrawPoint(float x, float y, float z, Color color) { // Clipping what's visible on screen if (x >= 0 && y >= 0 && x < renderWidth && y < renderHeight) { // Drawing a point PutPixel((int)x, (int)y, z, color); } } void Device::DrawPoint(int x, int y, const Color& c) { if (x >= 0 && x < screen->w && y >= 0 && y < screen->h) { PutPixel(x, y, c); } } Vector3 Device::Project(const Vector3& v, const Matrix& transform) const { Vector3 projectedVector = transform.Transform(v); return Vector3( ((screen->w / 2) * projectedVector.x) + (screen->w / 2), -(((screen->h / 2) * projectedVector.y) - (screen->h / 2)), projectedVector.z ); } void WriteHexString(SDL_RWops* file, char *s) { Uint32 value; char hex[3]; for (int i = 0; i < SDL_strlen(s); i += 2) { hex[0] = s[i]; hex[1] = s[i + 1]; hex[2] = '\0'; SDL_sscanf(hex, "%X", &value); SDL_WriteU8(file, value); } } void Device::WriteToFile(const char* filename) { SDL_RWops* file = SDL_RWFromFile(filename, "w+b"); if (file) { // Writing out a tiff (Code taken from http://paulbourke.net/dataformats/tiff/) switch with a lib later Uint32 numbytes = renderWidth * renderHeight * 3; // Header of the file SDL_RWwrite(file, "MM", 2, 1); SDL_WriteBE16(file, 42); Uint32 offset = numbytes + 8; // 8 bytes are from the header including this offset SDL_WriteBE32(file, offset); // Then the actual data Uint32* pixels = (Uint32 *)screen->pixels; // to avoid a bunch of file io and hopefully speed up the function we're gonna buffer pixel writes and do them at once Uint8* buffer = new Uint8[numbytes]; Uint32 bufferOffset = 0; for (int y = 0; y < renderHeight; ++y) { for (int x = 0; x < renderWidth; ++x) { Uint32 pixelIndex = x + y * renderWidth; Uint32 pixel = pixels[pixelIndex]; Color color = Color(pixel); buffer[bufferOffset++] = color.r; buffer[bufferOffset++] = color.g; buffer[bufferOffset++] = color.b; } } SDL_RWwrite(file, buffer, numbytes, 1); delete buffer; // Finally the IFD // The number of directory entries SDL_WriteBE16(file, 14); /* Width tag, short int */ WriteHexString(file, "0100000300000001"); SDL_WriteBE16(file, renderWidth); WriteHexString(file, "0000"); /* Height tag, short int */ WriteHexString(file, "0101000300000001"); SDL_WriteBE16(file, renderHeight); WriteHexString(file, "0000"); /* Bits per sample tag, short int */ WriteHexString(file, "0102000300000003"); SDL_WriteBE32(file, numbytes + 182); /* Compression flag, short int */ WriteHexString(file, "010300030000000100010000"); /* Photometric interpolation tag, short int */ WriteHexString(file, "010600030000000100020000"); /* Strip offset tag, long int */ WriteHexString(file, "011100040000000100000008"); /* Orientation flag, short int */ WriteHexString(file, "011200030000000100010000"); /* Sample per pixel tag, short int */ WriteHexString(file, "011500030000000100030000"); /* Rows per strip tag, short int */ WriteHexString(file, "0116000300000001"); SDL_WriteBE16(file, renderHeight); WriteHexString(file, "0000"); /* Strip byte count flag, long int */ WriteHexString(file, "0117000400000001"); SDL_WriteBE32(file, numbytes); /* Minimum sample value flag, short int */ WriteHexString(file, "0118000300000003"); SDL_WriteBE32(file, numbytes + 188); /* Maximum sample value tag, short int */ WriteHexString(file, "0119000300000003"); SDL_WriteBE32(file, numbytes + 194); /* Planar configuration tag, short int */ WriteHexString(file, "011c00030000000100010000"); /* Sample format tag, short int */ WriteHexString(file, "0153000300000003"); SDL_WriteBE32(file, numbytes + 200); /* End of the directory entry */ WriteHexString(file, "00000000"); /* Bits for each colour channel */ WriteHexString(file, "000800080008"); /* Minimum value for each component */ WriteHexString(file, "000000000000"); /* Maximum value per channel */ WriteHexString(file, "00ff00ff00ff"); /* Samples per pixel for each channel */ WriteHexString(file, "000100010001"); SDL_RWclose(file); } }
30.252294
127
0.576952
mattwamboldt
aa6a135b84a3c9c22aa97a1a22aeb51036d01903
7,005
cpp
C++
c/src/execution_engine.cpp
tydeu/lean4-papyrus
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
[ "Apache-2.0" ]
9
2021-07-22T11:37:59.000Z
2022-02-23T05:39:35.000Z
c/src/execution_engine.cpp
tydeu/lean4-papyrus
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
[ "Apache-2.0" ]
2
2021-09-17T15:59:21.000Z
2021-09-24T23:52:23.000Z
c/src/execution_engine.cpp
tydeu/lean4-papyrus
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
[ "Apache-2.0" ]
2
2021-09-06T09:45:21.000Z
2022-03-09T12:24:53.000Z
#include "papyrus.h" #include "papyrus_ffi.h" #include <lean/lean.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> using namespace llvm; namespace papyrus { struct EEExternal { // The execution engine handle. ExecutionEngine* ee; // The modules controlled by the execution engine. SmallVector<Module*, 1> modules; // The error message owned by the execution engine. std::string* errMsg; EEExternal(ExecutionEngine* ee, std::string* errMsg) : ee(ee), errMsg(errMsg) {} EEExternal(const EEExternal&) = delete; ~EEExternal() { // remove all the modules from the execution engine so they don't get deleted for (auto it = modules.begin(), end = modules.end(); it != end; ++it) { ee->removeModule(*it); } delete ee; delete errMsg; } }; // Lean object class for an LLVM ExecutionEngine. static lean_external_class* getExecutionEngineClass() { // Use static to make this thread safe by static initialization rules. static lean_external_class* c = lean_register_external_class(&deleteFinalize<EEExternal>, &nopForeach); return c; } // Wrap a ExecutionEngine in a Lean object. lean_object* mkExecutionEngineRef(EEExternal* ee) { return lean_alloc_external(getExecutionEngineClass(), ee); } // Get the ExecutionEngine external wrapped in an object. EEExternal* toEEExternal(lean_object* eeRef) { auto external = lean_to_external(eeRef); assert(external->m_class == getExecutionEngineClass()); return static_cast<EEExternal*>(external->m_data); } // Get the ExecutionEngine wrapped in an object. ExecutionEngine* toExecutionEngine(lean_object* eeRef) { return toEEExternal(eeRef)->ee; } // Unpack the Lean representation of an engine kind into the LLVM one. EngineKind::Kind unpackEngineKnd(uint8_t kind) { return kind == 0 ? EngineKind::Either : static_cast<EngineKind::Kind>(kind); } //extern "C" lean_object* mk_io_user_error(lean_object* str); // Create a new execution engine for the given module. extern "C" lean_obj_res papyrus_execution_engine_create_for_module (b_lean_obj_res modObj, uint8_t kindObj, b_lean_obj_res marchStr, b_lean_obj_res mcpuStr, b_lean_obj_res mattrsObj, uint8_t optLevel, uint8_t verifyModules, lean_obj_arg /* w */) { // Create an engine builder EngineBuilder builder(std::unique_ptr<Module>(toModule(modObj))); // Configure the builder auto errMsg = new std::string(); auto kind = unpackEngineKnd(kindObj); builder.setEngineKind(kind); builder.setErrorStr(errMsg); builder.setOptLevel(static_cast<CodeGenOpt::Level>(optLevel)); builder.setVerifyModules(verifyModules); builder.setMArch(refOfString(marchStr)); builder.setMCPU(refOfString(mcpuStr)); LEAN_ARRAY_TO_REF(std::string, stdOfString, mattrsObj, mattrs); builder.setMAttrs(mattrs); // Try to construct the execution engine if (ExecutionEngine* ee = builder.create()) { auto eee = new EEExternal(ee, errMsg); eee->modules.push_back(toModule(modObj)); return lean_io_result_mk_ok(mkExecutionEngineRef(eee)); } else { // Steal back the module pointer before it gets deleted reinterpret_cast<std::unique_ptr<Module>&>(builder).release(); auto res = mkStdStringError(*errMsg); delete errMsg; return res; } return lean_io_result_mk_ok(lean_box(0)); } // Run the given function with given arguments // in the given execution engine and return the result. extern "C" lean_obj_res papyrus_execution_engine_run_function (b_lean_obj_res funRef, b_lean_obj_res eeRef, b_lean_obj_res argsObj, lean_obj_arg /* w */) { LEAN_ARRAY_TO_REF(GenericValue, *toGenericValue, argsObj, args); auto ret = toExecutionEngine(eeRef)->runFunction(toFunction(funRef), args); return lean_io_result_mk_ok(mkGenericValueRef(new GenericValue(ret))); } class ArgvArray { public: std::unique_ptr<char[]> argv; std::vector<std::unique_ptr<char[]>> ptrs; // Turn a Lean array of string objects // into a nice argv style null terminated array of pointers. void* set(PointerType* pInt8Ty, ExecutionEngine *ee, const lean_array_object* args); }; void* ArgvArray::set (PointerType* pInt8Ty, ExecutionEngine *ee, const lean_array_object* args) { auto argc = args->m_size; unsigned ptrSize = ee->getDataLayout().getPointerSize(); argv = std::make_unique<char[]>((argc+1)*ptrSize); ptrs.reserve(argc); auto data = args->m_data; for (unsigned i = 0; i != argc; ++i) { auto str = lean_to_string(data[i]); // copy the string so that the user may edit it auto ptr = std::make_unique<char[]>(str->m_size); std::copy(str->m_data, str->m_data + str->m_size, ptr.get()); // endian safe: argv[i] = ptr.get() ee->StoreValueToMemory(PTOGV(ptr.get()), (GenericValue*)(&argv[i*ptrSize]), pInt8Ty); // pointer will be deallocated when the `ArgvArray` is ptrs.push_back(std::move(ptr)); } // null terminate the array ee->StoreValueToMemory(PTOGV(nullptr), (GenericValue*)(&argv[argc*ptrSize]), pInt8Ty); return argv.get(); } /* A helper function to wrap the behavior of `runFunction` to handle common task of starting up a `main` function with the usual `argc`, `argv`, and `envp` parameters. Instead of using LLVM's `runFunctionAsMain` directly, we adapt its code to Lean's data structures. */ extern "C" lean_obj_res papyrus_execution_engine_run_function_as_main (b_lean_obj_res funRef, b_lean_obj_res eeRef, b_lean_obj_res argsObj, b_lean_obj_res envObj, lean_obj_arg /* w */) { auto fn = toFunction(funRef); auto fnTy = fn->getFunctionType(); auto& ctx = fnTy->getContext(); auto fnArgc = fnTy->getNumParams(); auto pInt8Ty = Type::getInt8PtrTy(ctx); auto ppInt8Ty = pInt8Ty->getPointerTo(); if (fnArgc > 3) return mkStdStringError("Invalid number of arguments of main() supplied"); if (fnArgc >= 3 && fnTy->getParamType(2) != ppInt8Ty) return mkStdStringError("Invalid type for third argument of main() supplied"); if (fnArgc >= 2 && fnTy->getParamType(1) != ppInt8Ty) return mkStdStringError("Invalid type for second argument of main() supplied"); if (fnArgc >= 1 && !fnTy->getParamType(0)->isIntegerTy(32)) return mkStdStringError("Invalid type for first argument of main() supplied"); if (!fnTy->getReturnType()->isIntegerTy() && !fnTy->getReturnType()->isVoidTy()) return mkStdStringError("Invalid return type of main() supplied"); ArgvArray argv, env; GenericValue fnArgs[fnArgc]; auto ee = toExecutionEngine(eeRef); if (fnArgc > 0) { auto argsArr = lean_to_array(argsObj); fnArgs[0].IntVal = APInt(32, argsArr->m_size); // argc if (fnArgc > 1) { fnArgs[1].PointerVal = argv.set(pInt8Ty, ee, argsArr); if (fnArgc > 2) { fnArgs[2].PointerVal = env.set(pInt8Ty, ee, lean_to_array(envObj)); } } } auto gRc = ee->runFunction(toFunction(funRef), ArrayRef<GenericValue>(fnArgs, fnArgc)); return lean_io_result_mk_ok(lean_box_uint32(gRc.IntVal.getZExtValue())); } } // end namespace papyrus
35.739796
116
0.725625
tydeu
aa758cb0138d5f90c4021b9915746cbb16252dd4
2,457
cpp
C++
src/engine/Scrap.cpp
m1cr0lab-gamebuino/apollo
79c71d0ca44301d05d284a7f2bc5137fe80c911a
[ "MIT" ]
1
2021-07-28T12:35:52.000Z
2021-07-28T12:35:52.000Z
src/engine/Scrap.cpp
m1cr0lab-gamebuino/apollo
79c71d0ca44301d05d284a7f2bc5137fe80c911a
[ "MIT" ]
null
null
null
src/engine/Scrap.cpp
m1cr0lab-gamebuino/apollo
79c71d0ca44301d05d284a7f2bc5137fe80c911a
[ "MIT" ]
null
null
null
/** * ------------------------------------------------------------------------- * Apollo * ------------------------------------------------------------------------- * a tiny game for the Gamebuino META retro gaming handheld * inspired by the famous Lunar Lander * https://youtu.be/McAhSoAEbhM * https://en.wikipedia.org/wiki/Lunar_Lander_(1979_video_game) * ------------------------------------------------------------------------- * © 2021 Steph @ m1cr0lab * https://gamebuino.m1cr0lab.com * ------------------------------------------------------------------------- */ #include <Gamebuino-Meta.h> #include "Scrap.h" #include "../data/assets.h" #include "../data/config.h" void Scrap::init(float_t x, float_t y, float_t radius, float_t vx, float_t vy, float_t vrot) { _x = x; _y = y; _r = radius; _vx = vx; _vy = vy; _rot = 0; _vrot = vrot; uint8_t n = VERTICE_NB << 1; for (uint8_t i=0; i<n; i+=2) { _vertice[i] = radius * .1f * random(4, 11); _vertice[i+1] = i * 2*PI / VERTICE_NB; } _visible = true; } void Scrap::draw(Camera &camera) { if (!_visible) return; float_t cx = camera.ox(); float_t cy = camera.oy(); float_t cz = camera.zoom(); float_t r = _vertice[0]; float_t a = _vertice[1] + _rot; float_t x0 = _x + r*cos(a), x1 = x0; float_t y0 = _y + r*sin(a), y1 = y0; float_t x2, y2; uint8_t n = VERTICE_NB << 1; gb.display.setColor(COLOR_APOLLO); for (uint8_t i=2; i<n; i+=2) { r = _vertice[i]; a = _vertice[i+1] + _rot; x2 = _x + r*cos(a); y2 = _y + r*sin(a); gb.display.drawLine( cz * (x1 - cx), cz * (y1 - cy), cz * (x2 - cx), cz * (y2 - cy) ); x1 = x2; y1 = y2; } gb.display.drawLine( cz * (x0 - cx), cz * (y0 - cy), cz * (x2 - cx), cz * (y2 - cy) ); } void Scrap::loop() { if (!_visible) return; _rot += _vrot; if (_rot < 0) _rot += 2*PI; else if (_rot > 2*PI) _rot -= 2*PI; _vy += GRAVITY; _x += _vx; _y += _vy; _visible = !( _x + _r < 0 || _x > _r + SCREEN_WIDTH || _y + _r < 0 || _y > _r + SCREEN_HEIGHT ); }
21.743363
94
0.406186
m1cr0lab-gamebuino
aa7a2fcd8bf0b9f7a98b3ed7882b6772e93e279c
2,128
cpp
C++
Image_editor/Image_editor.cpp
Aroidzap/VUT-FIT-IPA-Project-2017-2018
c199b3165a1e282f78d3afb7104f35772b13ca6c
[ "MIT" ]
1
2017-12-05T09:25:09.000Z
2017-12-05T09:25:09.000Z
Image_editor/Image_editor.cpp
Aroidzap/VUT-FIT-IPA-Project-2017-2018
c199b3165a1e282f78d3afb7104f35772b13ca6c
[ "MIT" ]
null
null
null
Image_editor/Image_editor.cpp
Aroidzap/VUT-FIT-IPA-Project-2017-2018
c199b3165a1e282f78d3afb7104f35772b13ca6c
[ "MIT" ]
null
null
null
/*Sablona pro projekty do predmetu IPA, tema graficky editor *Autor: Tomas Goldmann, [email protected] * *LOGIN STUDENTA: xpazdi02 */ #include <opencv2/core/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <intrin.h> #include <inttypes.h> #include <windows.h> #include "ipa_tool.h" #define WIN_WIDTH 800.0f #define PROJECT_NAME "IPA - graficky editor 2017" #define PROJECT_NAME_WIN_IN "IPA - graficky editor 2017-IN" #define PROJECT_NAME_WIN_OUT "IPA - graficky editor 2017-OUT" using namespace cv; using namespace std; typedef void(*Ipa_algorithm)(unsigned char *input_data, unsigned char *output_data, unsigned int width, unsigned int height, int argc, char** argv); int main(int argc, char** argv) { unsigned __int64 cycles_start = 0; if (argc < 2) { cout << " Usage: display_image ImageToLoadAndDisplay" << endl; return -1; } Mat output, window_img,image; image = imread(argv[1], CV_LOAD_IMAGE_COLOR); if (!image.data) { cout << "Could not open or find the image" << std::endl; return -1; } //koeficient pro prijatelne vykresleni float q = WIN_WIDTH / static_cast<float>(image.cols); //vytvoreni vystupniho obrazu image.copyTo(output); cv::resize(image, window_img, cv::Size(static_cast<int>(q*image.cols), static_cast<int>(q*image.rows))); namedWindow(PROJECT_NAME_WIN_IN, WINDOW_AUTOSIZE); imshow(PROJECT_NAME_WIN_IN, window_img); HINSTANCE hInstLibrary = LoadLibrary("Student_DLL.dll"); if (!hInstLibrary) { std::cout << "DLL Failed To Load!" << std::endl; return EXIT_FAILURE; } else { //Algoritmus InstructionCounter counter; Ipa_algorithm f; f = (Ipa_algorithm)GetProcAddress(hInstLibrary, "ipa_algorithm"); if (f) { counter.start(); f(image.data, output.data,image.cols, image.rows, argc, argv); counter.print(); } } namedWindow(PROJECT_NAME_WIN_OUT, WINDOW_AUTOSIZE); cv::resize(output, output, cv::Size(static_cast<int>(q*image.cols), static_cast<int>(q*image.rows))); imshow(PROJECT_NAME_WIN_OUT, output); waitKey(0); FreeLibrary(hInstLibrary); return 0; }
24.181818
148
0.725094
Aroidzap
aa8820758c4bd30b2af0aaa56aa2d5004e8bb278
2,571
cpp
C++
UVa/UVA - 190/Accepted (4).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
UVa/UVA - 190/Accepted (4).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
UVa/UVA - 190/Accepted (4).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2017-10-13 13:03:12 * solution_verdict: Accepted language: C++ * run_time: 0 memory_used: * problem: https://vjudge.net/problem/UVA-190 ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; double s1,s2; struct point { double x; double y; }center,a,b,c; struct equation { double qx; double qy; double cn; }e1,e2; double dist(point aa,point bb) { return sqrt((aa.x-bb.x)*(aa.x-bb.x)+(aa.y-bb.y)*(aa.y-bb.y)); } void solve_equation(void) { double D=(e1.qx*e2.qy)-(e1.qy*e2.qx); double Dx=(e1.cn*e2.qy)-(e1.qy*e2.cn); double Dy=(e1.qx*e2.cn)-(e1.cn*e2.qx); center.x=Dx/D; center.y=Dy/D; } void print(void) { double r1=dist(center,a); if(r1<0)center.x*=-1,center.y*=-1; cout<<"(x"; if(center.x>=0)cout<<" - "; else cout<<" + "; cout<<setprecision(3)<<fixed<<fabs(center.x); cout<<")^2 + (y"; if(center.y>=0)cout<<" - "; else cout<<" + "; cout<<setprecision(3)<<fixed<<fabs(center.y); cout<<")^2 = "; cout<<setprecision(3)<<fixed<<fabs(r1); cout<<"^2"<<endl; double hx=-2*center.x; double yk=-2*center.y; double cns=center.x*center.x+center.y*center.y-r1*r1; cout<<"x^2 + y^2"; if(hx>=0)cout<<" + "; else cout<<" - "; cout<<setprecision(3)<<fixed<<fabs(hx)<<"x"; if(yk>=0)cout<<" + "; else cout<<" - "; cout<<setprecision(3)<<fixed<<fabs(yk)<<"y"; if(cns>=0)cout<<" + "; else cout<<" - "; cout<<setprecision(3)<<fixed<<fabs(cns); cout<<" = 0"<<endl<<endl; } int main() { ///ofstream cout("out.txt"); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); while(cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y) { point mid1; mid1.x=(a.x+b.x)/2.0; mid1.y=(a.y+b.y)/2.0; s1=(1/((a.y-b.y)/(a.x-b.x)))*(-1); e1.cn=mid1.y-s1*mid1.x; e1.qx=-s1; e1.qy=1; point mid2; mid2.x=(b.x+c.x)/2.0; mid2.y=(b.y+c.y)/2.0; s2=(1/((b.y-c.y)/(b.x-c.x)))*(-1); e2.cn=mid2.y-s2*mid2.x; e2.qx=-s2; e2.qy=1; solve_equation(); print(); } return 0; }
24.485714
111
0.439129
kzvd4729
aa8d44e6b8873f26185035812f46c6b84a16c02b
3,723
hpp
C++
libvast/vast/bloom_filter_synopsis.hpp
krionbsd/vast
c9fbc7230cac21886cf9d032e57b752276ba7ff7
[ "BSD-3-Clause" ]
249
2019-08-26T01:44:45.000Z
2022-03-26T14:12:32.000Z
libvast/vast/bloom_filter_synopsis.hpp
krionbsd/vast
c9fbc7230cac21886cf9d032e57b752276ba7ff7
[ "BSD-3-Clause" ]
586
2019-08-06T13:10:36.000Z
2022-03-31T08:31:00.000Z
libvast/vast/bloom_filter_synopsis.hpp
krionbsd/vast
c9fbc7230cac21886cf9d032e57b752276ba7ff7
[ "BSD-3-Clause" ]
37
2019-08-16T02:01:14.000Z
2022-02-21T16:13:59.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2020 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #pragma once #include "vast/bloom_filter.hpp" #include "vast/detail/legacy_deserialize.hpp" #include "vast/synopsis.hpp" #include "vast/type.hpp" #include <caf/deserializer.hpp> #include <caf/optional.hpp> #include <caf/serializer.hpp> #include <optional> namespace vast { /// A Bloom filter synopsis. template <class T, class HashFunction> class bloom_filter_synopsis : public synopsis { public: using bloom_filter_type = bloom_filter<HashFunction>; using hasher_type = typename bloom_filter_type::hasher_type; bloom_filter_synopsis(vast::type x, bloom_filter_type bf) : synopsis{std::move(x)}, bloom_filter_{std::move(bf)} { // nop } void add(data_view x) override { VAST_ASSERT(caf::holds_alternative<view<T>>(x), "invalid data"); bloom_filter_.add(caf::get<view<T>>(x)); } [[nodiscard]] std::optional<bool> lookup(relational_operator op, data_view rhs) const override { switch (op) { default: return {}; case relational_operator::equal: // TODO: We should treat 'nil' as a normal value and // hash it, so we can exclude synopsis where all values // are non-nil. if (caf::holds_alternative<view<caf::none_t>>(rhs)) return {}; if (!caf::holds_alternative<view<T>>(rhs)) return false; return bloom_filter_.lookup(caf::get<view<T>>(rhs)); case relational_operator::in: { if (auto xs = caf::get_if<view<list>>(&rhs)) { for (auto x : **xs) { if (caf::holds_alternative<view<caf::none_t>>(x)) return {}; if (!caf::holds_alternative<view<T>>(x)) continue; if (bloom_filter_.lookup(caf::get<view<T>>(x))) return true; } return false; } return {}; } } } [[nodiscard]] bool equals(const synopsis& other) const noexcept override { if (typeid(other) != typeid(bloom_filter_synopsis)) return false; auto& rhs = static_cast<const bloom_filter_synopsis&>(other); return this->type() == rhs.type() && bloom_filter_ == rhs.bloom_filter_; } [[nodiscard]] size_t memusage() const override { return bloom_filter_.memusage(); } caf::error serialize(caf::serializer& sink) const override { return sink(bloom_filter_); } caf::error deserialize(caf::deserializer& source) override { return source(bloom_filter_); } bool deserialize(vast::detail::legacy_deserializer& source) override { return source(bloom_filter_); } protected: bloom_filter<HashFunction> bloom_filter_; }; // Because VAST deserializes a synopsis with empty options and // construction of an address synopsis fails without any sizing // information, we augment the type with the synopsis options. /// Creates a new type annotation from a set of bloom filter parameters. /// @returns The provided type with a new `#synopsis=bloom_filter(n,p)` /// attribute. Note that all previous attributes are discarded. type annotate_parameters(const type& type, const bloom_filter_parameters& params); /// Parses Bloom filter parameters from type attributes of the form /// `#synopsis=bloom_filter(n,p)`. /// @param x The type whose attributes to parse. /// @returns The parsed and evaluated Bloom filter parameters. /// @relates bloom_filter_synopsis std::optional<bloom_filter_parameters> parse_parameters(const type& x); } // namespace vast
31.820513
76
0.659952
krionbsd
aa8e1e5f59c0290cf380add3b9c0bec92a63f80a
16,191
cpp
C++
src/BezierScheme.cpp
Junology/bord2
0068885144032d4a8e30c6f2c5898918d00b1d8f
[ "MIT" ]
null
null
null
src/BezierScheme.cpp
Junology/bord2
0068885144032d4a8e30c6f2c5898918d00b1d8f
[ "MIT" ]
null
null
null
src/BezierScheme.cpp
Junology/bord2
0068885144032d4a8e30c6f2c5898918d00b1d8f
[ "MIT" ]
null
null
null
/*! * \file BezierScheme.cpp * \author Jun Yoshida * \copyright (c) 2020 Jun Yoshida. * The project is released under the MIT License. * \date February 23, 2020: created */ #include "BezierScheme.hpp" #include <set> #include <thread> #include <mutex> #include <iostream> using BezierSequence = typename BezierScheme::BezierSequence; //* Debug static std::mutex ostr_mutex; // */ /*********************************************************! * Information on cutting a sequence of Bezier curves. *********************************************************/ struct BezierCutter { size_t index; double param; //! \name Comparison operators. //@{ constexpr bool operator==(BezierCutter const& rhs) const noexcept { return index == rhs.index && param == rhs.param; } constexpr bool operator<(BezierCutter const& rhs) const noexcept { return index < rhs.index || (index == rhs.index && param < rhs.param); } constexpr bool operator>(BezierCutter const& rhs) const noexcept { return rhs < *this; } constexpr bool operator<=(BezierCutter const& rhs) const noexcept { return !(*this > rhs); } constexpr bool operator>=(BezierCutter const& rhs) const noexcept { return !(*this < rhs); } //@} }; /**********************************! * Cut a sequence of Bezier curves **********************************/ void cutoutBezSeq(BezierSequence const& src, std::set<BezierCutter> const& cutters, std::vector<BezierSequence> & out) { BezierCutter lastcut{0, 0.0}; bool carryover = false; // Traverse all cuts. for(auto& cut : cutters) { if(cut <= lastcut) continue; // Append the Bezier curves in the given sequence that are irrelevant to cutting. if (carryover) { if (lastcut.index + 1 < cut.index) out.back().insert( out.back().end(), std::next(src.begin(), lastcut.index+1), std::next(src.begin(), cut.index)); } else { out.emplace_back( std::next(src.begin(), lastcut.index), std::next(src.begin(), cut.index)); } // Divide the Bezier curve in the specified index. auto bezdiv = (lastcut.index == cut.index && carryover) ? out.back().back().divide( (cut.param - lastcut.param)/(1.0 - lastcut.param) ) : src[cut.index].divide(cut.param); // Append the first half. if(cut.param > 0.0) { if(lastcut.index == cut.index && carryover) { out.back().back() = bezdiv.first; } else { out.back().push_back(bezdiv.first); } } // If the division actually divides the curve, carry over the latter half to the next step. if(cut.param < 1.0) { out.emplace_back(1, bezdiv.second); carryover = true; lastcut = cut; } else { carryover = false; lastcut = {cut.index+1, 0.0}; } } // If there are remaining parts, add them. if(carryover && lastcut.index+1 < src.size()) { out.back().insert( out.back().end(), std::next(src.begin(), lastcut.index+1), src.end() ); } else if (!carryover && lastcut.index < src.size()) { out.emplace_back( std::next(src.begin(), lastcut.index), src.end() ); } } /*******************************************************************! * Computes cuttings of an under-strand of crossing Bezier curves. * \param f A function-like object computing the "height" of signature * > double(bool,BezierCutter const&) * where the first parameter indicates which we are looking at; LHS (true) or RHS (false). *******************************************************************/ template <class BezierT, class F> auto crosscut(std::vector<BezierT> const& lhs, std::vector<BezierT> const& rhs, F const& f, std::atomic_bool const& flag = std::atomic_bool{true} ) -> std::pair<std::set<BezierCutter>,std::set<BezierCutter>> { static_assert( std::is_same<typename BezierTraits<BezierT>::vertex_type, Eigen::Vector2d>::value, "The control points must be of type Eigen::Vector2d."); bool to_be_continued = true; auto result = std::make_pair( std::set<BezierCutter>{}, std::set<BezierCutter>{} ); // Traverse all parings. for(size_t i = 0; i < lhs.size() && to_be_continued; ++i) { for(size_t j = 0; j < rhs.size() && to_be_continued; ++j) { auto crosses = intersect<12,3>( lhs[i], rhs[j], [&flag]() -> bool { return flag.load(std::memory_order_acquire); } ); for(auto& params : crosses) { // Compute the heights at the crossing in the projections. double lhei = f(true, BezierCutter{i, params.first}); double rhei = f(false, BezierCutter{j, params.second}); // Append the parameter of the under-strand. if (lhei < rhei) result.first.insert(BezierCutter{i, params.first}); else result.second.insert(BezierCutter{j, params.second}); } to_be_continued = flag.load(std::memory_order_acquire); } } return result; } /*******************************************************************! * Computes cuttings of an under-strand in self-crossing. * \param f A function-like object computing the "height" of signature * > double(BezierCutter const&) *******************************************************************/ template <class BezierT, class F> auto crosscut_self(std::vector<BezierT> const& bezseq, F const& f, std::atomic_bool const &flag = std::atomic_bool{true} ) -> std::set<BezierCutter> { static_assert( std::is_same<typename BezierTraits<BezierT>::vertex_type, Eigen::Vector2d>::value, "The control points must be of type Eigen::Vector2d."); bool to_be_continued = true; std::set<BezierCutter> result{}; // Traverse all parings. for(size_t i = 0; i < bezseq.size() && to_be_continued; ++i) { for(size_t j = i+1; j < bezseq.size() && to_be_continued; ++j) { auto crosses = intersect<12,3>( bezseq[i], bezseq[j], [&flag]() -> bool { return flag.load(std::memory_order_acquire); }); for(auto& params : crosses) { // Compute the heights at the crossing in the projections. double lhei = f(BezierCutter{i, params.first}); double rhei = f(BezierCutter{j, params.second}); // Append the parameter of the under-strand. if (lhei < rhei) result.insert(BezierCutter{i, params.first}); else result.insert(BezierCutter{j, params.second}); } to_be_continued = flag.load(std::memory_order_acquire); } } return result; } /*********************************************************************! * Implementation of getProject member function of BezierScheme class * This function should return as soon as possible when the value of the argument flag becomes false. *********************************************************************/ auto getProject_impl( std::vector<BezierSequence> const& bezseqs, Eigen::Matrix3d const& basis, std::atomic_bool const& flag = std::atomic_bool{true} ) -> std::vector<BezierSequence> { // Type aliases. using BezierVarType = BezierScheme::BezierVarType; using BezierProjected = typename BezierTraits<BezierVarType>::template converted_type<Eigen::Vector2d>; // 2d projected Bezier sequences std::vector<std::vector<BezierProjected>> bezseqs_2d( bezseqs.size(), std::vector<BezierProjected>{} ); for(size_t i = 0; i < bezseqs.size(); ++i) { std::transform( bezseqs[i].begin(), bezseqs[i].end(), std::back_inserter(bezseqs_2d[i]), [&basis](BezierVarType const& bez3d) -> BezierProjected { return bez3d.convert( [&basis](Eigen::Vector3d const& v) -> Eigen::Vector2d { return basis.block<2,3>(0,0) * v; } ); } ); } std::vector<std::set<BezierCutter>> cutters( bezseqs.size(), std::set<BezierCutter>{} ); /* Debug std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "In Thread: " << std::this_thread::get_id() << std::endl; // */ /* Compute the self-crossings concurrently.*/ { std::vector<std::thread> workers; for(size_t i = 0; i < bezseqs.size(); ++i) { workers.emplace_back( [&cuts=cutters[i], &bezseq_2d=bezseqs_2d[i], &bezseq=bezseqs[i], &basis, &flag, /* Debug */ i] { /* Debug { std::lock_guard<std::mutex> _(ostr_mutex); std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "Launch the Thread: " << std::this_thread::get_id() << std::endl; std::cout << "Computing self-crossings of " << i << std::endl; } // */ auto selfcuts = crosscut_self( bezseq_2d, [&bezseq, &basis](BezierCutter const& cut) -> double { return -basis.row(2)*bezseq[cut.index].eval(cut.param); }, flag ); cuts.insert( std::make_move_iterator(selfcuts.begin()), std::make_move_iterator(selfcuts.end())); /* Debug { std::lock_guard<std::mutex> _(ostr_mutex); std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "Finish the Thread: " << std::this_thread::get_id() << std::endl; std::cout << "Finish self-crossings of " << i << std::endl; } // */ } ); } for(auto& worker : workers) worker.join(); } /*** Compute crossings of different strands. ***/ { // Mutexex for Bezier sequences. std::vector<std::mutex> mutexes(bezseqs.size()); // Thread computing crossings of Bezier sequences. std::vector<std::thread> workers; workers.reserve(bezseqs.size()*(bezseqs.size()-1)/2); for(size_t stride = 1; stride < bezseqs.size(); ++stride) { for(size_t i = 0; i+stride < bezseqs.size(); ++i) { /* Debug std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "i=" << i << " vs i+stride=" << i+stride << std::endl; // */ workers.emplace_back( [&cutsL = cutters[i], &cutsR = cutters[i+stride], &lhs2d = bezseqs_2d[i], &rhs2d = bezseqs_2d[i+stride], &lhs = bezseqs[i], &rhs = bezseqs[i+stride], &basis, &mutexL = mutexes[i], &mutexR = mutexes[i+stride], &flag, /*Debug*/ i, /*Debug*/ j=i+stride]() { /* Debug { std::lock_guard<std::mutex> _(ostr_mutex); std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "Launch the Thread: " << std::this_thread::get_id() << std::endl; std::cout << "Computing crossings of " << i << " and " << j << std::endl; } // */ auto crscuts = crosscut( lhs2d, rhs2d, [&lhs, &rhs, &basis](bool flag, BezierCutter const& cut) -> double { return -basis.row(2)*(flag ? lhs[cut.index].eval(cut.param) : rhs[cut.index].eval(cut.param)); }, flag); { std::lock_guard<std::mutex> gurdL(mutexL); cutsL.insert( std::make_move_iterator(crscuts.first.begin()), std::make_move_iterator(crscuts.first.end()) ); } { std::lock_guard<std::mutex> gurdR(mutexR); cutsR.insert( std::make_move_iterator(crscuts.second.begin()), std::make_move_iterator(crscuts.second.end()) ); } /* Debug { std::lock_guard<std::mutex> _(ostr_mutex); std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "Finish the Thread: " << std::this_thread::get_id() << std::endl; std::cout << "Finish " << i << " and " << j << std::endl; } // */ } ); } } // Wait for the computations. for(auto& worker : workers) worker.join(); } // Cut-out the sequences of Bezier curves and write the results std::vector<BezierSequence> result{}; result.reserve(bezseqs.size()); for(size_t i = 0; i < bezseqs.size() && flag.load(std::memory_order_acquire); ++i) { /* Debug std::cout << __FILE__":" << __LINE__ << std::endl; std::cout << "i=" << i << " #cuts=" << cutters[i].size() << std::endl; // */ cutoutBezSeq(bezseqs[i], cutters[i], result); } return result; } /****************************** * BezierScheme::getProject ******************************/ auto BezierScheme::getProject( Eigen::Matrix<double,2,3> const& prmat, std::function<void(void)> fun ) const -> std::future<std::vector<BezierSequence>> { std::promise<std::vector<BezierSequence>> p; auto fut = p.get_future(); Eigen::RowVector3d kernel = prmat.row(0).cross(prmat.row(1)); // If the depth vector is the zero vector, return immediately. if (kernel.isZero()) { std::cerr << __FILE__":" << __LINE__ << std::endl; std::cerr << "Projection direction is zero vector." << std::endl; p.set_value({}); return fut; } // Compute a projection matrix onto the plane. // Notice that the result depends not on this projection but only on the kernel. Eigen::Matrix3d basis; kernel.normalize(); basis.block<2,3>(0,0) = prmat; basis.row(2) = kernel; terminate(); m_to_be_computed.store(true); m_computer = std::thread( [basis, bezseqs=m_bezseqs, p=std::move(p), f=std::move(fun), &flag=m_to_be_computed]() mutable { p.set_value_at_thread_exit( getProject_impl(bezseqs, basis, flag)); // p.set_value(getProject_impl(bezseqs, basis, flag)); // Invoke f() if the computation successfully finished. if(flag.load(std::memory_order_acquire)) f(); } ); return fut; }
36.140625
126
0.481379
Junology
aa8e712b7b0e6b54a17e5b31de3357c0df06dd91
1,488
cpp
C++
sha3/main.cpp
skapix/sha3
6cbec1d0cf6eebe3ce4182da303d70c741cae30c
[ "MIT" ]
7
2018-11-21T20:33:05.000Z
2022-03-21T16:47:33.000Z
sha3/main.cpp
skapix/sha3
6cbec1d0cf6eebe3ce4182da303d70c741cae30c
[ "MIT" ]
null
null
null
sha3/main.cpp
skapix/sha3
6cbec1d0cf6eebe3ce4182da303d70c741cae30c
[ "MIT" ]
4
2018-08-30T14:17:45.000Z
2021-12-03T23:54:39.000Z
#include <iostream> #include <fstream> #include <vector> #include <cassert> #include <cstdint> #include <CLI/CLI.hpp> #include "util.h" #include "sha3_cpu.h" #include "sha3_gpu.h" template<typename T> std::vector<uint8_t> doCalculation(std::istream &is, size_t digestSize, size_t bufSize) { T s(digestSize); std::vector<uint8_t> data; data.resize(bufSize); while (true) { is.read(reinterpret_cast<char *>(data.data()), data.size()); std::streamsize nread = is.gcount(); assert(nread >= 0); if (nread == 0) { break; } s.add(data.data(), static_cast<size_t>(nread)); } return s.digest(); } int main(int argc, const char *argv[]) { size_t digestSize = 512; std::string inputFile; bool isGpu = false; CLI::App app("SHA3 hash calculation"); app.add_set("-d,--digest", digestSize, {224, 256, 384, 512}, "Digest length", true); app.add_option("input", inputFile, "File to calculate SHA3")->check(CLI::ExistingFile); app.add_flag("-g,--gpu", isGpu, "Calculate SHA3 hash usign gpu"); CLI11_PARSE(app, argc, argv); std::ifstream f(inputFile, std::ifstream::binary); if (!f.is_open()) { std::cerr << "Can't open file " << argv[1] << std::endl; return 1; } size_t size = 1024 * 1024; std::vector<uint8_t> digest; if (isGpu) { digest = doCalculation<SHA3_gpu>(f, digestSize, size); } else { digest = doCalculation<SHA3_cpu>(f, digestSize, size); } std::cout << digest << std::endl; }
21.882353
89
0.638441
skapix
aa8f09e170bee1bcb8708673be76fff5cccd3c10
57
cpp
C++
src/stb_image.cpp
MickAlmighty/StudyOpenGL
aebebc9e89cca5a00569e7c5876045e36eed0c3b
[ "MIT" ]
null
null
null
src/stb_image.cpp
MickAlmighty/StudyOpenGL
aebebc9e89cca5a00569e7c5876045e36eed0c3b
[ "MIT" ]
null
null
null
src/stb_image.cpp
MickAlmighty/StudyOpenGL
aebebc9e89cca5a00569e7c5876045e36eed0c3b
[ "MIT" ]
null
null
null
#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
28.5
34
0.824561
MickAlmighty
aa955910105940546d3c77a4ed6a0647aec689f1
3,373
cpp
C++
src/autowiring/CoreThreadMac.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/CoreThreadMac.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/CoreThreadMac.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "BasicThread.h" #include "BasicThreadStateBlock.h" #include <pthread.h> #include <libproc.h> #include <mach/thread_info.h> #include <mach/thread_act.h> #include <sys/proc_info.h> #include <sys/sysctl.h> #include <sys/types.h> #include <unistd.h> #include <iostream> #include <pthread.h> #include THREAD_HEADER // Missing definitions from pthreads.h #if !defined(PTHREAD_MIN_PRIORITY) #define PTHREAD_MIN_PRIORITY 0 #endif #if !defined(PTHREAD_MAX_PRIORITY) #define PTHREAD_MAX_PRIORITY 63 #endif using std::chrono::milliseconds; using std::chrono::nanoseconds; void BasicThread::SetCurrentThreadName(void) const { pthread_setname_np(m_name); } std::chrono::steady_clock::time_point BasicThread::GetCreationTime(void) { return std::chrono::steady_clock::time_point::min(); } void BasicThread::GetThreadTimes(std::chrono::milliseconds& kernelTime, std::chrono::milliseconds& userTime) { // Obtain the thread port from the Unix pthread wrapper pthread_t pthread = m_state->m_thisThread.native_handle(); thread_t threadport = pthread_mach_thread_np(pthread); // Now use the Mac thread type to obtain the kernel thread handle thread_identifier_info_data_t identifier_info; mach_msg_type_number_t tident_count = THREAD_IDENTIFIER_INFO_COUNT; thread_info(threadport, THREAD_IDENTIFIER_INFO, (thread_info_t) &identifier_info, &tident_count); // Finally, we can obtain the actual thread times the user wants to know about proc_threadinfo info; proc_pidinfo(getpid(), PROC_PIDTHREADINFO, identifier_info.thread_handle, &info, sizeof(info)); // User time is in ns increments kernelTime = std::chrono::duration_cast<milliseconds>(nanoseconds(info.pth_system_time)); userTime = std::chrono::duration_cast<milliseconds>(nanoseconds(info.pth_user_time)); } void BasicThread::SetThreadPriority(const std::thread::native_handle_type& handle, ThreadPriority threadPriority, SchedulingPolicy schedPolicy) { struct sched_param param = { 0 }; int policy; int percent = 0; switch (schedPolicy) { case SchedulingPolicy::StandardRoundRobin: policy = SCHED_OTHER; break; case SchedulingPolicy::RealtimeFIFO: policy = SCHED_FIFO; break; case SchedulingPolicy::RealtimeRoundRobin: policy = SCHED_RR; break; default: throw std::invalid_argument("Attempted to assign an unrecognized scheduling policy"); break; } switch (threadPriority) { case ThreadPriority::Idle: percent = 0; break; case ThreadPriority::Lowest: percent = 1; break; case ThreadPriority::BelowNormal: percent = 20; break; case ThreadPriority::Normal: case ThreadPriority::Default: percent = 50; break; case ThreadPriority::AboveNormal: percent = 66; break; case ThreadPriority::Highest: percent = 83; break; case ThreadPriority::TimeCritical: percent = 99; break; case ThreadPriority::Multimedia: percent = 100; break; default: throw std::invalid_argument("Attempted to assign an unrecognized thread priority"); } int prev_policy; pthread_getschedparam(handle, &prev_policy, &param); param.sched_priority = PTHREAD_MIN_PRIORITY + (percent*(PTHREAD_MAX_PRIORITY - PTHREAD_MIN_PRIORITY) + 50) / 100; pthread_setschedparam(handle, policy, &param); }
30.944954
145
0.752149
CaseyCarter
aa95867ef96c61515f5499d55034234deded6767
230
cpp
C++
3rdparty/build_opencv-4.5.2/modules/core/test/test_intrin128.avx512_skx.cpp
LordOfTheUnicorn/trdrop
6da4bf1528878e90cf14232dfb4adeec3458ee0f
[ "MIT" ]
null
null
null
3rdparty/build_opencv-4.5.2/modules/core/test/test_intrin128.avx512_skx.cpp
LordOfTheUnicorn/trdrop
6da4bf1528878e90cf14232dfb4adeec3458ee0f
[ "MIT" ]
7
2021-05-24T22:57:32.000Z
2021-08-23T05:32:30.000Z
3rdparty/build_opencv-4.5.2/modules/core/test/test_intrin128.ssse3.cpp
LordOfTheUnicorn/trdrop
6da4bf1528878e90cf14232dfb4adeec3458ee0f
[ "MIT" ]
null
null
null
#include "/Users/unicorn1343/Documents/GitHub/trdrop/3rdParty/opencv-4.5.2/modules/core/test/test_precomp.hpp" #include "/Users/unicorn1343/Documents/GitHub/trdrop/3rdParty/opencv-4.5.2/modules/core/test/test_intrin128.simd.hpp"
57.5
117
0.817391
LordOfTheUnicorn