blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
0b11dd97b4df8bf9d007ee52ab73916cee60bde4
0b60493522498390d25a8d6f701be80d8cae8538
/ProjektProbaSFML/ProjektProbaSFML/Standby.cpp
6de2abaef525c4d1f6d8098577b4614e2bff4cc6
[]
no_license
alekkul271/Programowanie2
1fa26aa942428b167372d7b385585afa8c773f89
174734743b97c8a2b9a46c8a588b8095b23d3066
refs/heads/master
2022-06-28T10:44:58.625051
2020-05-11T18:31:27
2020-05-11T18:31:27
262,615,273
0
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
#include "Standby.h" Standby::Standby(sf::Texture* texture, sf::Vector2u imageCount, float switch_time) { this->imageCount = imageCount; this->switch_time = switch_time; total_time = 0.0f; currentImage.x = 0; uvRect.width = texture->getSize().x / static_cast<float>(imageCount.x); uvRect.height = texture->getSize().y / static_cast<float>(imageCount.y); } Standby::~Standby() { } void Standby::Update(int row, float deltaTime, bool faceRight) { currentImage.y = row; total_time += deltaTime; if (total_time >= switch_time) { total_time -= switch_time; currentImage.x++; if (currentImage.x >= imageCount.x) { currentImage.x = 0; } } uvRect.top = currentImage.y * uvRect.height; if (faceRight) { uvRect.left = currentImage.x * uvRect.width; uvRect.width = abs(uvRect.width); } else { uvRect.left = (currentImage.x + 1) * abs(uvRect.width); uvRect.width = -abs(uvRect.width); } }
[ "alekkul271@polsl.pl" ]
alekkul271@polsl.pl
e2b7eb25d4c63e72d05fcf11d64a1dca32d6c8d1
be806ebbf0f1a7d05f1a24101ba957c450f2e902
/src/libmilkcat.cc
6d655c55e48c92cb582d8fa9074945b8af474c61
[ "MIT" ]
permissive
kasuganosora/MilkCat
2e97d271ed4cd1e57a4b38c6f2c36a6eb4b29ea4
e0d137ff830f2e2abd749a9106609b0d7307b337
refs/heads/master
2020-12-31T03:55:53.659000
2015-01-17T08:57:01
2015-01-17T08:57:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,271
cc
// // The MIT License (MIT) // // Copyright 2013-2014 The MilkCat Project Developers // // 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. // // libyaca.cc // libmilkcat.cc --- Created at 2013-09-03 // #include "include/milkcat.h" #include "libmilkcat.h" #include <stdio.h> #include <string.h> #include <string> #include <utility> #include <vector> #include "common/model_impl.h" #include "ml/crf_tagger.h" #include "segmenter/bigram_segmenter.h" #include "segmenter/mixed_segmenter.h" #include "segmenter/out_of_vocabulary_word_recognition.h" #include "segmenter/term_instance.h" #include "tagger/crf_part_of_speech_tagger.h" #include "tagger/hmm_part_of_speech_tagger.h" #include "tagger/part_of_speech_tag_instance.h" #include "parser/beam_arceager_dependency_parser.h" #include "parser/dependency_parser.h" #include "parser/tree_instance.h" #include "tokenizer/tokenizer.h" #include "tokenizer/token_instance.h" #include "utils/utils.h" namespace milkcat { // This enum represents the type or the algorithm of Parser. It could be // kDefault which indicates using the default algorithm for segmentation and // part-of-speech tagging. Meanwhile, it could also be // kTextTokenizer | kBigramSegmenter | kHmmTagger // which indicates using bigram segmenter for segmentation, using HMM model // for part-of-speech tagging. enum ParserType { // Tokenizer type kTextTokenizer = 0, // Segmenter type kMixedSegmenter = 0x00000000, kCrfSegmenter = 0x00000010, kUnigramSegmenter = 0x00000020, kBigramSegmenter = 0x00000030, // Part-of-speech tagger type kMixedTagger = 0x00000000, kHmmTagger = 0x00001000, kCrfTagger = 0x00002000, kNoTagger = 0x000ff000, // Depengency parser type kArcEagerParser = 0x00100000, kNoParser = 0x00000000, }; Tokenization *TokenizerFactory(int analyzer_type) { int tokenizer_type = analyzer_type & kTokenizerMask; switch (tokenizer_type) { case kTextTokenizer: return new Tokenization(); default: return NULL; } } Segmenter *SegmenterFactory(Model::Impl *factory, int analyzer_type, Status *status) { int segmenter_type = analyzer_type & kSegmenterMask; switch (segmenter_type) { case kBigramSegmenter: return BigramSegmenter::New(factory, true, status); case kUnigramSegmenter: return BigramSegmenter::New(factory, false, status); case kCrfSegmenter: return CRFSegmenter::New(factory, status); case kMixedSegmenter: return MixedSegmenter::New(factory, status); default: *status = Status::NotImplemented("Invalid segmenter type"); return NULL; } } PartOfSpeechTagger *PartOfSpeechTaggerFactory(Model::Impl *factory, int analyzer_type, Status *status) { const CRFModel *crf_pos_model = NULL; const HMMModel *hmm_pos_model = NULL; int tagger_type = analyzer_type & kPartOfSpeechTaggerMask; switch (tagger_type) { case kCrfTagger: if (status->ok()) crf_pos_model = factory->CRFPosModel(status); if (status->ok()) { return CRFPartOfSpeechTagger::New(crf_pos_model, NULL, status); } else { return NULL; } case kHmmTagger: if (status->ok()) { return HMMPartOfSpeechTagger::New(factory, status); } else { return NULL; } case kMixedTagger: if (status->ok()) crf_pos_model = factory->CRFPosModel(status); if (status->ok()) hmm_pos_model = factory->HMMPosModel(status); if (status->ok()) { return CRFPartOfSpeechTagger::New(crf_pos_model, hmm_pos_model, status); } else { return NULL; } case kNoTagger: return NULL; default: *status = Status::NotImplemented("Invalid Part-of-speech tagger type"); return NULL; } } DependencyParser *DependencyParserFactory(Model::Impl *factory, int parser_type, Status *status) { parser_type = kParserMask & parser_type; switch (parser_type) { case kArcEagerParser: if (status->ok()) { return BeamArceagerDependencyParser::New(factory, status); } else { return NULL; } case kNoParser: return NULL; default: *status = Status::NotImplemented("Invalid parser type"); return NULL; } } // The global state saves the current of model and analyzer. // If any errors occured, global_status != Status::OK() Status global_status; // ----------------------------- Parser::Iterator ----------------------------- Parser::Iterator::Impl::Impl(): parser_(NULL), tokenizer_(TokenizerFactory(kTextTokenizer)), token_instance_(new TokenInstance()), term_instance_(new TermInstance()), tree_instance_(new TreeInstance()), part_of_speech_tag_instance_(new PartOfSpeechTagInstance()), sentence_length_(0), current_position_(0), end_(false) { } Parser::Iterator::Impl::~Impl() { delete tokenizer_; tokenizer_ = NULL; delete token_instance_; token_instance_ = NULL; delete term_instance_; term_instance_ = NULL; delete part_of_speech_tag_instance_; part_of_speech_tag_instance_ = NULL; delete tree_instance_; tree_instance_ = NULL; parser_ = NULL; } void Parser::Iterator::Impl::Scan(const char *text) { tokenizer_->Scan(text); sentence_length_ = 0; current_position_ = 0; end_ = false; } void Parser::Iterator::Impl::Next() { if (End()) return ; current_position_++; if (current_position_ > sentence_length_ - 1) { // If reached the end of current sentence if (tokenizer_->GetSentence(token_instance_) == false) { end_ = true; } else { parser_->segmenter()->Segment(term_instance_, token_instance_); // If the parser have part-of-speech tagger, tag the term_instance if (parser_->part_of_speech_tagger()) { parser_->part_of_speech_tagger()->Tag(part_of_speech_tag_instance_, term_instance_); } // Dependency Parsing if (parser_->dependency_parser()) { parser_->dependency_parser()->Parse(tree_instance_, term_instance_, part_of_speech_tag_instance_); } sentence_length_ = term_instance_->size(); current_position_ = 0; is_begin_of_sentence_ = true; } } else { is_begin_of_sentence_ = false; } } Parser::Iterator::Iterator() { impl_ = new Parser::Iterator::Impl(); } Parser::Iterator::~Iterator() { delete impl_; impl_ = NULL; } bool Parser::Iterator::End() { return impl_->End(); } void Parser::Iterator::Next() { impl_->Next(); } const char *Parser::Iterator::word() const { return impl_->word(); } const char *Parser::Iterator::part_of_speech_tag() const { return impl_->part_of_speech_tag(); } int Parser::Iterator::type() const { return impl_->type(); } int Parser::Iterator::head_node() const { return impl_->head_node(); } const char *Parser::Iterator::dependency_type() const { return impl_->dependency_type(); } bool Parser::Iterator::is_begin_of_sentence() const { return impl_->is_begin_of_sentence(); } // ----------------------------- Parser -------------------------------------- Parser::Impl::Impl(): segmenter_(NULL), part_of_speech_tagger_(NULL), dependency_parser_(NULL), model_impl_(NULL), own_model_(false), iterator_alloced_(0) { } Parser::Impl::~Impl() { delete segmenter_; segmenter_ = NULL; delete part_of_speech_tagger_; part_of_speech_tagger_ = NULL; delete dependency_parser_; dependency_parser_ = NULL; if (own_model_) delete model_impl_; model_impl_ = NULL; } Parser::Impl *Parser::Impl::New(const Options &options, Model *model) { global_status = Status::OK(); Impl *self = new Parser::Impl(); int type = options.TypeValue(); Model::Impl *model_impl = model? model->impl(): NULL; if (model_impl == NULL) { self->model_impl_ = new Model::Impl(MODEL_PATH); self->own_model_ = true; } else { self->model_impl_ = model_impl; self->own_model_ = false; } if (global_status.ok()) self->segmenter_ = SegmenterFactory( self->model_impl_, type, &global_status); if (global_status.ok()) self->part_of_speech_tagger_ = PartOfSpeechTaggerFactory( self->model_impl_, type, &global_status); if (global_status.ok()) self->dependency_parser_ = DependencyParserFactory( self->model_impl_, type, &global_status); if (!global_status.ok()) { delete self; return NULL; } else { return self; } } void Parser::Impl::Parse(const char *text, Parser::Iterator *iterator) { iterator->impl()->set_parser(this); iterator->impl()->Scan(text); iterator->Next(); } Parser::Parser(): impl_(NULL) { } Parser::~Parser() { delete impl_; impl_ = NULL; } Parser *Parser::New() { return New(Options(), NULL); } Parser *Parser::New(const Options &options) { return New(options, NULL); } Parser *Parser::New(const Options &options, Model *model) { Parser *self = new Parser(); self->impl_ = Impl::New(options, model); if (self->impl_) { return self; } else { delete self; return NULL; } } void Parser::Parse(const char *text, Parser::Iterator *iterator) { return impl_->Parse(text, iterator); } Parser::Options::Options(): segmenter_type_(kMixedSegmenter), tagger_type_(kMixedTagger), parser_type_(kNoParser) { } void Parser::Options::UseMixedSegmenter() { segmenter_type_ = kMixedSegmenter; } void Parser::Options::UseCrfSegmenter() { segmenter_type_ = kCrfSegmenter; } void Parser::Options::UseUnigramSegmenter() { segmenter_type_ = kUnigramSegmenter; } void Parser::Options::UseBigramSegmenter() { segmenter_type_ = kBigramSegmenter; } void Parser::Options::UseMixedPOSTagger() { tagger_type_ = kMixedTagger; } void Parser::Options::UseHmmPOSTagger() { tagger_type_ = kHmmTagger; } void Parser::Options::UseCrfPOSTagger() { tagger_type_ = kCrfTagger; } void Parser::Options::NoPOSTagger() { tagger_type_ = kNoTagger; } void Parser::Options::UseArcEagerDependencyParser() { if (tagger_type_ == kNoTagger) tagger_type_ = kMixedTagger; parser_type_ = kArcEagerParser; } void Parser::Options::NoDependencyParser() { parser_type_ = kNoParser; } int Parser::Options::TypeValue() const { return segmenter_type_ | tagger_type_ | parser_type_; } // ------------------------------- Model ------------------------------------- Model::Model(): impl_(NULL) { } Model::~Model() { delete impl_; impl_ = NULL; } Model *Model::New(const char *model_dir) { Model *self = new Model(); self->impl_ = new Model::Impl(model_dir? model_dir: MODEL_PATH); return self; } bool Model::SetUserDictionary(const char *userdict_path) { return impl_->SetUserDictionary(userdict_path); } const char *LastError() { return global_status.what(); } } // namespace milkcat
[ "ling032x@gmail.com" ]
ling032x@gmail.com
298575b1069692f56cc6281240fe4ceeb0a090dd
ba916d93dfb8074241b0ea1f39997cb028509240
/cpp/sorting.cpp
a8664377c0dbaa46b0d0a6aacab753a39917391b
[]
no_license
satojkovic/algorithms
ecc1589898c61d2eef562093d3d2a9a2d127faa8
f666b215bc9bbdab2d2257c83ff1ee2c31c6ff8e
refs/heads/master
2023-09-06T08:17:08.712555
2023-08-31T14:19:01
2023-08-31T14:19:01
169,414,662
2
3
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include <bits/stdc++.h> typedef long long ll; using namespace std; void print(const vector<int> &data) { for (int i = 0; i < data.size(); ++i) { cout << data[i]; if (i == data.size() - 1) cout << endl; else cout << ","; } } void partition(vector<int> &data, int l, int r) { int m = l; for (int i = l + 1; i <= r; ++i) { if (data[i] < data[l]) swap(data[i], data[++m]); } swap(data[l], data[m]); } int main() { vector<int> data{55, 41, 59, 26, 53, 58, 97, 93}; partition(data, 0, data.size() - 1); print(data); }
[ "satojkovic@gmail.com" ]
satojkovic@gmail.com
d2b1482e37b794a57e30898177f0a745146e3029
c26dc7928b1facac2c0912f6532076d35c19e835
/devel/include/ros_arduino_msgs/Analog.h
b74669547528ba3c083bac79d4d00106d139c939
[]
no_license
mattedminster/inmoov_ros
33c29a2ea711f61f15ad5e2c53dd9db65ef6437f
e063a90b61418c3612b8df7876a633bc0dc2c428
refs/heads/master
2021-01-23T02:39:36.090746
2017-08-09T02:56:42
2017-08-09T02:56:42
85,995,826
0
0
null
2017-03-23T20:45:32
2017-03-23T20:45:32
null
UTF-8
C++
false
false
5,960
h
// Generated by gencpp from file ros_arduino_msgs/Analog.msg // DO NOT EDIT! #ifndef ROS_ARDUINO_MSGS_MESSAGE_ANALOG_H #define ROS_ARDUINO_MSGS_MESSAGE_ANALOG_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace ros_arduino_msgs { template <class ContainerAllocator> struct Analog_ { typedef Analog_<ContainerAllocator> Type; Analog_() : header() , value(0) { } Analog_(const ContainerAllocator& _alloc) : header(_alloc) , value(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef uint16_t _value_type; _value_type value; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> ConstPtr; }; // struct Analog_ typedef ::ros_arduino_msgs::Analog_<std::allocator<void> > Analog; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog > AnalogPtr; typedef boost::shared_ptr< ::ros_arduino_msgs::Analog const> AnalogConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::Analog_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ros_arduino_msgs::Analog_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace ros_arduino_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/robot/inmoov_ros/src/ros_arduino_bridge/ros_arduino_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::Analog_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::Analog_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::Analog_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_arduino_msgs::Analog_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "5760aa9c40c2caa52a04d293094e679d"; } static const char* value(const ::ros_arduino_msgs::Analog_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x5760aa9c40c2caa5ULL; static const uint64_t static_value2 = 0x2a04d293094e679dULL; }; template<class ContainerAllocator> struct DataType< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "ros_arduino_msgs/Analog"; } static const char* value(const ::ros_arduino_msgs::Analog_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "# Reading from a single analog IO pin.\n\ Header header\n\ uint16 value\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ "; } static const char* value(const ::ros_arduino_msgs::Analog_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.value); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Analog_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ros_arduino_msgs::Analog_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ros_arduino_msgs::Analog_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "value: "; Printer<uint16_t>::stream(s, indent + " ", v.value); } }; } // namespace message_operations } // namespace ros #endif // ROS_ARDUINO_MSGS_MESSAGE_ANALOG_H
[ "mattedminster@gmail.com" ]
mattedminster@gmail.com
c7e4f7f2b84bad1bf29e4c9bc878ecf73944d3e5
0203c18e12531e00ef5154776cb32b731e6688d0
/PBINFO/284-interclsare3.cpp
b27d8ebe7b6b90d1cfa8a46b3161822dc6b56ec7
[]
no_license
KiraBeleaua/Solved-Problems
a656566e4592f206365a11cff670139baa27c80a
99a2343883faa9e0d61d8a92b8e82f9a0d89c2c2
refs/heads/main
2023-06-20T23:10:18.496603
2021-07-15T22:50:56
2021-07-15T22:50:56
359,094,167
0
0
null
null
null
null
UTF-8
C++
false
false
4,598
cpp
#include <iostream> #include <vector> #include <math.h> #include <algorithm> #include <iomanip> #include <array> #include <fstream> using namespace std; void printVector(vector<int64_t> v) { for (auto& el : v) { cout << el << " "; } cout << "\n"; } int maximAdi(vector<int64_t> v) { int64_t maxim = v[0], indice = 0; for (int i = 0; i < v.size() - 1; i++) { if (v[i] < v[i + 1] && maxim < v[i + 1]) { maxim = v[i + 1]; indice = i + 1; } else if (v[i] > v[i + 1] && maxim < v[i]) { maxim = v[i]; indice = i; } } return maxim; } int maxim(vector<int64_t> v) { int64_t m = v[0]; for (auto el : v) { m = max(el, m); } return m; } vector<int64_t> generateRandomVector(int64_t n, int64_t left, int64_t right) { srand(time(NULL)); int64_t space = right - left; vector <int64_t> v; for (int i = 0; i < n; i++) { int64_t el = rand() % space + left; v.push_back(el); } return v; } int64_t maxVector(vector<int64_t> a) { int64_t m = a[0]; for (int i = 1; i < a.size(); i++) { m = max(a[i], m); } return m; } int64_t maximIndiceVector(vector<int64_t> a) { int64_t m = a[0]; int indice = 0; for (int i = 1; i < a.size(); i++) { if (a[i] > m) { m = a[i]; indice = i; } } return indice; } int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int strlen(char v[]) { int size = 0; for (int i = 0; true; i++) { if (v[i] == '\0') { size = i; break; } } return size; } void strcpy(char v[], char w[]) { for (int i = 0; true; i++) { if (w[i] == '\0') { break; } v[i] = w[i]; } return; } int strcmp(char v[], char w[]) { int result = 0; for (int i = 0; true; i++) { if (v[i] > w[i]) { result++; break; } else if (w[i] > v[i]) { result--; break; } if (v[i] == '\0' || w[i] == '\0') { break; } } return result; } //refa ,de gasit tot w in v; return partea de unde incepe; int strstr(char v[], char w[]) { int indice = 0; for (int i = 0; strlen(v); i++) { for (int j = 0; true; j++) { if (w[j] == '\0') { break; } if (w[j] == v[i]) { indice = i; } } } return indice; } int strchr(char v[], char x) { int indice = 0; for (int i = 0; strlen(v); i++) { if (v[i] == x) { indice = i; break; } } return indice; } void strlower(char v[]) { for (int i = 0; strlen(v); i++) { if (v[i] == '\0') { break; } if (v[i] <= 'Z' && v[i] >= 'A') { v[i] += 'a' - 'A'; } } return; } void strupper(char v[]) { for (int i = 0; i < strlen(v); i++) { if (v[i] >= 'z' && v[i] <= 'a') { v[i] -= 'a' - 'A'; } } return; } int findstr(char v[], char w[]) { int64_t indice = -1, k = 0, lenv = 0, lenw = 0; lenv = strlen(v); lenw = strlen(w); for (int i = 0; i < lenv; i++) { k = 0; for (int j = 0; j < lenw; j++) { if (v[i + j] != w[j]) break; k++; } if (k == lenw) { indice = i; break; } } return indice; } int main() { ifstream fin("interclasare3.in"); ofstream fout("interclasare3.out"); int64_t n, m, i = 0, j = 0; vector <int64_t> v, w, e; fin >> n; fin >> m; v.resize(n); w.resize(m); for (auto& el : v) { fin >> el; } for (auto& el : w) { fin >> el; } j = w.size() - 1; while (i < v.size() && j >= 0) { if (v[i] >= w[j]) { if (w[j] % 2 == 0) { e.push_back(w[j]); } j--; } else if (v[i] < w[j]) { if (v[i] % 2 == 0) { e.push_back(v[i]); } i++; } } for (; i < v.size(); i++) { if (v[i] % 2 == 0) { e.push_back(v[i]); } } for (; j >= 0 ; j--) { if (w[j] % 2 == 0) { e.push_back(w[j]); } } for (int i = 0; i < e.size(); i++) { fout << e[i] << " "; if (i % 20 == 19 && i != 0) { fout << "\n"; } } }
[ "necula.adrian2009@gmail.com" ]
necula.adrian2009@gmail.com
5d2eda42570892f426fb8e1be0d9095a6fb197c3
bcd122dc1ec9131f148178950a1a9b6e0b61c808
/src/libinterpol/include/interpol/euclidean/bezier.hpp
8b1056d8138ff12436dc06e0ad4be5e6199e327c
[ "MIT" ]
permissive
QubingHuo-source/interpolation-methods
88d73cef91ad4ad4b2a8455a79d0bffc9817b535
094cbabbd0c25743d088a623f5913149c6b8a2ab
refs/heads/master
2023-04-30T19:55:29.781785
2020-02-21T13:14:30
2020-02-21T13:16:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,989
hpp
/** * This file is part of https://github.com/adrelino/interpolation-methods * * Copyright (c) 2018 Adrian Haarbach <mail@adrian-haarbach.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #ifndef INTERPOL_BEZIER_HPP #define INTERPOL_BEZIER_HPP #include <spline.h> //tk::spline #include <interpol/utils/vector_a.hpp> namespace interpol { namespace bezier { template<unsigned int Dim> class Spline{ public: Spline() = default; Spline(vector_a<Eigen::Matrix<double,Dim,1>>& pts, std::vector<double>& t_vec, bool firstDerivBoundary=false, Eigen::Matrix<double,Dim,1> leftBoundary=Eigen::Matrix<double,Dim,1>::Zero(), Eigen::Matrix<double,Dim,1> rightBoundary=Eigen::Matrix<double,Dim,1>::Zero()){ n = pts.size(); assertCustom(n >= 2); assertCustom(n == t_vec.size()); std::vector<double> x_vecs[Dim]; for(size_t i=0; i<n; i++){ /* double tGlobal = i*1.0/(n-1); t_vec.push_back(tGlobal);*/ const Eigen::Matrix<double,Dim,1>& pos = pts[i]; for(unsigned int j=0; j<Dim; j++){ x_vecs[j].push_back(pos(j)); } } for(unsigned int j=0; j<Dim; j++){ if(firstDerivBoundary){ splines[j].set_boundary(tk::spline::bd_type::first_deriv,leftBoundary(j),tk::spline::bd_type::first_deriv,rightBoundary(j)); }else{ splines[j].set_boundary(tk::spline::bd_type::second_deriv,leftBoundary(j),tk::spline::bd_type::second_deriv,rightBoundary(j)); } splines[j].set_points(t_vec,x_vecs[j]); /* if(j==0){ splines[j].m_a={-4,-4,-4}; splines[j].m_b={6,6,6}; splines[j].m_c={0,0,0}; splines[j].m_y={-1,1,3}; }else if(j==1){ splines[j].m_a={0,0,0}; splines[j].m_b={-6,-6,-6}; splines[j].m_c={6,6,6}; splines[j].m_y={-1,-1,-1}; }*/ } } Eigen::Matrix<double,Dim,1> eval(double tGlobal) const{ Eigen::Matrix<double,Dim,1> p; for(unsigned int j=0; j<Dim; j++){ p(j)=splines[j](tGlobal); } return p; } vector_a<Eigen::Matrix<double,Dim,1>> getBasisPoints(){ vector_a<Eigen::Matrix<double,Dim,1>> pts; for(unsigned int i=0; i<n-1; i++) { for (int k = 0; k <= 3; k++) { Eigen::Matrix<double, Dim, 1> p; for (unsigned int j = 0; j < Dim; j++) { p(j) = splines[j].control_polygon(i, k); } pts.push_back(p); } } return pts; } private: // interpolated positions tk::spline splines[Dim]; size_t n; }; typedef Spline<3> Spline3d; typedef Spline<4> Spline4d; } // ns bezier } // ns interpol #endif // INTERPOL_BEZIER_HPP
[ "mail@adrian-haarbach.de" ]
mail@adrian-haarbach.de
db9ac4af91f2cf8669b9470099df81d264c7f0cb
2588ad590b4df910fa5477ee84101b56dba69144
/MyTree/MyTree/TreeOperation.cpp
8124f26032e718494a2647cf3d40d93cc7c2a4e6
[]
no_license
Mr-Jason-Sam/Algorithms
e6829cf55addb7a01c425f8f8c732dce1082901c
6f015cc63407cda1aae310aefd3b705fcc00a361
refs/heads/master
2021-01-19T10:53:22.400040
2019-05-23T17:06:42
2019-05-23T17:06:42
87,910,106
0
1
null
null
null
null
UTF-8
C++
false
false
168
cpp
// // TreeOperation.cpp // MyTree // // Created by Jason_Sam on 2017/4/6. // Copyright © 2017年 Jason_Sam. All rights reserved. // #include "TreeOperation.hpp"
[ "Mr.Jason_Sam@iCloud.com" ]
Mr.Jason_Sam@iCloud.com
6726f97200d0787bfaad09d7b9fb781b3e7d7d7b
65025edce8120ec0c601bd5e6485553697c5c132
/Engine/addons/myguiengine/src/MyGUI_SkinItem.cpp
2fd27e264a854438134b454b1cf07cba6968c38b
[ "MIT" ]
permissive
stonejiang/genesis-3d
babfc99cfc9085527dff35c7c8662d931fbb1780
df5741e7003ba8e21d21557d42f637cfe0f6133c
refs/heads/master
2020-12-25T18:22:32.752912
2013-12-13T07:45:17
2013-12-13T07:45:17
15,157,071
4
4
null
null
null
null
UTF-8
C++
false
false
4,799
cpp
/*! @file @author Albert Semenov @date 06/2008 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_SkinItem.h" #include "MyGUI_FactoryManager.h" #include "MyGUI_Widget.h" #include "MyGUI_RenderManager.h" namespace MyGUI { SkinItem::SkinItem() : mText(nullptr), mMainSkin(nullptr), mTexture(nullptr), mSubSkinsVisible(true) { } void SkinItem::_setSkinItemAlign(const IntSize& _size) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->_setAlign(_size); } void SkinItem::_setSkinItemVisible(bool _value) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->setVisible(_value); } void SkinItem::_setSkinItemColour(const Colour& _value) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) { ISubWidgetRect* rect = (*skin)->castType<ISubWidgetRect>(false); if (rect) rect->_setColour(_value); } } void SkinItem::_setSkinItemAlpha(float _value) { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->setAlpha(_value); } void SkinItem::_correctSkinItemView() { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->_correctView(); } void SkinItem::_updateSkinItemView() { for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) (*skin)->_updateView(); } bool SkinItem::_setSkinItemState(const std::string& _state) { MapWidgetStateInfo::const_iterator iter = mStateInfo.find(_state); if (iter == mStateInfo.end()) return false; size_t index = 0; for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin, ++index) { IStateInfo* data = (*iter).second[index]; if (data != nullptr) (*skin)->setStateData(data); } return true; } void SkinItem::_createSkinItem(ResourceSkin* _info) { mStateInfo = _info->getStateInfo(); // все что с текстурой можно тоже перенести в скин айтем и setRenderItemTexture mTextureName = _info->getTextureName(); mTexture = RenderManager::getInstance().getTexture(mTextureName); setRenderItemTexture(mTexture); // загружаем кирпичики виджета FactoryManager& factory = FactoryManager::getInstance(); for (VectorSubWidgetInfo::const_iterator iter = _info->getBasisInfo().begin(); iter != _info->getBasisInfo().end(); ++iter) { IObject* object = factory.createObject("BasisSkin", (*iter).type); if (object == nullptr) continue; ISubWidget* sub = object->castType<ISubWidget>(); sub->_setCroppedParent(static_cast<Widget*>(this)); sub->setCoord((*iter).coord); sub->setAlign((*iter).align); mSubSkinChild.push_back(sub); addRenderItem(sub); // ищем дефолтные сабвиджеты if (mMainSkin == nullptr) mMainSkin = sub->castType<ISubWidgetRect>(false); if (mText == nullptr) mText = sub->castType<ISubWidgetText>(false); } _setSkinItemState("normal"); } void SkinItem::_deleteSkinItem() { mTexture = nullptr; mStateInfo.clear(); removeAllRenderItems(); // удаляем все сабскины mMainSkin = nullptr; mText = nullptr; for (VectorSubWidget::iterator skin = mSubSkinChild.begin(); skin != mSubSkinChild.end(); ++skin) delete (*skin); mSubSkinChild.clear(); } void SkinItem::_setTextureName(const std::string& _texture) { mTextureName = _texture; mTexture = RenderManager::getInstance().getTexture(mTextureName); setRenderItemTexture(mTexture); } const std::string& SkinItem::_getTextureName() const { return mTextureName; } void SkinItem::_setSubSkinVisible(bool _visible) { if (mSubSkinsVisible == _visible) return; mSubSkinsVisible = _visible; _updateSkinItemView(); } ISubWidgetText* SkinItem::getSubWidgetText() { return mText; } ISubWidgetRect* SkinItem::getSubWidgetMain() { return mMainSkin; } } // namespace MyGUI
[ "jiangtao@tao-studio.net" ]
jiangtao@tao-studio.net
d9b6bd6e6c55323933ce5c8d07c2f39a466791bc
0f62b851257647d01658fdef5714586dc3c56a27
/PKU_20120224_1789.cpp
69c55ef547862050247339d39bc415bd148454eb
[]
no_license
cheeseonhead/PKUProblems
5de3a5d6e8f23d87873ce382d56b25a593460a11
65b0a3a20b551166d9e23644b90e06ca847cc541
refs/heads/master
2021-01-15T23:40:09.666781
2015-03-26T00:16:40
2015-03-26T00:16:40
32,898,397
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
cpp
/* Judge: PKU PROG: 1789 */ #include <cstdio> #include <cstring> #include <algorithm> #define MAXN 2147483647 using namespace std; int N,ans,minid,least[2001]={0},mind; char s[2001][8]; int dis(int x, int y) { int dif=0; for(int i=0;i<6;i++) if(s[x][i]!=s[y][i])dif++; return dif; } int main() { #ifndef ONLINE_JUDGE freopen("PKU_20120224_1789.in","r",stdin); freopen("PKU_20120224_1789.out","w",stdout); #endif while(~scanf("%d\n",&N)) { if(!N)return 0; ans=0; for(int i=0;i<N;i++) gets(s[i]); for(int i=1;i<N;i++) least[i]=dis(0,i); for(int n=0;n<N-1;n++) { mind = MAXN; for(int i=0;i<N;i++) if(least[i]<mind && least[i]>0) { mind = least[i]; minid = i; } ans+=mind; least[minid] = -1; for(int i=0;i<N;i++) if(least[i]>0) if(dis(i,minid)<least[i]) least[i]=dis(i,minid); } printf("The highest possible quality is 1/%d.\n",ans); } return 0; }
[ "cheeseonhead@gmail.com" ]
cheeseonhead@gmail.com
83f2bbd32912516c93250f2cef037232df122a28
c78023bb0d524f172e54ded23fa595861346531d
/MaterialLib/MPL/Properties/RelativePermeability/RelPermUdell.cpp
5e70d82b34a6ac16ed180c37f4b7a67db505cd57
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
TH2M-NGH-group-zju/ogs
2f0d7fe050d9d65c27bd37b08cd32bb247ba292f
074c5129680e87516477708b081afe79facabe87
refs/heads/master
2023-02-06T16:56:28.454514
2020-12-24T13:13:01
2020-12-24T13:13:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,391
cpp
/** * \file * \author Norbert Grunwald * \date 01.12.2020 * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "RelPermUdell.h" #include <algorithm> #include <cmath> #include "MaterialLib/MPL/Medium.h" namespace MaterialPropertyLib { RelPermUdell::RelPermUdell(std::string name, const double residual_liquid_saturation, const double residual_gas_saturation, const double min_relative_permeability_liquid, const double min_relative_permeability_gas) : residual_liquid_saturation_(residual_liquid_saturation), residual_gas_saturation_(residual_gas_saturation), min_relative_permeability_liquid_(min_relative_permeability_liquid), min_relative_permeability_gas_(min_relative_permeability_gas) { name_ = std::move(name); } PropertyDataType RelPermUdell::value( VariableArray const& variable_array, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { const double s_L = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); if (std::isnan(s_L)) { OGS_FATAL("Liquid saturation not set in RelPermUdell::value()."); } auto const s_L_res = residual_liquid_saturation_; auto const s_L_max = 1. - residual_gas_saturation_; auto const k_rel_min_LR = min_relative_permeability_liquid_; auto const k_rel_min_GR = min_relative_permeability_gas_; auto const s = (s_L - s_L_res) / (s_L_max - s_L_res); if (s >= 1.0) { // fully saturated medium return Eigen::Vector2d{1.0, k_rel_min_GR}; } if (s <= 0.0) { // dry medium return Eigen::Vector2d{k_rel_min_LR, 1.0}; } auto const k_rel_LR = s * s * s; auto const k_rel_GR = (1. - s) * (1. - s) * (1. - s); return Eigen::Vector2d{std::max(k_rel_LR, k_rel_min_LR), std::max(k_rel_GR, k_rel_min_GR)}; } PropertyDataType RelPermUdell::dValue( VariableArray const& variable_array, Variable const primary_variable, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { (void)primary_variable; assert((primary_variable == Variable::liquid_saturation) && "RelPermUdell::dValue is implemented for " " derivatives with respect to liquid saturation only."); const double s_L = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); auto const s_L_res = residual_liquid_saturation_; auto const s_L_max = 1. - residual_gas_saturation_; auto const s = (s_L - s_L_res) / (s_L_max - s_L_res); if ((s < 0.) || (s > 1.)) { return Eigen::Vector2d{0., 0.}; } auto const d_se_d_sL = 1. / (s_L_max - s_L_res); auto const dk_rel_LRdse = 3. * s * s; auto const dk_rel_LRdsL = dk_rel_LRdse * d_se_d_sL; auto const dk_rel_GRdse = -3. * (1. - s) * (1. - s); auto const dk_rel_GRdsL = dk_rel_GRdse * d_se_d_sL; return Eigen::Vector2d{dk_rel_LRdsL, dk_rel_GRdsL}; } } // namespace MaterialPropertyLib
[ "Norbert.Grunwald@ufz.de" ]
Norbert.Grunwald@ufz.de
ed6c0ccee6dd44e5b7e6318621076a29b5731f7b
e3d7d6ddd33d0e0886199af66a281b83b4903d91
/C++02096.cpp
ec1978bfc5a5182bd69b6ca2066bc33b5de16bdb
[]
no_license
flydog98/CppBaekjoon
6c1805222c6669b0793d23cf64902677628c0ddb
6b218c371d39a2ccf1f2922b6fc4275c91c2bafb
refs/heads/master
2020-09-05T13:13:48.343902
2020-08-26T14:25:18
2020-08-26T14:25:18
220,116,434
0
0
null
null
null
null
UHC
C++
false
false
1,332
cpp
// 2096번 내려가기 #include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void) { int amount = 0; vector<vector<int>> map; int higha = 0, highb = 0, highc = 0; int lowa = 0, lowb = 0, lowc = 0; int new_higha = 0, new_highb = 0, new_highc = 0; int new_lowa = 0, new_lowb = 0, new_lowc = 0; ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> amount; for (int i = 0; i < 3; i++) { vector<int> temp; map.push_back(temp); } for (int i = 0; i < amount; i++) { for (int j = 0; j < 3; j++) { int temp; cin >> temp; map[j].push_back(temp); } } higha = map[0][0]; highb = map[1][0]; highc = map[2][0]; lowa = map[0][0]; lowb = map[1][0]; lowc = map[2][0]; for (int i = 1; i < amount; i++) { new_higha = map[0][i] + max(higha, highb); new_highb = map[1][i] + max(highc, max(higha, highb)); new_highc = map[2][i] + max(highc, highb); higha = new_higha; highb = new_highb; highc = new_highc; new_lowa = map[0][i] + min(lowa, lowb); new_lowb = map[1][i] + min(lowc, min(lowa, lowb)); new_lowc = map[2][i] + min(lowc, lowb); lowa = new_lowa; lowb = new_lowb; lowc = new_lowc; } int ans1 = max(max(higha, highb), highc); int ans2 = min(min(lowa, lowb), lowc); cout << ans1 << ' ' << ans2 << '\n'; return 0; }
[ "pyjpyj0825@gmail.com" ]
pyjpyj0825@gmail.com
93900d034516b9093ad1129fc63919ce288df7f6
e9a8f00bce09954668fb3f84382bc29397c78965
/src/rpcprotocol.cpp
5ede4ac80aa5320d4926d2f51d7a209dc87fe983
[ "MIT" ]
permissive
SkullCash/SkullCash
4b7dec25759d9012abfae0f678bcaed982a2d49f
7d8d87b4a6a24e9768d667b45e31d51e5cea1cd1
refs/heads/master
2020-03-23T04:51:38.559112
2018-07-16T08:30:12
2018-07-16T08:30:12
141,109,595
0
0
null
null
null
null
UTF-8
C++
false
false
9,661
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcprotocol.h" #include "util.h" #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include "json/json_spirit_writer_template.h" #include <fstream> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: skullcash-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } static string rfc1123Time() { return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime()); } string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: skullcash-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time(), FormatFullVersion()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %u\r\n" "Content-Type: application/json\r\n" "Server: skullcash-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion(), strMsg); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } // // JSON-RPC protocol. SkullCash speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } /** Username used when cookie authentication is in use (arbitrary, only for * recognizability in debugging/logging purposes) */ static const std::string COOKIEAUTH_USER = "__cookie__"; /** Default name for auth cookie file */ static const std::string COOKIEAUTH_FILE = "cookie"; boost::filesystem::path GetAuthCookieFile() { boost::filesystem::path path(GetArg("-rpccookiefile", COOKIEAUTH_FILE)); if (!path.is_complete()) path = GetDataDir() / path; return path; } bool GenerateAuthCookie(std::string *cookie_out) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); std::string cookie = COOKIEAUTH_USER + ":" + EncodeBase64(&rand_pwd[0],32); /* these are set to 077 in init.cpp unless overridden with -sysperms. */ std::ofstream file; boost::filesystem::path filepath = GetAuthCookieFile(); file.open(filepath.string().c_str()); if (!file.is_open()) { LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath.string()); return false; } file << cookie; file.close(); LogPrintf("Generated RPC authentication cookie %s\n", filepath.string()); if (cookie_out) *cookie_out = cookie; return true; } bool GetAuthCookie(std::string *cookie_out) { std::ifstream file; std::string cookie; boost::filesystem::path filepath = GetAuthCookieFile(); file.open(filepath.string().c_str()); if (!file.is_open()) return false; std::getline(file, cookie); file.close(); if (cookie_out) *cookie_out = cookie; return true; } void DeleteAuthCookie() { try { boost::filesystem::remove(GetAuthCookieFile()); } catch (const boost::filesystem::filesystem_error& e) { LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, e.what()); } }
[ "skullcash@users.noreply.github.com" ]
skullcash@users.noreply.github.com
3eb519c289b12e3daccc44701418266ce6e47721
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s11/CWE122_Heap_Based_Buffer_Overflow__placement_new_64b.cpp
67462a2cc5472ce5a9bbb7a199b4da8bea4c6cb3
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,879
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__placement_new_64b.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__placement_new.label.xml Template File: sources-sinks-64b.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize data to a small buffer * GoodSource: Initialize data to a buffer large enough to hold a TwoIntsClass * Sinks: * GoodSink: Allocate a new class using placement new and a buffer that is large enough to hold the class * BadSink : Allocate a new class using placement new and a buffer that is too small * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE122_Heap_Based_Buffer_Overflow__placement_new_64 { #ifndef OMITBAD void badSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { /* The Visual C++ compiler generates a warning if you initialize the class with (). * This will cause the compile to default-initialize the object. * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx */ /* POTENTIAL FLAW: data may not be large enough to hold a TwoIntsClass */ TwoIntsClass * classTwo = new(data) TwoIntsClass; /* Initialize and make use of the class */ classTwo->intOne = 5; classTwo->intTwo = 10; /* POTENTIAL FLAW: If sizeof(data) < sizeof(TwoIntsClass) then this line will be a buffer overflow */ printIntLine(classTwo->intOne); /* skip printing classTwo->intTwo since that could be a buffer overread */ free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { /* The Visual C++ compiler generates a warning if you initialize the class with (). * This will cause the compile to default-initialize the object. * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx */ /* POTENTIAL FLAW: data may not be large enough to hold a TwoIntsClass */ TwoIntsClass * classTwo = new(data) TwoIntsClass; /* Initialize and make use of the class */ classTwo->intOne = 5; classTwo->intTwo = 10; /* POTENTIAL FLAW: If sizeof(data) < sizeof(TwoIntsClass) then this line will be a buffer overflow */ printIntLine(classTwo->intOne); /* skip printing classTwo->intTwo since that could be a buffer overread */ free(data); } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { /* The Visual C++ compiler generates a warning if you initialize the class with (). * This will cause the compile to default-initialize the object. * See http://msdn.microsoft.com/en-us/library/wewb47ee%28v=VS.100%29.aspx */ /* FIX: data will at least be the sizeof(OneIntClass) */ OneIntClass * classOne = new(data) OneIntClass; /* Initialize and make use of the class */ classOne->intOne = 5; printIntLine(classOne->intOne); free(data); } } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
0ef2802fa0956c6d4510768793bd8d3ebbc7eb8e
5a1b773669c9a340b68065b76b0149c511d511ef
/Practicas/2º Cuatrimestre/8-Evaluacion/main.cpp
558f15db02310001adfbb6c79d602909ed116864
[]
no_license
ivangulyk/EDA
5ace42f07ad00423754e4b9a06d6cdf029964ee8
673fcf06283fb31e8d06073a7bbb3ad6ee3b4045
refs/heads/master
2021-09-15T09:14:45.472945
2018-05-29T16:03:26
2018-05-29T16:03:26
112,352,885
1
0
null
null
null
null
UTF-8
C++
false
false
2,489
cpp
#include "diccionario.h" #include "lista.h" #include <iostream> #include <string> using namespace std; // Clase Puntuacion. Sirve para representar la puntuacion final (nota) // obtenida por un alumno. class Puntuacion { public: string alumno; int nota; Puntuacion(const string& nombre, int puntuacion): alumno(nombre), nota(puntuacion) {} }; void sumaBien(const Lista<string>& bien,Diccionario<string,int> &d){ Lista<string>:: ConstIterator i = bien.cbegin(); Lista<string>:: ConstIterator f = bien.cend(); while(i != f){ if(!d.contiene(i.elem())) d.inserta(i.elem(),1); else d.inserta(i.elem(),d.valorPara(i.elem())+1); i.next(); } } void restaMal(const Lista<string>& mal,Diccionario<string,int> &d){ Lista<string>:: ConstIterator i = mal.cbegin(); Lista<string>:: ConstIterator f = mal.cend(); while(i != f){ if(!d.contiene(i.elem())) d.inserta(i.elem(),-1); else d.inserta(i.elem(),d.valorPara(i.elem())-1); i.next(); } } void generaListado(const Diccionario<string,int> &d, Lista<Puntuacion>& listado){ Diccionario<string,int>::ConstIterator i = d.cbegin(); Diccionario<string,int>::ConstIterator f = d.cend(); while (i != f){ Puntuacion notaFinal = Puntuacion(i.clave(),i.valor()); if(notaFinal.nota != 0) listado.pon_final(notaFinal); i.next(); } } void califica(const Lista<string>& bien, const Lista<string>& mal, Lista<Puntuacion>& listado) { // A IMPLEMENTAR Diccionario<string,int> resultados; sumaBien(bien,resultados); restaMal(mal,resultados); generaListado(resultados,listado); } void imprimePuntuaciones(Lista<Puntuacion>& listado) { Lista<Puntuacion>::ConstIterator i = listado.cbegin(); Lista<Puntuacion>::ConstIterator e = listado.cend(); while (i != e) { cout << "[" << i.elem().alumno << ":" << i.elem().nota << "]"; i.next(); } cout << endl; } void leeResultados(Lista<string>& bien, Lista<string>& mal) { string nombre; do { cin >> nombre; if (nombre != "#") { string resultado; cin >> resultado; if (resultado == "+") bien.pon_final(nombre); else mal.pon_final(nombre); } } while (nombre != "#"); } int main() { string comienzo; while (cin >> comienzo) { Lista<string> bien; Lista<string> mal; Lista<Puntuacion> listado; leeResultados(bien, mal); califica(bien, mal,listado); imprimePuntuaciones(listado); } return 0; }
[ "noreply@github.com" ]
ivangulyk.noreply@github.com
361b162440c7959958e32218bb3412fec7209a56
35c90b9d070d6593a136a5e848c5b37142ff1748
/tools/bonsaiRenderer/splotch/renderloop.cpp
863d97e9485ef1dc177de2de0298963d1e6066a2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ericchill/Bonsai
b2979badcce5d0b26f76d9dff3d44d265f0e1e9c
8904dd3ebf395ccaaf0eacef38933002b49fc3ba
refs/heads/master
2022-01-24T04:45:09.787812
2020-10-10T09:09:33
2020-10-10T09:09:33
71,961,070
0
0
null
2016-10-26T03:05:49
2016-10-26T03:05:49
null
UTF-8
C++
false
false
15,992
cpp
#include <stdio.h> #include "GLSLProgram.h" #ifdef WIN32 #define NOMINMAX #endif #include <GL/glew.h> #ifdef WIN32 #include <GL/wglew.h> #else #include <GL/glxew.h> #endif #if defined(__APPLE__) || defined(MACOSX) #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif #include <algorithm> #include "renderloop.h" #include "renderer.h" #include "vector_math.h" #include <cstdarg> #include "colorMap" #include "Splotch.h" #include <sys/time.h> static inline double rtc(void) { struct timeval Tvalue; double etime; struct timezone dummy; gettimeofday(&Tvalue,&dummy); etime = (double) Tvalue.tv_sec + 1.e-6*((double) Tvalue.tv_usec); return etime; } unsigned long long fpsCount; double timeBegin; const char passThruVS[] = { " void main() \n " " { \n " " gl_Position = gl_Vertex; \n " " gl_TexCoord[0] = gl_MultiTexCoord0; \n " " gl_FrontColor = gl_Color; \n " " } \n " }; const char texture2DPS[] = { " uniform sampler2D tex; \n " " void main() \n " " { \n " " vec4 c = texture2D(tex, gl_TexCoord[0].xy); \n " " gl_FragColor = c; \n " " } \n " }; void beginDeviceCoords(void) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), 0, glutGet(GLUT_WINDOW_HEIGHT), -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); } void glutStrokePrint(float x, float y, const char *s, void *font) { glPushMatrix(); glTranslatef(x, y, 0.0f); int len = (int) strlen(s); for (int i = 0; i < len; i++) { glutStrokeCharacter(font, s[i]); } glPopMatrix(); } void glPrintf(float x, float y, const char* format, ...) { //void *font = GLUT_STROKE_ROMAN; void *font = GLUT_STROKE_MONO_ROMAN; char buffer[256]; va_list args; va_start (args, format); vsnprintf (buffer, 255, format, args); glutStrokePrint(x, y, buffer, font); va_end(args); } class Demo { public: Demo(RendererData &idata) : m_idata(idata), m_ox(0), m_oy(0), m_buttonState(0), m_inertia(0.1f), m_paused(false), m_displayFps(true), m_displaySliders(true), m_texture(0), m_displayTexProg(0) // m_fov(40.0f)k // m_params(m_renderer.getParams()) { m_windowDims = make_int2(720, 480); m_cameraTrans = make_float3(0, -2, -10); m_cameraTransLag = m_cameraTrans; m_cameraRot = make_float3(0, 0, 0); m_cameraRotLag = m_cameraRot; //float color[4] = { 0.8f, 0.7f, 0.95f, 0.5f}; // float4 color = make_float4(1.0f, 1.0f, 1.0f, 1.0f); // m_renderer.setBaseColor(color); // m_renderer.setSpriteSizeScale(1.0f); m_displayTexProg = new GLSLProgram(passThruVS, texture2DPS); m_renderer.setColorMap(reinterpret_cast<float3*>(colorMap),256,256, 1.0f/255.0f); m_renderer.setWidth (m_windowDims.x); m_renderer.setHeight(m_windowDims.y); m_spriteSize = 0.1f; } ~Demo() { delete m_displayTexProg; } void cycleDisplayMode() {} void toggleSliders() { m_displaySliders = !m_displaySliders; } void toggleFps() { m_displayFps = !m_displayFps; } void drawQuad(const float s = 1.0f, const float z = 0.0f) { glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-s, -s, z); glTexCoord2f(1.0, 0.0); glVertex3f(s, -s, z); glTexCoord2f(1.0, 1.0); glVertex3f(s, s, z); glTexCoord2f(0.0, 1.0); glVertex3f(-s, s, z); glEnd(); } void displayTexture(const GLuint tex) { m_displayTexProg->enable(); m_displayTexProg->bindTexture("tex", tex, GL_TEXTURE_2D, 0); drawQuad(); m_displayTexProg->disable(); } GLuint createTexture(GLenum target, int w, int h, GLint internalformat, GLenum format, void *data) { GLuint texid; glGenTextures(1, &texid); glBindTexture(target, texid); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(target, 0, internalformat, w, h, 0, format, GL_FLOAT, data); return texid; } void drawStats() { const float fps = fpsCount/(rtc() - timeBegin); if (fpsCount > 10*fps) { fpsCount = 0; timeBegin = rtc(); } beginDeviceCoords(); glScalef(0.25f, 0.25f, 1.0f); glEnable(GL_LINE_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glColor4f(0.0f, 1.0f, 0.0f, 1.0f); float x = 100.0f; float y = glutGet(GLUT_WINDOW_HEIGHT)*4.0f - 200.0f; const float lineSpacing = 140.0f; if (m_displayFps) { glPrintf(x, y, "FPS: %.2f", fps); y -= lineSpacing; } glDisable(GL_BLEND); endWinCoords(); char str[256]; sprintf(str, "N-Body Renderer: %0.1f fps", fps); glutSetWindowTitle(str); } void display() { getBodyData(); fpsCount++; // view transform { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); m_cameraTransLag += (m_cameraTrans - m_cameraTransLag) * m_inertia; m_cameraRotLag += (m_cameraRot - m_cameraRotLag) * m_inertia; glTranslatef(m_cameraTransLag.x, m_cameraTransLag.y, m_cameraTransLag.z); glRotatef(m_cameraRotLag.x, 1.0, 0.0, 0.0); glRotatef(m_cameraRotLag.y, 0.0, 1.0, 0.0); } #if 0 if (m_displaySliders) { m_params->Render(0, 0); } #endif #if 1 glGetDoublev( GL_MODELVIEW_MATRIX, (GLdouble*)m_modelView); glGetDoublev(GL_PROJECTION_MATRIX, (GLdouble*)m_projection); m_renderer. setModelViewMatrix(m_modelView); m_renderer.setProjectionMatrix(m_projection); m_renderer.genImage(); fprintf(stderr, " --- frame done --- \n"); const int width = m_renderer.getWidth(); const int height = m_renderer.getHeight(); const float4 *img = &m_renderer.getImage()[0]; m_texture = createTexture(GL_TEXTURE_2D, width, height, GL_RGBA, GL_RGBA, (void*)img); #else const int width = 128; const int height = 128; std::vector<float> data(4*width*height); { using ShortVec3 = MathArray<float,3>; std::vector<ShortVec3> tex(256*256); int idx = 0; for (int i = 0; i < 256; i++) for (int j = 0; j < 256; j++) { tex[idx][0] = colorMap[i][j][0]/255.0f; tex[idx][1] = colorMap[i][j][1]/255.0f; tex[idx][2] = colorMap[i][j][2]/255.0f; idx++; } Texture2D<ShortVec3> texMap(&tex[0],256,256); for (int j = 0; j < height; j++) for (int i = 0; i < width; i++) { auto f = texMap(1.0f*i/width, j*1.0f/height); // f = texMap(1.0f, j*1.0f/height); data[0 + 4*(i + width*j)] = f[0]; data[1 + 4*(i + width*j)] = f[1]; data[2 + 4*(i + width*j)] = f[2]; data[3 + 4*(i + width*j)] = 1.0f; } } m_texture = createTexture(GL_TEXTURE_2D, width, height, GL_RGBA, GL_RGBA, &data[0]); #endif displayTexture(m_texture); drawStats(); } void mouse(int button, int state, int x, int y) { int mods; if (state == GLUT_DOWN) { m_buttonState |= 1<<button; } else if (state == GLUT_UP) { m_buttonState = 0; } mods = glutGetModifiers(); if (mods & GLUT_ACTIVE_SHIFT) { m_buttonState = 2; } else if (mods & GLUT_ACTIVE_CTRL) { m_buttonState = 3; } m_ox = x; m_oy = y; } void motion(int x, int y) { float dx = (float)(x - m_ox); float dy = (float)(y - m_oy); #if 0 if (m_displaySliders) { if (m_params->Motion(x, y)) return; } #endif if (m_buttonState == 3) { // left+middle = zoom m_cameraTrans.z += (dy / 100.0f) * 0.5f * fabs(m_cameraTrans.z); } else if (m_buttonState & 2) { // middle = translate m_cameraTrans.x += dx / 10.0f; m_cameraTrans.y -= dy / 10.0f; } else if (m_buttonState & 1) { // left = rotate m_cameraRot.x += dy / 5.0f; m_cameraRot.y += dx / 5.0f; } m_ox = x; m_oy = y; } void reshape(int w, int h) { m_windowDims = make_int2(w, h); fitCamera(); glMatrixMode(GL_MODELVIEW); glViewport(0, 0, m_windowDims.x, m_windowDims.y); m_renderer.setWidth (w); m_renderer.setHeight(h); } void fitCamera() { float3 boxMin = make_float3(m_idata.rmin()); float3 boxMax = make_float3(m_idata.rmax()); const float pi = 3.1415926f; float3 center = 0.5f * (boxMin + boxMax); float radius = std::max(length(boxMax), length(boxMin)); const float fovRads = (m_windowDims.x / (float)m_windowDims.y) * pi / 3.0f ; // 60 degrees float distanceToCenter = radius / sinf(0.5f * fovRads); m_cameraTrans = center + make_float3(0, 0, - distanceToCenter); m_cameraTransLag = m_cameraTrans; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, (float) m_windowDims.x / (float) m_windowDims.y, 0.0001 * distanceToCenter, 4 * (radius + distanceToCenter)); } private: void getBodyData() { int n = m_idata.n(); const float velMax = m_idata.attributeMax(RendererData::VEL); const float velMin = m_idata.attributeMin(RendererData::VEL); const float rhoMax = m_idata.attributeMax(RendererData::RHO); const float rhoMin = m_idata.attributeMin(RendererData::RHO); const bool hasRHO = rhoMax > 0.0f; const float scaleVEL = 1.0/(velMax - velMin); const float scaleRHO = hasRHO ? 1.0/(rhoMax - rhoMin) : 0.0; m_renderer.resize(n); #pragma omp parallel for for (int i = 0; i < n; i++) { auto vtx = m_renderer.vertex_at(i); vtx.pos = Splotch::pos3d_t(m_idata.posx(i), m_idata.posy(i), m_idata.posz(i), m_spriteSize); // vtx.pos.h = m_idata.attribute(RendererData::H,i)*2; // vtx.pos.h *= m_spriteScale; vtx.color = make_float4(1.0f); float vel = m_idata.attribute(RendererData::VEL,i); float rho = m_idata.attribute(RendererData::RHO,i); vel = (vel - velMin) * scaleVEL; vel = std::pow(vel, 1.0f); rho = hasRHO ? (rho - rhoMin) * scaleRHO : 0.5f; assert(vel >= 0.0f && vel <= 1.0f); assert(rho >= 0.0f && rho <= 1.0f); vtx.attr = Splotch::attr_t(rho, vel, m_spriteIntensity, m_idata.type(i)); } } RendererData &m_idata; Splotch m_renderer; // view params int m_ox; // = 0 int m_oy; // = 0; int m_buttonState; int2 m_windowDims; float3 m_cameraTrans; float3 m_cameraRot; float3 m_cameraTransLag; float3 m_cameraRotLag; const float m_inertia; bool m_paused; bool m_displayBoxes; bool m_displayFps; bool m_displaySliders; ParamListGL *m_params; float m_spriteSize; float m_spriteIntensity; unsigned int m_texture; GLSLProgram *m_displayTexProg; double m_modelView [4][4]; double m_projection[4][4]; }; Demo *theDemo = NULL; void onexit() { if (theDemo) delete theDemo; } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); theDemo->display(); glutSwapBuffers(); } void reshape(int w, int h) { theDemo->reshape(w, h); glutPostRedisplay(); } void mouse(int button, int state, int x, int y) { theDemo->mouse(button, state, x, y); glutPostRedisplay(); } void motion(int x, int y) { theDemo->motion(x, y); glutPostRedisplay(); } // commented out to remove unused parameter warnings in Linux void key(unsigned char key, int /*x*/, int /*y*/) { switch (key) { case ' ': // theDemo->togglePause(); break; case 27: // escape case 'q': case 'Q': // cudaDeviceReset(); exit(0); break; /*case '`': bShowSliders = !bShowSliders; break;*/ case 'p': case 'P': theDemo->cycleDisplayMode(); break; case 'b': case 'B': // theDemo->toggleBoxes(); break; case 'd': case 'D': //displayEnabled = !displayEnabled; break; case 'f': case 'F': theDemo->fitCamera(); break; case ',': case '<': // theDemo->incrementOctreeDisplayLevel(-1); break; case '.': case '>': // theDemo->incrementOctreeDisplayLevel(+1); break; case 'h': case 'H': theDemo->toggleSliders(); // m_enableStats = !m_displaySliders; break; case '0': theDemo->toggleFps(); break; } glutPostRedisplay(); } void special(int key, int x, int y) { //paramlist->Special(key, x, y); glutPostRedisplay(); } void idle(void) { glutPostRedisplay(); } void initGL(int argc, char** argv) { // First initialize OpenGL context, so we can properly set the GL for CUDA. // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop. glutInit(&argc, argv); //glutInitWindowSize(720, 480); glutInitWindowSize(1024, 768); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutCreateWindow("Bonsai Tree-code Gravitational N-body Simulation"); //if (bFullscreen) // glutFullScreen(); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); // cudaDeviceReset(); exit(-1); } else if (!glewIsSupported("GL_VERSION_2_0 " "GL_VERSION_1_5 " "GL_ARB_multitexture " "GL_ARB_vertex_buffer_object")) { fprintf(stderr, "Required OpenGL extensions missing."); exit(-1); } else { #if defined(WIN32) wglSwapIntervalEXT(0); #elif defined(LINUX) glxSwapIntervalSGI(0); #endif } glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(key); glutSpecialFunc(special); glutIdleFunc(idle); glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0.0, 1.0); checkGLErrors("initGL"); atexit(onexit); } void initAppRenderer( int argc, char** argv, RendererData &idata) { initGL(argc, argv); theDemo = new Demo(idata); fpsCount = 0; timeBegin = rtc(); glutMainLoop(); }
[ "egaburov@dds.nl" ]
egaburov@dds.nl
7958fc141f8fdd76c1ba8f708b692f49d0a56b20
999f5f1f2aa209f44b9e7e7f143282d7ab6a25c0
/devel/include/slam_tutorials/test.h
7b4939c94a0510a13df3044a5762c043fff114e8
[]
no_license
MenethilArthas/catkin_ws
ac9ebcece01f7011208e34f58659f715215ccc73
ade8ab3982466414ce69052ae3654485e1375a10
refs/heads/master
2021-01-20T07:22:58.774464
2017-03-15T02:09:06
2017-03-15T02:09:06
83,886,383
0
0
null
null
null
null
UTF-8
C++
false
false
4,383
h
// Generated by gencpp from file slam_tutorials/test.msg // DO NOT EDIT! #ifndef SLAM_TUTORIALS_MESSAGE_TEST_H #define SLAM_TUTORIALS_MESSAGE_TEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace slam_tutorials { template <class ContainerAllocator> struct test_ { typedef test_<ContainerAllocator> Type; test_() { } test_(const ContainerAllocator& _alloc) { (void)_alloc; } typedef boost::shared_ptr< ::slam_tutorials::test_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::slam_tutorials::test_<ContainerAllocator> const> ConstPtr; }; // struct test_ typedef ::slam_tutorials::test_<std::allocator<void> > test; typedef boost::shared_ptr< ::slam_tutorials::test > testPtr; typedef boost::shared_ptr< ::slam_tutorials::test const> testConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::slam_tutorials::test_<ContainerAllocator> & v) { ros::message_operations::Printer< ::slam_tutorials::test_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace slam_tutorials namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'slam_tutorials': ['/home/action/catkin_ws/src/slam_tutorials/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::slam_tutorials::test_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::slam_tutorials::test_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::slam_tutorials::test_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::slam_tutorials::test_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::slam_tutorials::test_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::slam_tutorials::test_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::slam_tutorials::test_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::slam_tutorials::test_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::slam_tutorials::test_<ContainerAllocator> > { static const char* value() { return "slam_tutorials/test"; } static const char* value(const ::slam_tutorials::test_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::slam_tutorials::test_<ContainerAllocator> > { static const char* value() { return "\n\ "; } static const char* value(const ::slam_tutorials::test_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::slam_tutorials::test_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER }; // struct test_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::slam_tutorials::test_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::slam_tutorials::test_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // SLAM_TUTORIALS_MESSAGE_TEST_H
[ "690540319@qq.com" ]
690540319@qq.com
33eaf7aee5d94513a89b93675781f339d1ce494b
a998bfde47dc0f18382741212edd56e07c035070
/cc/layers/layer_impl_unittest.cc
8d120bef621d19b9f40f424451858278f6ed743b
[ "BSD-3-Clause" ]
permissive
dalecurtis/mojo
92c8ce2e339ae923d387e2bdab4591f2165a9e25
e8ee0eb8a26abe43299b95054275939da9defd14
refs/heads/master
2021-01-15T11:44:31.238006
2014-10-23T18:48:50
2014-10-23T18:48:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,383
cc
// Copyright 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/layers/layer_impl.h" #include "cc/layers/painted_scrollbar_layer_impl.h" #include "cc/output/filter_operation.h" #include "cc/output/filter_operations.h" #include "cc/test/fake_impl_proxy.h" #include "cc/test/fake_layer_tree_host_impl.h" #include "cc/test/fake_output_surface.h" #include "cc/test/geometry_test_utils.h" #include "cc/test/test_shared_bitmap_manager.h" #include "cc/trees/layer_tree_impl.h" #include "cc/trees/single_thread_proxy.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/effects/SkBlurImageFilter.h" namespace cc { namespace { #define EXECUTE_AND_VERIFY_SUBTREE_CHANGED(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_TRUE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_TRUE(root->LayerPropertyChanged()); \ EXPECT_TRUE(child->LayerPropertyChanged()); \ EXPECT_TRUE(grand_child->LayerPropertyChanged()); #define EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_FALSE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_FALSE(root->LayerPropertyChanged()); \ EXPECT_FALSE(child->LayerPropertyChanged()); \ EXPECT_FALSE(grand_child->LayerPropertyChanged()); #define EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( \ code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_TRUE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_FALSE(root->LayerPropertyChanged()); \ EXPECT_FALSE(child->LayerPropertyChanged()); \ EXPECT_FALSE(grand_child->LayerPropertyChanged()); #define EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ code_to_test; \ EXPECT_TRUE(root->needs_push_properties()); \ EXPECT_FALSE(child->needs_push_properties()); \ EXPECT_FALSE(grand_child->needs_push_properties()); \ EXPECT_TRUE(root->LayerPropertyChanged()); \ EXPECT_FALSE(child->LayerPropertyChanged()); \ EXPECT_FALSE(grand_child->LayerPropertyChanged()); #define VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ host_impl.ForcePrepareToDraw(); \ EXPECT_FALSE(host_impl.active_tree()->needs_update_draw_properties()); \ code_to_test; \ EXPECT_TRUE(host_impl.active_tree()->needs_update_draw_properties()); #define VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(code_to_test) \ root->ResetAllChangeTrackingForSubtree(); \ host_impl.ForcePrepareToDraw(); \ EXPECT_FALSE(host_impl.active_tree()->needs_update_draw_properties()); \ code_to_test; \ EXPECT_FALSE(host_impl.active_tree()->needs_update_draw_properties()); TEST(LayerImplTest, VerifyLayerChangesAreTrackedProperly) { // // This test checks that layerPropertyChanged() has the correct behavior. // // The constructor on this will fake that we are on the correct thread. // Create a simple LayerImpl tree: FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); EXPECT_TRUE(host_impl.InitializeRenderer(FakeOutputSurface::Create3d())); scoped_ptr<LayerImpl> root_clip = LayerImpl::Create(host_impl.active_tree(), 1); scoped_ptr<LayerImpl> root_ptr = LayerImpl::Create(host_impl.active_tree(), 2); LayerImpl* root = root_ptr.get(); root_clip->AddChild(root_ptr.Pass()); scoped_ptr<LayerImpl> scroll_parent = LayerImpl::Create(host_impl.active_tree(), 3); LayerImpl* scroll_child = LayerImpl::Create(host_impl.active_tree(), 4).get(); std::set<LayerImpl*>* scroll_children = new std::set<LayerImpl*>(); scroll_children->insert(scroll_child); scroll_children->insert(root); scoped_ptr<LayerImpl> clip_parent = LayerImpl::Create(host_impl.active_tree(), 5); LayerImpl* clip_child = LayerImpl::Create(host_impl.active_tree(), 6).get(); std::set<LayerImpl*>* clip_children = new std::set<LayerImpl*>(); clip_children->insert(clip_child); clip_children->insert(root); root->AddChild(LayerImpl::Create(host_impl.active_tree(), 7)); LayerImpl* child = root->children()[0]; child->AddChild(LayerImpl::Create(host_impl.active_tree(), 8)); LayerImpl* grand_child = child->children()[0]; root->SetScrollClipLayer(root_clip->id()); // Adding children is an internal operation and should not mark layers as // changed. EXPECT_FALSE(root->LayerPropertyChanged()); EXPECT_FALSE(child->LayerPropertyChanged()); EXPECT_FALSE(grand_child->LayerPropertyChanged()); gfx::PointF arbitrary_point_f = gfx::PointF(0.125f, 0.25f); gfx::Point3F arbitrary_point_3f = gfx::Point3F(0.125f, 0.25f, 0.f); float arbitrary_number = 0.352f; gfx::Size arbitrary_size = gfx::Size(111, 222); gfx::Point arbitrary_point = gfx::Point(333, 444); gfx::Vector2d arbitrary_vector2d = gfx::Vector2d(111, 222); gfx::Rect arbitrary_rect = gfx::Rect(arbitrary_point, arbitrary_size); gfx::RectF arbitrary_rect_f = gfx::RectF(arbitrary_point_f, gfx::SizeF(1.234f, 5.678f)); SkColor arbitrary_color = SkColorSetRGB(10, 20, 30); gfx::Transform arbitrary_transform; arbitrary_transform.Scale3d(0.1f, 0.2f, 0.3f); FilterOperations arbitrary_filters; arbitrary_filters.Append(FilterOperation::CreateOpacityFilter(0.5f)); SkXfermode::Mode arbitrary_blend_mode = SkXfermode::kMultiply_Mode; // These properties are internal, and should not be considered "change" when // they are used. EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetUpdateRect(arbitrary_rect)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetBounds(arbitrary_size)); // Changing these properties affects the entire subtree of layers. EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetTransformOrigin(arbitrary_point_3f)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetFilters(arbitrary_filters)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetFilters(FilterOperations())); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetMaskLayer(LayerImpl::Create(host_impl.active_tree(), 9))); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetMasksToBounds(true)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetContentsOpaque(true)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetReplicaLayer(LayerImpl::Create(host_impl.active_tree(), 10))); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetPosition(arbitrary_point_f)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetShouldFlattenTransform(false)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->Set3dSortingContextId(1)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetDoubleSided(false)); // constructor initializes it to "true". EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->ScrollBy(arbitrary_vector2d)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetScrollDelta(gfx::Vector2d())); EXECUTE_AND_VERIFY_SUBTREE_CHANGED( root->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetHideLayerAndSubtree(true)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetOpacity(arbitrary_number)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetBlendMode(arbitrary_blend_mode)); EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetTransform(arbitrary_transform)); // Changing these properties only affects the layer itself. EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetContentBounds(arbitrary_size)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED( root->SetContentsScale(arbitrary_number, arbitrary_number)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetDrawsContent(true)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED( root->SetBackgroundColor(arbitrary_color)); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED( root->SetBackgroundFilters(arbitrary_filters)); // Special case: check that SetBounds changes behavior depending on // masksToBounds. root->SetMasksToBounds(false); EXECUTE_AND_VERIFY_ONLY_LAYER_CHANGED(root->SetBounds(gfx::Size(135, 246))); root->SetMasksToBounds(true); // Should be a different size than previous call, to ensure it marks tree // changed. EXECUTE_AND_VERIFY_SUBTREE_CHANGED(root->SetBounds(arbitrary_size)); // Changing this property does not cause the layer to be marked as changed // but does cause the layer to need to push properties. EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetIsRootForIsolatedGroup(true)); // Changing these properties should cause the layer to need to push properties EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetScrollParent(scroll_parent.get())); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetScrollChildren(scroll_children)); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetClipParent(clip_parent.get())); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetClipChildren(clip_children)); EXECUTE_AND_VERIFY_NEEDS_PUSH_PROPERTIES_AND_SUBTREE_DID_NOT_CHANGE( root->SetNumDescendantsThatDrawContent(10)); // After setting all these properties already, setting to the exact same // values again should not cause any change. EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetTransformOrigin(arbitrary_point_3f)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetMasksToBounds(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetPosition(arbitrary_point_f)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetShouldFlattenTransform(false)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->Set3dSortingContextId(1)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetTransform(arbitrary_transform)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetDoubleSided(false)); // constructor initializes it to "true". EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollDelta(gfx::Vector2d())); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetContentBounds(arbitrary_size)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetContentsScale(arbitrary_number, arbitrary_number)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetContentsOpaque(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetOpacity(arbitrary_number)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetBlendMode(arbitrary_blend_mode)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetIsRootForIsolatedGroup(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetDrawsContent(true)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE(root->SetBounds(arbitrary_size)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollParent(scroll_parent.get())); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetScrollChildren(scroll_children)); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetClipParent(clip_parent.get())); EXECUTE_AND_VERIFY_SUBTREE_DID_NOT_CHANGE( root->SetClipChildren(clip_children)); } TEST(LayerImplTest, VerifyNeedsUpdateDrawProperties) { FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); EXPECT_TRUE(host_impl.InitializeRenderer(FakeOutputSurface::Create3d())); host_impl.active_tree()->SetRootLayer( LayerImpl::Create(host_impl.active_tree(), 1)); LayerImpl* root = host_impl.active_tree()->root_layer(); scoped_ptr<LayerImpl> layer_ptr = LayerImpl::Create(host_impl.active_tree(), 2); LayerImpl* layer = layer_ptr.get(); root->AddChild(layer_ptr.Pass()); layer->SetScrollClipLayer(root->id()); DCHECK(host_impl.CanDraw()); gfx::PointF arbitrary_point_f = gfx::PointF(0.125f, 0.25f); float arbitrary_number = 0.352f; gfx::Size arbitrary_size = gfx::Size(111, 222); gfx::Point arbitrary_point = gfx::Point(333, 444); gfx::Vector2d arbitrary_vector2d = gfx::Vector2d(111, 222); gfx::Size large_size = gfx::Size(1000, 1000); gfx::Rect arbitrary_rect = gfx::Rect(arbitrary_point, arbitrary_size); gfx::RectF arbitrary_rect_f = gfx::RectF(arbitrary_point_f, gfx::SizeF(1.234f, 5.678f)); SkColor arbitrary_color = SkColorSetRGB(10, 20, 30); gfx::Transform arbitrary_transform; arbitrary_transform.Scale3d(0.1f, 0.2f, 0.3f); FilterOperations arbitrary_filters; arbitrary_filters.Append(FilterOperation::CreateOpacityFilter(0.5f)); SkXfermode::Mode arbitrary_blend_mode = SkXfermode::kMultiply_Mode; // Related filter functions. VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(FilterOperations())); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); // Related scrolling functions. VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(large_size)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(large_size)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->ScrollBy(arbitrary_vector2d)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->ScrollBy(gfx::Vector2d())); layer->SetScrollDelta(gfx::Vector2d(0, 0)); host_impl.ForcePrepareToDraw(); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollDelta(arbitrary_vector2d)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollDelta(arbitrary_vector2d)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetScrollOffset(gfx::ScrollOffset(arbitrary_vector2d))); // Unrelated functions, always set to new values, always set needs update. VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetMaskLayer(LayerImpl::Create(host_impl.active_tree(), 4))); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetMasksToBounds(true)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetContentsOpaque(true)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetReplicaLayer(LayerImpl::Create(host_impl.active_tree(), 5))); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetPosition(arbitrary_point_f)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetShouldFlattenTransform(false)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->Set3dSortingContextId(1)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetDoubleSided(false)); // constructor initializes it to "true". VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetContentBounds(arbitrary_size)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetContentsScale(arbitrary_number, arbitrary_number)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetDrawsContent(true)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundColor(arbitrary_color)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundFilters(arbitrary_filters)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetOpacity(arbitrary_number)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBlendMode(arbitrary_blend_mode)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetTransform(arbitrary_transform)); VERIFY_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(arbitrary_size)); // Unrelated functions, set to the same values, no needs update. VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetIsRootForIsolatedGroup(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetFilters(arbitrary_filters)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetMasksToBounds(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetContentsOpaque(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetPosition(arbitrary_point_f)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->Set3dSortingContextId(1)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetDoubleSided(false)); // constructor initializes it to "true". VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetContentBounds(arbitrary_size)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetContentsScale(arbitrary_number, arbitrary_number)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetDrawsContent(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundColor(arbitrary_color)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBackgroundFilters(arbitrary_filters)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetOpacity(arbitrary_number)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetBlendMode(arbitrary_blend_mode)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetIsRootForIsolatedGroup(true)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES( layer->SetTransform(arbitrary_transform)); VERIFY_NO_NEEDS_UPDATE_DRAW_PROPERTIES(layer->SetBounds(arbitrary_size)); } TEST(LayerImplTest, SafeOpaqueBackgroundColor) { FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); EXPECT_TRUE(host_impl.InitializeRenderer(FakeOutputSurface::Create3d())); scoped_ptr<LayerImpl> layer = LayerImpl::Create(host_impl.active_tree(), 1); for (int contents_opaque = 0; contents_opaque < 2; ++contents_opaque) { for (int layer_opaque = 0; layer_opaque < 2; ++layer_opaque) { for (int host_opaque = 0; host_opaque < 2; ++host_opaque) { layer->SetContentsOpaque(!!contents_opaque); layer->SetBackgroundColor(layer_opaque ? SK_ColorRED : SK_ColorTRANSPARENT); host_impl.active_tree()->set_background_color( host_opaque ? SK_ColorRED : SK_ColorTRANSPARENT); SkColor safe_color = layer->SafeOpaqueBackgroundColor(); if (contents_opaque) { EXPECT_EQ(SkColorGetA(safe_color), 255u) << "Flags: " << contents_opaque << ", " << layer_opaque << ", " << host_opaque << "\n"; } else { EXPECT_NE(SkColorGetA(safe_color), 255u) << "Flags: " << contents_opaque << ", " << layer_opaque << ", " << host_opaque << "\n"; } } } } } TEST(LayerImplTest, TransformInvertibility) { FakeImplProxy proxy; TestSharedBitmapManager shared_bitmap_manager; FakeLayerTreeHostImpl host_impl(&proxy, &shared_bitmap_manager); scoped_ptr<LayerImpl> layer = LayerImpl::Create(host_impl.active_tree(), 1); EXPECT_TRUE(layer->transform().IsInvertible()); EXPECT_TRUE(layer->transform_is_invertible()); gfx::Transform transform; transform.Scale3d( SkDoubleToMScalar(1.0), SkDoubleToMScalar(1.0), SkDoubleToMScalar(0.0)); layer->SetTransform(transform); EXPECT_FALSE(layer->transform().IsInvertible()); EXPECT_FALSE(layer->transform_is_invertible()); transform.MakeIdentity(); transform.ApplyPerspectiveDepth(SkDoubleToMScalar(100.0)); transform.RotateAboutZAxis(75.0); transform.RotateAboutXAxis(32.2); transform.RotateAboutZAxis(-75.0); transform.Translate3d(SkDoubleToMScalar(50.5), SkDoubleToMScalar(42.42), SkDoubleToMScalar(-100.25)); layer->SetTransform(transform); EXPECT_TRUE(layer->transform().IsInvertible()); EXPECT_TRUE(layer->transform_is_invertible()); } class LayerImplScrollTest : public testing::Test { public: LayerImplScrollTest() : host_impl_(settings(), &proxy_, &shared_bitmap_manager_), root_id_(7) { host_impl_.active_tree()->SetRootLayer( LayerImpl::Create(host_impl_.active_tree(), root_id_)); host_impl_.active_tree()->root_layer()->AddChild( LayerImpl::Create(host_impl_.active_tree(), root_id_ + 1)); layer()->SetScrollClipLayer(root_id_); // Set the max scroll offset by noting that the root layer has bounds (1,1), // thus whatever bounds are set for the layer will be the max scroll // offset plus 1 in each direction. host_impl_.active_tree()->root_layer()->SetBounds(gfx::Size(1, 1)); gfx::Vector2d max_scroll_offset(51, 81); layer()->SetBounds(gfx::Size(max_scroll_offset.x(), max_scroll_offset.y())); } LayerImpl* layer() { return host_impl_.active_tree()->root_layer()->children()[0]; } LayerTreeImpl* tree() { return host_impl_.active_tree(); } LayerTreeSettings settings() { LayerTreeSettings settings; settings.use_pinch_virtual_viewport = true; return settings; } private: FakeImplProxy proxy_; TestSharedBitmapManager shared_bitmap_manager_; FakeLayerTreeHostImpl host_impl_; int root_id_; }; TEST_F(LayerImplScrollTest, ScrollByWithZeroOffset) { // Test that LayerImpl::ScrollBy only affects ScrollDelta and total scroll // offset is bounded by the range [0, max scroll offset]. EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(layer()->ScrollDelta(), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->scroll_offset()); layer()->ScrollBy(gfx::Vector2dF(100, -100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 0), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(layer()->ScrollDelta(), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->scroll_offset()); } TEST_F(LayerImplScrollTest, ScrollByWithNonZeroOffset) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, layer()->ScrollDelta()), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->ScrollBy(gfx::Vector2dF(100, -100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 0), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, layer()->ScrollDelta()), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); } class ScrollDelegateIgnore : public LayerImpl::ScrollOffsetDelegate { public: void SetTotalScrollOffset(const gfx::ScrollOffset& new_value) override {} gfx::ScrollOffset GetTotalScrollOffset() override { return gfx::ScrollOffset(fixed_offset_); } bool IsExternalFlingActive() const override { return false; } void set_fixed_offset(const gfx::Vector2dF& fixed_offset) { fixed_offset_ = fixed_offset; } private: gfx::Vector2dF fixed_offset_; }; TEST_F(LayerImplScrollTest, ScrollByWithIgnoringDelegate) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); ScrollDelegateIgnore delegate; gfx::Vector2dF fixed_offset(32, 12); delegate.set_fixed_offset(fixed_offset); layer()->SetScrollOffsetDelegate(&delegate); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->SetScrollOffsetDelegate(nullptr); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); gfx::Vector2dF scroll_delta(1, 1); layer()->ScrollBy(scroll_delta); EXPECT_VECTOR_EQ(fixed_offset + scroll_delta, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); } class ScrollDelegateAccept : public LayerImpl::ScrollOffsetDelegate { public: void SetTotalScrollOffset(const gfx::ScrollOffset& new_value) override { current_offset_ = new_value; } gfx::ScrollOffset GetTotalScrollOffset() override { return current_offset_; } bool IsExternalFlingActive() const override { return false; } private: gfx::ScrollOffset current_offset_; }; TEST_F(LayerImplScrollTest, ScrollByWithAcceptingDelegate) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); ScrollDelegateAccept delegate; layer()->SetScrollOffsetDelegate(&delegate); EXPECT_VECTOR_EQ(scroll_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2dF(), layer()->ScrollDelta()); layer()->ScrollBy(gfx::Vector2dF(-100, 100)); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); layer()->SetScrollOffsetDelegate(nullptr); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); gfx::Vector2dF scroll_delta(1, 1); layer()->ScrollBy(scroll_delta); EXPECT_VECTOR_EQ(gfx::Vector2dF(1, 80), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); } TEST_F(LayerImplScrollTest, ApplySentScrollsNoDelegate) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2dF scroll_delta(20.5f, 8.5f); gfx::Vector2d sent_scroll_delta(12, -3); layer()->SetScrollOffset(scroll_offset); layer()->ScrollBy(scroll_delta); layer()->SetSentScrollDelta(sent_scroll_delta); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_delta, layer()->ScrollDelta()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(sent_scroll_delta, layer()->sent_scroll_delta()); layer()->ApplySentScrollDeltasFromAbortedCommit(); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_delta - sent_scroll_delta, layer()->ScrollDelta()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, sent_scroll_delta), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2d(), layer()->sent_scroll_delta()); } TEST_F(LayerImplScrollTest, ApplySentScrollsWithIgnoringDelegate) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2d sent_scroll_delta(12, -3); gfx::Vector2dF fixed_offset(32, 12); layer()->SetScrollOffset(scroll_offset); ScrollDelegateIgnore delegate; delegate.set_fixed_offset(fixed_offset); layer()->SetScrollOffsetDelegate(&delegate); layer()->SetSentScrollDelta(sent_scroll_delta); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(sent_scroll_delta, layer()->sent_scroll_delta()); layer()->ApplySentScrollDeltasFromAbortedCommit(); EXPECT_VECTOR_EQ(fixed_offset, layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, sent_scroll_delta), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2d(), layer()->sent_scroll_delta()); } TEST_F(LayerImplScrollTest, ApplySentScrollsWithAcceptingDelegate) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2d sent_scroll_delta(12, -3); gfx::Vector2dF scroll_delta(20.5f, 8.5f); layer()->SetScrollOffset(scroll_offset); ScrollDelegateAccept delegate; layer()->SetScrollOffsetDelegate(&delegate); layer()->ScrollBy(scroll_delta); layer()->SetSentScrollDelta(sent_scroll_delta); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(scroll_offset, layer()->scroll_offset()); EXPECT_VECTOR_EQ(sent_scroll_delta, layer()->sent_scroll_delta()); layer()->ApplySentScrollDeltasFromAbortedCommit(); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, scroll_delta), layer()->TotalScrollOffset()); EXPECT_VECTOR_EQ(gfx::ScrollOffsetWithDelta(scroll_offset, sent_scroll_delta), layer()->scroll_offset()); EXPECT_VECTOR_EQ(gfx::Vector2d(), layer()->sent_scroll_delta()); } TEST_F(LayerImplScrollTest, ScrollUserUnscrollableLayer) { gfx::ScrollOffset scroll_offset(10, 5); gfx::Vector2dF scroll_delta(20.5f, 8.5f); layer()->set_user_scrollable_vertical(false); layer()->SetScrollOffset(scroll_offset); gfx::Vector2dF unscrolled = layer()->ScrollBy(scroll_delta); EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 8.5f), unscrolled); EXPECT_VECTOR_EQ(gfx::Vector2dF(30.5f, 5), layer()->TotalScrollOffset()); } TEST_F(LayerImplScrollTest, SetNewScrollbarParameters) { gfx::ScrollOffset scroll_offset(10, 5); layer()->SetScrollOffset(scroll_offset); scoped_ptr<PaintedScrollbarLayerImpl> vertical_scrollbar( PaintedScrollbarLayerImpl::Create(tree(), 100, VERTICAL)); vertical_scrollbar->SetScrollLayerAndClipLayerByIds( layer()->id(), tree()->root_layer()->id()); int expected_vertical_maximum = layer()->bounds().height() - tree()->root_layer()->bounds().height(); EXPECT_EQ(expected_vertical_maximum, vertical_scrollbar->maximum()); EXPECT_EQ(scroll_offset.y(), vertical_scrollbar->current_pos()); scoped_ptr<PaintedScrollbarLayerImpl> horizontal_scrollbar( PaintedScrollbarLayerImpl::Create(tree(), 101, HORIZONTAL)); horizontal_scrollbar->SetScrollLayerAndClipLayerByIds( layer()->id(), tree()->root_layer()->id()); int expected_horizontal_maximum = layer()->bounds().width() - tree()->root_layer()->bounds().width(); EXPECT_EQ(expected_horizontal_maximum, horizontal_scrollbar->maximum()); EXPECT_EQ(scroll_offset.x(), horizontal_scrollbar->current_pos()); } } // namespace } // namespace cc
[ "jamesr@chromium.org" ]
jamesr@chromium.org
a77f243423384769fdec1b4382a2e0f27517a617
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/pdfium/fxjs/cjs_font.cpp
fcf69ac02900d66cc5de386b8a84de3d0d640289
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
1,318
cpp
// Copyright 2017 The PDFium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "fxjs/cjs_font.h" const JSConstSpec CJS_Font::ConstSpecs[] = { {"Times", JSConstSpec::String, 0, "Times-Roman"}, {"TimesB", JSConstSpec::String, 0, "Times-Bold"}, {"TimesI", JSConstSpec::String, 0, "Times-Italic"}, {"TimesBI", JSConstSpec::String, 0, "Times-BoldItalic"}, {"Helv", JSConstSpec::String, 0, "Helvetica"}, {"HelvB", JSConstSpec::String, 0, "Helvetica-Bold"}, {"HelvI", JSConstSpec::String, 0, "Helvetica-Oblique"}, {"HelvBI", JSConstSpec::String, 0, "Helvetica-BoldOblique"}, {"Cour", JSConstSpec::String, 0, "Courier"}, {"CourB", JSConstSpec::String, 0, "Courier-Bold"}, {"CourI", JSConstSpec::String, 0, "Courier-Oblique"}, {"CourBI", JSConstSpec::String, 0, "Courier-BoldOblique"}, {"Symbol", JSConstSpec::String, 0, "Symbol"}, {"ZapfD", JSConstSpec::String, 0, "ZapfDingbats"}}; uint32_t CJS_Font::ObjDefnID = 0; // static void CJS_Font::DefineJSObjects(CFXJS_Engine* pEngine) { ObjDefnID = pEngine->DefineObj("font", FXJSOBJTYPE_STATIC, nullptr, nullptr); DefineConsts(pEngine, ObjDefnID, ConstSpecs); }
[ "jengelh@inai.de" ]
jengelh@inai.de
eea1fff89142c5ab42489be27930058bfc690a26
2070bbef01a4e6865b384647532de509c76def17
/代码/VMD/vmdWriter.h
d860300121985f058ca21bc95a6d85a26d2c669d
[]
no_license
KIE9542c/3D-Motion-Tracking-and-Output
a8343609cad43aeb04eb7d29caf8404326db21b5
45ae4d38f5d4ec73f13610d415aa44a08fe293b0
refs/heads/master
2020-05-31T23:05:53.707801
2019-07-17T09:25:50
2019-07-17T09:25:50
190,531,486
0
0
null
null
null
null
GB18030
C++
false
false
1,104
h
//#pragma once #include <iostream> #include <fstream> #include <string> #include <vector> #include <json\json.h> #include <QtGui\qquaternion.h> #include <QtGui\qvector3d.h> class vmdWriter { public: vmdWriter(std::string filename, std::string modelname, bool type); bool readPosition(); bool isOpenMMD(); void setBoneIndex(); void transferCoordinate(); void processRotaion(int index); void processPosition(int index); void writeFile(); void test(); private: char version[30] = "Vocaloid Motion Data 0002"; char modelName[20]; uint32_t keyFrameNumber; uint32_t frameTime; float position[4][3]; //0~3分别是其他骨骼,センター,左足IK,右足IK float rotation[10][4]; //0~9分别是センター,下半身,上半身,首,左腕,左ひじ,右腕,右ひじ,左足IK,右足IK uint32_t XCurve[4]; uint32_t YCurve[4]; uint32_t ZCurve[4]; uint32_t RCurve[4]; bool isopenMMD; //true表示输入的骨骼坐标是openMMD导出的,否则为Vnect导出的 int boneIndex[17]; std::string fileName; std::vector<std::vector<QVector3D>> gPosition; };
[ "51349604+scutWu@users.noreply.github.com" ]
51349604+scutWu@users.noreply.github.com
164e3f64688101f50169012a6e0885936cb808bf
fca16f6b7838bd515de786cf6e8c01aee348c1f9
/fps2015aels/uilibgp2015/OGL/GRect/GRect.cpp
0fdec020dd3808dee38e3a1b500c24bc9208fc7c
[]
no_license
antoinechene/FPS-openGL
0de726658ffa278289fd89c1410c490b3dad7f54
c7b3cbca8c6dc4f190dc92a273fe1b8ed74b7900
refs/heads/master
2020-04-06T07:01:17.983451
2012-09-06T14:06:25
2012-09-06T14:06:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
#include "GRect.h" #include "../Draw_Geometry/Draw_Geometry_Rect.h" ID::GRect::GRect(int16_t w, int16_t h, bool f, ID::Color* color) : /*__w(w), __h(h),*/ __fulfil(f), __color(*color) { this->_w = w; this->_h = h; } ID::GRect::~GRect() { } void ID::GRect::SetDimension(int16_t w, int16_t h) { this->_w = w; this->_h = h; } void ID::GRect::SetFulfil(bool f) { this->__fulfil = f; } void ID::GRect::SetColor(uint32_t c) { this->__color = c; } void ID::GRect::SetColor(ID::Color c) { this->__color = c; } int ID::GRect::RefreshToSurface(Surface* s, int x, int y) { if (this->GetOnScreen() == false) return 0; if (s == NULL) return 0; ID::Draw_Geometry_Rect::GetInstance()->Draw(s, x + this->_x, y + this->_y, this->GetWidth(), this->GetHeight(), this->__fulfil, this->__color.ConvertToInt()); return 0; }
[ "antoinechene@hotmail.fr" ]
antoinechene@hotmail.fr
2ff190919f3c980c1cae116aa885d2e951501482
f9485b64c2f0632572423e3c29d4911846849c6c
/src/PaymentServer.cpp
af5b188bd9874b80d093fee2344bb776c2e1b0b4
[ "MIT" ]
permissive
prascoin/prascoinwallet
55928aabaa1360099cf42a58e69436e4269f9d50
27bae19ded60a9b72c71cfe6471c9cc27a38eb99
refs/heads/master
2020-03-08T23:54:08.453684
2018-04-06T22:14:19
2018-04-06T22:14:19
128,367,020
0
0
null
null
null
null
UTF-8
C++
false
false
4,238
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2016 The PrasCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include <cstdlib> #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include "PaymentServer.h" #include "Settings.h" #include "CurrencyAdapter.h" using namespace boost; using namespace WalletGui; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("prascoin:"); static QString ipcServerName() { QString name("PrasCoin"); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start prascoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on prascoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else Q_EMIT receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) Q_EMIT receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else Q_EMIT receivedURI(message); }
[ "prascoin@prascoin.com" ]
prascoin@prascoin.com
c6c5168f579c610a3e93a72598fa375028052fa4
25509aa66ad1a65663d42bf4ddbe9d1fa295fdab
/MyOpenGL/RendererPlayer.h
f3eccb68d467d7c6bd5da6e248393fa544f98d92
[]
no_license
NathanVss/Noxel-OpenGL
24b5d820d9df48bd5b68048a58ec056a3b93d28e
c48203cefc0e4eeaccb78868bd2609b2762666e0
refs/heads/master
2016-09-06T14:09:01.472705
2015-02-27T17:41:24
2015-02-27T17:41:24
29,501,753
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
#pragma once #include "Object.h" #include <YuEngine\EventTimer.h> class Player; class RendererPlayer : public Object { public: RendererPlayer(void); RendererPlayer(Container* c, Player* player); ~RendererPlayer(void); void update(); void render(); void renderArm(); float getPixelSize() { return pixelSize; } private: float pixelSize; float armAngle; bool armAnglePhase; Player* player; YuEngine::EventTimer legsAnimationTimer; };
[ "nathan.vasse@gmail.com" ]
nathan.vasse@gmail.com
40e7b6c68a55e42d298282bba70c15edda5727d9
dccd1058e723b6617148824dc0243dbec4c9bd48
/codeforces/1092D2.cpp
c0a17b25f584401bb4966e57ce346629370f3fbf
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
2,553
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} struct UF{ int n; //正だったらその頂点の親,負だったら根で連結成分の個数 vector<int> d; UF() {} UF(int N):n(N), d(N,-1){} int root(int v){ if(d[v]<0) return v; return d[v]=root(d[v]); } bool unite(int X,int Y){ X=root(X); Y=root(Y); if(X==Y) return false; // if(size(X) < size(Y)) swap(X,Y); d[X]+=d[Y]; d[Y]=X; return true; } int size(int v){ return -d[root(v)]; } bool same(int X,int Y){ return root(X)==root(Y); } }; const int INF = 1e9+19191919; struct R{ int val,len,lh,rh; }; bool solve(){ int n; scanf(" %d", &n); vector<int> a(n); rep(i,n) scanf(" %d", &a[i]); int V = 0; vector<R> v; int s = 0; while(s<n){ int e = s; while(e<n && a[s] == a[e]) ++e; v.pb({a[s], e-s, V-1, V+1}); ++V; s = e; } UF uf(V); int L = -1, R = V; using pi = pair<int,int>; set<pi> ms; rep(i,V){ ms.insert({v[i].val, i}); } while(1){ pi pp = *ms.begin(); int idx = pp.se; int l = v[idx].lh, r = v[idx].rh; // printf(" %d %d %d\n",idx,l,r); if(l==L && r==R) break; if(v[idx].len%2 == 1) return false; if(l!=L) l = uf.root(l); if(r!=R) r = uf.root(r); // printf(" cv lr %d %d\n", l,r); int tgt = INF; if(l!=L) tgt = min(tgt, v[l].val); if(r!=R) tgt = min(tgt, v[r].val); ms.erase(pp); v[idx].val = tgt; if(l!=L && v[l].val == tgt){ v[idx].len += v[l].len; v[idx].lh = v[l].lh; ms.erase({v[l].val, l}); uf.unite(idx,l); } if(r!=R && v[r].val == tgt){ v[idx].len += v[r].len; v[idx].rh = v[r].rh; ms.erase({v[r].val, r}); uf.unite(idx,r); } ms.insert({v[idx].val, idx}); } return true; } int main(){ cout << (solve()?"YES":"NO") << endl; return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
56015f7916338bac09edf3f55bbe3100a4b5febf
ed10dc841d5b4f6a038e8f24f603750992d9fae9
/clang/lib/Sema/SemaStmt.cpp
e85fa34596f7a566d096e858b6d1427ef61f14c1
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
WYK15/swift-Ollvm10
90c2f0ade099a1cc545183eba5c5a69765320401
ea68224ab23470963b68dfcc28b5ac769a070ea3
refs/heads/main
2023-03-30T20:02:58.305792
2021-04-07T02:41:01
2021-04-07T02:41:01
355,189,226
5
0
null
null
null
null
UTF-8
C++
false
false
170,107
cpp
//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for statements. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTLambda.h" #include "clang/AST/CharUnits.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/CharUnits.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/EvaluatedExprVisitor.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/TargetInfo.h" #include "clang/Edit/RefactoringFixits.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" using namespace clang; using namespace sema; StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) { if (FE.isInvalid()) return StmtError(); FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue); if (FE.isInvalid()) return StmtError(); // C99 6.8.3p2: The expression in an expression statement is evaluated as a // void expression for its side effects. Conversion to void allows any // operand, even incomplete types. // Same thing in for stmt first clause (when expr) and third clause. return StmtResult(FE.getAs<Stmt>()); } StmtResult Sema::ActOnExprStmtError() { DiscardCleanupsInEvaluationContext(); return StmtError(); } StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro) { return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro); } StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, SourceLocation EndLoc) { DeclGroupRef DG = dg.get(); // If we have an invalid decl, just return an error. if (DG.isNull()) return StmtError(); return new (Context) DeclStmt(DG, StartLoc, EndLoc); } void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { DeclGroupRef DG = dg.get(); // If we don't have a declaration, or we have an invalid declaration, // just return. if (DG.isNull() || !DG.isSingleDecl()) return; Decl *decl = DG.getSingleDecl(); if (!decl || decl->isInvalidDecl()) return; // Only variable declarations are permitted. VarDecl *var = dyn_cast<VarDecl>(decl); if (!var) { Diag(decl->getLocation(), diag::err_non_variable_decl_in_for); decl->setInvalidDecl(); return; } // foreach variables are never actually initialized in the way that // the parser came up with. var->setInit(nullptr); // In ARC, we don't need to retain the iteration variable of a fast // enumeration loop. Rather than actually trying to catch that // during declaration processing, we remove the consequences here. if (getLangOpts().ObjCAutoRefCount) { QualType type = var->getType(); // Only do this if we inferred the lifetime. Inferred lifetime // will show up as a local qualifier because explicit lifetime // should have shown up as an AttributedType instead. if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { // Add 'const' and mark the variable as pseudo-strong. var->setType(type.withConst()); var->setARCPseudoStrong(true); } } } /// Diagnose unused comparisons, both builtin and overloaded operators. /// For '==' and '!=', suggest fixits for '=' or '|='. /// /// Adding a cast to void (or other expression wrappers) will prevent the /// warning from firing. static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { SourceLocation Loc; bool CanAssign; enum { Equality, Inequality, Relational, ThreeWay } Kind; if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { if (!Op->isComparisonOp()) return false; if (Op->getOpcode() == BO_EQ) Kind = Equality; else if (Op->getOpcode() == BO_NE) Kind = Inequality; else if (Op->getOpcode() == BO_Cmp) Kind = ThreeWay; else { assert(Op->isRelationalOp()); Kind = Relational; } Loc = Op->getOperatorLoc(); CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { switch (Op->getOperator()) { case OO_EqualEqual: Kind = Equality; break; case OO_ExclaimEqual: Kind = Inequality; break; case OO_Less: case OO_Greater: case OO_GreaterEqual: case OO_LessEqual: Kind = Relational; break; case OO_Spaceship: Kind = ThreeWay; break; default: return false; } Loc = Op->getOperatorLoc(); CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); } else { // Not a typo-prone comparison. return false; } // Suppress warnings when the operator, suspicious as it may be, comes from // a macro expansion. if (S.SourceMgr.isMacroBodyExpansion(Loc)) return false; S.Diag(Loc, diag::warn_unused_comparison) << (unsigned)Kind << E->getSourceRange(); // If the LHS is a plausible entity to assign to, provide a fixit hint to // correct common typos. if (CanAssign) { if (Kind == Inequality) S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) << FixItHint::CreateReplacement(Loc, "|="); else if (Kind == Equality) S.Diag(Loc, diag::note_equality_comparison_to_assign) << FixItHint::CreateReplacement(Loc, "="); } return true; } static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A, SourceLocation Loc, SourceRange R1, SourceRange R2, bool IsCtor) { if (!A) return false; StringRef Msg = A->getMessage(); if (Msg.empty()) { if (IsCtor) return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2; return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2; } if (IsCtor) return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1 << R2; return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2; } void Sema::DiagnoseUnusedExprResult(const Stmt *S) { if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) return DiagnoseUnusedExprResult(Label->getSubStmt()); const Expr *E = dyn_cast_or_null<Expr>(S); if (!E) return; // If we are in an unevaluated expression context, then there can be no unused // results because the results aren't expected to be used in the first place. if (isUnevaluatedContext()) return; SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc(); // In most cases, we don't want to warn if the expression is written in a // macro body, or if the macro comes from a system header. If the offending // expression is a call to a function with the warn_unused_result attribute, // we warn no matter the location. Because of the order in which the various // checks need to happen, we factor out the macro-related test here. bool ShouldSuppress = SourceMgr.isMacroBodyExpansion(ExprLoc) || SourceMgr.isInSystemMacro(ExprLoc); const Expr *WarnExpr; SourceLocation Loc; SourceRange R1, R2; if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context)) return; // If this is a GNU statement expression expanded from a macro, it is probably // unused because it is a function-like macro that can be used as either an // expression or statement. Don't warn, because it is almost certainly a // false positive. if (isa<StmtExpr>(E) && Loc.isMacroID()) return; // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers. // That macro is frequently used to suppress "unused parameter" warnings, // but its implementation makes clang's -Wunused-value fire. Prevent this. if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) { SourceLocation SpellLoc = Loc; if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER")) return; } // Okay, we have an unused result. Depending on what the base expression is, // we might want to make a more specific diagnostic. Check for one of these // cases now. unsigned DiagID = diag::warn_unused_expr; if (const FullExpr *Temps = dyn_cast<FullExpr>(E)) E = Temps->getSubExpr(); if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) E = TempExpr->getSubExpr(); if (DiagnoseUnusedComparison(*this, E)) return; E = WarnExpr; if (const auto *Cast = dyn_cast<CastExpr>(E)) if (Cast->getCastKind() == CK_NoOp || Cast->getCastKind() == CK_ConstructorConversion) E = Cast->getSubExpr()->IgnoreImpCasts(); if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { if (E->getType()->isVoidType()) return; if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>( CE->getUnusedResultAttr(Context)), Loc, R1, R2, /*isCtor=*/false)) return; // If the callee has attribute pure, const, or warn_unused_result, warn with // a more specific message to make it clear what is happening. If the call // is written in a macro body, only warn if it has the warn_unused_result // attribute. if (const Decl *FD = CE->getCalleeDecl()) { if (ShouldSuppress) return; if (FD->hasAttr<PureAttr>()) { Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; return; } if (FD->hasAttr<ConstAttr>()) { Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; return; } } } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) { if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { const auto *A = Ctor->getAttr<WarnUnusedResultAttr>(); A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>(); if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true)) return; } } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) { if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) { if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1, R2, /*isCtor=*/false)) return; } } else if (ShouldSuppress) return; E = WarnExpr; if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { Diag(Loc, diag::err_arc_unused_init_message) << R1; return; } const ObjCMethodDecl *MD = ME->getMethodDecl(); if (MD) { if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1, R2, /*isCtor=*/false)) return; } } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { const Expr *Source = POE->getSyntacticForm(); if (isa<ObjCSubscriptRefExpr>(Source)) DiagID = diag::warn_unused_container_subscript_expr; else DiagID = diag::warn_unused_property_expr; } else if (const CXXFunctionalCastExpr *FC = dyn_cast<CXXFunctionalCastExpr>(E)) { const Expr *E = FC->getSubExpr(); if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E)) E = TE->getSubExpr(); if (isa<CXXTemporaryObjectExpr>(E)) return; if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl()) if (!RD->getAttr<WarnUnusedAttr>()) return; } // Diagnose "(void*) blah" as a typo for "(void) blah". else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); QualType T = TI->getType(); // We really do want to use the non-canonical type here. if (T == Context.VoidPtrTy) { PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>(); Diag(Loc, diag::warn_unused_voidptr) << FixItHint::CreateRemoval(TL.getStarLoc()); return; } } // Tell the user to assign it into a variable to force a volatile load if this // isn't an array. if (E->isGLValue() && E->getType().isVolatileQualified() && !E->getType()->isArrayType()) { Diag(Loc, diag::warn_unused_volatile) << R1 << R2; return; } DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2); } void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) { PushCompoundScope(IsStmtExpr); } void Sema::ActOnFinishOfCompoundStmt() { PopCompoundScope(); } sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { return getCurFunction()->CompoundScopes.back(); } StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr) { const unsigned NumElts = Elts.size(); // If we're in C89 mode, check that we don't have any decls after stmts. If // so, emit an extension diagnostic. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) { // Note that __extension__ can be around a decl. unsigned i = 0; // Skip over all declarations. for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) /*empty*/; // We found the end of the list or a statement. Scan for another declstmt. for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) /*empty*/; if (i != NumElts) { Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); Diag(D->getLocation(), diag::ext_mixed_decls_code); } } // Check for suspicious empty body (null statement) in `for' and `while' // statements. Don't do anything for template instantiations, this just adds // noise. if (NumElts != 0 && !CurrentInstantiationScope && getCurCompoundScope().HasEmptyLoopBodies) { for (unsigned i = 0; i != NumElts - 1; ++i) DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); } return CompoundStmt::Create(Context, Elts, L, R); } ExprResult Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) { if (!Val.get()) return Val; if (DiagnoseUnexpandedParameterPack(Val.get())) return ExprError(); // If we're not inside a switch, let the 'case' statement handling diagnose // this. Just clean up after the expression as best we can. if (getCurFunction()->SwitchStack.empty()) return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false, getLangOpts().CPlusPlus11); Expr *CondExpr = getCurFunction()->SwitchStack.back().getPointer()->getCond(); if (!CondExpr) return ExprError(); QualType CondType = CondExpr->getType(); auto CheckAndFinish = [&](Expr *E) { if (CondType->isDependentType() || E->isTypeDependent()) return ExprResult(E); if (getLangOpts().CPlusPlus11) { // C++11 [stmt.switch]p2: the constant-expression shall be a converted // constant expression of the promoted type of the switch condition. llvm::APSInt TempVal; return CheckConvertedConstantExpression(E, CondType, TempVal, CCEK_CaseValue); } ExprResult ER = E; if (!E->isValueDependent()) ER = VerifyIntegerConstantExpression(E); if (!ER.isInvalid()) ER = DefaultLvalueConversion(ER.get()); if (!ER.isInvalid()) ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast); if (!ER.isInvalid()) ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false); return ER; }; ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish); if (Converted.get() == Val.get()) Converted = CheckAndFinish(Val.get()); return Converted; } StmtResult Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal, SourceLocation DotDotDotLoc, ExprResult RHSVal, SourceLocation ColonLoc) { assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value"); assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset() : RHSVal.isInvalid() || RHSVal.get()) && "missing RHS value"); if (getCurFunction()->SwitchStack.empty()) { Diag(CaseLoc, diag::err_case_not_in_switch); return StmtError(); } if (LHSVal.isInvalid() || RHSVal.isInvalid()) { getCurFunction()->SwitchStack.back().setInt(true); return StmtError(); } auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(), CaseLoc, DotDotDotLoc, ColonLoc); getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS); return CS; } /// ActOnCaseStmtBody - This installs a statement as the body of a case. void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) { cast<CaseStmt>(S)->setSubStmt(SubStmt); } StmtResult Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope) { if (getCurFunction()->SwitchStack.empty()) { Diag(DefaultLoc, diag::err_default_not_in_switch); return SubStmt; } DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS); return DS; } StmtResult Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt) { // If the label was multiply defined, reject it now. if (TheDecl->getStmt()) { Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); Diag(TheDecl->getLocation(), diag::note_previous_definition); return SubStmt; } // Otherwise, things are good. Fill in the declaration and return it. LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); TheDecl->setStmt(LS); if (!TheDecl->isGnuLocal()) { TheDecl->setLocStart(IdentLoc); if (!TheDecl->isMSAsmLabel()) { // Don't update the location of MS ASM labels. These will result in // a diagnostic, and changing the location here will mess that up. TheDecl->setLocation(IdentLoc); } } return LS; } StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt) { // Fill in the declaration and return it. AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt); return LS; } namespace { class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> { typedef EvaluatedExprVisitor<CommaVisitor> Inherited; Sema &SemaRef; public: CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {} void VisitBinaryOperator(BinaryOperator *E) { if (E->getOpcode() == BO_Comma) SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc()); EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E); } }; } StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *thenStmt, SourceLocation ElseLoc, Stmt *elseStmt) { if (Cond.isInvalid()) Cond = ConditionResult( *this, nullptr, MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(), Context.BoolTy, VK_RValue), IfLoc), false); Expr *CondExpr = Cond.get().second; // Only call the CommaVisitor when not C89 due to differences in scope flags. if ((getLangOpts().C99 || getLangOpts().CPlusPlus) && !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc())) CommaVisitor(*this).Visit(CondExpr); if (!elseStmt) DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt, diag::warn_empty_if_body); return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc, elseStmt); } StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *thenStmt, SourceLocation ElseLoc, Stmt *elseStmt) { if (Cond.isInvalid()) return StmtError(); if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second)) setFunctionHasBranchProtectedScope(); return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first, Cond.get().second, thenStmt, ElseLoc, elseStmt); } namespace { struct CaseCompareFunctor { bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, const llvm::APSInt &RHS) { return LHS.first < RHS; } bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, const std::pair<llvm::APSInt, CaseStmt*> &RHS) { return LHS.first < RHS.first; } bool operator()(const llvm::APSInt &LHS, const std::pair<llvm::APSInt, CaseStmt*> &RHS) { return LHS < RHS.first; } }; } /// CmpCaseVals - Comparison predicate for sorting case values. /// static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, const std::pair<llvm::APSInt, CaseStmt*>& rhs) { if (lhs.first < rhs.first) return true; if (lhs.first == rhs.first && lhs.second->getCaseLoc().getRawEncoding() < rhs.second->getCaseLoc().getRawEncoding()) return true; return false; } /// CmpEnumVals - Comparison predicate for sorting enumeration values. /// static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) { return lhs.first < rhs.first; } /// EqEnumVals - Comparison preficate for uniqing enumeration values. /// static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) { return lhs.first == rhs.first; } /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of /// potentially integral-promoted expression @p expr. static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) { if (const auto *FE = dyn_cast<FullExpr>(E)) E = FE->getSubExpr(); while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { if (ImpCast->getCastKind() != CK_IntegralCast) break; E = ImpCast->getSubExpr(); } return E->getType(); } ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) { class SwitchConvertDiagnoser : public ICEConvertDiagnoser { Expr *Cond; public: SwitchConvertDiagnoser(Expr *Cond) : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true), Cond(Cond) {} SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T; } SemaDiagnosticBuilder diagnoseIncomplete( Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_switch_incomplete_class_type) << T << Cond->getSourceRange(); } SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy; } SemaDiagnosticBuilder noteExplicitConv( Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_switch_conversion) << ConvTy->isEnumeralType() << ConvTy; } SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override { return S.Diag(Loc, diag::err_switch_multiple_conversions) << T; } SemaDiagnosticBuilder noteAmbiguous( Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_switch_conversion) << ConvTy->isEnumeralType() << ConvTy; } SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { llvm_unreachable("conversion functions are permitted"); } } SwitchDiagnoser(Cond); ExprResult CondResult = PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser); if (CondResult.isInvalid()) return ExprError(); // FIXME: PerformContextualImplicitConversion doesn't always tell us if it // failed and produced a diagnostic. Cond = CondResult.get(); if (!Cond->isTypeDependent() && !Cond->getType()->isIntegralOrEnumerationType()) return ExprError(); // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. return UsualUnaryConversions(Cond); } StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond) { Expr *CondExpr = Cond.get().second; assert((Cond.isInvalid() || CondExpr) && "switch with no condition"); if (CondExpr && !CondExpr->isTypeDependent()) { // We have already converted the expression to an integral or enumeration // type, when we parsed the switch condition. If we don't have an // appropriate type now, enter the switch scope but remember that it's // invalid. assert(CondExpr->getType()->isIntegralOrEnumerationType() && "invalid condition type"); if (CondExpr->isKnownToHaveBooleanValue()) { // switch(bool_expr) {...} is often a programmer error, e.g. // switch(n && mask) { ... } // Doh - should be "n & mask". // One can always use an if statement instead of switch(bool_expr). Diag(SwitchLoc, diag::warn_bool_switch_condition) << CondExpr->getSourceRange(); } } setFunctionHasBranchIntoScope(); auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr); getCurFunction()->SwitchStack.push_back( FunctionScopeInfo::SwitchInfo(SS, false)); return SS; } static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { Val = Val.extOrTrunc(BitWidth); Val.setIsSigned(IsSigned); } /// Check the specified case value is in range for the given unpromoted switch /// type. static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val, unsigned UnpromotedWidth, bool UnpromotedSign) { // In C++11 onwards, this is checked by the language rules. if (S.getLangOpts().CPlusPlus11) return; // If the case value was signed and negative and the switch expression is // unsigned, don't bother to warn: this is implementation-defined behavior. // FIXME: Introduce a second, default-ignored warning for this case? if (UnpromotedWidth < Val.getBitWidth()) { llvm::APSInt ConvVal(Val); AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign); AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned()); // FIXME: Use different diagnostics for overflow in conversion to promoted // type versus "switch expression cannot have this value". Use proper // IntRange checking rather than just looking at the unpromoted type here. if (ConvVal != Val) S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10) << ConvVal.toString(10); } } typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy; /// Returns true if we should emit a diagnostic about this case expression not /// being a part of the enum used in the switch controlling expression. static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S, const EnumDecl *ED, const Expr *CaseExpr, EnumValsTy::iterator &EI, EnumValsTy::iterator &EIEnd, const llvm::APSInt &Val) { if (!ED->isClosed()) return false; if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) { if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { QualType VarType = VD->getType(); QualType EnumType = S.Context.getTypeDeclType(ED); if (VD->hasGlobalStorage() && VarType.isConstQualified() && S.Context.hasSameUnqualifiedType(EnumType, VarType)) return false; } } if (ED->hasAttr<FlagEnumAttr>()) return !S.IsValueInFlagEnum(ED, Val, false); while (EI != EIEnd && EI->first < Val) EI++; if (EI != EIEnd && EI->first == Val) return false; return true; } static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond, const Expr *Case) { QualType CondType = Cond->getType(); QualType CaseType = Case->getType(); const EnumType *CondEnumType = CondType->getAs<EnumType>(); const EnumType *CaseEnumType = CaseType->getAs<EnumType>(); if (!CondEnumType || !CaseEnumType) return; // Ignore anonymous enums. if (!CondEnumType->getDecl()->getIdentifier() && !CondEnumType->getDecl()->getTypedefNameForAnonDecl()) return; if (!CaseEnumType->getDecl()->getIdentifier() && !CaseEnumType->getDecl()->getTypedefNameForAnonDecl()) return; if (S.Context.hasSameUnqualifiedType(CondType, CaseType)) return; S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch) << CondType << CaseType << Cond->getSourceRange() << Case->getSourceRange(); } StmtResult Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *BodyStmt) { SwitchStmt *SS = cast<SwitchStmt>(Switch); bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt(); assert(SS == getCurFunction()->SwitchStack.back().getPointer() && "switch stack missing push/pop!"); getCurFunction()->SwitchStack.pop_back(); if (!BodyStmt) return StmtError(); SS->setBody(BodyStmt, SwitchLoc); Expr *CondExpr = SS->getCond(); if (!CondExpr) return StmtError(); QualType CondType = CondExpr->getType(); // C++ 6.4.2.p2: // Integral promotions are performed (on the switch condition). // // A case value unrepresentable by the original switch condition // type (before the promotion) doesn't make sense, even when it can // be represented by the promoted type. Therefore we need to find // the pre-promotion type of the switch condition. const Expr *CondExprBeforePromotion = CondExpr; QualType CondTypeBeforePromotion = GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); // Get the bitwidth of the switched-on value after promotions. We must // convert the integer case values to this width before comparison. bool HasDependentValue = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType); bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType(); // Get the width and signedness that the condition might actually have, for // warning purposes. // FIXME: Grab an IntRange for the condition rather than using the unpromoted // type. unsigned CondWidthBeforePromotion = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); bool CondIsSignedBeforePromotion = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); // Accumulate all of the case values in a vector so that we can sort them // and detect duplicates. This vector contains the APInt for the case after // it has been converted to the condition type. typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; CaseValsTy CaseVals; // Keep track of any GNU case ranges we see. The APSInt is the low value. typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; CaseRangesTy CaseRanges; DefaultStmt *TheDefaultStmt = nullptr; bool CaseListIsErroneous = false; for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; SC = SC->getNextSwitchCase()) { if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { if (TheDefaultStmt) { Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); // FIXME: Remove the default statement from the switch block so that // we'll return a valid AST. This requires recursing down the AST and // finding it, not something we are set up to do right now. For now, // just lop the entire switch stmt out of the AST. CaseListIsErroneous = true; } TheDefaultStmt = DS; } else { CaseStmt *CS = cast<CaseStmt>(SC); Expr *Lo = CS->getLHS(); if (Lo->isValueDependent()) { HasDependentValue = true; break; } // We already verified that the expression has a constant value; // get that value (prior to conversions). const Expr *LoBeforePromotion = Lo; GetTypeBeforeIntegralPromotion(LoBeforePromotion); llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context); // Check the unconverted value is within the range of possible values of // the switch expression. checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion, CondIsSignedBeforePromotion); // FIXME: This duplicates the check performed for warn_not_in_enum below. checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion, LoBeforePromotion); // Convert the value to the same width/sign as the condition. AdjustAPSInt(LoVal, CondWidth, CondIsSigned); // If this is a case range, remember it in CaseRanges, otherwise CaseVals. if (CS->getRHS()) { if (CS->getRHS()->isValueDependent()) { HasDependentValue = true; break; } CaseRanges.push_back(std::make_pair(LoVal, CS)); } else CaseVals.push_back(std::make_pair(LoVal, CS)); } } if (!HasDependentValue) { // If we don't have a default statement, check whether the // condition is constant. llvm::APSInt ConstantCondValue; bool HasConstantCond = false; if (!TheDefaultStmt) { Expr::EvalResult Result; HasConstantCond = CondExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects); if (Result.Val.isInt()) ConstantCondValue = Result.Val.getInt(); assert(!HasConstantCond || (ConstantCondValue.getBitWidth() == CondWidth && ConstantCondValue.isSigned() == CondIsSigned)); } bool ShouldCheckConstantCond = HasConstantCond; // Sort all the scalar case values so we can easily detect duplicates. llvm::stable_sort(CaseVals, CmpCaseVals); if (!CaseVals.empty()) { for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { if (ShouldCheckConstantCond && CaseVals[i].first == ConstantCondValue) ShouldCheckConstantCond = false; if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { // If we have a duplicate, report it. // First, determine if either case value has a name StringRef PrevString, CurrString; Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts(); Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts(); if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) { PrevString = DeclRef->getDecl()->getName(); } if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) { CurrString = DeclRef->getDecl()->getName(); } SmallString<16> CaseValStr; CaseVals[i-1].first.toString(CaseValStr); if (PrevString == CurrString) Diag(CaseVals[i].second->getLHS()->getBeginLoc(), diag::err_duplicate_case) << (PrevString.empty() ? StringRef(CaseValStr) : PrevString); else Diag(CaseVals[i].second->getLHS()->getBeginLoc(), diag::err_duplicate_case_differing_expr) << (PrevString.empty() ? StringRef(CaseValStr) : PrevString) << (CurrString.empty() ? StringRef(CaseValStr) : CurrString) << CaseValStr; Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(), diag::note_duplicate_case_prev); // FIXME: We really want to remove the bogus case stmt from the // substmt, but we have no way to do this right now. CaseListIsErroneous = true; } } } // Detect duplicate case ranges, which usually don't exist at all in // the first place. if (!CaseRanges.empty()) { // Sort all the case ranges by their low value so we can easily detect // overlaps between ranges. llvm::stable_sort(CaseRanges); // Scan the ranges, computing the high values and removing empty ranges. std::vector<llvm::APSInt> HiVals; for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { llvm::APSInt &LoVal = CaseRanges[i].first; CaseStmt *CR = CaseRanges[i].second; Expr *Hi = CR->getRHS(); const Expr *HiBeforePromotion = Hi; GetTypeBeforeIntegralPromotion(HiBeforePromotion); llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context); // Check the unconverted value is within the range of possible values of // the switch expression. checkCaseValue(*this, Hi->getBeginLoc(), HiVal, CondWidthBeforePromotion, CondIsSignedBeforePromotion); // Convert the value to the same width/sign as the condition. AdjustAPSInt(HiVal, CondWidth, CondIsSigned); // If the low value is bigger than the high value, the case is empty. if (LoVal > HiVal) { Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range) << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc()); CaseRanges.erase(CaseRanges.begin()+i); --i; --e; continue; } if (ShouldCheckConstantCond && LoVal <= ConstantCondValue && ConstantCondValue <= HiVal) ShouldCheckConstantCond = false; HiVals.push_back(HiVal); } // Rescan the ranges, looking for overlap with singleton values and other // ranges. Since the range list is sorted, we only need to compare case // ranges with their neighbors. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { llvm::APSInt &CRLo = CaseRanges[i].first; llvm::APSInt &CRHi = HiVals[i]; CaseStmt *CR = CaseRanges[i].second; // Check to see whether the case range overlaps with any // singleton cases. CaseStmt *OverlapStmt = nullptr; llvm::APSInt OverlapVal(32); // Find the smallest value >= the lower bound. If I is in the // case range, then we have overlap. CaseValsTy::iterator I = llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor()); if (I != CaseVals.end() && I->first < CRHi) { OverlapVal = I->first; // Found overlap with scalar. OverlapStmt = I->second; } // Find the smallest value bigger than the upper bound. I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); if (I != CaseVals.begin() && (I-1)->first >= CRLo) { OverlapVal = (I-1)->first; // Found overlap with scalar. OverlapStmt = (I-1)->second; } // Check to see if this case stmt overlaps with the subsequent // case range. if (i && CRLo <= HiVals[i-1]) { OverlapVal = HiVals[i-1]; // Found overlap with range. OverlapStmt = CaseRanges[i-1].second; } if (OverlapStmt) { // If we have a duplicate, report it. Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case) << OverlapVal.toString(10); Diag(OverlapStmt->getLHS()->getBeginLoc(), diag::note_duplicate_case_prev); // FIXME: We really want to remove the bogus case stmt from the // substmt, but we have no way to do this right now. CaseListIsErroneous = true; } } } // Complain if we have a constant condition and we didn't find a match. if (!CaseListIsErroneous && !CaseListIsIncomplete && ShouldCheckConstantCond) { // TODO: it would be nice if we printed enums as enums, chars as // chars, etc. Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) << ConstantCondValue.toString(10) << CondExpr->getSourceRange(); } // Check to see if switch is over an Enum and handles all of its // values. We only issue a warning if there is not 'default:', but // we still do the analysis to preserve this information in the AST // (which can be used by flow-based analyes). // const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); // If switch has default case, then ignore it. if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond && ET && ET->getDecl()->isCompleteDefinition()) { const EnumDecl *ED = ET->getDecl(); EnumValsTy EnumVals; // Gather all enum values, set their type and sort them, // allowing easier comparison with CaseVals. for (auto *EDI : ED->enumerators()) { llvm::APSInt Val = EDI->getInitVal(); AdjustAPSInt(Val, CondWidth, CondIsSigned); EnumVals.push_back(std::make_pair(Val, EDI)); } llvm::stable_sort(EnumVals, CmpEnumVals); auto EI = EnumVals.begin(), EIEnd = std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); // See which case values aren't in enum. for (CaseValsTy::const_iterator CI = CaseVals.begin(); CI != CaseVals.end(); CI++) { Expr *CaseExpr = CI->second->getLHS(); if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, CI->first)) Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) << CondTypeBeforePromotion; } // See which of case ranges aren't in enum EI = EnumVals.begin(); for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); RI != CaseRanges.end(); RI++) { Expr *CaseExpr = RI->second->getLHS(); if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, RI->first)) Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) << CondTypeBeforePromotion; llvm::APSInt Hi = RI->second->getRHS()->EvaluateKnownConstInt(Context); AdjustAPSInt(Hi, CondWidth, CondIsSigned); CaseExpr = RI->second->getRHS(); if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, Hi)) Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) << CondTypeBeforePromotion; } // Check which enum vals aren't in switch auto CI = CaseVals.begin(); auto RI = CaseRanges.begin(); bool hasCasesNotInSwitch = false; SmallVector<DeclarationName,8> UnhandledNames; for (EI = EnumVals.begin(); EI != EIEnd; EI++) { // Don't warn about omitted unavailable EnumConstantDecls. switch (EI->second->getAvailability()) { case AR_Deprecated: // Omitting a deprecated constant is ok; it should never materialize. case AR_Unavailable: continue; case AR_NotYetIntroduced: // Partially available enum constants should be present. Note that we // suppress -Wunguarded-availability diagnostics for such uses. case AR_Available: break; } if (EI->second->hasAttr<UnusedAttr>()) continue; // Drop unneeded case values while (CI != CaseVals.end() && CI->first < EI->first) CI++; if (CI != CaseVals.end() && CI->first == EI->first) continue; // Drop unneeded case ranges for (; RI != CaseRanges.end(); RI++) { llvm::APSInt Hi = RI->second->getRHS()->EvaluateKnownConstInt(Context); AdjustAPSInt(Hi, CondWidth, CondIsSigned); if (EI->first <= Hi) break; } if (RI == CaseRanges.end() || EI->first < RI->first) { hasCasesNotInSwitch = true; UnhandledNames.push_back(EI->second->getDeclName()); } } if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag()) Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); // Produce a nice diagnostic if multiple values aren't handled. if (!UnhandledNames.empty()) { { DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt ? diag::warn_def_missing_case : diag::warn_missing_case) << (int)UnhandledNames.size(); for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3); I != E; ++I) DB << UnhandledNames[I]; } auto DB = Diag(CondExpr->getExprLoc(), diag::note_fill_in_missing_cases); edit::fillInMissingSwitchEnumCases( Context, SS, ED, CurContext, [&](const FixItHint &Hint) { DB << Hint; }); } if (!hasCasesNotInSwitch) SS->setAllEnumCasesCovered(); } } if (BodyStmt) DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt, diag::warn_empty_switch_body); // FIXME: If the case list was broken is some way, we don't have a good system // to patch it up. Instead, just return the whole substmt as broken. if (CaseListIsErroneous) return StmtError(); return SS; } void Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr) { if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc())) return; if (const EnumType *ET = DstType->getAs<EnumType>()) if (!Context.hasSameUnqualifiedType(SrcType, DstType) && SrcType->isIntegerType()) { if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() && SrcExpr->isIntegerConstantExpr(Context)) { // Get the bitwidth of the enum value before promotions. unsigned DstWidth = Context.getIntWidth(DstType); bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType(); llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context); AdjustAPSInt(RhsVal, DstWidth, DstIsSigned); const EnumDecl *ED = ET->getDecl(); if (!ED->isClosed()) return; if (ED->hasAttr<FlagEnumAttr>()) { if (!IsValueInFlagEnum(ED, RhsVal, true)) Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) << DstType.getUnqualifiedType(); } else { typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64> EnumValsTy; EnumValsTy EnumVals; // Gather all enum values, set their type and sort them, // allowing easier comparison with rhs constant. for (auto *EDI : ED->enumerators()) { llvm::APSInt Val = EDI->getInitVal(); AdjustAPSInt(Val, DstWidth, DstIsSigned); EnumVals.push_back(std::make_pair(Val, EDI)); } if (EnumVals.empty()) return; llvm::stable_sort(EnumVals, CmpEnumVals); EnumValsTy::iterator EIend = std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); // See which values aren't in the enum. EnumValsTy::const_iterator EI = EnumVals.begin(); while (EI != EIend && EI->first < RhsVal) EI++; if (EI == EIend || EI->first != RhsVal) { Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) << DstType.getUnqualifiedType(); } } } } } StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body) { if (Cond.isInvalid()) return StmtError(); auto CondVal = Cond.get(); CheckBreakContinueBinding(CondVal.second); if (CondVal.second && !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc())) CommaVisitor(*this).Visit(CondVal.second); if (isa<NullStmt>(Body)) getCurCompoundScope().setHasEmptyLoopBodies(); return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body, WhileLoc); } StmtResult Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen) { assert(Cond && "ActOnDoStmt(): missing expression"); CheckBreakContinueBinding(Cond); ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond); if (CondResult.isInvalid()) return StmtError(); Cond = CondResult.get(); CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false); if (CondResult.isInvalid()) return StmtError(); Cond = CondResult.get(); // Only call the CommaVisitor for C89 due to differences in scope flags. if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus && !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc())) CommaVisitor(*this).Visit(Cond); return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen); } namespace { // Use SetVector since the diagnostic cares about the ordering of the Decl's. using DeclSetVector = llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>, llvm::SmallPtrSet<VarDecl *, 8>>; // This visitor will traverse a conditional statement and store all // the evaluated decls into a vector. Simple is set to true if none // of the excluded constructs are used. class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> { DeclSetVector &Decls; SmallVectorImpl<SourceRange> &Ranges; bool Simple; public: typedef EvaluatedExprVisitor<DeclExtractor> Inherited; DeclExtractor(Sema &S, DeclSetVector &Decls, SmallVectorImpl<SourceRange> &Ranges) : Inherited(S.Context), Decls(Decls), Ranges(Ranges), Simple(true) {} bool isSimple() { return Simple; } // Replaces the method in EvaluatedExprVisitor. void VisitMemberExpr(MemberExpr* E) { Simple = false; } // Any Stmt not whitelisted will cause the condition to be marked complex. void VisitStmt(Stmt *S) { Simple = false; } void VisitBinaryOperator(BinaryOperator *E) { Visit(E->getLHS()); Visit(E->getRHS()); } void VisitCastExpr(CastExpr *E) { Visit(E->getSubExpr()); } void VisitUnaryOperator(UnaryOperator *E) { // Skip checking conditionals with derefernces. if (E->getOpcode() == UO_Deref) Simple = false; else Visit(E->getSubExpr()); } void VisitConditionalOperator(ConditionalOperator *E) { Visit(E->getCond()); Visit(E->getTrueExpr()); Visit(E->getFalseExpr()); } void VisitParenExpr(ParenExpr *E) { Visit(E->getSubExpr()); } void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { Visit(E->getOpaqueValue()->getSourceExpr()); Visit(E->getFalseExpr()); } void VisitIntegerLiteral(IntegerLiteral *E) { } void VisitFloatingLiteral(FloatingLiteral *E) { } void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { } void VisitCharacterLiteral(CharacterLiteral *E) { } void VisitGNUNullExpr(GNUNullExpr *E) { } void VisitImaginaryLiteral(ImaginaryLiteral *E) { } void VisitDeclRefExpr(DeclRefExpr *E) { VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); if (!VD) { // Don't allow unhandled Decl types. Simple = false; return; } Ranges.push_back(E->getSourceRange()); Decls.insert(VD); } }; // end class DeclExtractor // DeclMatcher checks to see if the decls are used in a non-evaluated // context. class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> { DeclSetVector &Decls; bool FoundDecl; public: typedef EvaluatedExprVisitor<DeclMatcher> Inherited; DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) : Inherited(S.Context), Decls(Decls), FoundDecl(false) { if (!Statement) return; Visit(Statement); } void VisitReturnStmt(ReturnStmt *S) { FoundDecl = true; } void VisitBreakStmt(BreakStmt *S) { FoundDecl = true; } void VisitGotoStmt(GotoStmt *S) { FoundDecl = true; } void VisitCastExpr(CastExpr *E) { if (E->getCastKind() == CK_LValueToRValue) CheckLValueToRValueCast(E->getSubExpr()); else Visit(E->getSubExpr()); } void CheckLValueToRValueCast(Expr *E) { E = E->IgnoreParenImpCasts(); if (isa<DeclRefExpr>(E)) { return; } if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { Visit(CO->getCond()); CheckLValueToRValueCast(CO->getTrueExpr()); CheckLValueToRValueCast(CO->getFalseExpr()); return; } if (BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(E)) { CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr()); CheckLValueToRValueCast(BCO->getFalseExpr()); return; } Visit(E); } void VisitDeclRefExpr(DeclRefExpr *E) { if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) if (Decls.count(VD)) FoundDecl = true; } void VisitPseudoObjectExpr(PseudoObjectExpr *POE) { // Only need to visit the semantics for POE. // SyntaticForm doesn't really use the Decal. for (auto *S : POE->semantics()) { if (auto *OVE = dyn_cast<OpaqueValueExpr>(S)) // Look past the OVE into the expression it binds. Visit(OVE->getSourceExpr()); else Visit(S); } } bool FoundDeclInUse() { return FoundDecl; } }; // end class DeclMatcher void CheckForLoopConditionalStatement(Sema &S, Expr *Second, Expr *Third, Stmt *Body) { // Condition is empty if (!Second) return; if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body, Second->getBeginLoc())) return; PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body); DeclSetVector Decls; SmallVector<SourceRange, 10> Ranges; DeclExtractor DE(S, Decls, Ranges); DE.Visit(Second); // Don't analyze complex conditionals. if (!DE.isSimple()) return; // No decls found. if (Decls.size() == 0) return; // Don't warn on volatile, static, or global variables. for (auto *VD : Decls) if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage()) return; if (DeclMatcher(S, Decls, Second).FoundDeclInUse() || DeclMatcher(S, Decls, Third).FoundDeclInUse() || DeclMatcher(S, Decls, Body).FoundDeclInUse()) return; // Load decl names into diagnostic. if (Decls.size() > 4) { PDiag << 0; } else { PDiag << (unsigned)Decls.size(); for (auto *VD : Decls) PDiag << VD->getDeclName(); } for (auto Range : Ranges) PDiag << Range; S.Diag(Ranges.begin()->getBegin(), PDiag); } // If Statement is an incemement or decrement, return true and sets the // variables Increment and DRE. bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment, DeclRefExpr *&DRE) { if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement)) if (!Cleanups->cleanupsHaveSideEffects()) Statement = Cleanups->getSubExpr(); if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) { switch (UO->getOpcode()) { default: return false; case UO_PostInc: case UO_PreInc: Increment = true; break; case UO_PostDec: case UO_PreDec: Increment = false; break; } DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()); return DRE; } if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) { FunctionDecl *FD = Call->getDirectCallee(); if (!FD || !FD->isOverloadedOperator()) return false; switch (FD->getOverloadedOperator()) { default: return false; case OO_PlusPlus: Increment = true; break; case OO_MinusMinus: Increment = false; break; } DRE = dyn_cast<DeclRefExpr>(Call->getArg(0)); return DRE; } return false; } // A visitor to determine if a continue or break statement is a // subexpression. class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> { SourceLocation BreakLoc; SourceLocation ContinueLoc; bool InSwitch = false; public: BreakContinueFinder(Sema &S, const Stmt* Body) : Inherited(S.Context) { Visit(Body); } typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited; void VisitContinueStmt(const ContinueStmt* E) { ContinueLoc = E->getContinueLoc(); } void VisitBreakStmt(const BreakStmt* E) { if (!InSwitch) BreakLoc = E->getBreakLoc(); } void VisitSwitchStmt(const SwitchStmt* S) { if (const Stmt *Init = S->getInit()) Visit(Init); if (const Stmt *CondVar = S->getConditionVariableDeclStmt()) Visit(CondVar); if (const Stmt *Cond = S->getCond()) Visit(Cond); // Don't return break statements from the body of a switch. InSwitch = true; if (const Stmt *Body = S->getBody()) Visit(Body); InSwitch = false; } void VisitForStmt(const ForStmt *S) { // Only visit the init statement of a for loop; the body // has a different break/continue scope. if (const Stmt *Init = S->getInit()) Visit(Init); } void VisitWhileStmt(const WhileStmt *) { // Do nothing; the children of a while loop have a different // break/continue scope. } void VisitDoStmt(const DoStmt *) { // Do nothing; the children of a while loop have a different // break/continue scope. } void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { // Only visit the initialization of a for loop; the body // has a different break/continue scope. if (const Stmt *Init = S->getInit()) Visit(Init); if (const Stmt *Range = S->getRangeStmt()) Visit(Range); if (const Stmt *Begin = S->getBeginStmt()) Visit(Begin); if (const Stmt *End = S->getEndStmt()) Visit(End); } void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { // Only visit the initialization of a for loop; the body // has a different break/continue scope. if (const Stmt *Element = S->getElement()) Visit(Element); if (const Stmt *Collection = S->getCollection()) Visit(Collection); } bool ContinueFound() { return ContinueLoc.isValid(); } bool BreakFound() { return BreakLoc.isValid(); } SourceLocation GetContinueLoc() { return ContinueLoc; } SourceLocation GetBreakLoc() { return BreakLoc; } }; // end class BreakContinueFinder // Emit a warning when a loop increment/decrement appears twice per loop // iteration. The conditions which trigger this warning are: // 1) The last statement in the loop body and the third expression in the // for loop are both increment or both decrement of the same variable // 2) No continue statements in the loop body. void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) { // Return when there is nothing to check. if (!Body || !Third) return; if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration, Third->getBeginLoc())) return; // Get the last statement from the loop body. CompoundStmt *CS = dyn_cast<CompoundStmt>(Body); if (!CS || CS->body_empty()) return; Stmt *LastStmt = CS->body_back(); if (!LastStmt) return; bool LoopIncrement, LastIncrement; DeclRefExpr *LoopDRE, *LastDRE; if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return; if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return; // Check that the two statements are both increments or both decrements // on the same variable. if (LoopIncrement != LastIncrement || LoopDRE->getDecl() != LastDRE->getDecl()) return; if (BreakContinueFinder(S, Body).ContinueFound()) return; S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration) << LastDRE->getDecl() << LastIncrement; S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here) << LoopIncrement; } } // end namespace void Sema::CheckBreakContinueBinding(Expr *E) { if (!E || getLangOpts().CPlusPlus) return; BreakContinueFinder BCFinder(*this, E); Scope *BreakParent = CurScope->getBreakParent(); if (BCFinder.BreakFound() && BreakParent) { if (BreakParent->getFlags() & Scope::SwitchScope) { Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch); } else { Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner) << "break"; } } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) { Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner) << "continue"; } } StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg third, SourceLocation RParenLoc, Stmt *Body) { if (Second.isInvalid()) return StmtError(); if (!getLangOpts().CPlusPlus) { if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { // C99 6.8.5p3: The declaration part of a 'for' statement shall only // declare identifiers for objects having storage class 'auto' or // 'register'. for (auto *DI : DS->decls()) { VarDecl *VD = dyn_cast<VarDecl>(DI); if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) VD = nullptr; if (!VD) { Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for); DI->setInvalidDecl(); } } } } CheckBreakContinueBinding(Second.get().second); CheckBreakContinueBinding(third.get()); if (!Second.get().first) CheckForLoopConditionalStatement(*this, Second.get().second, third.get(), Body); CheckForRedundantIteration(*this, third.get(), Body); if (Second.get().second && !Diags.isIgnored(diag::warn_comma_operator, Second.get().second->getExprLoc())) CommaVisitor(*this).Visit(Second.get().second); Expr *Third = third.release().getAs<Expr>(); if (isa<NullStmt>(Body)) getCurCompoundScope().setHasEmptyLoopBodies(); return new (Context) ForStmt(Context, First, Second.get().second, Second.get().first, Third, Body, ForLoc, LParenLoc, RParenLoc); } /// In an Objective C collection iteration statement: /// for (x in y) /// x can be an arbitrary l-value expression. Bind it up as a /// full-expression. StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { // Reduce placeholder expressions here. Note that this rejects the // use of pseudo-object l-values in this position. ExprResult result = CheckPlaceholderExpr(E); if (result.isInvalid()) return StmtError(); E = result.get(); ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false); if (FullExpr.isInvalid()) return StmtError(); return StmtResult(static_cast<Stmt*>(FullExpr.get())); } ExprResult Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { if (!collection) return ExprError(); ExprResult result = CorrectDelayedTyposInExpr(collection); if (!result.isUsable()) return ExprError(); collection = result.get(); // Bail out early if we've got a type-dependent expression. if (collection->isTypeDependent()) return collection; // Perform normal l-value conversion. result = DefaultFunctionArrayLvalueConversion(collection); if (result.isInvalid()) return ExprError(); collection = result.get(); // The operand needs to have object-pointer type. // TODO: should we do a contextual conversion? const ObjCObjectPointerType *pointerType = collection->getType()->getAs<ObjCObjectPointerType>(); if (!pointerType) return Diag(forLoc, diag::err_collection_expr_type) << collection->getType() << collection->getSourceRange(); // Check that the operand provides // - countByEnumeratingWithState:objects:count: const ObjCObjectType *objectType = pointerType->getObjectType(); ObjCInterfaceDecl *iface = objectType->getInterface(); // If we have a forward-declared type, we can't do this check. // Under ARC, it is an error not to have a forward-declared class. if (iface && (getLangOpts().ObjCAutoRefCount ? RequireCompleteType(forLoc, QualType(objectType, 0), diag::err_arc_collection_forward, collection) : !isCompleteType(forLoc, QualType(objectType, 0)))) { // Otherwise, if we have any useful type information, check that // the type declares the appropriate method. } else if (iface || !objectType->qual_empty()) { IdentifierInfo *selectorIdents[] = { &Context.Idents.get("countByEnumeratingWithState"), &Context.Idents.get("objects"), &Context.Idents.get("count") }; Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); ObjCMethodDecl *method = nullptr; // If there's an interface, look in both the public and private APIs. if (iface) { method = iface->lookupInstanceMethod(selector); if (!method) method = iface->lookupPrivateMethod(selector); } // Also check protocol qualifiers. if (!method) method = LookupMethodInQualifiedType(selector, pointerType, /*instance*/ true); // If we didn't find it anywhere, give up. if (!method) { Diag(forLoc, diag::warn_collection_expr_type) << collection->getType() << selector << collection->getSourceRange(); } // TODO: check for an incompatible signature? } // Wrap up any cleanups in the expression. return collection; } StmtResult Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc) { setFunctionHasBranchProtectedScope(); ExprResult CollectionExprResult = CheckObjCForCollectionOperand(ForLoc, collection); if (First) { QualType FirstType; if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { if (!DS->isSingleDecl()) return StmtError(Diag((*DS->decl_begin())->getLocation(), diag::err_toomany_element_decls)); VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl()); if (!D || D->isInvalidDecl()) return StmtError(); FirstType = D->getType(); // C99 6.8.5p3: The declaration part of a 'for' statement shall only // declare identifiers for objects having storage class 'auto' or // 'register'. if (!D->hasLocalStorage()) return StmtError(Diag(D->getLocation(), diag::err_non_local_variable_decl_in_for)); // If the type contained 'auto', deduce the 'auto' to 'id'. if (FirstType->getContainedAutoType()) { OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(), VK_RValue); Expr *DeducedInit = &OpaqueId; if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) == DAR_Failed) DiagnoseAutoDeductionFailure(D, DeducedInit); if (FirstType.isNull()) { D->setInvalidDecl(); return StmtError(); } D->setType(FirstType); if (!inTemplateInstantiation()) { SourceLocation Loc = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); Diag(Loc, diag::warn_auto_var_is_id) << D->getDeclName(); } } } else { Expr *FirstE = cast<Expr>(First); if (!FirstE->isTypeDependent() && !FirstE->isLValue()) return StmtError( Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue) << First->getSourceRange()); FirstType = static_cast<Expr*>(First)->getType(); if (FirstType.isConstQualified()) Diag(ForLoc, diag::err_selector_element_const_type) << FirstType << First->getSourceRange(); } if (!FirstType->isDependentType() && !FirstType->isObjCObjectPointerType() && !FirstType->isBlockPointerType()) return StmtError(Diag(ForLoc, diag::err_selector_element_type) << FirstType << First->getSourceRange()); } if (CollectionExprResult.isInvalid()) return StmtError(); CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false); if (CollectionExprResult.isInvalid()) return StmtError(); return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(), nullptr, ForLoc, RParenLoc); } /// Finish building a variable declaration for a for-range statement. /// \return true if an error occurs. static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, SourceLocation Loc, int DiagID) { if (Decl->getType()->isUndeducedType()) { ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init); if (!Res.isUsable()) { Decl->setInvalidDecl(); return true; } Init = Res.get(); } // Deduce the type for the iterator variable now rather than leaving it to // AddInitializerToDecl, so we can produce a more suitable diagnostic. QualType InitType; if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) || SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) == Sema::DAR_Failed) SemaRef.Diag(Loc, DiagID) << Init->getType(); if (InitType.isNull()) { Decl->setInvalidDecl(); return true; } Decl->setType(InitType); // In ARC, infer lifetime. // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if // we're doing the equivalent of fast iteration. if (SemaRef.getLangOpts().ObjCAutoRefCount && SemaRef.inferObjCARCLifetime(Decl)) Decl->setInvalidDecl(); SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false); SemaRef.FinalizeDeclaration(Decl); SemaRef.CurContext->addHiddenDecl(Decl); return false; } namespace { // An enum to represent whether something is dealing with a call to begin() // or a call to end() in a range-based for loop. enum BeginEndFunction { BEF_begin, BEF_end }; /// Produce a note indicating which begin/end function was implicitly called /// by a C++11 for-range statement. This is often not obvious from the code, /// nor from the diagnostics produced when analysing the implicit expressions /// required in a for-range statement. void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, BeginEndFunction BEF) { CallExpr *CE = dyn_cast<CallExpr>(E); if (!CE) return; FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); if (!D) return; SourceLocation Loc = D->getLocation(); std::string Description; bool IsTemplate = false; if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { Description = SemaRef.getTemplateArgumentBindingsText( FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); IsTemplate = true; } SemaRef.Diag(Loc, diag::note_for_range_begin_end) << BEF << IsTemplate << Description << E->getType(); } /// Build a variable declaration for a for-range statement. VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, StringRef Name) { DeclContext *DC = SemaRef.CurContext; IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); Decl->setImplicit(); return Decl; } } static bool ObjCEnumerationCollection(Expr *Collection) { return !Collection->isTypeDependent() && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr; } /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. /// /// C++11 [stmt.ranged]: /// A range-based for statement is equivalent to /// /// { /// auto && __range = range-init; /// for ( auto __begin = begin-expr, /// __end = end-expr; /// __begin != __end; /// ++__begin ) { /// for-range-declaration = *__begin; /// statement /// } /// } /// /// The body of the loop is not available yet, since it cannot be analysed until /// we have determined the type of the for-range-declaration. StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc, BuildForRangeKind Kind) { if (!First) return StmtError(); if (Range && ObjCEnumerationCollection(Range)) { // FIXME: Support init-statements in Objective-C++20 ranged for statement. if (InitStmt) return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt) << InitStmt->getSourceRange(); return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc); } DeclStmt *DS = dyn_cast<DeclStmt>(First); assert(DS && "first part of for range not a decl stmt"); if (!DS->isSingleDecl()) { Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range); return StmtError(); } Decl *LoopVar = DS->getSingleDecl(); if (LoopVar->isInvalidDecl() || !Range || DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) { LoopVar->setInvalidDecl(); return StmtError(); } // Build the coroutine state immediately and not later during template // instantiation if (!CoawaitLoc.isInvalid()) { if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) return StmtError(); } // Build auto && __range = range-init // Divide by 2, since the variables are in the inner scope (loop body). const auto DepthStr = std::to_string(S->getDepth() / 2); SourceLocation RangeLoc = Range->getBeginLoc(); VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, Context.getAutoRRefDeductType(), std::string("__range") + DepthStr); if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, diag::err_for_range_deduction_failure)) { LoopVar->setInvalidDecl(); return StmtError(); } // Claim the type doesn't contain auto: we've already done the checking. DeclGroupPtrTy RangeGroup = BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1)); StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); if (RangeDecl.isInvalid()) { LoopVar->setInvalidDecl(); return StmtError(); } return BuildCXXForRangeStmt( ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(), /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr, /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind); } /// Create the initialization, compare, and increment steps for /// the range-based for loop expression. /// This function does not handle array-based for loops, /// which are created in Sema::BuildCXXForRangeStmt. /// /// \returns a ForRangeStatus indicating success or what kind of error occurred. /// BeginExpr and EndExpr are set and FRS_Success is returned on success; /// CandidateSet and BEF are set and some non-success value is returned on /// failure. static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange, QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar, SourceLocation ColonLoc, SourceLocation CoawaitLoc, OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr, ExprResult *EndExpr, BeginEndFunction *BEF) { DeclarationNameInfo BeginNameInfo( &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc); DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"), ColonLoc); LookupResult BeginMemberLookup(SemaRef, BeginNameInfo, Sema::LookupMemberName); LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName); auto BuildBegin = [&] { *BEF = BEF_begin; Sema::ForRangeStatus RangeStatus = SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo, BeginMemberLookup, CandidateSet, BeginRange, BeginExpr); if (RangeStatus != Sema::FRS_Success) { if (RangeStatus == Sema::FRS_DiagnosticIssued) SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range) << ColonLoc << BEF_begin << BeginRange->getType(); return RangeStatus; } if (!CoawaitLoc.isInvalid()) { // FIXME: getCurScope() should not be used during template instantiation. // We should pick up the set of unqualified lookup results for operator // co_await during the initial parse. *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc, BeginExpr->get()); if (BeginExpr->isInvalid()) return Sema::FRS_DiagnosticIssued; } if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF); return Sema::FRS_DiagnosticIssued; } return Sema::FRS_Success; }; auto BuildEnd = [&] { *BEF = BEF_end; Sema::ForRangeStatus RangeStatus = SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo, EndMemberLookup, CandidateSet, EndRange, EndExpr); if (RangeStatus != Sema::FRS_Success) { if (RangeStatus == Sema::FRS_DiagnosticIssued) SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range) << ColonLoc << BEF_end << EndRange->getType(); return RangeStatus; } if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF); return Sema::FRS_DiagnosticIssued; } return Sema::FRS_Success; }; if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { // - if _RangeT is a class type, the unqualified-ids begin and end are // looked up in the scope of class _RangeT as if by class member access // lookup (3.4.5), and if either (or both) finds at least one // declaration, begin-expr and end-expr are __range.begin() and // __range.end(), respectively; SemaRef.LookupQualifiedName(BeginMemberLookup, D); if (BeginMemberLookup.isAmbiguous()) return Sema::FRS_DiagnosticIssued; SemaRef.LookupQualifiedName(EndMemberLookup, D); if (EndMemberLookup.isAmbiguous()) return Sema::FRS_DiagnosticIssued; if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { // Look up the non-member form of the member we didn't find, first. // This way we prefer a "no viable 'end'" diagnostic over a "i found // a 'begin' but ignored it because there was no member 'end'" // diagnostic. auto BuildNonmember = [&]( BeginEndFunction BEFFound, LookupResult &Found, llvm::function_ref<Sema::ForRangeStatus()> BuildFound, llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) { LookupResult OldFound = std::move(Found); Found.clear(); if (Sema::ForRangeStatus Result = BuildNotFound()) return Result; switch (BuildFound()) { case Sema::FRS_Success: return Sema::FRS_Success; case Sema::FRS_NoViableFunction: CandidateSet->NoteCandidates( PartialDiagnosticAt(BeginRange->getBeginLoc(), SemaRef.PDiag(diag::err_for_range_invalid) << BeginRange->getType() << BEFFound), SemaRef, OCD_AllCandidates, BeginRange); LLVM_FALLTHROUGH; case Sema::FRS_DiagnosticIssued: for (NamedDecl *D : OldFound) { SemaRef.Diag(D->getLocation(), diag::note_for_range_member_begin_end_ignored) << BeginRange->getType() << BEFFound; } return Sema::FRS_DiagnosticIssued; } llvm_unreachable("unexpected ForRangeStatus"); }; if (BeginMemberLookup.empty()) return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin); return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd); } } else { // - otherwise, begin-expr and end-expr are begin(__range) and // end(__range), respectively, where begin and end are looked up with // argument-dependent lookup (3.4.2). For the purposes of this name // lookup, namespace std is an associated namespace. } if (Sema::ForRangeStatus Result = BuildBegin()) return Result; return BuildEnd(); } /// Speculatively attempt to dereference an invalid range expression. /// If the attempt fails, this function will return a valid, null StmtResult /// and emit no diagnostics. static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVarDecl, SourceLocation ColonLoc, Expr *Range, SourceLocation RangeLoc, SourceLocation RParenLoc) { // Determine whether we can rebuild the for-range statement with a // dereferenced range expression. ExprResult AdjustedRange; { Sema::SFINAETrap Trap(SemaRef); AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range); if (AdjustedRange.isInvalid()) return StmtResult(); StmtResult SR = SemaRef.ActOnCXXForRangeStmt( S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, AdjustedRange.get(), RParenLoc, Sema::BFRK_Check); if (SR.isInvalid()) return StmtResult(); } // The attempt to dereference worked well enough that it could produce a valid // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in // case there are any other (non-fatal) problems with it. SemaRef.Diag(RangeLoc, diag::err_for_range_dereference) << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*"); return SemaRef.ActOnCXXForRangeStmt( S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild); } namespace { /// RAII object to automatically invalidate a declaration if an error occurs. struct InvalidateOnErrorScope { InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled) : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {} ~InvalidateOnErrorScope() { if (Enabled && Trap.hasErrorOccurred()) D->setInvalidDecl(); } DiagnosticErrorTrap Trap; Decl *D; bool Enabled; }; } /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind) { // FIXME: This should not be used during template instantiation. We should // pick up the set of unqualified lookup results for the != and + operators // in the initial parse. // // Testcase (accepts-invalid): // template<typename T> void f() { for (auto x : T()) {} } // namespace N { struct X { X begin(); X end(); int operator*(); }; } // bool operator!=(N::X, N::X); void operator++(N::X); // void g() { f<N::X>(); } Scope *S = getCurScope(); DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); QualType RangeVarType = RangeVar->getType(); DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); // If we hit any errors, mark the loop variable as invalid if its type // contains 'auto'. InvalidateOnErrorScope Invalidate(*this, LoopVar, LoopVar->getType()->isUndeducedType()); StmtResult BeginDeclStmt = Begin; StmtResult EndDeclStmt = End; ExprResult NotEqExpr = Cond, IncrExpr = Inc; if (RangeVarType->isDependentType()) { // The range is implicitly used as a placeholder when it is dependent. RangeVar->markUsed(Context); // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill // them in properly when we instantiate the loop. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar)) for (auto *Binding : DD->bindings()) Binding->setType(Context.DependentTy); LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy)); } } else if (!BeginDeclStmt.get()) { SourceLocation RangeLoc = RangeVar->getLocation(); const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, VK_LValue, ColonLoc); if (BeginRangeRef.isInvalid()) return StmtError(); ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, VK_LValue, ColonLoc); if (EndRangeRef.isInvalid()) return StmtError(); QualType AutoType = Context.getAutoDeductType(); Expr *Range = RangeVar->getInit(); if (!Range) return StmtError(); QualType RangeType = Range->getType(); if (RequireCompleteType(RangeLoc, RangeType, diag::err_for_range_incomplete_type)) return StmtError(); // Build auto __begin = begin-expr, __end = end-expr. // Divide by 2, since the variables are in the inner scope (loop body). const auto DepthStr = std::to_string(S->getDepth() / 2); VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, std::string("__begin") + DepthStr); VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, std::string("__end") + DepthStr); // Build begin-expr and end-expr and attach to __begin and __end variables. ExprResult BeginExpr, EndExpr; if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { // - if _RangeT is an array type, begin-expr and end-expr are __range and // __range + __bound, respectively, where __bound is the array bound. If // _RangeT is an array of unknown size or an array of incomplete type, // the program is ill-formed; // begin-expr is __range. BeginExpr = BeginRangeRef; if (!CoawaitLoc.isInvalid()) { BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get()); if (BeginExpr.isInvalid()) return StmtError(); } if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); return StmtError(); } // Find the array bound. ExprResult BoundExpr; if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) BoundExpr = IntegerLiteral::Create( Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc); else if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(UnqAT)) { // For a variably modified type we can't just use the expression within // the array bounds, since we don't want that to be re-evaluated here. // Rather, we need to determine what it was when the array was first // created - so we resort to using sizeof(vla)/sizeof(element). // For e.g. // void f(int b) { // int vla[b]; // b = -1; <-- This should not affect the num of iterations below // for (int &c : vla) { .. } // } // FIXME: This results in codegen generating IR that recalculates the // run-time number of elements (as opposed to just using the IR Value // that corresponds to the run-time value of each bound that was // generated when the array was created.) If this proves too embarrassing // even for unoptimized IR, consider passing a magic-value/cookie to // codegen that then knows to simply use that initial llvm::Value (that // corresponds to the bound at time of array creation) within // getelementptr. But be prepared to pay the price of increasing a // customized form of coupling between the two components - which could // be hard to maintain as the codebase evolves. ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr( EndVar->getLocation(), UETT_SizeOf, /*IsType=*/true, CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo( VAT->desugar(), RangeLoc)) .getAsOpaquePtr(), EndVar->getSourceRange()); if (SizeOfVLAExprR.isInvalid()) return StmtError(); ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr( EndVar->getLocation(), UETT_SizeOf, /*IsType=*/true, CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo( VAT->getElementType(), RangeLoc)) .getAsOpaquePtr(), EndVar->getSourceRange()); if (SizeOfEachElementExprR.isInvalid()) return StmtError(); BoundExpr = ActOnBinOp(S, EndVar->getLocation(), tok::slash, SizeOfVLAExprR.get(), SizeOfEachElementExprR.get()); if (BoundExpr.isInvalid()) return StmtError(); } else { // Can't be a DependentSizedArrayType or an IncompleteArrayType since // UnqAT is not incomplete and Range is not type-dependent. llvm_unreachable("Unexpected array type in for-range"); } // end-expr is __range + __bound. EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), BoundExpr.get()); if (EndExpr.isInvalid()) return StmtError(); if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, diag::err_for_range_iter_deduction_failure)) { NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); return StmtError(); } } else { OverloadCandidateSet CandidateSet(RangeLoc, OverloadCandidateSet::CSK_Normal); BeginEndFunction BEFFailure; ForRangeStatus RangeStatus = BuildNonArrayForRange( *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar, EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr, &BEFFailure); if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction && BEFFailure == BEF_begin) { // If the range is being built from an array parameter, emit a // a diagnostic that it is being treated as a pointer. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) { if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { QualType ArrayTy = PVD->getOriginalType(); QualType PointerTy = PVD->getType(); if (PointerTy->isPointerType() && ArrayTy->isArrayType()) { Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter) << RangeLoc << PVD << ArrayTy << PointerTy; Diag(PVD->getLocation(), diag::note_declared_at); return StmtError(); } } } // If building the range failed, try dereferencing the range expression // unless a diagnostic was issued or the end function is problematic. StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, Range, RangeLoc, RParenLoc); if (SR.isInvalid() || SR.isUsable()) return SR; } // Otherwise, emit diagnostics if we haven't already. if (RangeStatus == FRS_NoViableFunction) { Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get(); CandidateSet.NoteCandidates( PartialDiagnosticAt(Range->getBeginLoc(), PDiag(diag::err_for_range_invalid) << RangeLoc << Range->getType() << BEFFailure), *this, OCD_AllCandidates, Range); } // Return an error if no fix was discovered. if (RangeStatus != FRS_Success) return StmtError(); } assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() && "invalid range expression in for loop"); // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same. // C++1z removes this restriction. QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); if (!Context.hasSameType(BeginType, EndType)) { Diag(RangeLoc, getLangOpts().CPlusPlus17 ? diag::warn_for_range_begin_end_types_differ : diag::ext_for_range_begin_end_types_differ) << BeginType << EndType; NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); } BeginDeclStmt = ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc); EndDeclStmt = ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc); const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, VK_LValue, ColonLoc); if (BeginRef.isInvalid()) return StmtError(); ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), VK_LValue, ColonLoc); if (EndRef.isInvalid()) return StmtError(); // Build and check __begin != __end expression. NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, BeginRef.get(), EndRef.get()); if (!NotEqExpr.isInvalid()) NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get()); if (!NotEqExpr.isInvalid()) NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false); if (NotEqExpr.isInvalid()) { Diag(RangeLoc, diag::note_for_range_invalid_iterator) << RangeLoc << 0 << BeginRangeRef.get()->getType(); NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); if (!Context.hasSameType(BeginType, EndType)) NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); return StmtError(); } // Build and check ++__begin expression. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, VK_LValue, ColonLoc); if (BeginRef.isInvalid()) return StmtError(); IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); if (!IncrExpr.isInvalid() && CoawaitLoc.isValid()) // FIXME: getCurScope() should not be used during template instantiation. // We should pick up the set of unqualified lookup results for operator // co_await during the initial parse. IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get()); if (!IncrExpr.isInvalid()) IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false); if (IncrExpr.isInvalid()) { Diag(RangeLoc, diag::note_for_range_invalid_iterator) << RangeLoc << 2 << BeginRangeRef.get()->getType() ; NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); return StmtError(); } // Build and check *__begin expression. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, VK_LValue, ColonLoc); if (BeginRef.isInvalid()) return StmtError(); ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); if (DerefExpr.isInvalid()) { Diag(RangeLoc, diag::note_for_range_invalid_iterator) << RangeLoc << 1 << BeginRangeRef.get()->getType(); NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); return StmtError(); } // Attach *__begin as initializer for VD. Don't touch it if we're just // trying to determine whether this would be a valid range. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false); if (LoopVar->isInvalidDecl()) NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); } } // Don't bother to actually allocate the result if we're just trying to // determine whether it would be valid. if (Kind == BFRK_Check) return StmtResult(); // In OpenMP loop region loop control variable must be private. Perform // analysis of first part (if any). if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable()) ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get()); return new (Context) CXXForRangeStmt( InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()), cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(), IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc, ColonLoc, RParenLoc); } /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach /// statement. StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) { if (!S || !B) return StmtError(); ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S); ForStmt->setBody(B); return S; } // Warn when the loop variable is a const reference that creates a copy. // Suggest using the non-reference type for copies. If a copy can be prevented // suggest the const reference type that would do so. // For instance, given "for (const &Foo : Range)", suggest // "for (const Foo : Range)" to denote a copy is made for the loop. If // possible, also suggest "for (const &Bar : Range)" if this type prevents // the copy altogether. static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef, const VarDecl *VD, QualType RangeInitType) { const Expr *InitExpr = VD->getInit(); if (!InitExpr) return; QualType VariableType = VD->getType(); if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr)) if (!Cleanups->cleanupsHaveSideEffects()) InitExpr = Cleanups->getSubExpr(); const MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(InitExpr); // No copy made. if (!MTE) return; const Expr *E = MTE->getSubExpr()->IgnoreImpCasts(); // Searching for either UnaryOperator for dereference of a pointer or // CXXOperatorCallExpr for handling iterators. while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) { if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) { E = CCE->getArg(0); } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) { const MemberExpr *ME = cast<MemberExpr>(Call->getCallee()); E = ME->getBase(); } else { const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E); E = MTE->getSubExpr(); } E = E->IgnoreImpCasts(); } bool ReturnsReference = false; if (isa<UnaryOperator>(E)) { ReturnsReference = true; } else { const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E); const FunctionDecl *FD = Call->getDirectCallee(); QualType ReturnType = FD->getReturnType(); ReturnsReference = ReturnType->isReferenceType(); } if (ReturnsReference) { // Loop variable creates a temporary. Suggest either to go with // non-reference loop variable to indicate a copy is made, or // the correct time to bind a const reference. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy) << VD << VariableType << E->getType(); QualType NonReferenceType = VariableType.getNonReferenceType(); NonReferenceType.removeLocalConst(); QualType NewReferenceType = SemaRef.Context.getLValueReferenceType(E->getType().withConst()); SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference) << NonReferenceType << NewReferenceType << VD->getSourceRange() << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc()); } else if (!VariableType->isRValueReferenceType()) { // The range always returns a copy, so a temporary is always created. // Suggest removing the reference from the loop variable. // If the type is a rvalue reference do not warn since that changes the // semantic of the code. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy) << VD << RangeInitType; QualType NonReferenceType = VariableType.getNonReferenceType(); NonReferenceType.removeLocalConst(); SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type) << NonReferenceType << VD->getSourceRange() << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc()); } } // Warns when the loop variable can be changed to a reference type to // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest // "for (const Foo &x : Range)" if this form does not make a copy. static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef, const VarDecl *VD) { const Expr *InitExpr = VD->getInit(); if (!InitExpr) return; QualType VariableType = VD->getType(); if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) { if (!CE->getConstructor()->isCopyConstructor()) return; } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) { if (CE->getCastKind() != CK_LValueToRValue) return; } else { return; } // TODO: Determine a maximum size that a POD type can be before a diagnostic // should be emitted. Also, only ignore POD types with trivial copy // constructors. if (VariableType.isPODType(SemaRef.Context)) return; // Suggest changing from a const variable to a const reference variable // if doing so will prevent a copy. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy) << VD << VariableType << InitExpr->getType(); SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type) << SemaRef.Context.getLValueReferenceType(VariableType) << VD->getSourceRange() << FixItHint::CreateInsertion(VD->getLocation(), "&"); } /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them. /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest /// using "const foo x" to show that a copy is made /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar. /// Suggest either "const bar x" to keep the copying or "const foo& x" to /// prevent the copy. /// 3) for (const foo x : foos) where x is constructed from a reference foo. /// Suggest "const foo &x" to prevent the copy. static void DiagnoseForRangeVariableCopies(Sema &SemaRef, const CXXForRangeStmt *ForStmt) { if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy, ForStmt->getBeginLoc()) && SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy, ForStmt->getBeginLoc()) && SemaRef.Diags.isIgnored(diag::warn_for_range_copy, ForStmt->getBeginLoc())) { return; } const VarDecl *VD = ForStmt->getLoopVariable(); if (!VD) return; QualType VariableType = VD->getType(); if (VariableType->isIncompleteType()) return; const Expr *InitExpr = VD->getInit(); if (!InitExpr) return; if (VariableType->isReferenceType()) { DiagnoseForRangeReferenceVariableCopies(SemaRef, VD, ForStmt->getRangeInit()->getType()); } else if (VariableType.isConstQualified()) { DiagnoseForRangeConstVariableCopies(SemaRef, VD); } } /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. /// This is a separate step from ActOnCXXForRangeStmt because analysis of the /// body cannot be performed until after the type of the range variable is /// determined. StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { if (!S || !B) return StmtError(); if (isa<ObjCForCollectionStmt>(S)) return FinishObjCForCollectionStmt(S, B); CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); ForStmt->setBody(B); DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, diag::warn_empty_range_based_for_body); DiagnoseForRangeVariableCopies(*this, ForStmt); return S; } StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl) { setFunctionHasBranchIntoScope(); TheDecl->markUsed(Context); return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc); } StmtResult Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *E) { // Convert operand to void* if (!E->isTypeDependent()) { QualType ETy = E->getType(); QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); ExprResult ExprRes = E; AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DestTy, ExprRes); if (ExprRes.isInvalid()) return StmtError(); E = ExprRes.get(); if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) return StmtError(); } ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false); if (ExprRes.isInvalid()) return StmtError(); E = ExprRes.get(); setFunctionHasIndirectGoto(); return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E); } static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc, const Scope &DestScope) { if (!S.CurrentSEHFinally.empty() && DestScope.Contains(*S.CurrentSEHFinally.back())) { S.Diag(Loc, diag::warn_jump_out_of_seh_finally); } } StmtResult Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { Scope *S = CurScope->getContinueParent(); if (!S) { // C99 6.8.6.2p1: A break shall appear only in or as a loop body. return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); } CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S); return new (Context) ContinueStmt(ContinueLoc); } StmtResult Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { Scope *S = CurScope->getBreakParent(); if (!S) { // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); } if (S->isOpenMPLoopScope()) return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt) << "break"); CheckJumpOutOfSEHFinally(*this, BreakLoc, *S); return new (Context) BreakStmt(BreakLoc); } /// Determine whether the given expression is a candidate for /// copy elision in either a return statement or a throw expression. /// /// \param ReturnType If we're determining the copy elision candidate for /// a return statement, this is the return type of the function. If we're /// determining the copy elision candidate for a throw expression, this will /// be a NULL type. /// /// \param E The expression being returned from the function or block, or /// being thrown. /// /// \param CESK Whether we allow function parameters or /// id-expressions that could be moved out of the function to be considered NRVO /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to /// determine whether we should try to move as part of a return or throw (which /// does allow function parameters). /// /// \returns The NRVO candidate variable, if the return statement may use the /// NRVO, or NULL if there is no such candidate. VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK) { // - in a return statement in a function [where] ... // ... the expression is the name of a non-volatile automatic object ... DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); if (!DR || DR->refersToEnclosingVariableOrCapture()) return nullptr; VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); if (!VD) return nullptr; if (isCopyElisionCandidate(ReturnType, VD, CESK)) return VD; return nullptr; } bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK) { QualType VDType = VD->getType(); // - in a return statement in a function with ... // ... a class return type ... if (!ReturnType.isNull() && !ReturnType->isDependentType()) { if (!ReturnType->isRecordType()) return false; // ... the same cv-unqualified type as the function return type ... // When considering moving this expression out, allow dissimilar types. if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() && !Context.hasSameUnqualifiedType(ReturnType, VDType)) return false; } // ...object (other than a function or catch-clause parameter)... if (VD->getKind() != Decl::Var && !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar)) return false; if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable()) return false; // ...automatic... if (!VD->hasLocalStorage()) return false; // Return false if VD is a __block variable. We don't want to implicitly move // out of a __block variable during a return because we cannot assume the // variable will no longer be used. if (VD->hasAttr<BlocksAttr>()) return false; if (CESK & CES_AllowDifferentTypes) return true; // ...non-volatile... if (VD->getType().isVolatileQualified()) return false; // Variables with higher required alignment than their type's ABI // alignment cannot use NRVO. if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() && Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) return false; return true; } /// Try to perform the initialization of a potentially-movable value, /// which is the operand to a return or throw statement. /// /// This routine implements C++14 [class.copy]p32, which attempts to treat /// returned lvalues as rvalues in certain cases (to prefer move construction), /// then falls back to treating them as lvalues if that failed. /// /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject /// resolutions that find non-constructors, such as derived-to-base conversions /// or `operator T()&&` member functions. If false, do consider such /// conversion sequences. /// /// \param Res We will fill this in if move-initialization was possible. /// If move-initialization is not possible, such that we must fall back to /// treating the operand as an lvalue, we will leave Res in its original /// invalid state. static void TryMoveInitialization(Sema& S, const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *&Value, bool ConvertingConstructorsOnly, ExprResult &Res) { ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(), CK_NoOp, Value, VK_XValue); Expr *InitExpr = &AsRvalue; InitializationKind Kind = InitializationKind::CreateCopy( Value->getBeginLoc(), Value->getBeginLoc()); InitializationSequence Seq(S, Entity, Kind, InitExpr); if (!Seq) return; for (const InitializationSequence::Step &Step : Seq.steps()) { if (Step.Kind != InitializationSequence::SK_ConstructorInitialization && Step.Kind != InitializationSequence::SK_UserConversion) continue; FunctionDecl *FD = Step.Function.Function; if (ConvertingConstructorsOnly) { if (isa<CXXConstructorDecl>(FD)) { // C++14 [class.copy]p32: // [...] If the first overload resolution fails or was not performed, // or if the type of the first parameter of the selected constructor // is not an rvalue reference to the object's type (possibly // cv-qualified), overload resolution is performed again, considering // the object as an lvalue. const RValueReferenceType *RRefType = FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>(); if (!RRefType) break; if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(), NRVOCandidate->getType())) break; } else { continue; } } else { if (isa<CXXConstructorDecl>(FD)) { // Check that overload resolution selected a constructor taking an // rvalue reference. If it selected an lvalue reference, then we // didn't need to cast this thing to an rvalue in the first place. if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType())) break; } else if (isa<CXXMethodDecl>(FD)) { // Check that overload resolution selected a conversion operator // taking an rvalue reference. if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue) break; } else { continue; } } // Promote "AsRvalue" to the heap, since we now need this // expression node to persist. Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp, Value, nullptr, VK_XValue); // Complete type-checking the initialization of the return type // using the constructor we found. Res = Seq.Perform(S, Entity, Kind, Value); } } /// Perform the initialization of a potentially-movable value, which /// is the result of return value. /// /// This routine implements C++14 [class.copy]p32, which attempts to treat /// returned lvalues as rvalues in certain cases (to prefer move construction), /// then falls back to treating them as lvalues if that failed. ExprResult Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO) { // C++14 [class.copy]p32: // When the criteria for elision of a copy/move operation are met, but not for // an exception-declaration, and the object to be copied is designated by an // lvalue, or when the expression in a return statement is a (possibly // parenthesized) id-expression that names an object with automatic storage // duration declared in the body or parameter-declaration-clause of the // innermost enclosing function or lambda-expression, overload resolution to // select the constructor for the copy is first performed as if the object // were designated by an rvalue. ExprResult Res = ExprError(); if (AllowNRVO) { bool AffectedByCWG1579 = false; if (!NRVOCandidate) { NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default); if (NRVOCandidate && !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11, Value->getExprLoc())) { const VarDecl *NRVOCandidateInCXX11 = getCopyElisionCandidate(ResultType, Value, CES_FormerDefault); AffectedByCWG1579 = (!NRVOCandidateInCXX11); } } if (NRVOCandidate) { TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value, true, Res); } if (!Res.isInvalid() && AffectedByCWG1579) { QualType QT = NRVOCandidate->getType(); if (QT.getNonReferenceType() .getUnqualifiedType() .isTriviallyCopyableType(Context)) { // Adding 'std::move' around a trivially copyable variable is probably // pointless. Don't suggest it. } else { // Common cases for this are returning unique_ptr<Derived> from a // function of return type unique_ptr<Base>, or returning T from a // function of return type Expected<T>. This is totally fine in a // post-CWG1579 world, but was not fine before. assert(!ResultType.isNull()); SmallString<32> Str; Str += "std::move("; Str += NRVOCandidate->getDeclName().getAsString(); Str += ")"; Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11) << Value->getSourceRange() << NRVOCandidate->getDeclName() << ResultType << QT; Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11) << FixItHint::CreateReplacement(Value->getSourceRange(), Str); } } else if (Res.isInvalid() && !getDiagnostics().isIgnored(diag::warn_return_std_move, Value->getExprLoc())) { const VarDecl *FakeNRVOCandidate = getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove); if (FakeNRVOCandidate) { QualType QT = FakeNRVOCandidate->getType(); if (QT->isLValueReferenceType()) { // Adding 'std::move' around an lvalue reference variable's name is // dangerous. Don't suggest it. } else if (QT.getNonReferenceType() .getUnqualifiedType() .isTriviallyCopyableType(Context)) { // Adding 'std::move' around a trivially copyable variable is probably // pointless. Don't suggest it. } else { ExprResult FakeRes = ExprError(); Expr *FakeValue = Value; TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType, FakeValue, false, FakeRes); if (!FakeRes.isInvalid()) { bool IsThrow = (Entity.getKind() == InitializedEntity::EK_Exception); SmallString<32> Str; Str += "std::move("; Str += FakeNRVOCandidate->getDeclName().getAsString(); Str += ")"; Diag(Value->getExprLoc(), diag::warn_return_std_move) << Value->getSourceRange() << FakeNRVOCandidate->getDeclName() << IsThrow; Diag(Value->getExprLoc(), diag::note_add_std_move) << FixItHint::CreateReplacement(Value->getSourceRange(), Str); } } } } } // Either we didn't meet the criteria for treating an lvalue as an rvalue, // above, or overload resolution failed. Either way, we need to try // (again) now with the return value expression as written. if (Res.isInvalid()) Res = PerformCopyInitialization(Entity, SourceLocation(), Value); return Res; } /// Determine whether the declared return type of the specified function /// contains 'auto'. static bool hasDeducedReturnType(FunctionDecl *FD) { const FunctionProtoType *FPT = FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); return FPT->getReturnType()->isUndeducedType(); } /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements /// for capturing scopes. /// StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { // If this is the first return we've seen, infer the return type. // [expr.prim.lambda]p4 in C++11; block literals follow the same rules. CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); QualType FnRetType = CurCap->ReturnType; LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap); bool HasDeducedReturnType = CurLambda && hasDeducedReturnType(CurLambda->CallOperator); if (ExprEvalContexts.back().Context == ExpressionEvaluationContext::DiscardedStatement && (HasDeducedReturnType || CurCap->HasImplicitReturnType)) { if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } return ReturnStmt::Create(Context, ReturnLoc, RetValExp, /* NRVOCandidate=*/nullptr); } if (HasDeducedReturnType) { // In C++1y, the return type may involve 'auto'. // FIXME: Blocks might have a return type of 'auto' explicitly specified. FunctionDecl *FD = CurLambda->CallOperator; if (CurCap->ReturnType.isNull()) CurCap->ReturnType = FD->getReturnType(); AutoType *AT = CurCap->ReturnType->getContainedAutoType(); assert(AT && "lost auto type from lambda return type"); if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { FD->setInvalidDecl(); return StmtError(); } CurCap->ReturnType = FnRetType = FD->getReturnType(); } else if (CurCap->HasImplicitReturnType) { // For blocks/lambdas with implicit return types, we check each return // statement individually, and deduce the common return type when the block // or lambda is completed. // FIXME: Fold this into the 'auto' codepath above. if (RetValExp && !isa<InitListExpr>(RetValExp)) { ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); if (Result.isInvalid()) return StmtError(); RetValExp = Result.get(); // DR1048: even prior to C++14, we should use the 'auto' deduction rules // when deducing a return type for a lambda-expression (or by extension // for a block). These rules differ from the stated C++11 rules only in // that they remove top-level cv-qualifiers. if (!CurContext->isDependentContext()) FnRetType = RetValExp->getType().getUnqualifiedType(); else FnRetType = CurCap->ReturnType = Context.DependentTy; } else { if (RetValExp) { // C++11 [expr.lambda.prim]p4 bans inferring the result from an // initializer list, because it is not an expression (even // though we represent it as one). We still deduce 'void'. Diag(ReturnLoc, diag::err_lambda_return_init_list) << RetValExp->getSourceRange(); } FnRetType = Context.VoidTy; } // Although we'll properly infer the type of the block once it's completed, // make sure we provide a return type now for better error recovery. if (CurCap->ReturnType.isNull()) CurCap->ReturnType = FnRetType; } assert(!FnRetType.isNull()); if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) { Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); return StmtError(); } } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) { Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName(); return StmtError(); } else { assert(CurLambda && "unknown kind of captured scope"); if (CurLambda->CallOperator->getType() ->castAs<FunctionType>() ->getNoReturnAttr()) { Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); return StmtError(); } } // Otherwise, verify that this result type matches the previous one. We are // pickier with blocks than for normal functions because we don't have GCC // compatibility to worry about here. const VarDecl *NRVOCandidate = nullptr; if (FnRetType->isDependentType()) { // Delay processing for now. TODO: there are lots of dependent // types we can conclusively prove aren't void. } else if (FnRetType->isVoidType()) { if (RetValExp && !isa<InitListExpr>(RetValExp) && !(getLangOpts().CPlusPlus && (RetValExp->isTypeDependent() || RetValExp->getType()->isVoidType()))) { if (!getLangOpts().CPlusPlus && RetValExp->getType()->isVoidType()) Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; else { Diag(ReturnLoc, diag::err_return_block_has_expr); RetValExp = nullptr; } } } else if (!RetValExp) { return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); } else if (!RetValExp->isTypeDependent()) { // we have a non-void block with an expression, continue checking // C99 6.8.6.4p3(136): The return statement is not an assignment. The // overlap restriction of subclause 6.5.16.1 does not apply to the case of // function return. // In C++ the return statement is handled via a copy initialization. // the C version of which boils down to CheckSingleAssignmentConstraints. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, FnRetType, NRVOCandidate != nullptr); ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, FnRetType, RetValExp); if (Res.isInvalid()) { // FIXME: Cleanup temporaries here, anyway? return StmtError(); } RetValExp = Res.get(); CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc); } else { NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); } if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } auto *Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); // If we need to check for the named return value optimization, // or if we need to infer the return type, // save the return statement in our scope for later processing. if (CurCap->HasImplicitReturnType || NRVOCandidate) FunctionScopes.back()->Returns.push_back(Result); if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) FunctionScopes.back()->FirstReturnLoc = ReturnLoc; return Result; } namespace { /// Marks all typedefs in all local classes in a type referenced. /// /// In a function like /// auto f() { /// struct S { typedef int a; }; /// return S(); /// } /// /// the local type escapes and could be referenced in some TUs but not in /// others. Pretend that all local typedefs are always referenced, to not warn /// on this. This isn't necessary if f has internal linkage, or the typedef /// is private. class LocalTypedefNameReferencer : public RecursiveASTVisitor<LocalTypedefNameReferencer> { public: LocalTypedefNameReferencer(Sema &S) : S(S) {} bool VisitRecordType(const RecordType *RT); private: Sema &S; }; bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) { auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl()); if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() || R->isDependentType()) return true; for (auto *TmpD : R->decls()) if (auto *T = dyn_cast<TypedefNameDecl>(TmpD)) if (T->getAccess() != AS_private || R->hasFriends()) S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false); return true; } } TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const { return FD->getTypeSourceInfo() ->getTypeLoc() .getAsAdjusted<FunctionProtoTypeLoc>() .getReturnLoc(); } /// Deduce the return type for a function from a returned expression, per /// C++1y [dcl.spec.auto]p6. bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT) { // If this is the conversion function for a lambda, we choose to deduce it // type from the corresponding call operator, not from the synthesized return // statement within it. See Sema::DeduceReturnType. if (isLambdaConversionOperator(FD)) return false; TypeLoc OrigResultType = getReturnTypeLoc(FD); QualType Deduced; if (RetExpr && isa<InitListExpr>(RetExpr)) { // If the deduction is for a return statement and the initializer is // a braced-init-list, the program is ill-formed. Diag(RetExpr->getExprLoc(), getCurLambda() ? diag::err_lambda_return_init_list : diag::err_auto_fn_return_init_list) << RetExpr->getSourceRange(); return true; } if (FD->isDependentContext()) { // C++1y [dcl.spec.auto]p12: // Return type deduction [...] occurs when the definition is // instantiated even if the function body contains a return // statement with a non-type-dependent operand. assert(AT->isDeduced() && "should have deduced to dependent type"); return false; } if (RetExpr) { // Otherwise, [...] deduce a value for U using the rules of template // argument deduction. DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced); if (DAR == DAR_Failed && !FD->isInvalidDecl()) Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure) << OrigResultType.getType() << RetExpr->getType(); if (DAR != DAR_Succeeded) return true; // If a local type is part of the returned type, mark its fields as // referenced. LocalTypedefNameReferencer Referencer(*this); Referencer.TraverseType(RetExpr->getType()); } else { // In the case of a return with no operand, the initializer is considered // to be void(). // // Deduction here can only succeed if the return type is exactly 'cv auto' // or 'decltype(auto)', so just check for that case directly. if (!OrigResultType.getType()->getAs<AutoType>()) { Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto) << OrigResultType.getType(); return true; } // We always deduce U = void in this case. Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy); if (Deduced.isNull()) return true; } // CUDA: Kernel function must have 'void' return type. if (getLangOpts().CUDA) if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) { Diag(FD->getLocation(), diag::err_kern_type_not_void_return) << FD->getType() << FD->getSourceRange(); return true; } // If a function with a declared return type that contains a placeholder type // has multiple return statements, the return type is deduced for each return // statement. [...] if the type deduced is not the same in each deduction, // the program is ill-formed. QualType DeducedT = AT->getDeducedType(); if (!DeducedT.isNull() && !FD->isInvalidDecl()) { AutoType *NewAT = Deduced->getContainedAutoType(); // It is possible that NewAT->getDeducedType() is null. When that happens, // we should not crash, instead we ignore this deduction. if (NewAT->getDeducedType().isNull()) return false; CanQualType OldDeducedType = Context.getCanonicalFunctionResultType( DeducedT); CanQualType NewDeducedType = Context.getCanonicalFunctionResultType( NewAT->getDeducedType()); if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) { const LambdaScopeInfo *LambdaSI = getCurLambda(); if (LambdaSI && LambdaSI->HasImplicitReturnType) { Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) << NewAT->getDeducedType() << DeducedT << true /*IsLambda*/; } else { Diag(ReturnLoc, diag::err_auto_fn_different_deductions) << (AT->isDecltypeAuto() ? 1 : 0) << NewAT->getDeducedType() << DeducedT; } return true; } } else if (!FD->isInvalidDecl()) { // Update all declarations of the function to have the deduced return type. Context.adjustDeducedFunctionResultType(FD, Deduced); } return false; } StmtResult Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope) { // Correct typos, in case the containing function returns 'auto' and // RetValExp should determine the deduced type. ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp); if (RetVal.isInvalid()) return StmtError(); StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get()); if (R.isInvalid() || ExprEvalContexts.back().Context == ExpressionEvaluationContext::DiscardedStatement) return R; if (VarDecl *VD = const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) { CurScope->addNRVOCandidate(VD); } else { CurScope->setNoNRVO(); } CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent()); return R; } StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { // Check for unexpanded parameter packs. if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) return StmtError(); if (isa<CapturingScopeInfo>(getCurFunction())) return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); QualType FnRetType; QualType RelatedRetType; const AttrVec *Attrs = nullptr; bool isObjCMethod = false; if (const FunctionDecl *FD = getCurFunctionDecl()) { FnRetType = FD->getReturnType(); if (FD->hasAttrs()) Attrs = &FD->getAttrs(); if (FD->isNoReturn()) Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD->getDeclName(); if (FD->isMain() && RetValExp) if (isa<CXXBoolLiteralExpr>(RetValExp)) Diag(ReturnLoc, diag::warn_main_returns_bool_literal) << RetValExp->getSourceRange(); } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { FnRetType = MD->getReturnType(); isObjCMethod = true; if (MD->hasAttrs()) Attrs = &MD->getAttrs(); if (MD->hasRelatedResultType() && MD->getClassInterface()) { // In the implementation of a method with a related return type, the // type used to type-check the validity of return statements within the // method body is a pointer to the type of the class being implemented. RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); } } else // If we don't have a function/method context, bail. return StmtError(); // C++1z: discarded return statements are not considered when deducing a // return type. if (ExprEvalContexts.back().Context == ExpressionEvaluationContext::DiscardedStatement && FnRetType->getContainedAutoType()) { if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } return ReturnStmt::Create(Context, ReturnLoc, RetValExp, /* NRVOCandidate=*/nullptr); } // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing // deduction. if (getLangOpts().CPlusPlus14) { if (AutoType *AT = FnRetType->getContainedAutoType()) { FunctionDecl *FD = cast<FunctionDecl>(CurContext); if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { FD->setInvalidDecl(); return StmtError(); } else { FnRetType = FD->getReturnType(); } } } bool HasDependentReturnType = FnRetType->isDependentType(); ReturnStmt *Result = nullptr; if (FnRetType->isVoidType()) { if (RetValExp) { if (isa<InitListExpr>(RetValExp)) { // We simply never allow init lists as the return value of void // functions. This is compatible because this was never allowed before, // so there's no legacy code to deal with. NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); int FunctionKind = 0; if (isa<ObjCMethodDecl>(CurDecl)) FunctionKind = 1; else if (isa<CXXConstructorDecl>(CurDecl)) FunctionKind = 2; else if (isa<CXXDestructorDecl>(CurDecl)) FunctionKind = 3; Diag(ReturnLoc, diag::err_return_init_list) << CurDecl->getDeclName() << FunctionKind << RetValExp->getSourceRange(); // Drop the expression. RetValExp = nullptr; } else if (!RetValExp->isTypeDependent()) { // C99 6.8.6.4p1 (ext_ since GCC warns) unsigned D = diag::ext_return_has_expr; if (RetValExp->getType()->isVoidType()) { NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); if (isa<CXXConstructorDecl>(CurDecl) || isa<CXXDestructorDecl>(CurDecl)) D = diag::err_ctor_dtor_returns_void; else D = diag::ext_return_has_void_expr; } else { ExprResult Result = RetValExp; Result = IgnoredValueConversions(Result.get()); if (Result.isInvalid()) return StmtError(); RetValExp = Result.get(); RetValExp = ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid).get(); } // return of void in constructor/destructor is illegal in C++. if (D == diag::err_ctor_dtor_returns_void) { NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); Diag(ReturnLoc, D) << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl) << RetValExp->getSourceRange(); } // return (some void expression); is legal in C++. else if (D != diag::ext_return_has_void_expr || !getLangOpts().CPlusPlus) { NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); int FunctionKind = 0; if (isa<ObjCMethodDecl>(CurDecl)) FunctionKind = 1; else if (isa<CXXConstructorDecl>(CurDecl)) FunctionKind = 2; else if (isa<CXXDestructorDecl>(CurDecl)) FunctionKind = 3; Diag(ReturnLoc, D) << CurDecl->getDeclName() << FunctionKind << RetValExp->getSourceRange(); } } if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } } Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, /* NRVOCandidate=*/nullptr); } else if (!RetValExp && !HasDependentReturnType) { FunctionDecl *FD = getCurFunctionDecl(); unsigned DiagID; if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) { // C++11 [stmt.return]p2 DiagID = diag::err_constexpr_return_missing_expr; FD->setInvalidDecl(); } else if (getLangOpts().C99) { // C99 6.8.6.4p1 (ext_ since GCC warns) DiagID = diag::ext_return_missing_expr; } else { // C90 6.6.6.4p4 DiagID = diag::warn_return_missing_expr; } if (FD) Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval(); else Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr, /* NRVOCandidate=*/nullptr); } else { assert(RetValExp || HasDependentReturnType); const VarDecl *NRVOCandidate = nullptr; QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType; // C99 6.8.6.4p3(136): The return statement is not an assignment. The // overlap restriction of subclause 6.5.16.1 does not apply to the case of // function return. // In C++ the return statement is handled via a copy initialization, // the C version of which boils down to CheckSingleAssignmentConstraints. if (RetValExp) NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); if (!HasDependentReturnType && !RetValExp->isTypeDependent()) { // we have a non-void function with an expression, continue checking InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, RetType, NRVOCandidate != nullptr); ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, RetType, RetValExp); if (Res.isInvalid()) { // FIXME: Clean up temporaries here anyway? return StmtError(); } RetValExp = Res.getAs<Expr>(); // If we have a related result type, we need to implicitly // convert back to the formal result type. We can't pretend to // initialize the result again --- we might end double-retaining // --- so instead we initialize a notional temporary. if (!RelatedRetType.isNull()) { Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(), FnRetType); Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp); if (Res.isInvalid()) { // FIXME: Clean up temporaries here anyway? return StmtError(); } RetValExp = Res.getAs<Expr>(); } CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs, getCurFunctionDecl()); } if (RetValExp) { ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); if (ER.isInvalid()) return StmtError(); RetValExp = ER.get(); } Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); } // If we need to check for the named return value optimization, save the // return statement in our scope for later processing. if (Result->getNRVOCandidate()) FunctionScopes.back()->Returns.push_back(Result); if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) FunctionScopes.back()->FirstReturnLoc = ReturnLoc; return Result; } StmtResult Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body) { VarDecl *Var = cast_or_null<VarDecl>(Parm); if (Var && Var->isInvalidDecl()) return StmtError(); return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body); } StmtResult Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { return new (Context) ObjCAtFinallyStmt(AtLoc, Body); } StmtResult Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg CatchStmts, Stmt *Finally) { if (!getLangOpts().ObjCExceptions) Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; setFunctionHasBranchProtectedScope(); unsigned NumCatchStmts = CatchStmts.size(); return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(), NumCatchStmts, Finally); } StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { if (Throw) { ExprResult Result = DefaultLvalueConversion(Throw); if (Result.isInvalid()) return StmtError(); Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false); if (Result.isInvalid()) return StmtError(); Throw = Result.get(); QualType ThrowType = Throw->getType(); // Make sure the expression type is an ObjC pointer or "void *". if (!ThrowType->isDependentType() && !ThrowType->isObjCObjectPointerType()) { const PointerType *PT = ThrowType->getAs<PointerType>(); if (!PT || !PT->getPointeeType()->isVoidType()) return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object) << Throw->getType() << Throw->getSourceRange()); } } return new (Context) ObjCAtThrowStmt(AtLoc, Throw); } StmtResult Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope) { if (!getLangOpts().ObjCExceptions) Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; if (!Throw) { // @throw without an expression designates a rethrow (which must occur // in the context of an @catch clause). Scope *AtCatchParent = CurScope; while (AtCatchParent && !AtCatchParent->isAtCatchScope()) AtCatchParent = AtCatchParent->getParent(); if (!AtCatchParent) return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch)); } return BuildObjCAtThrowStmt(AtLoc, Throw); } ExprResult Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { ExprResult result = DefaultLvalueConversion(operand); if (result.isInvalid()) return ExprError(); operand = result.get(); // Make sure the expression type is an ObjC pointer or "void *". QualType type = operand->getType(); if (!type->isDependentType() && !type->isObjCObjectPointerType()) { const PointerType *pointerType = type->getAs<PointerType>(); if (!pointerType || !pointerType->getPointeeType()->isVoidType()) { if (getLangOpts().CPlusPlus) { if (RequireCompleteType(atLoc, type, diag::err_incomplete_receiver_type)) return Diag(atLoc, diag::err_objc_synchronized_expects_object) << type << operand->getSourceRange(); ExprResult result = PerformContextuallyConvertToObjCPointer(operand); if (result.isInvalid()) return ExprError(); if (!result.isUsable()) return Diag(atLoc, diag::err_objc_synchronized_expects_object) << type << operand->getSourceRange(); operand = result.get(); } else { return Diag(atLoc, diag::err_objc_synchronized_expects_object) << type << operand->getSourceRange(); } } } // The operand to @synchronized is a full-expression. return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false); } StmtResult Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, Stmt *SyncBody) { // We can't jump into or indirect-jump out of a @synchronized block. setFunctionHasBranchProtectedScope(); return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody); } /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block /// and creates a proper catch handler from them. StmtResult Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock) { // There's nothing to test that ActOnExceptionDecl didn't already test. return new (Context) CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock); } StmtResult Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { setFunctionHasBranchProtectedScope(); return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body); } namespace { class CatchHandlerType { QualType QT; unsigned IsPointer : 1; // This is a special constructor to be used only with DenseMapInfo's // getEmptyKey() and getTombstoneKey() functions. friend struct llvm::DenseMapInfo<CatchHandlerType>; enum Unique { ForDenseMap }; CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {} public: /// Used when creating a CatchHandlerType from a handler type; will determine /// whether the type is a pointer or reference and will strip off the top /// level pointer and cv-qualifiers. CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) { if (QT->isPointerType()) IsPointer = true; if (IsPointer || QT->isReferenceType()) QT = QT->getPointeeType(); QT = QT.getUnqualifiedType(); } /// Used when creating a CatchHandlerType from a base class type; pretends the /// type passed in had the pointer qualifier, does not need to get an /// unqualified type. CatchHandlerType(QualType QT, bool IsPointer) : QT(QT), IsPointer(IsPointer) {} QualType underlying() const { return QT; } bool isPointer() const { return IsPointer; } friend bool operator==(const CatchHandlerType &LHS, const CatchHandlerType &RHS) { // If the pointer qualification does not match, we can return early. if (LHS.IsPointer != RHS.IsPointer) return false; // Otherwise, check the underlying type without cv-qualifiers. return LHS.QT == RHS.QT; } }; } // namespace namespace llvm { template <> struct DenseMapInfo<CatchHandlerType> { static CatchHandlerType getEmptyKey() { return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(), CatchHandlerType::ForDenseMap); } static CatchHandlerType getTombstoneKey() { return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(), CatchHandlerType::ForDenseMap); } static unsigned getHashValue(const CatchHandlerType &Base) { return DenseMapInfo<QualType>::getHashValue(Base.underlying()); } static bool isEqual(const CatchHandlerType &LHS, const CatchHandlerType &RHS) { return LHS == RHS; } }; } namespace { class CatchTypePublicBases { ASTContext &Ctx; const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck; const bool CheckAgainstPointer; CXXCatchStmt *FoundHandler; CanQualType FoundHandlerType; public: CatchTypePublicBases( ASTContext &Ctx, const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C) : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C), FoundHandler(nullptr) {} CXXCatchStmt *getFoundHandler() const { return FoundHandler; } CanQualType getFoundHandlerType() const { return FoundHandlerType; } bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) { if (S->getAccessSpecifier() == AccessSpecifier::AS_public) { CatchHandlerType Check(S->getType(), CheckAgainstPointer); const auto &M = TypesToCheck; auto I = M.find(Check); if (I != M.end()) { FoundHandler = I->second; FoundHandlerType = Ctx.getCanonicalType(S->getType()); return true; } } return false; } }; } /// ActOnCXXTryBlock - Takes a try compound-statement and a number of /// handlers and creates a try statement from them. StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers) { // Don't report an error if 'try' is used in system headers. if (!getLangOpts().CXXExceptions && !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) { // Delay error emission for the OpenMP device code. targetDiag(TryLoc, diag::err_exceptions_disabled) << "try"; } // Exceptions aren't allowed in CUDA device code. if (getLangOpts().CUDA) CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions) << "try" << CurrentCUDATarget(); if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try"; sema::FunctionScopeInfo *FSI = getCurFunction(); // C++ try is incompatible with SEH __try. if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) { Diag(TryLoc, diag::err_mixing_cxx_try_seh_try); Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'"; } const unsigned NumHandlers = Handlers.size(); assert(!Handlers.empty() && "The parser shouldn't call this if there are no handlers."); llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes; for (unsigned i = 0; i < NumHandlers; ++i) { CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]); // Diagnose when the handler is a catch-all handler, but it isn't the last // handler for the try block. [except.handle]p5. Also, skip exception // declarations that are invalid, since we can't usefully report on them. if (!H->getExceptionDecl()) { if (i < NumHandlers - 1) return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all)); continue; } else if (H->getExceptionDecl()->isInvalidDecl()) continue; // Walk the type hierarchy to diagnose when this type has already been // handled (duplication), or cannot be handled (derivation inversion). We // ignore top-level cv-qualifiers, per [except.handle]p3 CatchHandlerType HandlerCHT = (QualType)Context.getCanonicalType(H->getCaughtType()); // We can ignore whether the type is a reference or a pointer; we need the // underlying declaration type in order to get at the underlying record // decl, if there is one. QualType Underlying = HandlerCHT.underlying(); if (auto *RD = Underlying->getAsCXXRecordDecl()) { if (!RD->hasDefinition()) continue; // Check that none of the public, unambiguous base classes are in the // map ([except.handle]p1). Give the base classes the same pointer // qualification as the original type we are basing off of. This allows // comparison against the handler type using the same top-level pointer // as the original type. CXXBasePaths Paths; Paths.setOrigin(RD); CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer()); if (RD->lookupInBases(CTPB, Paths)) { const CXXCatchStmt *Problem = CTPB.getFoundHandler(); if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) { Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), diag::warn_exception_caught_by_earlier_handler) << H->getCaughtType(); Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), diag::note_previous_exception_handler) << Problem->getCaughtType(); } } } // Add the type the list of ones we have handled; diagnose if we've already // handled it. auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H)); if (!R.second) { const CXXCatchStmt *Problem = R.first->second; Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), diag::warn_exception_caught_by_earlier_handler) << H->getCaughtType(); Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), diag::note_previous_exception_handler) << Problem->getCaughtType(); } } FSI->setHasCXXTry(TryLoc); return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers); } StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler) { assert(TryBlock && Handler); sema::FunctionScopeInfo *FSI = getCurFunction(); // SEH __try is incompatible with C++ try. Borland appears to support this, // however. if (!getLangOpts().Borland) { if (FSI->FirstCXXTryLoc.isValid()) { Diag(TryLoc, diag::err_mixing_cxx_try_seh_try); Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'"; } } FSI->setHasSEHTry(TryLoc); // Reject __try in Obj-C methods, blocks, and captured decls, since we don't // track if they use SEH. DeclContext *DC = CurContext; while (DC && !DC->isFunctionOrMethod()) DC = DC->getParent(); FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC); if (FD) FD->setUsesSEHTry(true); else Diag(TryLoc, diag::err_seh_try_outside_functions); // Reject __try on unsupported targets. if (!Context.getTargetInfo().isSEHTrySupported()) Diag(TryLoc, diag::err_seh_try_unsupported); return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler); } StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block) { assert(FilterExpr && Block); QualType FTy = FilterExpr->getType(); if (!FTy->isIntegerType() && !FTy->isDependentType()) { return StmtError( Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral) << FTy); } return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block); } void Sema::ActOnStartSEHFinallyBlock() { CurrentSEHFinally.push_back(CurScope); } void Sema::ActOnAbortSEHFinallyBlock() { CurrentSEHFinally.pop_back(); } StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) { assert(Block); CurrentSEHFinally.pop_back(); return SEHFinallyStmt::Create(Context, Loc, Block); } StmtResult Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) { Scope *SEHTryParent = CurScope; while (SEHTryParent && !SEHTryParent->isSEHTryScope()) SEHTryParent = SEHTryParent->getParent(); if (!SEHTryParent) return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try)); CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent); return new (Context) SEHLeaveStmt(Loc); } StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested) { return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, QualifierLoc, NameInfo, cast<CompoundStmt>(Nested)); } StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested) { return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, SS.getWithLocInContext(Context), GetNameFromUnqualifiedId(Name), Nested); } RecordDecl* Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams) { DeclContext *DC = CurContext; while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) DC = DC->getParent(); RecordDecl *RD = nullptr; if (getLangOpts().CPlusPlus) RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr); else RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr); RD->setCapturedRecord(); DC->addDecl(RD); RD->setImplicit(); RD->startDefinition(); assert(NumParams > 0 && "CapturedStmt requires context parameter"); CD = CapturedDecl::Create(Context, CurContext, NumParams); DC->addDecl(CD); return RD; } static bool buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI, SmallVectorImpl<CapturedStmt::Capture> &Captures, SmallVectorImpl<Expr *> &CaptureInits) { for (const sema::Capture &Cap : RSI->Captures) { if (Cap.isInvalid()) continue; // Form the initializer for the capture. ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(), RSI->CapRegionKind == CR_OpenMP); // FIXME: Bail out now if the capture is not used and the initializer has // no side-effects. // Create a field for this capture. FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap); // Add the capture to our list of captures. if (Cap.isThisCapture()) { Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_This)); } else if (Cap.isVLATypeCapture()) { Captures.push_back( CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType)); } else { assert(Cap.isVariableCapture() && "unknown kind of capture"); if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel); Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef : CapturedStmt::VCK_ByCopy, Cap.getVariable())); } CaptureInits.push_back(Init.get()); } return false; } void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams) { CapturedDecl *CD = nullptr; RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams); // Build the context parameter DeclContext *DC = CapturedDecl::castToDeclContext(CD); IdentifierInfo *ParamName = &Context.Idents.get("__context"); QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setContextParam(0, Param); // Enter the capturing scope for this captured region. PushCapturedRegionScope(CurScope, CD, RD, Kind); if (CurScope) PushDeclContext(CurScope, CD); else CurContext = CD; PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); } void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel) { CapturedDecl *CD = nullptr; RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size()); // Build the context parameter DeclContext *DC = CapturedDecl::castToDeclContext(CD); bool ContextIsFound = false; unsigned ParamNum = 0; for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(), E = Params.end(); I != E; ++I, ++ParamNum) { if (I->second.isNull()) { assert(!ContextIsFound && "null type has been found already for '__context' parameter"); IdentifierInfo *ParamName = &Context.Idents.get("__context"); QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)) .withConst() .withRestrict(); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setContextParam(ParamNum, Param); ContextIsFound = true; } else { IdentifierInfo *ParamName = &Context.Idents.get(I->first); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setParam(ParamNum, Param); } } assert(ContextIsFound && "no null type for '__context' parameter"); if (!ContextIsFound) { // Add __context implicitly if it is not specified. IdentifierInfo *ParamName = &Context.Idents.get("__context"); QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); auto *Param = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, ImplicitParamDecl::CapturedContext); DC->addDecl(Param); CD->setContextParam(ParamNum, Param); } // Enter the capturing scope for this captured region. PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel); if (CurScope) PushDeclContext(CurScope, CD); else CurContext = CD; PushExpressionEvaluationContext( ExpressionEvaluationContext::PotentiallyEvaluated); } void Sema::ActOnCapturedRegionError() { DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); PopDeclContext(); PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); RecordDecl *Record = RSI->TheRecordDecl; Record->setInvalidDecl(); SmallVector<Decl*, 4> Fields(Record->fields()); ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields, SourceLocation(), SourceLocation(), ParsedAttributesView()); } StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) { // Leave the captured scope before we start creating captures in the // enclosing scope. DiscardCleanupsInEvaluationContext(); PopExpressionEvaluationContext(); PopDeclContext(); PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); SmallVector<CapturedStmt::Capture, 4> Captures; SmallVector<Expr *, 4> CaptureInits; if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits)) return StmtError(); CapturedDecl *CD = RSI->TheCapturedDecl; RecordDecl *RD = RSI->TheRecordDecl; CapturedStmt *Res = CapturedStmt::Create( getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind), Captures, CaptureInits, CD, RD); CD->setBody(Res->getCapturedStmt()); RD->completeDefinition(); return Res; }
[ "wangyankun@ishumei.com" ]
wangyankun@ishumei.com
ba02245772a933678a716b061ffbacb20c345c8e
a816e8ab3043f8775f20776e0f48072c379dbbc3
/labs/lab3/E.cpp
f1966ed8c1825f6701198b385ed99e71b4e747f7
[]
no_license
AruzhanBazarbai/pp1
1dee51b6ef09a094072f89359883600937faf558
317d488a1ffec9108d71e8bf976a9a1c0896745e
refs/heads/master
2023-07-16T14:37:20.131167
2021-08-25T17:08:41
2021-08-25T17:08:41
399,890,781
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
//Given an array consisting of integers. // Write a program, which finds sum of all elements #include <iostream> using namespace std; int main(){ int n; cin >> n; int a[n]; long long sum=0; for(int i=0; i<n; i++){ cin >> a[i]; } for(int i=0; i<n; i++){ sum+=a[i]; } cout << sum << "\n"; return 0; }
[ "aruzhanart2003@mail.ru" ]
aruzhanart2003@mail.ru
21bcf4c8c5f40d0afb73d1e3dc05b977d9dd0f6d
6b8f7c30e619bd6de18c6f3273a58f6c181abfba
/20201028_함수 n!의 값.cpp
8241afedffbb614975392eeb2bd391749bba5cfb
[]
no_license
msk20msk20/C_language
3e31599daa37a9ac9bb77c2138ac4b53f390d0d8
08255b828fc9ae0c00c9d694c3eb278cf8b6fa55
refs/heads/main
2023-01-06T18:19:25.347931
2020-10-28T07:08:51
2020-10-28T07:08:51
303,948,117
0
0
null
null
null
null
UTF-8
C++
false
false
255
cpp
#include <stdio.h> int n; long long int f(int a) { long long int result = 1; for(int i = 1; i <= a ; i++) { result = result * i; } return result; } int main(void) { scanf("%d", &n); printf("%lld \n", f(n)); return 0; }
[ "noreply@github.com" ]
msk20msk20.noreply@github.com
8ef0f75eb73dfdcaf7b2c7e11819d9da523b6251
09a4f7e32a0efb2b18c1fcd3c501ecc6becb0852
/Builder/main.cpp
40f1995b85e3e640d7691f210a3b0845ded6ef3c
[]
no_license
IngwarSV/Patterns
8a230005ac37ab699217c3cb5ae5d81b857ace4c
a557aa9532f95d6c12dcea836d4e614ed5a326b3
refs/heads/master
2020-12-26T07:20:01.572200
2020-02-12T09:13:20
2020-02-12T09:13:20
237,431,316
0
0
null
null
null
null
UTF-8
C++
false
false
946
cpp
#include <iostream> #include "Smith.h" #include "Sword.h" // #include "SwordTemplate.h" #include "GladiusTemplate.h" #include "LongSwordTemplate.h" #include "LongSword.h" int main() { Smith* blacksmith = new Smith(); GladiusTemplate* gTemplate = new GladiusTemplate(); LongSwordTemplate* lsTemplate = new LongSwordTemplate(); blacksmith->setSwordTemplate(gTemplate); Sword* arm1 = blacksmith->createSword(); std::cout << *arm1 << std::endl; std::cout << "----------------------" << std::endl; blacksmith->setSwordTemplate(lsTemplate); Sword* arm2 = blacksmith->createSword(); std::cout << *arm2 << std::endl; std::cout << "----------------------" << std::endl; arm1->info(); arm2->info(); std::cout << "----------------------" << std::endl; delete (blacksmith); delete(gTemplate); delete(lsTemplate); delete (arm1); delete (arm2); return 0; }
[ "sviatskyi@gmail.com" ]
sviatskyi@gmail.com
11b5436479da047d576381bb86fcb1dcbed4581b
f76792be9b6b12ccde8a6ab64c0462846039cfa5
/287_find_the_duplicate_number.cpp
06681de8d5d3ee4ec86a73a685cadba6cb1af966
[]
no_license
netario/leetcode-solutions
844c0fbf7f97a71eba3b59e7643c7104cef4a590
b289891115927d90bd59ec53f173121a1158e524
refs/heads/master
2021-01-19T12:52:15.653561
2017-09-16T23:28:52
2017-09-16T23:28:52
100,814,944
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
class Solution { public: int findDuplicate(vector<int>& nums) { int ret = -1, p = 1, q = (int)nums.size() - 1; while (p <= q) { int mid = p + (q - p) / 2, cnt = 0; for (auto& num : nums) cnt += num <= mid; if (cnt >= mid + 1) { ret = mid; q = mid - 1; } else { p = mid + 1; } } return ret; } };
[ "fycanyue@163.com" ]
fycanyue@163.com
45a7ddd357d5fc069b48636f5c17bdabd8ef399f
f3b3bf886392024e0bbddf2ca2c4f59ed067008d
/code/day3/day2.cpp
d473d3f5a8ae4ef4573e950ea9caefc299c5d69e
[]
no_license
Cuong-star/30daysofcode
b8a03e908966c887cfefcf46dd0b25b1c29a10e1
255c7a680ae9b9c09d1e14f9e0586209def042ce
refs/heads/master
2020-12-18T21:05:23.759728
2020-01-22T03:50:49
2020-01-22T03:50:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include <bits/stdc++.h> #include <cmath> using namespace std; // Complete the solve function below. void solve(double meal_cost, int tip_percent, int tax_percent) { double tip,tax,total; tip = meal_cost * tip_percent/100; tax = meal_cost * tax_percent/100; total = meal_cost + tip + tax; cout << round(total); } int main() { double meal_cost; cin >> meal_cost; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int tip_percent; cin >> tip_percent; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int tax_percent; cin >> tax_percent; cin.ignore(numeric_limits<streamsize>::max(), '\n'); solve(meal_cost, tip_percent, tax_percent); return 0; }
[ "pduongpdu99@gmail.com" ]
pduongpdu99@gmail.com
d8e6b93ad77248d2d4fa2cf879f4c420eb2e6804
0dc405a395af56e01cd4efb699ab00b192ac0a0c
/1day/dfs.cpp
585ed7e157d74accb3232058c3f9be5a32a50c1a
[]
no_license
DanielYe1/winterSchool
fb336ebd2692f13840aabe4e529fc89df09089e8
d91adb91fabc64ac32bce573889d9fb5713e6a91
refs/heads/master
2021-06-21T19:30:52.883509
2017-08-25T02:37:24
2017-08-25T02:37:24
101,393,883
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include <iostream> using namespace std; const int timer = 0; int color[10]; void dfs(int node) { color[node] = 1; } const int max_log = 20; const int size = 100000; int par[size][size]; int depth[size]; void dfsAnt(int node, int h, int p) { par[node][0] = p; depth[node] = h; for (int i = 0; i < max_log; ++i) { par[node][i] = -1; if (par[node][i - 1] != -1) { par[node][i] = par[par[node][i - 1]][i - 1]; } } for (int j = 0; j <; ++j) { if (viz != p) { dfsAnt(viz, h + w[node][j], node); } } } int main() { return 0; }
[ "danielxinxin1@gmail.com" ]
danielxinxin1@gmail.com
66eab72d4240498f0d725f66e39c7412f4c2d645
565b4e773bd7892364e078195752af8428b0516c
/A09/A09_Source.cpp
697649ec908ecf520ed9f8f19c2ecc31a5254d7e
[]
no_license
xavigp98/CppProjects_XavierGracia
be348f8e113f18f921461c020c9e57ff7bd89f66
b29bdeda35a6c540b8568f2608c81e1d7b117335
refs/heads/master
2021-01-22T03:48:46.442263
2017-09-12T09:41:50
2017-09-12T09:41:50
81,460,048
0
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
#include "myStack.h" int main() { myStack uno; uno.push(3); int tres = uno.top(); int size = uno.size(); uno.pop(); bool isEmpty = uno.isEmpty(); return 0; }
[ "xaviergraciapereniguez@enti.cat" ]
xaviergraciapereniguez@enti.cat
cbe589d93f3f6beaab6f602ffc9583e3cf1eabcc
7f69e98afe43db75c3d33f7e99dbba702a37a0a7
/src/plugins/thirdParty/LLVM/lib/IR/IRBuilder.cpp
af1b2fbfadfaf56cdc1792d5410847e2c080f7a1
[ "Apache-2.0" ]
permissive
hsorby/opencor
ce1125ba6a6cd86a811d13d4b54fb12a53a3cc7c
4ce3332fed67069bd093a6215aeaf81be81c9933
refs/heads/master
2021-01-19T07:23:07.743445
2015-11-08T13:17:29
2015-11-08T13:17:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,578
cpp
//===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IRBuilder class, which is used as a convenient way // to create LLVM instructions with a consistent and simplified interface. // //===----------------------------------------------------------------------===// #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Statepoint.h" using namespace llvm; /// CreateGlobalString - Make a new global variable with an initializer that /// has array of i8 type filled in with the nul terminated string value /// specified. If Name is specified, it is the name of the global variable /// created. GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str, const Twine &Name, unsigned AddressSpace) { Constant *StrConstant = ConstantDataArray::getString(Context, Str); Module &M = *BB->getParent()->getParent(); GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(), true, GlobalValue::PrivateLinkage, StrConstant, Name, nullptr, GlobalVariable::NotThreadLocal, AddressSpace); GV->setUnnamedAddr(true); return GV; } Type *IRBuilderBase::getCurrentFunctionReturnType() const { assert(BB && BB->getParent() && "No current function!"); return BB->getParent()->getReturnType(); } Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) { PointerType *PT = cast<PointerType>(Ptr->getType()); if (PT->getElementType()->isIntegerTy(8)) return Ptr; // Otherwise, we need to insert a bitcast. PT = getInt8PtrTy(PT->getAddressSpace()); BitCastInst *BCI = new BitCastInst(Ptr, PT, ""); BB->getInstList().insert(InsertPt, BCI); SetInstDebugLocation(BCI); return BCI; } static CallInst *createCallHelper(Value *Callee, ArrayRef<Value *> Ops, IRBuilderBase *Builder, const Twine& Name="") { CallInst *CI = CallInst::Create(Callee, Ops, Name); Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI); Builder->SetInstDebugLocation(CI); return CI; } static InvokeInst *createInvokeHelper(Value *Invokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Value *> Ops, IRBuilderBase *Builder, const Twine &Name = "") { InvokeInst *II = InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name); Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(), II); Builder->SetInstDebugLocation(II); return II; } CallInst *IRBuilderBase:: CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align, bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag, MDNode *NoAliasTag) { Ptr = getCastedInt8PtrValue(Ptr); Value *Ops[] = { Ptr, Val, Size, getInt32(Align), getInt1(isVolatile) }; Type *Tys[] = { Ptr->getType(), Size->getType() }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys); CallInst *CI = createCallHelper(TheFn, Ops, this); // Set the TBAA info if present. if (TBAATag) CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); if (ScopeTag) CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag); if (NoAliasTag) CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag); return CI; } CallInst *IRBuilderBase:: CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align, bool isVolatile, MDNode *TBAATag, MDNode *TBAAStructTag, MDNode *ScopeTag, MDNode *NoAliasTag) { Dst = getCastedInt8PtrValue(Dst); Src = getCastedInt8PtrValue(Src); Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) }; Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys); CallInst *CI = createCallHelper(TheFn, Ops, this); // Set the TBAA info if present. if (TBAATag) CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); // Set the TBAA Struct info if present. if (TBAAStructTag) CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag); if (ScopeTag) CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag); if (NoAliasTag) CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag); return CI; } CallInst *IRBuilderBase:: CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align, bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag, MDNode *NoAliasTag) { Dst = getCastedInt8PtrValue(Dst); Src = getCastedInt8PtrValue(Src); Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) }; Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys); CallInst *CI = createCallHelper(TheFn, Ops, this); // Set the TBAA info if present. if (TBAATag) CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); if (ScopeTag) CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag); if (NoAliasTag) CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag); return CI; } CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) { assert(isa<PointerType>(Ptr->getType()) && "lifetime.start only applies to pointers."); Ptr = getCastedInt8PtrValue(Ptr); if (!Size) Size = getInt64(-1); else assert(Size->getType() == getInt64Ty() && "lifetime.start requires the size to be an i64"); Value *Ops[] = { Size, Ptr }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start); return createCallHelper(TheFn, Ops, this); } CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) { assert(isa<PointerType>(Ptr->getType()) && "lifetime.end only applies to pointers."); Ptr = getCastedInt8PtrValue(Ptr); if (!Size) Size = getInt64(-1); else assert(Size->getType() == getInt64Ty() && "lifetime.end requires the size to be an i64"); Value *Ops[] = { Size, Ptr }; Module *M = BB->getParent()->getParent(); Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end); return createCallHelper(TheFn, Ops, this); } CallInst *IRBuilderBase::CreateAssumption(Value *Cond) { assert(Cond->getType() == getInt1Ty() && "an assumption condition must be of type i1"); Value *Ops[] = { Cond }; Module *M = BB->getParent()->getParent(); Value *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume); return createCallHelper(FnAssume, Ops, this); } /// Create a call to a Masked Load intrinsic. /// Ptr - the base pointer for the load /// Align - alignment of the source location /// Mask - an vector of booleans which indicates what vector lanes should /// be accessed in memory /// PassThru - a pass-through value that is used to fill the masked-off lanes /// of the result /// Name - name of the result variable CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask, Value *PassThru, const Twine &Name) { assert(Ptr->getType()->isPointerTy() && "Ptr must be of pointer type"); // DataTy is the overloaded type Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); assert(DataTy->isVectorTy() && "Ptr should point to a vector"); if (!PassThru) PassThru = UndefValue::get(DataTy); Value *Ops[] = { Ptr, getInt32(Align), Mask, PassThru}; return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops, DataTy, Name); } /// Create a call to a Masked Store intrinsic. /// Val - the data to be stored, /// Ptr - the base pointer for the store /// Align - alignment of the destination location /// Mask - an vector of booleans which indicates what vector lanes should /// be accessed in memory CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align, Value *Mask) { Value *Ops[] = { Val, Ptr, getInt32(Align), Mask }; // Type of the data to be stored - the only one overloaded type return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, Val->getType()); } /// Create a call to a Masked intrinsic, with given intrinsic Id, /// an array of operands - Ops, and one overloaded type - DataTy CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops, Type *DataTy, const Twine &Name) { Module *M = BB->getParent()->getParent(); Type *OverloadedTypes[] = { DataTy }; Value *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes); return createCallHelper(TheFn, Ops, this, Name); } static std::vector<Value *> getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs) { std::vector<Value *> Args; Args.push_back(B.getInt64(ID)); Args.push_back(B.getInt32(NumPatchBytes)); Args.push_back(ActualCallee); Args.push_back(B.getInt32(CallArgs.size())); Args.push_back(B.getInt32((unsigned)StatepointFlags::None)); Args.insert(Args.end(), CallArgs.begin(), CallArgs.end()); Args.push_back(B.getInt32(0 /* no transition args */)); Args.push_back(B.getInt32(DeoptArgs.size())); Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end()); Args.insert(Args.end(), GCArgs.begin(), GCArgs.end()); return Args; } CallInst *IRBuilderBase::CreateGCStatepointCall( uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { // Extract out the type of the callee. PointerType *FuncPtrType = cast<PointerType>(ActualCallee->getType()); assert(isa<FunctionType>(FuncPtrType->getElementType()) && "actual callee must be a callable value"); Module *M = BB->getParent()->getParent(); // Fill in the one generic type'd argument (the function is also vararg) Type *ArgTypes[] = { FuncPtrType }; Function *FnStatepoint = Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint, ArgTypes); std::vector<llvm::Value *> Args = getStatepointArgs( *this, ID, NumPatchBytes, ActualCallee, CallArgs, DeoptArgs, GCArgs); return createCallHelper(FnStatepoint, Args, this, Name); } CallInst *IRBuilderBase::CreateGCStatepointCall( uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { std::vector<Value *> VCallArgs; for (auto &U : CallArgs) VCallArgs.push_back(U.get()); return CreateGCStatepointCall(ID, NumPatchBytes, ActualCallee, VCallArgs, DeoptArgs, GCArgs, Name); } InvokeInst *IRBuilderBase::CreateGCStatepointInvoke( uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { // Extract out the type of the callee. PointerType *FuncPtrType = cast<PointerType>(ActualInvokee->getType()); assert(isa<FunctionType>(FuncPtrType->getElementType()) && "actual callee must be a callable value"); Module *M = BB->getParent()->getParent(); // Fill in the one generic type'd argument (the function is also vararg) Function *FnStatepoint = Intrinsic::getDeclaration( M, Intrinsic::experimental_gc_statepoint, {FuncPtrType}); std::vector<llvm::Value *> Args = getStatepointArgs( *this, ID, NumPatchBytes, ActualInvokee, InvokeArgs, DeoptArgs, GCArgs); return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, this, Name); } InvokeInst *IRBuilderBase::CreateGCStatepointInvoke( uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs, ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) { std::vector<Value *> VCallArgs; for (auto &U : InvokeArgs) VCallArgs.push_back(U.get()); return CreateGCStatepointInvoke(ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, VCallArgs, DeoptArgs, GCArgs, Name); } CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint, Type *ResultType, const Twine &Name) { Intrinsic::ID ID = Intrinsic::experimental_gc_result; Module *M = BB->getParent()->getParent(); Type *Types[] = {ResultType}; Value *FnGCResult = Intrinsic::getDeclaration(M, ID, Types); Value *Args[] = {Statepoint}; return createCallHelper(FnGCResult, Args, this, Name); } CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint, int BaseOffset, int DerivedOffset, Type *ResultType, const Twine &Name) { Module *M = BB->getParent()->getParent(); Type *Types[] = {ResultType}; Value *FnGCRelocate = Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types); Value *Args[] = {Statepoint, getInt32(BaseOffset), getInt32(DerivedOffset)}; return createCallHelper(FnGCRelocate, Args, this, Name); }
[ "agarny@hellix.com" ]
agarny@hellix.com
e80ec41c56d94a4c3de845de4e4ccb810f1af059
9639e3e55f2ab6113e3d7499ee2a35a4c54ebd95
/tests/cpp/visitor_tests.cpp
11175adc191b98bb41f1d811c5a1e5eba83d1d83
[ "MIT", "BSD-3-Clause" ]
permissive
wayrick/yaramod
111d59507b98ea6642d948ba24d552bf5cd78249
e3b8528c7f4167047e5ffbb0e3fef91eecb5aaa4
refs/heads/master
2022-11-11T23:04:56.014495
2020-06-30T12:47:27
2020-06-30T12:47:27
276,095,733
0
0
null
2020-06-30T12:44:19
2020-06-30T12:44:19
null
UTF-8
C++
false
false
26,833
cpp
/** * @file tests/visitor_tests.cpp * @brief Tests for the YARA representation. * @copyright (c) 2019 Avast Software, licensed under the MIT license */ #include <clocale> #include <gtest/gtest.h> #include "yaramod/builder/yara_expression_builder.h" #include "yaramod/parser/parser_driver.h" #include "yaramod/utils/modifying_visitor.h" using namespace ::testing; namespace yaramod { namespace tests { class VisitorTests : public Test { public: VisitorTests() : driver() {} void prepareInput(const std::string& inputText) { input.str(std::string()); input.clear(); input << inputText; input_text = inputText; } std::stringstream input; std::string input_text; ParserDriver driver; }; TEST_F(VisitorTests, StringExpressionVisitorInpactOnTokenStream) { class StringExpressionUpper : public yaramod::ModifyingVisitor { public: void process(const YaraFile& file) { for (const std::shared_ptr<Rule>& rule : file.getRules()) modify(rule->getCondition()); } virtual yaramod::VisitResult visit(StringExpression* expr) override { std::string id = expr->getId(); std::string upper; for (char c : id) upper += std::toupper(c); expr->setId(upper); return {}; } }; prepareInput( R"( import "cuckoo" rule rule_name { strings: $string1 = "string 1" condition: $string1 and !string1 == 1 } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); StringExpressionUpper visitor; visitor.process(yara_file); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; EXPECT_EQ("rule_name", rule->getName()); EXPECT_EQ("$STRING1 and !STRING1 == 1", rule->getCondition()->getText()); std::string expected = R"( import "cuckoo" rule rule_name { strings: $STRING1 = "string 1" condition: $STRING1 and !STRING1 == 1 } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, RegexpModifyingVisitorInpactOnTokenStream) { class TestModifyingVisitor : public yaramod::ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { modify(rule->getCondition()); } virtual yaramod::VisitResult visit(RegexpExpression* expr) override { auto new_condition = regexp("abc", "i").get(); expr->exchangeTokens(new_condition.get()); return new_condition; } }; prepareInput( R"( import "cuckoo" rule rule_name { condition: true and cuckoo.network.http_request(/http:\/\/someone\.doingevil\.com/) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; TestModifyingVisitor visitor; visitor.process_rule(rule); EXPECT_EQ("rule_name", rule->getName()); EXPECT_EQ("true and cuckoo.network.http_request(/abc/i)", rule->getCondition()->getText()); std::string expected = R"( import "cuckoo" rule rule_name { condition: true and cuckoo.network.http_request(/abc/i) } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, BoolModifyingVisitorInpactOnTokenStream1) { class TestModifyingVisitor : public yaramod::ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { auto modified = modify(rule->getCondition()); rule->setCondition(std::move(modified)); } virtual yaramod::VisitResult visit(BoolLiteralExpression* expr) override { auto new_condition = boolVal(false).get(); expr->exchangeTokens(new_condition.get()); return new_condition; } }; prepareInput( R"( import "cuckoo" rule rule_name { condition: true } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; TestModifyingVisitor visitor; visitor.process_rule(rule); EXPECT_EQ("rule_name", rule->getName()); std::string expected = R"( import "cuckoo" rule rule_name { condition: false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); EXPECT_EQ("false", rule->getCondition()->getText()); } TEST_F(VisitorTests, BoolModifyingVisitorInpactOnTokenStream2) { class TestModifyingVisitor : public yaramod::ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { auto modified = modify(rule->getCondition()); rule->setCondition(std::move(modified)); } virtual yaramod::VisitResult visit(BoolLiteralExpression* expr) override { auto new_condition = boolVal(false).get(); expr->exchangeTokens(new_condition.get()); return new_condition; } }; prepareInput( R"( import "cuckoo" rule rule_name { condition: true and true } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; TestModifyingVisitor visitor; visitor.process_rule(rule); EXPECT_EQ("rule_name", rule->getName()); std::string expected = R"( import "cuckoo" rule rule_name { condition: false and false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); EXPECT_EQ("false and false", rule->getCondition()->getText()); } TEST_F(VisitorTests, IntLiteralModifyingVisitorInpactOnTokenStream) { class TestModifyingVisitor : public yaramod::ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { auto modified = modify(rule->getCondition()); rule->setCondition(std::move(modified)); } virtual yaramod::VisitResult visit(IntLiteralExpression* expr) override { auto new_condition = yaramod::intVal(111).get(); expr->exchangeTokens(new_condition.get()); return new_condition; } }; prepareInput( R"( import "cuckoo" rule rule_name { condition: 10 } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; TestModifyingVisitor visitor; visitor.process_rule(rule); std::string expected = R"( import "cuckoo" rule rule_name { condition: 111 } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); EXPECT_EQ("111", rule->getCondition()->getText()); } class CuckooFunctionReplacer : public ModifyingVisitor { public: CuckooFunctionReplacer(YaraFile* yaraFile) : _yaraFile(yaraFile) , _needsToBeRemoved(false) , _fileAccessSymbol(nullptr) , _keyAccessSymbol(nullptr) { } bool preFileTransform() { auto cuckooStruct = std::static_pointer_cast<yaramod::StructureSymbol>(_yaraFile->findSymbol("cuckoo")); if (cuckooStruct == nullptr) return false; auto filesystemStruct = std::static_pointer_cast<yaramod::StructureSymbol>(cuckooStruct->getAttribute("filesystem").value()); _fileAccessSymbol = filesystemStruct->getAttribute("file_access").value(); auto registryStruct = std::static_pointer_cast<yaramod::StructureSymbol>(cuckooStruct->getAttribute("registry").value()); _keyAccessSymbol = registryStruct->getAttribute("key_access").value(); return true; } void postRuleTransform(const std::shared_ptr<Rule>& rule) { if (_needsToBeRemoved) { auto new_condition = boolVal(false).get(); rule->getCondition()->exchangeTokens(new_condition.get()); rule->setCondition(new_condition); } _needsToBeRemoved = false; } void process_rule(const std::shared_ptr<Rule>& rule) { preFileTransform(); auto modified = modify(rule->getCondition()); if (!_needsToBeRemoved) rule->setCondition(std::move(modified)); postRuleTransform(rule); } virtual yaramod::VisitResult visit(IntLiteralExpression* expr) override { auto new_condition = yaramod::intVal(111).get(); expr->exchangeTokens(new_condition.get()); return new_condition; } virtual VisitResult visit(NotExpression* expr) override { expr->getOperand()->accept(this); if (_needsToBeRemoved) { auto new_condition = boolVal(false).get(); expr->getOperand()->exchangeTokens(new_condition.get()); expr->setOperand(new_condition); } _needsToBeRemoved = false; return {}; } virtual VisitResult visit(AndExpression* expr) override { _handleBinaryExpression(expr); return {}; } virtual VisitResult visit(OrExpression* expr) override { _handleBinaryExpression(expr); return {}; } virtual VisitResult visit(FunctionCallExpression* expr) override { auto functionName = expr->getFunction()->getText(); if (isFunctionInBlacklist(functionName, avastOnlyFunctionsRemove)) _needsToBeRemoved = true; return expr; } virtual VisitResult visit(ParenthesesExpression* expr) override { expr->getEnclosedExpression()->accept(this); if (_needsToBeRemoved) { auto new_condition = boolVal(false).get(); expr->getEnclosedExpression()->exchangeTokens(new_condition.get()); expr->setEnclosedExpression(new_condition); } _needsToBeRemoved = false; return {}; } private: bool isFunctionInBlacklist(const std::string& functionName, const std::unordered_set<std::string>& blacklist) { return blacklist.find(functionName) != blacklist.end(); } template <typename BinaryExp> void _handleBinaryExpression(BinaryExp* expr) { expr->getLeftOperand()->accept(this); bool leftNeedsToBeRemoved = _needsToBeRemoved; _needsToBeRemoved = false; expr->getRightOperand()->accept(this); bool rightNeedsToBeRemoved = _needsToBeRemoved; _needsToBeRemoved = false; if (leftNeedsToBeRemoved && rightNeedsToBeRemoved) { _needsToBeRemoved = true; } else if (leftNeedsToBeRemoved) { auto new_condition = boolVal(false).get(); expr->getLeftOperand()->exchangeTokens(new_condition.get()); expr->setLeftOperand(new_condition); } else if (rightNeedsToBeRemoved) { auto new_condition = boolVal(false).get(); expr->getRightOperand()->exchangeTokens(new_condition.get()); expr->setRightOperand(new_condition); } } YaraFile* _yaraFile; bool _needsToBeRemoved; std::shared_ptr<Symbol> _fileAccessSymbol; std::shared_ptr<Symbol> _keyAccessSymbol; const std::unordered_set<std::string> avastOnlyFunctionsRemove = { "cuckoo.network.http_request_body" }; }; TEST_F(VisitorTests, CuckooFunctionReplacerBoolLiteralExpression) { prepareInput( R"( import "cuckoo" rule rule_name { condition: false } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule); std::string expected = R"( import "cuckoo" rule rule_name { condition: false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); EXPECT_EQ("false", rule->getCondition()->getText()); } TEST_F(VisitorTests, CuckooFunctionReplacerCuckooSyncEvent) { prepareInput( R"( import "cuckoo" rule rule_name { condition: cuckoo.network.http_request_body(/http:\/\/someone\.doingevil\.com/) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule); ASSERT_EQ(R"(import "cuckoo" rule rule_name { condition: false })", yara_file.getText()); std::string expected = R"( import "cuckoo" rule rule_name { condition: false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("false", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, CuckooFunctionReplacerOrExpression1) { prepareInput( R"( import "cuckoo" rule rule_name { condition: cuckoo.network.http_request_body(/a/) or cuckoo.network.http_request_body(/b/) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule); ASSERT_EQ(R"(import "cuckoo" rule rule_name { condition: false })", yara_file.getText()); std::string expected = R"( import "cuckoo" rule rule_name { condition: false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("false", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, CuckooFunctionReplacerOrExpression2) { prepareInput( R"( import "cuckoo" rule rule_name { condition: entrypoint == 0 or cuckoo.network.http_request_body(/b/) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule); ASSERT_EQ(R"(import "cuckoo" rule rule_name { condition: entrypoint == 111 or false })", yara_file.getText()); std::string expected = R"( import "cuckoo" rule rule_name { condition: entrypoint == 111 or false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("entrypoint == 111 or false", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, CuckooFunctionReplacerOrExpression3) { prepareInput( R"( import "cuckoo" rule rule_name { condition: entrypoint == 0 or ( cuckoo.network.http_request_body(/a/) or cuckoo.network.http_request_body(/b/) ) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule); ASSERT_EQ(R"(import "cuckoo" rule rule_name { condition: entrypoint == 111 or (false) })", yara_file.getText()); std::string expected = R"( import "cuckoo" rule rule_name { condition: entrypoint == 111 or ( false ) } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("entrypoint == 111 or (false)", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, CuckooFunctionReplacerOrExpression4) { prepareInput( R"( import "cuckoo" rule rule_name { condition: cuckoo.network.http_request_body(/a/) or ( filesize > 12 and true or cuckoo.network.http_request_body(/b/) ) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule); ASSERT_EQ(R"(import "cuckoo" rule rule_name { condition: false or (filesize > 111 and true or false) })", yara_file.getText()); std::string expected = R"( import "cuckoo" rule rule_name { condition: false or ( filesize > 111 and true or false ) } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("false or (filesize > 111 and true or false)", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, CuckooFunctionReplacerAndExpression1) { prepareInput( R"( import "pe" import "elf" import "cuckoo" /** * Random block comment */ rule rule_1 : Tag1 Tag2 { meta: info = "meta info" version = 2 strings: $1 = "plain string" wide $2 = { ab cd ef } $3 = /ab*c/ condition: pe.exports("ExitProcess") and cuckoo.network.http_request_body(/a/) and for any of them : ( $ at pe.entry_point ) } // Random one-line comment rule rule_2 { meta: valid = true strings: $abc = "no case full word" nocase fullword condition: elf.type == elf.ET_EXEC and $abc at elf.entry_point and cuckoo.network.http_request_body(/b/) and filesize == 10 } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(2u, yara_file.getRules().size()); const auto& rule1 = yara_file.getRules()[0]; const auto& rule2 = yara_file.getRules()[1]; CuckooFunctionReplacer cuckooReplacer(&yara_file); cuckooReplacer.process_rule(rule1); cuckooReplacer.process_rule(rule2); EXPECT_EQ( R"(import "pe" import "elf" import "cuckoo" rule rule_1 : Tag1 Tag2 { meta: info = "meta info" version = 2 strings: $1 = "plain string" wide $2 = { AB CD EF } $3 = /ab*c/ condition: pe.exports("ExitProcess") and false and for any of them : ( $ at pe.entry_point ) } rule rule_2 { meta: valid = true strings: $abc = "no case full word" nocase fullword condition: elf.type == elf.ET_EXEC and $abc at elf.entry_point and false and filesize == 111 })", yara_file.getText()); std::string expected = R"( import "pe" import "elf" import "cuckoo" /** * Random block comment */ rule rule_1 : Tag1 Tag2 { meta: info = "meta info" version = 2 strings: $1 = "plain string" wide $2 = { ab cd ef } $3 = /ab*c/ condition: pe.exports("ExitProcess") and false and for any of them : ( $ at pe.entry_point ) } // Random one-line comment rule rule_2 { meta: valid = true strings: $abc = "no case full word" nocase fullword condition: elf.type == elf.ET_EXEC and $abc at elf.entry_point and false and filesize == 111 } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("pe.exports(\"ExitProcess\") and false and for any of them : ( $ at pe.entry_point )", rule1->getCondition()->getText()); EXPECT_EQ(expected, rule1->getCondition()->getTokenStream()->getText()); EXPECT_EQ("elf.type == elf.ET_EXEC and $abc at elf.entry_point and false and filesize == 111", rule2->getCondition()->getText()); EXPECT_EQ(expected, rule2->getCondition()->getTokenStream()->getText()); } class AndExpressionSwitcher : public ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { auto modified = modify(rule->getCondition()); rule->setCondition(std::move(modified)); } virtual VisitResult visit(AndExpression* expr) override { _handleBinaryExpression(expr); return {}; } private: template <typename BinaryExp> void _handleBinaryExpression(BinaryExp* expr) { expr->getLeftOperand()->accept(this); expr->getRightOperand()->accept(this); std::shared_ptr<Expression> tmp_condition = expr->getLeftOperand(); expr->getLeftOperand()->exchangeTokens(expr->getRightOperand().get()); expr->setLeftOperand(expr->getRightOperand()); expr->setRightOperand(tmp_condition); } }; TEST_F(VisitorTests, AndExpressionSwitcherAndExpression1) { prepareInput( R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" condition: any of them and $2 } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; AndExpressionSwitcher visitor; visitor.process_rule(rule); EXPECT_EQ( R"(rule rule_1 { strings: $1 = "s1" wide $2 = "s2" condition: $2 and any of them })", yara_file.getText()); std::string expected = R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" condition: $2 and any of them } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("$2 and any of them", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } TEST_F(VisitorTests, AndExpressionSwitcherAndExpression2) { prepareInput( R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" $3 = "s3" $4 = "s4" $5 = "s5" fullword $6 = "s6" condition: ( $1 and $2 and $3 and true and $4 and $5 and $6 ) or false } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; AndExpressionSwitcher visitor; visitor.process_rule(rule); EXPECT_EQ( R"(rule rule_1 { strings: $1 = "s1" wide $2 = "s2" $3 = "s3" $4 = "s4" $5 = "s5" fullword $6 = "s6" condition: ($6 and $5 and $4 and true and $3 and $2 and $1) or false })", yara_file.getText()); std::string expected = R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" $3 = "s3" $4 = "s4" $5 = "s5" fullword $6 = "s6" condition: ( $6 and $5 and $4 and true and $3 and $2 and $1 ) or false } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("($6 and $5 and $4 and true and $3 and $2 and $1) or false", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } class OrExpressionSwitcher : public ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { auto modified = modify(rule->getCondition()); rule->setCondition(std::move(modified)); } virtual VisitResult visit(OrExpression* expr) override { auto output = _handleBinaryExpression(expr); return output; } private: template <typename BinaryExp> std::shared_ptr<Expression> _handleBinaryExpression(BinaryExp* expr) { //save old TS and expression start-end within it TokenStreamContext context(expr); auto leftResult = expr->getLeftOperand()->accept(this); if (resultIsModified(leftResult)) expr->setLeftOperand(std::get<std::shared_ptr<Expression>>(leftResult)); auto rightResult = expr->getRightOperand()->accept(this); if (resultIsModified(rightResult)) expr->setRightOperand(std::get<std::shared_ptr<Expression>>(rightResult)); //create new expression auto output = disjunction({YaraExpressionBuilder{expr->getRightOperand()}, YaraExpressionBuilder{expr->getLeftOperand()}}).get(); cleanUpTokenStreams(context, output.get()); return output; } }; TEST_F(VisitorTests, OrExpressionSwitcherOrExpression1) { prepareInput( R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" condition: true and ( any of them or $2 ) } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; OrExpressionSwitcher visitor; visitor.process_rule(rule); EXPECT_EQ( R"(rule rule_1 { strings: $1 = "s1" wide $2 = "s2" condition: true and ($2 or any of them) })", yara_file.getText()); std::string expected = R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" condition: true and ( $2 or any of them ) } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("true and ($2 or any of them)", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); EXPECT_EQ(rule->getCondition()->getFirstTokenIt()->getPureText(), "true"); EXPECT_EQ(rule->getCondition()->getLastTokenIt()->getPureText(), ")"); EXPECT_TRUE(rule->getCondition()->isBool()); auto expAnd = std::static_pointer_cast<const AndExpression>(rule->getCondition()); auto expPar = std::static_pointer_cast<const ParenthesesExpression>(expAnd->getRightOperand()); auto expOr = std::static_pointer_cast<const OrExpression>(expPar->getEnclosedExpression()); auto expLeft = std::static_pointer_cast<const StringExpression>(expOr->getLeftOperand()); auto expRight = std::static_pointer_cast<const OfExpression>(expOr->getRightOperand()); EXPECT_EQ(expOr->getOperator()->getPureText(), "or"); EXPECT_EQ(expLeft->getFirstTokenIt()->getPureText(), "$2"); EXPECT_EQ(expLeft->getLastTokenIt()->getPureText(), "$2"); EXPECT_EQ(expRight->getFirstTokenIt()->getPureText(), "any"); EXPECT_EQ(expRight->getLastTokenIt()->getPureText(), "them"); } TEST_F(VisitorTests, OrExpressionSwitcherOrExpression2) { prepareInput( R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" $3 = "s3" condition: $1 or $2 or $3 } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; OrExpressionSwitcher visitor; visitor.process_rule(rule); EXPECT_EQ( R"(rule rule_1 { strings: $1 = "s1" wide $2 = "s2" $3 = "s3" condition: $3 or $2 or $1 })", yara_file.getText()); std::string expected = R"( rule rule_1 { strings: $1 = "s1" wide $2 = "s2" $3 = "s3" condition: $3 or $2 or $1 } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("$3 or $2 or $1", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } class EqModifyer : public yaramod::ModifyingVisitor { public: void process_rule(const std::shared_ptr<Rule>& rule) { auto modified = modify(rule->getCondition()); rule->setCondition(std::move(modified)); } virtual VisitResult visit(EqExpression* expr) override { TokenStreamContext context(expr); auto leftResult = expr->getLeftOperand()->accept(this); if (resultIsModified(leftResult)) expr->setLeftOperand(std::get<std::shared_ptr<Expression>>(leftResult)); auto rightResult = expr->getRightOperand()->accept(this); if (resultIsModified(rightResult)) expr->setRightOperand(std::get<std::shared_ptr<Expression>>(rightResult)); auto output = ((YaraExpressionBuilder{expr->getRightOperand()}) != (YaraExpressionBuilder{expr->getLeftOperand()})).get(); cleanUpTokenStreams(context, output.get()); return output; } }; TEST_F(VisitorTests, EqExpressionSwitcher) { prepareInput( R"( rule rule_1 { strings: $str1 = "s1" wide $str2 = "s2" $str3 = "s3" condition: !str1 == !str2 or !str2 == !str3 or !str1 == !str3 } )"); EXPECT_TRUE(driver.parse(input)); auto yara_file = driver.getParsedFile(); ASSERT_EQ(1u, yara_file.getRules().size()); const auto& rule = yara_file.getRules()[0]; EqModifyer visitor; visitor.process_rule(rule); EXPECT_EQ( R"(rule rule_1 { strings: $str1 = "s1" wide $str2 = "s2" $str3 = "s3" condition: !str2 != !str1 or !str3 != !str2 or !str3 != !str1 })", yara_file.getText()); std::string expected = R"( rule rule_1 { strings: $str1 = "s1" wide $str2 = "s2" $str3 = "s3" condition: !str2 != !str1 or !str3 != !str2 or !str3 != !str1 } )"; EXPECT_EQ(expected, yara_file.getTextFormatted()); EXPECT_EQ("!str2 != !str1 or !str3 != !str2 or !str3 != !str1", rule->getCondition()->getText()); EXPECT_EQ(expected, rule->getCondition()->getTokenStream()->getText()); } } }
[ "noreply@github.com" ]
wayrick.noreply@github.com
4956cec3c49e64d7e64efe25f84a62e1cbaea5cc
e1e43f3e90aa96d758be7b7a8356413a61a2716f
/datacommsserver/esockserver/test/TE_ESock/EsockTestSection1.cpp
127f5edfdade5df4f41368d9a6a63c9107cd6ce6
[]
no_license
SymbianSource/oss.FCL.sf.os.commsfw
76b450b5f52119f6bf23ae8a5974c9a09018fdfa
bc8ac1a6d5273cbfa7852bbb8ce27d6ddc076984
refs/heads/master
2021-01-18T23:55:06.285537
2010-10-03T23:21:43
2010-10-03T23:21:43
72,773,202
0
1
null
null
null
null
UTF-8
C++
false
false
13,403
cpp
// Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // This contains ESock Test cases from section 1 // // // EPOC includes #include <e32base.h> #include <in_sock.h> // Test system includes #include "EsockTestSection1.h" // Test step 1.1 const TDesC& CEsockTest1_1::GetTestName() { // store the name of this test case _LIT(ret,"Test1.1"); return ret; } CEsockTest1_1::~CEsockTest1_1() { } enum TVerdict CEsockTest1_1::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.1")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d blank socket(s)"), nSockets); TInt ret = OpenSockets(nSockets); TESTEL(KErrNone == ret, ret); return EPass; } // Test step 1.2 const TDesC& CEsockTest1_2::GetTestName() { // store the name of this test case _LIT(ret,"Test1.2"); return ret; } CEsockTest1_2::~CEsockTest1_2() { } enum TVerdict CEsockTest1_2::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.2")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d TCP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockStream, KProtocolInetTcp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) (iEsockSuite->GetSocketHandle(i + 1)).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == 0); } return EPass; } // Test step 1.3 const TDesC& CEsockTest1_3::GetTestName() { // store the name of this test case _LIT(ret,"Test1.3"); return ret; } CEsockTest1_3::~CEsockTest1_3() { } enum TVerdict CEsockTest1_3::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.3")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d UDP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetUdp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<39> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) (iEsockSuite->GetSocketHandle(i + 1)).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == 0); } return EPass; } // Test step 1.4 const TDesC& CEsockTest1_4::GetTestName() { // store the name of this test case _LIT(ret,"Test1.4"); return ret; } CEsockTest1_4::~CEsockTest1_4() { } enum TVerdict CEsockTest1_4::easyTestStepL() { // Open n ICMP sockets // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.4")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d ICMP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetIcmp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.5 const TDesC& CEsockTest1_5::GetTestName() { // store the name of this test case _LIT(ret,"Test1.5"); return ret; } CEsockTest1_5::~CEsockTest1_5() { } enum TVerdict CEsockTest1_5::easyTestStepL() { // Open n IP sockets // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.5")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d IP socket(s)"), nSockets); TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetIp, nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.6 const TDesC& CEsockTest1_6::GetTestName() { // store the name of this test case _LIT(ret,"Test1.6"); return ret; } CEsockTest1_6::~CEsockTest1_6() { } enum TVerdict CEsockTest1_6::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.6")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d TCP socket(s) by name"), nSockets); TInt ret = OpenSockets(_L("tcp"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.7 const TDesC& CEsockTest1_7::GetTestName() { // store the name of this test case _LIT(ret,"Test1.7"); return ret; } CEsockTest1_7::~CEsockTest1_7() { } enum TVerdict CEsockTest1_7::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.7")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d UDP socket(s) by name"), nSockets); TInt ret = OpenSockets(_L("udp"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.8 const TDesC& CEsockTest1_8::GetTestName() { // store the name of this test case _LIT(ret,"Test1.8"); return ret; } CEsockTest1_8::~CEsockTest1_8() { } enum TVerdict CEsockTest1_8::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.8")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d ICMP socket(s) by name"), nSockets); TInt ret = OpenSockets(_L("icmp"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == 0); } return EPass; } // Test step 1.9 const TDesC& CEsockTest1_9::GetTestName() { // store the name of this test case _LIT(ret,"Test1.9"); return ret; } CEsockTest1_9::~CEsockTest1_9() { } enum TVerdict CEsockTest1_9::easyTestStepL() { // get number of sockets from script TInt nSockets; // number of sockets to open TESTL(GetIntFromConfig(SectionName(_L("Test_1.9")), _L("numSockets"), nSockets)); Logger().WriteFormat(_L("Open %d IP sockets by name"), nSockets); TInt ret = OpenSockets(_L("ip"), nSockets); TESTEL(KErrNone == ret, ret); TInetAddr addr; TBuf<32> buf; for (TInt i = 0; i < nSockets; i++) { // Get local address of the socket (Empty) iEsockSuite->GetSocketHandle(i + 1).LocalName(addr); // Check length of buffer, should be set to (Zero) addr.OutputWithScope(buf); TESTL(buf.Length() == KErrNone); } return EPass; } // Test step 1.10 const TDesC& CEsockTest1_10::GetTestName() { // store the name of this test case _LIT(ret,"Test1.10"); return ret; } CEsockTest1_10::~CEsockTest1_10() { } enum TVerdict CEsockTest1_10::easyTestStepL() { // Open a TCP socket with invalid socket type Logger().WriteFormat(_L("Open socket, of invalid type, for TCP")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, 0, KProtocolInetTcp); TESTEL(ret==KErrBadName, ret); // Open a UDP socket with invalid socket type Logger().WriteFormat(_L("Open socket, of invalid type, for UDP")); RSocket sock2; CleanupClosePushL(sock2); ret = sock2.Open(iEsockSuite->iSocketServer, KAfInet, 12, KProtocolInetUdp); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(2, &sock); return EPass; } // Test step 1.11 const TDesC& CEsockTest1_11::GetTestName() { // store the name of this test case _LIT(ret,"Test1.11"); return ret; } CEsockTest1_11::~CEsockTest1_11() { } enum TVerdict CEsockTest1_11::easyTestStepL() { // open sockets with an invalid protocol // get protocol id's from script TInt protocol1, protocol2; TESTL(GetIntFromConfig(SectionName(_L("Test_1.11")), _L("protocolId1"), protocol1)); TESTL(GetIntFromConfig(SectionName(_L("Test_1.11")), _L("protocolId2"), protocol2)); Logger().WriteFormat(_L("Open stream socket for invalid protocol")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockStream, protocol1); TESTEL(ret==KErrBadName, ret); Logger().WriteFormat(_L("Open datagram socket for invalid protocol")); RSocket sock2; CleanupClosePushL(sock2); ret = sock2.Open(iEsockSuite->iSocketServer, KAfInet, KSockDatagram, protocol2); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(2, &sock); return EPass; } // Test step 1.12 const TDesC& CEsockTest1_12::GetTestName() { // store the name of this test case _LIT(ret,"Test1.12"); return ret; } CEsockTest1_12::~CEsockTest1_12() { } enum TVerdict CEsockTest1_12::easyTestStepL() { Logger().WriteFormat(_L("Open stream socket for UDP")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockStream, KProtocolInetUdp); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(); return EPass; } // Test step 1.13 const TDesC& CEsockTest1_13::GetTestName() { // store the name of this test case _LIT(ret,"Test1.13"); return ret; } CEsockTest1_13::~CEsockTest1_13() { } enum TVerdict CEsockTest1_13::easyTestStepL() { Logger().WriteFormat(_L("Open datagram socket for TCP")); RSocket sock; CleanupClosePushL(sock); TInt ret = sock.Open(iEsockSuite->iSocketServer, KAfInet, KSockDatagram, KProtocolInetTcp); TESTEL(ret==KErrBadName, ret); CleanupStack::PopAndDestroy(); return EPass; } // Test step 1.14 const TDesC& CEsockTest1_14::GetTestName() { // store the name of this test case _LIT(ret,"Test1.14"); return ret; } CEsockTest1_14::~CEsockTest1_14() { } enum TVerdict CEsockTest1_14::easyTestStepL() { Logger().WriteFormat(_L("Open socket for invalid protocol by name")); RSocket sock; CleanupClosePushL(sock); TInt ret =sock.Open(iEsockSuite->iSocketServer, _L("abc")); TESTEL(ret==KErrNotFound, ret); CleanupStack::PopAndDestroy(); return EPass; } // Test step 1.15 const TDesC& CEsockTest1_15::GetTestName() { // store the name of this test case _LIT(ret,"Test1.15"); return ret; } CEsockTest1_15::~CEsockTest1_15() { } enum TVerdict CEsockTest1_15::easyTestStepL() { CloseSockets(2); return EPass; } // Test step 1.16 const TDesC& CEsockTest1_16::GetTestName() { // store the name of this test case _LIT(ret,"Test1.16"); return ret; } CEsockTest1_16::~CEsockTest1_16() { } enum TVerdict CEsockTest1_16::easyTestStepPreambleL() { TInt ret = OpenSockets(KAfInet, KSockDatagram, KProtocolInetUdp); Logger().WriteFormat(_L("Open a UDP socket, returned %d"), ret); if (KErrNone != ret) { return EFail; } return EPass; } enum TVerdict CEsockTest1_16::easyTestStepL() { TESTL(EPass == TestStepResult()); if (iEsockSuite->GetSocketListCount() < 1) { return EInconclusive; } const TInt KBufferLength = 10; TBuf8<KBufferLength> buffer; buffer.SetMax(); buffer.FillZ(); TInetAddr destAddr; TRequestStatus status; Logger().WriteFormat(_L("Issuing 'SendTo' with invalid destination...")); iEsockSuite->GetSocketHandle(1).SendTo(buffer, destAddr, 0, status); User::WaitForRequest(status); Logger().WriteFormat(_L("...which returned %d\n"), status.Int()); // Should return '-2' TESTEL(status == KErrGeneral, EFail); // Test 1.15 Close socket return EPass; } // Test step 1.17 // Open a socket using the RawIp protocol const TDesC& CEsockTest1_17::GetTestName() { // store the name of this test case _LIT(ret, "Test1.17"); return ret; } CEsockTest1_17::~CEsockTest1_17() { } enum TVerdict CEsockTest1_17::easyTestStepL() { Logger().WriteFormat(_L("Open a RawIP socket")); _LIT(KRawIp, "rawip"); TInt ret = OpenSockets(KRawIp); TESTEL(ret == KErrNone, ret); return EPass; }
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
c6792841f799c8bb25b92f74e39839ba58a2147f
e99887d75f79aace37b6fd99b7bdb0a739321aa9
/src/fixpoint/branch_conditions.h
e6c563dda71507121e43c74b97215beeef919ae9
[ "MIT" ]
permissive
peterrum/po-lab-2018
e14f98e876c91ee2bb381ff07c0ac04f2d84802e
e4547288c582f36bd73d94157ea157b0a631c4ae
refs/heads/master
2021-07-13T18:01:14.035456
2018-11-24T10:13:58
2018-11-24T10:13:58
136,142,467
3
4
null
2018-11-24T10:13:18
2018-06-05T08:06:06
C++
UTF-8
C++
false
false
1,114
h
#ifndef PROJECT_BRANCH_CONDITIONS_H #define PROJECT_BRANCH_CONDITIONS_H #include "../abstract_domain/AbstractDomain.h" #include "state.h" #include "llvm/IR/Value.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <memory> #include <utility> using namespace llvm; namespace pcpo { class BranchConditions { public: BranchConditions(std::map<BasicBlock *, State> &programPoints); bool isBasicBlockReachable(BasicBlock *pred, BasicBlock *bb); // apply conditions and return true if non of the variables are bottom bool applyCondition(BasicBlock *pred, BasicBlock *bb); void unApplyCondition(BasicBlock *pred); void putBranchConditions(BasicBlock *pred, BasicBlock *bb, Value *val, std::shared_ptr<AbstractDomain> ad); private: std::map<BasicBlock *, State> &programPoints; std::map<BasicBlock *, std::map<BasicBlock *, std::map<Value *, std::shared_ptr<AbstractDomain>>>> branchConditions; std::map<Value *, std::shared_ptr<AbstractDomain>> conditionCache; bool conditionCacheUsed; }; } /// namespace #endif
[ "peterrmuench@aol.com" ]
peterrmuench@aol.com
e5f9ca3dfdc9526dec098c4cf84dd89bf05e7534
435f79cf136034f86850780796536c82efebc83f
/src/qt/transactiontablemodel.h
5f4f01e73c1566a888ea69bae72f4635b01799f1
[ "MIT" ]
permissive
KazuPay/kazusilver
d7d3946cd677cf0f49c8c0d944544194df8bb0b4
fc81623ed5fd5f9f9fd9ce85139201ece6a2332e
refs/heads/master
2020-04-15T08:55:32.528511
2019-01-13T13:34:41
2019-01-13T13:34:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,332
h
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef KSLVCOIN_QT_TRANSACTIONTABLEMODEL_H #define KSLVCOIN_QT_TRANSACTIONTABLEMODEL_H #include "kazusilverunits.h" #include <QAbstractTableModel> #include <QStringList> class PlatformStyle; class TransactionRecord; class TransactionTablePriv; class WalletModel; class CWallet; /** UI model for the transaction table of a wallet. */ class TransactionTableModel : public QAbstractTableModel { Q_OBJECT public: explicit TransactionTableModel(const PlatformStyle *platformStyle, CWallet* wallet, WalletModel *parent = 0); ~TransactionTableModel(); enum ColumnIndex { Status = 0, Watchonly = 1, Date = 2, Type = 3, ToAddress = 4, Amount = 5 }; /** Roles to get specific information from a transaction row. These are independent of column. */ enum RoleIndex { /** Type of transaction */ TypeRole = Qt::UserRole, /** Date and time this transaction was created */ DateRole, /** Watch-only boolean */ WatchonlyRole, /** Watch-only icon */ WatchonlyDecorationRole, /** Long description (HTML format) */ LongDescriptionRole, /** Address of transaction */ AddressRole, /** Label of address related to transaction */ LabelRole, /** Net amount of transaction */ AmountRole, /** Unique identifier */ TxIDRole, /** Transaction hash */ TxHashRole, /** Transaction data, hex-encoded */ TxHexRole, /** Whole transaction as plain text */ TxPlainTextRole, /** Is transaction confirmed? */ ConfirmedRole, /** Formatted amount, without brackets when unconfirmed */ FormattedAmountRole, /** Transaction status (TransactionRecord::Status) */ StatusRole, /** Unprocessed icon */ RawDecorationRole, }; int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; bool processingQueuedTransactions() { return fProcessingQueuedTransactions; } private: CWallet* wallet; WalletModel *walletModel; QStringList columns; TransactionTablePriv *priv; bool fProcessingQueuedTransactions; const PlatformStyle *platformStyle; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); QString lookupAddress(const std::string &address, bool tooltip) const; QVariant addressColor(const TransactionRecord *wtx) const; QString formatTxStatus(const TransactionRecord *wtx) const; QString formatTxDate(const TransactionRecord *wtx) const; QString formatTxType(const TransactionRecord *wtx) const; QString formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const; QString formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed=true, KazuSilverUnits::SeparatorStyle separators=KazuSilverUnits::separatorStandard) const; QString formatTooltip(const TransactionRecord *rec) const; QVariant txStatusDecoration(const TransactionRecord *wtx) const; QVariant txWatchonlyDecoration(const TransactionRecord *wtx) const; QVariant txAddressDecoration(const TransactionRecord *wtx) const; public Q_SLOTS: /* New transaction, or transaction changed status */ void updateTransaction(const QString &hash, int status, bool showTransaction); void updateConfirmations(); void updateDisplayUnit(); /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void updateAmountColumnTitle(); /* Needed to update fProcessingQueuedTransactions through a QueuedConnection */ void setProcessingQueuedTransactions(bool value) { fProcessingQueuedTransactions = value; } friend class TransactionTablePriv; }; #endif // KSLVCOIN_QT_TRANSACTIONTABLEMODEL_H
[ "mike@altilly.com" ]
mike@altilly.com
03d64891c57f9d51659b155b825158464012e608
19e78b53f3b7c4e135f272a478d47df3d4a42cae
/source/common/utility/hash_table.h
10e1e6e1806f9ce249c4506a37a69b789cbb25ff
[]
no_license
Gumgo/WaveLang
5eaaa2f5d7876805fd5b353e1d885e630580d124
c993b4303de0889f63dda10a0fd4169aaa59d400
refs/heads/master
2021-06-17T23:24:07.827945
2021-03-12T18:22:19
2021-03-12T18:22:19
37,759,958
2
3
null
2015-07-18T11:54:16
2015-06-20T06:10:50
C++
UTF-8
C++
false
false
1,292
h
#pragma once #include "common/common.h" #include "common/utility/pod.h" #include <new> #include <vector> // This hash table preallocates its memory template<typename t_key, typename t_value, typename t_hash> class c_hash_table { public: c_hash_table(); ~c_hash_table(); // $TODO add move constructor void initialize(size_t bucket_count, size_t element_count); void terminate(); // Returns pointer to the value if successful, null pointer otherwise // $TODO add versions taking rvalue references t_value *insert(const t_key &key); // Uses default constructor for value t_value *insert(const t_key &key, const t_value &value); bool remove(const t_key &key); t_value *find(const t_key &key); const t_value *find(const t_key &key) const; private: static constexpr size_t k_invalid_element_index = static_cast<size_t>(-1); using s_pod_key = s_pod<t_key>; using s_pod_value = s_pod<t_value>; struct s_bucket { size_t first_element_index; }; struct s_element { size_t next_element_index; s_pod_key key; s_pod_value value; }; size_t get_bucket_index(const t_key &key) const; s_element *insert_internal(const t_key &key); std::vector<s_bucket> m_buckets; std::vector<s_element> m_elements; size_t m_free_list; }; #include "common/utility/hash_table.inl"
[ "gumgo1@gmail.com" ]
gumgo1@gmail.com
08b5f4a0a22efbe3acd3f24866346d75184ba44a
63ff954260ac9de2ac5420875f1bf7cf41eba2ff
/2019_06_30_Gunbird/2019_06_30_Gunbird/CSpriteDib.cpp
df17d5e96b71f2b1627c345a9fee55f9bb19d7dc
[]
no_license
kmj91/kmj-api
179b76e4d08c0654f074fadcfd8caae8832d7d7d
9a65e7b395199f8058ad615a4377973f53604305
refs/heads/master
2021-05-18T12:56:44.498606
2020-04-16T13:49:56
2020-04-16T13:49:56
251,250,883
0
0
null
null
null
null
UTF-8
C++
false
false
30,386
cpp
#include "stdafx.h" #include <windows.h> #include "CSpriteDib.h" #include "stdio.h" CSpriteDib::CSpriteDib() { int iCount; //----------------------------------------------------------------- // 최대 읽어올 개수 만큼 미리 할당 받는다. //----------------------------------------------------------------- m_iMaxSprite = 100; m_dwColorKey = 0x00ff00ff; m_stpSprite = new st_SPRITE[100]; // 초기화 iCount = 0; while (iCount < 100) { m_stpSprite[iCount].bypImage = NULL; ++iCount; } //기본 카메라 위치 m_iCameraPosX = 0; m_iCameraPosY = 0; } //////////////////////////////////////////////////////////////////// // 생성자, 파괴자. // // Parameters: (int)최대 스프라이트 개수. (DWORD)투명칼라. //////////////////////////////////////////////////////////////////// CSpriteDib::CSpriteDib(int iMaxSprite, DWORD dwColorKey) { int iCount; //----------------------------------------------------------------- // 최대 읽어올 개수 만큼 미리 할당 받는다. //----------------------------------------------------------------- m_iMaxSprite = iMaxSprite; m_dwColorKey = dwColorKey; m_stpSprite = new st_SPRITE[iMaxSprite]; // 초기화 iCount = 0; while (iCount < iMaxSprite) { m_stpSprite[iCount].bypImage = NULL; ++iCount; } //기본 카메라 위치 m_iCameraPosX = 0; m_iCameraPosY = 0; } CSpriteDib::~CSpriteDib() { int iCount; //----------------------------------------------------------------- // 전체를 돌면서 모두 지우자. //----------------------------------------------------------------- for (iCount = 0; iCount < m_iMaxSprite; iCount++) { ReleaseSprite(iCount); } delete[] m_stpSprite; } /////////////////////////////////////////////////////// // LoadDibSprite. // BMP파일을 읽어서 하나의 프레임으로 저장한다. // // Parameters: (int)SpriteIndex. (const wchar_t *)FileName. (int)CenterPointX. (int)CenterPointY. // Return: (BOOL)TRUE, FALSE. /////////////////////////////////////////////////////// BOOL CSpriteDib::LoadDibSprite(int iSpriteIndex, const wchar_t * szFileName, int iCenterPointX, int iCenterPointY) { //HANDLE hFile; //DWORD dwRead; int iPitch; size_t iImageSize; BITMAPFILEHEADER stFileHeader; BITMAPINFOHEADER stInfoHeader; FILE *fp; int err; int iCount; //----------------------------------------------------------------- // 비트맵 헤더를 열어 BMP 파일 확인. //----------------------------------------------------------------- err = _wfopen_s(&fp, szFileName, L"rb"); if (err != 0) { return 0; } fread(&stFileHeader, sizeof(BITMAPFILEHEADER), 1, fp); if (stFileHeader.bfType != 0x4d42) { return 0; } //----------------------------------------------------------------- // 한줄, 한줄의 피치값을 구한다. //----------------------------------------------------------------- fread(&stInfoHeader, sizeof(BITMAPINFOHEADER), 1, fp); iPitch = (stInfoHeader.biWidth * (stInfoHeader.biBitCount / 8) + 3) & ~3; //----------------------------------------------------------------- // 스프라이트 구조체에 크기 저장. //----------------------------------------------------------------- m_stpSprite[iSpriteIndex].iWidth = stInfoHeader.biWidth; m_stpSprite[iSpriteIndex].iHeight = stInfoHeader.biHeight; m_stpSprite[iSpriteIndex].iPitch = iPitch; m_stpSprite[iSpriteIndex].iCenterPointX = iCenterPointX; m_stpSprite[iSpriteIndex].iCenterPointY = iCenterPointY; //----------------------------------------------------------------- // 이미지에 대한 전체 크기를 구하고, 메모리 할당. //----------------------------------------------------------------- iImageSize = iPitch * stInfoHeader.biHeight; m_stpSprite[iSpriteIndex].bypImage = new BYTE[iImageSize]; //----------------------------------------------------------------- // 이미지 부분은 스프라이트 버퍼로 읽어온다. // DIB 는 뒤집어져 있으므로 이를 다시 뒤집자. // 임시 버퍼에 읽은 뒤에 뒤집으면서 복사한다. //----------------------------------------------------------------- BYTE *buffer = new BYTE[iImageSize]; BYTE *tempBuffer; BYTE *tempSprite = m_stpSprite[iSpriteIndex].bypImage; fread(buffer, iImageSize, 1, fp); tempBuffer = buffer +(iPitch * (stInfoHeader.biHeight - 1)); for (iCount = 0; iCount < stInfoHeader.biHeight; iCount++) { memcpy(tempSprite, tempBuffer, stInfoHeader.biWidth * 4); tempBuffer = tempBuffer - iPitch; tempSprite = tempSprite + iPitch; } delete[] buffer; fclose(fp); //CloseHandle(hFile); return FALSE; } /////////////////////////////////////////////////////// // ReleaseSprite. // 해당 스프라이트 해제. // // Parameters: (int)SpriteIndex. // Return: (BOOL)TRUE, FALSE. /////////////////////////////////////////////////////// void CSpriteDib::ReleaseSprite(int iSpriteIndex) { //----------------------------------------------------------------- // 최대 할당된 스프라이트를 넘어서면 안되지롱 //----------------------------------------------------------------- if (m_iMaxSprite <= iSpriteIndex) return; if (NULL != m_stpSprite[iSpriteIndex].bypImage) { //----------------------------------------------------------------- // 삭제 후 초기화. //----------------------------------------------------------------- delete[] m_stpSprite[iSpriteIndex].bypImage; memset(&m_stpSprite[iSpriteIndex], 0, sizeof(st_SPRITE)); } } /////////////////////////////////////////////////////// // DrawSprite. // 특정 메모리 위치에 스프라이트를 출력한다. (클리핑 처리) // 체력바 처리 // /////////////////////////////////////////////////////// void CSpriteDib::DrawSprite(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *dwpDest = *dwpSprite; } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } void CSpriteDib::DrawImage(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { *dwpDest = *dwpSprite; //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } /********************************* DrawSpriteRed 빨간색 톤으로 이미지 출력 **********************************/ void CSpriteDib::DrawSpriteRed(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *((BYTE *)dwpDest + 2) = *((BYTE *)dwpSprite + 2); *((BYTE *)dwpDest + 1) = *((BYTE *)dwpSprite + 1) / 2; *((BYTE *)dwpDest + 0) = *((BYTE *)dwpSprite + 0) / 2; } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } /********************************* DrawSpriteCompose 합성 출력 **********************************/ void CSpriteDib::DrawSpriteCompose(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *((BYTE *)dwpDest + 2) = (*((BYTE *)dwpSprite + 2) / 2) + (*((BYTE *)dwpDest + 2) / 2); *((BYTE *)dwpDest + 1) = (*((BYTE *)dwpSprite + 1) / 2) + (*((BYTE *)dwpDest + 1) / 2); *((BYTE *)dwpDest + 0) = (*((BYTE *)dwpSprite + 0) / 2) + (*((BYTE *)dwpDest + 0) / 2); } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } // 체력바 용 void CSpriteDib::DrawPercentage(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch, int iPercentage) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iCountY; int iCountX; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; BYTE *bypTempSprite; BYTE *bypTempDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; //----------------------------------------------------------------- // 화면에 찍을 위치로 이동한다. //----------------------------------------------------------------- dwpDest = (DWORD *)((BYTE *)(dwpDest + iDrawX) + (iDrawY * iDestPitch)); bypTempSprite = (BYTE *)dwpSprite; bypTempDest = (BYTE *)dwpDest; //----------------------------------------------------------------- // 전체 크기를 돌면서 픽셀마다 투명색 처리를 하며 그림 출력. //----------------------------------------------------------------- for (iCountY = 0; iSpriteHeight > iCountY; iCountY++) { for (iCountX = 0; iSpriteWidth - ((100 - iPercentage) * ((double)iSpriteWidth / (double)100)) > iCountX; iCountX++) { if (m_dwColorKey != (*dwpSprite & 0x00ffffff)) { *dwpDest = *dwpSprite; } //다음칸 이동 ++dwpDest; ++dwpSprite; } //----------------------------------------------------------------- // 다음줄로 이동, 화면과 스프라이트 모두.. //----------------------------------------------------------------- bypTempDest = bypTempDest + iDestPitch; bypTempSprite = bypTempSprite + iSpritePitch; dwpDest = (DWORD *)bypTempDest; dwpSprite = (DWORD *)bypTempSprite; } } // 테스트 용 void CSpriteDib::DrawTextID(int iSpriteIndex, int iDrawX, int iDrawY, BYTE *bypDest, int iDestWidth, int iDestHeight, int iDestPitch, HWND hWnd, UINT id) { //----------------------------------------------------------------- // 최대 스프라이트 개수를 초과 하거나, 로드되지 않는 스프라이트라면 무시 //----------------------------------------------------------------- if (m_iMaxSprite < iSpriteIndex) return; if (m_stpSprite[iSpriteIndex].bypImage == NULL) return; //----------------------------------------------------------------- // 지역변수로 필요정보 셋팅 //----------------------------------------------------------------- st_SPRITE *stpSprite = &m_stpSprite[iSpriteIndex]; int iSpriteHeight = stpSprite->iHeight; int iSpriteWidth = stpSprite->iWidth; int iSpritePitch = stpSprite->iPitch; int iSpriteCenterX = stpSprite->iCenterPointX; int iSpriteCenterY = stpSprite->iCenterPointY; DWORD *dwpSprite = (DWORD *)stpSprite->bypImage; DWORD *dwpDest = (DWORD *)bypDest; //----------------------------------------------------------------- // 출력 중점으로 좌표 계산 //----------------------------------------------------------------- iDrawX = iDrawX - iSpriteCenterX; iDrawY = iDrawY - iSpriteCenterY; //----------------------------------------------------------------- // 상단 에 대한 스프라이트 출력 위치 계산. (상단 클리핑) // 하단에 사이즈 계산. (하단 클리핑) // 왼쪽 출력 위치 계산. (좌측 클리핑) // 오른쪽 출력 위치 계산. (우측 클리핑) //----------------------------------------------------------------- //2018.02.08 //카메라 기준으로 스프라이트 값 클리핑 처리 int clippingY; int clippingX; if (iDrawY < m_iCameraPosY) { //2018.02.08 clippingY = m_iCameraPosY - iDrawY; iSpriteHeight = iSpriteHeight - clippingY; if (iSpriteHeight > 0) { dwpSprite = (DWORD *)((BYTE *)dwpSprite + iSpritePitch * clippingY); } iDrawY = m_iCameraPosY; } if (iDrawY + iSpriteHeight >= m_iCameraPosY + iDestHeight) { iSpriteHeight = iSpriteHeight - ((iDrawY + iSpriteHeight) - (m_iCameraPosY + iDestHeight)); } if (iDrawX < m_iCameraPosX) { //2018.02.08 clippingX = m_iCameraPosX - iDrawX; iSpriteWidth = iSpriteWidth - clippingX; if (iSpriteWidth > 0) { dwpSprite = dwpSprite + clippingX; } iDrawX = m_iCameraPosX; } if (iDrawX + iSpriteWidth >= m_iCameraPosX + iDestWidth) { iSpriteWidth = iSpriteWidth - ((iDrawX + iSpriteWidth) - (m_iCameraPosX + iDestWidth)); } if (iSpriteWidth <= 0 || iSpriteHeight <= 0) { return; } //2018.02.08 //카메라 기준으로 iDrawX iDrawY 값 좌표 맞추기 iDrawX = iDrawX - m_iCameraPosX; iDrawY = iDrawY - m_iCameraPosY; HDC hdc; RECT DCRect; GetClientRect(hWnd, &DCRect); hdc = GetDC(hWnd); WCHAR wchString[32]; wsprintfW(wchString, L"%d", id); TextOut(hdc, iDrawX, iDrawY, wchString, wcslen(wchString)); ReleaseDC(hWnd, hdc); } //카메라 위치 void CSpriteDib::SetCameraPosition(int iPosX, int iPosY) { m_iCameraPosX = iPosX; m_iCameraPosY = iPosY; } void CSpriteDib::Reset(int iMaxSprite, DWORD dwColorKey) { int iCount; //----------------------------------------------------------------- // 전체를 돌면서 모두 지우자. //----------------------------------------------------------------- for (iCount = 0; iCount < m_iMaxSprite; iCount++) { ReleaseSprite(iCount); } delete[] m_stpSprite; //----------------------------------------------------------------- // 최대 읽어올 개수 만큼 미리 할당 받는다. //----------------------------------------------------------------- m_iMaxSprite = iMaxSprite; m_dwColorKey = dwColorKey; m_stpSprite = new st_SPRITE[iMaxSprite]; // 초기화 iCount = 0; while (iCount < iMaxSprite) { m_stpSprite[iCount].bypImage = NULL; ++iCount; } //기본 카메라 위치 m_iCameraPosX = 0; m_iCameraPosY = 0; }
[ "lethita0302@gmail.com" ]
lethita0302@gmail.com
b4f41faea6150792a3e0c4130bcd4f58bd2739f4
8d4b95617d3db5e3346a6dae77e9315dfb0c2eef
/joystick.cpp
6cfe317ee26da90f45841cbb5f453d22e35c645a
[]
no_license
steaphangreene/user
8f4a0816e3b211ecbae6b07feb1032381b3cbe6d
4b11c4675a3a51f0d61488ce83abebf055e855ad
refs/heads/master
2021-01-13T02:19:33.118694
2014-02-04T07:39:52
2014-02-04T07:41:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,895
cpp
#include "config.h" #include "input.h" #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <linux/joystick.h> #include <ctype.h> #include "screen.h" #include "joystick.h" extern Screen *__Da_Screen; extern Joystick *__Da_Joystick[16]; extern InputQueue *__Da_InputQueue; extern char *U2_JoyDev[16]; Joystick::Joystick() { for(jnum = 0; jnum < 16; ++jnum) { if(__Da_Joystick[jnum] == NULL) break; } Create(U2_JoyDev[jnum]); } Joystick::Joystick(const char *devfl) { Create(devfl); } void Joystick::Create(const char *devfl) { if(__Da_Screen == NULL) U2_Exit(-1, "Must create Screen before Joystick!\n"); memset(AxisRemap, 0, 16*(sizeof(Sprite *))); memset(ButtonRemap, 0, 16*(sizeof(Sprite *))); memset((char *)AxisStats, 0, 16*sizeof(int)); memset((char *)ButtonStats, 0, 16*sizeof(char)); jdev = open(devfl, O_RDONLY|O_NONBLOCK); if(jdev < 0) { printf("Can not open Joystick device \"%s\"\n", devfl); printf("There will be no Joystick support.\n"); return; } crit = 0; for(jnum = 0; jnum < 16; ++jnum) { if(__Da_Joystick[jnum] == NULL) { __Da_Joystick[jnum] = this; break; } } if(jnum >= 16) { U2_Exit(-1, "More then 16 Joysticks unsupported!\n"); } } Joystick::~Joystick() { __Da_Joystick[jnum] = NULL; } void Joystick::Update() { if(crit) return; #ifdef X_WINDOWS struct js_event je; while(read(jdev, &je, sizeof(struct js_event)) > 0) { if(je.type == JS_EVENT_BUTTON) { ButtonStats[je.number] = je.value; } else if(je.type == JS_EVENT_AXIS) { AxisStats[je.number] = je.value; } // else if(je.type == JS_EVENT_INIT|JS_EVENT_BUTTON) { // ButtonStats[je.number] = je.value; // } // else if(je.type == JS_EVENT_INIT|JS_EVENT_AXIS) { // AxisStats[je.number] = je.value; // } } #endif } int Joystick::IsPressed(int k) { Update(); if(k >= JS_BUTTON && k < JS_BUTTON_MAX) { return ButtonStats[k-JS_BUTTON]; } else if(k >= JS_AXIS && k < JS_AXIS_MAX) { return AxisStats[k-JS_AXIS]; } else return 0; } unsigned int Joystick::Buttons() { int ctr; unsigned long ret = 0; for(ctr = 0; ctr < (JS_BUTTON_MAX-JS_BUTTON); ++ctr) { if(ButtonStats[ctr]) ret |= (1<<ctr); } return ret; } int Joystick::WaitForAction() { // crit = 1; // int ret = GetAKey(); // if(__Da_Screen == NULL) // while(ret==0) { ret = GetAKey(); } // else // while(ret==0) { __Da_Screen->RefreshFast(); ret = GetAKey(); } // crit = 0; // return ret; return 0; } int Joystick::GetAction(int t) { crit = 1; // int ret = GetAKey(); // if(__Da_Screen == NULL) // while(t>0&&ret==0) { t-=100; usleep(100000); ret = GetAKey(); } // else { // time_t dest; long udest; // timeval tv; // gettimeofday(&tv, NULL); // dest = t/1000; // udest = (t-dest*1000)*1000; // dest += tv.tv_sec; // udest += tv.tv_usec; // if(udest > 1000000) { udest -= 1000000; dest += 1; } // while((tv.tv_sec<dest ||(tv.tv_sec==dest && tv.tv_usec<udest)) && ret==0) { // __Da_Screen->RefreshFast(); ret = GetAKey(); gettimeofday(&tv, NULL); // } // } // crit = 0; // return ret; return 0; } int Joystick::GetAction() { int ret=0; //#ifdef X_WINDOWS // XEvent e; // XFlush(__Da_Screen->_Xdisplay); // while(ret == 0 && XCheckMaskEvent(__Da_Screen->_Xdisplay, // KeyPressMask|KeyReleaseMask, &e)) { // if(e.type == KeyPress) { // ret = XKeycodeToKeysym(__Da_Screen->_Xdisplay, e.xkey.keycode, 0); // key_stat[ret] = 1; // } // else { // key_stat[XKeycodeToKeysym(__Da_Screen->_Xdisplay, e.xkey.keycode, 0)]=0; // } // } //#endif return ret; } void Joystick::DisableQueue() { queue_actions=0; } void Joystick::EnableQueue() { queue_actions=1; } void Joystick::MapActionToControl(int k, Control &c) { MapActionToControl(k, &c); } void Joystick::MapActionToControl(int k, Control *c) { if(k >= JS_BUTTON && k < JS_BUTTON_MAX) ButtonRemap[k-JS_BUTTON] = c; else if(k >= JS_AXIS && k < JS_AXIS_MAX) AxisRemap[k-JS_AXIS] = c; } void Joystick::MapActionToControl(int k, int c) { if(__Da_Screen != NULL) MapActionToControl(k, (Control *)__Da_Screen->GetSpriteByNumber(c)); } /* void Joystick::Down(int k) { if(key_stat[k] == 1) return; key_stat[k] = 1; InputAction a; a.k.type = INPUTACTION_KEYDOWN; a.k.modkeys = ModKeys(); a.k.key = k; a.k.chr = KeyToChar(k); if(__Da_InputQueue != NULL) __Da_InputQueue->ActionOccurs(&a); } void Joystick::Up(int k) { if(key_stat[k] == 0) return; key_stat[k] = 0; InputAction a; a.k.type = INPUTACTION_KEYUP; a.k.modkeys = ModKeys(); a.k.key = k; a.k.chr = 0; if(__Da_InputQueue != NULL) __Da_InputQueue->ActionOccurs(&a); } */
[ "steaphan@gmail.com" ]
steaphan@gmail.com
f50bca1fee08ce6fc2eee1d35a664b8b63406682
a39da85f9c1abe0c21673cd0777f2ba6188d75ce
/Client/Client/Client.cpp
bf23e9056f21d84765e73ab13342f5355a34e101
[]
no_license
AndrewSavchuk1410/ServerTranslatorPrototype
ec4d84bd1ee8ea578ab193fc94151920f77ed4e5
8f859365f0e363c9f1cdf59ed236174f4c53aee7
refs/heads/master
2023-01-24T12:08:35.188481
2020-12-03T18:38:56
2020-12-03T18:38:56
318,287,067
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
#pragma comment (lib, "ws2_32.lib") #include <WinSock2.h> #include <iostream> #pragma warning(disable: 4996) int main(int argc, char* argv[]) { setlocale(LC_ALL, "Ukrainian"); WSADATA wsaData; WORD DLLVersion = MAKEWORD(2, 1); if (WSAStartup(DLLVersion, &wsaData) != 0) { std::cout << "Error" << std::endl; exit(1); } SOCKADDR_IN addr; int sizeofaddr = sizeof(addr); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(1487); addr.sin_family = AF_INET; SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL); if (connect(Connection, (SOCKADDR*)&addr, sizeof(addr)) != 0) { std::cout << "Error: failed connect to server.\n"; return 1; } std::cout << "Connected!\n"; while (true) { //std::string word; std::cout << "Enter the word in English: "; //std::cin >> word; char msg[256]; std::cin >> msg; //for (int i = 0; i < word.length(); i++) { // msg[i] = word[i]; //} char res[256]; send(Connection, msg, sizeof(msg), NULL); recv(Connection, res, sizeof(res), NULL); std::cout << "Слово " << msg << ' ' << "перекладється, як: " << res << '\n'; } system("pause"); return 0; }
[ "48767019+AndrewSavchuk1410@users.noreply.github.com" ]
48767019+AndrewSavchuk1410@users.noreply.github.com
7309947f55e1483fe44ebd5a720b883d07bf0fa1
a5223041f795bea49dc3917b24fbd1a5aa371876
/BankUI/BankUIDlg.cpp
9bb9d51b0cf892c91a0f4cb347ade17cb182ca77
[]
no_license
arkssss/BankSystem
72bd9fb97af63f14701404d7b9659b02a9ead9b5
3a2f901e0fd2e68a85291109562d24a53c3b7eca
refs/heads/master
2020-03-09T17:44:29.854007
2018-06-05T02:15:37
2018-06-05T02:15:37
128,915,215
2
0
null
null
null
null
GB18030
C++
false
false
7,467
cpp
// BankUIDlg.cpp : 实现文件 // #include "stdafx.h" #include "BankUI.h" #include "BankUIDlg.h" #include "afxdialogex.h" #include "LogInMenu.h" #include "MysqlForBank.h" #include "Function.h" #include "CLanguage.h" #ifdef _DEBUG #define new DEBUG_NEW #endif //-------静态成员变量初始化 int CBankUIDlg::m_LogInTimes=0; C_AIVoice CBankUIDlg::AIVoice; CCard CBankUIDlg::CurrentCard; Mysql_Op CBankUIDlg::DB; CLanguage CBankUIDlg::Language; //用户的语言选择 1英文 0中文 int CBankUIDlg::m_LanguageChose; // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 LogInInfo CBankUIDlg::LogInfo; MYsql CBankUIDlg::My_Mysql; //-------- class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { MessageBox(_T("111")); } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CBankUIDlg 对话框 CBankUIDlg::CBankUIDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CBankUIDlg::IDD, pParent) , CardNumber(_T("")) , CardPassWrod(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CBankUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_CardNumber, CardNumber); DDX_Text(pDX, IDC_PassWord, CardPassWrod); DDX_Control(pDX, IDC_COMBO_language, m_cb); DDX_Control(pDX, IDC_COMBO_language, m_cb); } BEGIN_MESSAGE_MAP(CBankUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDB_LOGIN, &CBankUIDlg::OnBnClickedButton1) ON_EN_CHANGE(IDC_CardNumber, &CBankUIDlg::OnEnChangeEdit1) ON_CBN_SELCHANGE(IDC_COMBO_language, &CBankUIDlg::OnCbnSelchangeCombolanguage) ON_WM_CTLCOLOR() END_MESSAGE_MAP() // CBankUIDlg 消息处理程序 BOOL CBankUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_cb.InsertString(0,_T("中文")); m_cb.InsertString(1,_T("English")); //Status tmp=Log_In; AIVoice.PlayThisVoice(Log_In); //初始化为次数 m_LogInTimes=0; //语言直接初始化为中文 Language(0); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CBankUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CBankUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CBankUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CBankUIDlg::OnBnClickedButton1() { // TODO: 在此添加控件通知处理程序代码 UpdateData(true); int status; if(m_LogInTimes==0){ //说明是新账号登陆 //则跟BeForeCardNum 赋值 BeforeCardNum=CardNumber; } if(CardNumber!=BeforeCardNum){ //登陆的为新账号 m_LogInTimes=0; BeforeCardNum=CardNumber; //同样的赋值 } if(CMysqlForBank::Login(CardNumber,CardPassWrod,status)){ //登陆成功 显示菜单界面 //AIVoice.PlayThisVoice(Login_Successful); OnOK(); CLogInMenu Menu; Menu.DoModal(); }else{ AIVoice.PlayThisVoice(Login_Fail); if(status==3){ if(!m_LanguageChose){ //中文 MessageBox(_T("账号不存在!")); }else{ MessageBox(_T("Account or password is not correct!")); } }else if(status==1){ //冻结 if(!m_LanguageChose){ //中文 MessageBox(_T("该账号被冻结")); }else{ MessageBox(_T("This account has been frozen!")); } }else if(status==2 && m_LogInTimes<3){ //密码错误 CString chi; chi.Format(_T("密码输入错误 !!您还有%d次输入机会"),3-m_LogInTimes); CString eng; eng.Format(_T("Incorrect password ! ! You also have %d chances to enter"),3-m_LogInTimes); if(!m_LanguageChose){ //中文 MessageBox(chi); }else{ MessageBox(eng); } }else if(status==2 && m_LogInTimes==3){ if(CMysqlForBank::FreezenCard(CardNumber)){ if(!m_LanguageChose){ //中文 MessageBox(_T("该账号被冻结")); }else{ MessageBox(_T("This account has been frozen!")); } }else{ if(!m_LanguageChose){ //中文 MessageBox(_T("服务器忙")); }else{ MessageBox(_T("Server busy!")); } } } } } void CBankUIDlg::OnEnChangeEdit1() { // TODO: 如果该控件是 RICHEDIT 控件,它将不 // 发送此通知,除非重写 CDialogEx::OnInitDialog() // 函数并调用 CRichEditCtrl().SetEventMask(), // 同时将 ENM_CHANGE 标志“或”运算到掩码中。 // TODO: 在此添加控件通知处理程序代码 } bool CBankUIDlg::KeyDown(MSG* pMsg){ if (WM_KEYFIRST <= pMsg->message && pMsg->message <= WM_KEYLAST) { MessageBox(_T("111")); } return true; } void CBankUIDlg::OnCbnSelchangeCombo1() { // TODO: 在此添加控件通知处理程序代码 } //下拉框的选择 void CBankUIDlg::OnCbnSelchangeCombolanguage() { // TODO: 在此添加控件通知处理程序代码 int nIndex = m_cb.GetCurSel(); //中文 0 英文 1 //m_cb.GetLBText( nIndex, strCBText); //MessageBox(strCBText); m_LanguageChose=nIndex; Language(m_LanguageChose); //设置语言 GetDlgItem(IDC_STATIC_Id)->SetWindowText(Language.BankCardId); GetDlgItem(IDC_STATIC_pwd)->SetWindowText(Language.Password); GetDlgItem(IDB_LOGIN)->SetWindowText(Language.Login); } BOOL CBankUIDlg::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if(pMsg->message == WM_KEYDOWN) { switch(pMsg->wParam) { case VK_RETURN: // 屏蔽回车 OnBnClickedButton1(); return true; } } return CDialogEx::PreTranslateMessage(pMsg); }
[ "522500442@qq.com" ]
522500442@qq.com
1d7c30b6465d13ebfd960b3f28870b5dcd155869
a523c6bd27af78a3d4e177d50fb0ef5cbd09f938
/atcoder/cpp/abc098/D.cpp
7640f7e336d0d1a8d4b81cabdb359c96736637a2
[]
no_license
darshimo/CompetitiveProgramming
ab032aefd03a26e65b8f6b3052cbeb0099857096
9ae43d0eac8111917bdf9496522f1f130bdd17b6
refs/heads/master
2020-08-11T02:40:57.444768
2019-10-11T15:56:26
2019-10-11T15:56:26
214,474,282
0
0
null
null
null
null
UTF-8
C++
false
false
1,054
cpp
#include <cstdio> #include <cstdlib> char *zero(){ char *p = (char *)malloc(sizeof(char)*20); for(int i=0;i<20;i++)p[i]=0; return p; } void add(char *a1, char *a2){ for(int i=0;i<20;i++)a1[i]+=a2[i]; return; } void sub(char *a1, char *a2){ for(int i=0;i<20;i++)a1[i]-=a2[i]; return; } bool ok(char *a1, char *a2){ for(int i=0;i<20;i++){ if(a1[i]*a2[i])return false; } return true; } char *setbit(int A){ char *p = (char *)malloc(sizeof(char)*20); for(int i=0;i<20;i++){ p[i]=A%2; A/=2; } return p; } int main(){ int i,n; scanf("%d",&n); int *A = (int *)malloc(sizeof(int)*n); char **a = (char **)malloc(sizeof(char *)*n); for(i=0;i<n;i++){ scanf("%d",A+i); a[i] = setbit(A[i]); } int j = 0; int c = 0; char *tmp=zero(); for(i=0;i<n;i++){ while(j<n&&ok(tmp,a[j])){ add(tmp,a[j]); j++; } sub(tmp,a[i]); c+=j-i; } printf("%d\n",c); return 0; }
[ "takumishimoda7623@gmail.com" ]
takumishimoda7623@gmail.com
7bc87cb23bb2eadadf5120b1eb9709bb13b65362
1d7f8363324c092b0f04144515bf0e46a0a14940
/2017/C语言课程设计/提交报告/16040310037朱云韬/elevator.cpp
e8e30b5463607b332921c589a402c1903caac313
[]
no_license
jtrfid/C-Repositories
ddd7f6ca82c275d299b8ffaca0b44b76c945f33d
c285cb308d23a07e1503c20def32b571876409be
refs/heads/master
2021-01-23T09:02:12.113799
2019-05-02T05:00:46
2019-05-02T05:00:46
38,694,237
0
0
null
null
null
null
GB18030
C++
false
false
3,845
cpp
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include "ElevatorLib.h" /********************************************** * Idle状态,电梯停止在某楼层,门是关闭的,处于静止状态,等待相关事件的发生,从而转换到下一个状态。 **********************************************/ void StateIdle(int *state) { int floor; bool up; floor = IdleWhatFloorToGoTo(&up); if (floor > 0 && up) { SetMotorPower(1); *state = MovingUp; printf("Transition: from Idle to MovingUp.\n"); } if (floor>0&&!up) { SetMotorPower(-1); *state = MovingDown; printf("Transition: from Idle to MovingDowm.\n"); } if (GetOpenDoorLight()||GetCallLight(GetNearestFloor(), true)||GetCallLight( GetNearestFloor(), false)) { SetDoor(floor,true); *state = DoorOpen; printf("Transition: from Idle to DoorOpen.\n"); SetOpenDoorLight(false); SetCallLight(GetNearestFloor(), true, false); SetCallLight(GetNearestFloor(), false, false); } if (GetCloseDoorLight()) { SetCloseDoorLight(false); return; } } void StateMovingUp(int *state) { int floor; floor = GoingUpToFloor(); if (fabs(GetFloor() - floor) < Lib_FloorTolerance) { SetMotorPower(0); SetDoor(floor, true); *state = DoorOpen; printf("Transition: from MovingUp to DoorOpen.\n"); floor = GetNearestFloor(); SetCallLight(floor, true, false); SetCallLight(floor, false, false); SetPanelFloorLight(GetNearestFloor(), false); } if (GetOpenDoorLight() || GetCloseDoorLight()) { SetOpenDoorLight(false); SetCloseDoorLight(false); } } void StateMovingDown(int *state) { int floor; floor = GoingDownToFloor(); if (fabs(GetFloor() - floor) < Lib_FloorTolerance) { SetMotorPower(0); SetDoor(floor, true); *state = DoorOpen; printf("Transition: from MovingDown to DoorOpen.\n"); SetCallLight(floor, true, false); SetCallLight(floor, false, false); SetPanelFloorLight(floor,false); } if (GetOpenDoorLight() || GetCloseDoorLight()) { SetOpenDoorLight(false); SetCloseDoorLight(false); } } void StateDoorOpen(int *state) { if (GetCloseDoorLight()) { SetCloseDoorLight(false); SetDoor(GetNearestFloor(), false); *state = DoorClosing; printf("Transition: from DoorOpen to DoorClosing.\n"); } if (IsDoorOpen(GetNearestFloor())) { SetDoor(GetNearestFloor(), false); *state = DoorClosing; printf("Transition: from MovingUp to DoorClosing.\n"); } if (GetOpenDoorLight()) { SetOpenDoorLight(false); } } void StateDoorClosing(int *state) { if (GetOpenDoorLight()) { SetOpenDoorLight(false); SetDoor(GetNearestFloor(), true); *state = DoorOpen; printf("Transition: from DoorClosing to DoorOpen.\n"); } if (GetCloseDoorLight()) { SetCloseDoorLight(false); } if (IsBeamBroken()) { SetDoor(GetNearestFloor(), true); *state = DoorOpen; printf("Transition: from DoorClosing to DoorOpen.\n"); } if (IsDoorClosed(GetNearestFloor())) { *state = Idle; } } /*********************************************** * 状态机,每隔一定时间(如,100ms)被调用一次,采集系统的运行状态 ***********************************************/ void main_control(int *state) { if(IsElevatorRunning()) // 仿真正在运行 { switch(*state) { case Idle: // Idle状态,一定时间无动作,自动到一楼 if(GetNearestFloor() !=1 ) { AutoTo1Floor(); } StateIdle(state); break; case MovingUp: CancelTo1Floor(); // 其它状态,取消自动到一楼 StateMovingUp(state); break; case MovingDown: CancelTo1Floor(); StateMovingDown(state); break; case DoorOpen: CancelTo1Floor(); StateDoorOpen(state); break; case DoorClosing: CancelTo1Floor(); StateDoorClosing(state); break; default: printf("没有这种状态!!!\n"); } } }
[ "jtrfid@qq.com" ]
jtrfid@qq.com
1b5f00e8c6c953ec6ea7d1b41825a792ff2a2d19
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/CodesNew/474.cpp
a3e49cdb8a5e99cf31d431f7c040a6a8ed2987e7
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
603
cpp
#include <iostream> using namespace std; long long n,t,l=1,r=1,a[100005],sum=0,ans=0; int main() { cin>>n>>t; for(int i=1;i<=n;i++){ cin>>a[i]; } for(int i=1;i<=n;i++){ a[i]+=a[i-1]; } while(r<=n && l<=n){ sum=a[r]-a[l-1]; if(sum<=t){ ans=max(ans,r-(l-1)); r++; } else{ if (l==r) { r++; l++; } else l++; } } cout<<ans; return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
c4a71455f1d402c94becd68c25466b04b147297a
7b00c6e83083727e455e40cbfc00b2fc035f6f86
/shaka/src/js/navigator.cc
3fa72e5534bbbbe11f87ebb5025dd02e52ebb4c5
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
nextsux/shaka-player-embedded
150ad30ce2dda8c1552027022cd185f2d0c78c40
dccd0bbe7f326e73ef4841700b9a65ded6353564
refs/heads/master
2023-01-08T05:17:09.681606
2020-10-23T21:49:30
2020-10-23T21:59:03
310,596,930
0
0
NOASSERTION
2020-11-06T12:53:50
2020-11-06T12:53:50
null
UTF-8
C++
false
false
2,742
cc
// Copyright 2016 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 // // https://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 "src/js/navigator.h" #include <utility> #include "src/core/js_manager_impl.h" #include "src/js/eme/search_registry.h" #include "src/js/js_error.h" namespace shaka { namespace js { Navigator::Navigator() {} // \cond Doxygen_Skip Navigator::~Navigator() {} // \endcond Doxygen_Skip Promise Navigator::RequestMediaKeySystemAccess( std::string key_system, std::vector<eme::MediaKeySystemConfiguration> configs) { // 1. If keySystem is the empty string, return a promise rejected with a // newly created TypeError. if (key_system.empty()) { return Promise::Rejected( JsError::TypeError("The keySystem parameter is empty.")); } // 2. If supportedConfigurations is empty, return a promise rejected with a // newly created TypeError. if (configs.empty()) { return Promise::Rejected( JsError::TypeError("The configuration parameter is empty.")); } // NA: 3. Let document be the calling context's Document. // NA: 4. Let origin be the origin of document. // 5. Let promise be a new Promise. Promise promise = Promise::PendingPromise(); // 6. Run the following steps in parallel: JsManagerImpl::Instance()->MainThread()->AddInternalTask( TaskPriority::Internal, "search eme registry", eme::SearchRegistry(promise, std::move(key_system), std::move(configs))); // 7. Return promise. return promise; } NavigatorFactory::NavigatorFactory() { AddReadOnlyProperty("appName", &Navigator::app_name); AddReadOnlyProperty("appCodeName", &Navigator::app_code_name); AddReadOnlyProperty("appVersion", &Navigator::app_version); AddReadOnlyProperty("platform", &Navigator::platform); AddReadOnlyProperty("product", &Navigator::product); AddReadOnlyProperty("productSub", &Navigator::product_sub); AddReadOnlyProperty("vendor", &Navigator::vendor); AddReadOnlyProperty("vendorSub", &Navigator::vendor_sub); AddReadOnlyProperty("userAgent", &Navigator::user_agent); AddMemberFunction("requestMediaKeySystemAccess", &Navigator::RequestMediaKeySystemAccess); } NavigatorFactory::~NavigatorFactory() {} } // namespace js } // namespace shaka
[ "modmaker@google.com" ]
modmaker@google.com
3752f4c245d77673509375e1ba397421ba0a720e
a6bf86c0474c78626adad1e00247938cf80b378a
/src/UdpSrv.cpp
200c72e9d34944c4eb148bc7462ba7c826cf294b
[]
no_license
vslavav/RPiHelper
dcea32d07bdd7c7d855a02fab7e7323619ad0d49
1a68fb18fe3f7e779d9455b414bbab8d19d1fbdb
refs/heads/master
2020-04-25T13:02:10.242121
2019-03-10T14:47:44
2019-03-10T14:47:44
172,793,970
0
0
null
null
null
null
UTF-8
C++
false
false
1,531
cpp
/* * UdpSrv.cpp * * Created on: 2019-01-29 * Author: pi */ #include "UdpSrv.h" #include <thread> #include <unistd.h> #include <string.h> ////https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.hala001/xsocudp.htm void Thread_Run(UdpSrv* pUdpSrv) { while(1) { //UdpSrv* pUdpSrv = static_cast<UdpSrv*> (pUdpSrv); //UdpSrv* pUdpSrv = (UdpSrv*) pUdpSrv; pUdpSrv->Run(); } } UdpSrv::UdpSrv() { // TODO Auto-generated constructor stub } UdpSrv::~UdpSrv() { // TODO Auto-generated destructor stub close(_socket); } void UdpSrv::Init() { unsigned short shPort = 14010; _socket = socket(AF_INET, SOCK_DGRAM, 0); _server.sin_family = AF_INET; /* Server is in Internet Domain */ _server.sin_port = htons(shPort); _server.sin_addr.s_addr = INADDR_ANY;/* Server's Internet Address */ if (bind(_socket, (struct sockaddr *)&_server, sizeof(_server)) < 0) { return; } thread t(Thread_Run,this); t.detach(); } void UdpSrv::Run() { char buff[1024]; memset(buff,0,1024); int client_address_size = sizeof(_client); while(1) { int nError = recvfrom(_socket, buff, sizeof(buff), 0, (struct sockaddr *) &_client, (socklen_t*)&client_address_size) ; if(nError < 0) { perror("recvfrom()"); return; } string sMsg = buff; memset(buff,0,1024); SetMessage( sMsg ); } } void UdpSrv::SetMessage(string sMsg) { _sMessage = sMsg; } string UdpSrv::GetMessage() { string sMsg = _sMessage; _sMessage = ""; return sMsg; }
[ "SlavaV@hotmail.com" ]
SlavaV@hotmail.com
96faf3b4158967d8bb5be713b178a220d91353a0
567ee72bfdd5b1dd0aa0f94ddf08f0900ba9cffe
/solarsystem.cpp
12d7ba84d4908d2a057d698c6d43065fa990829f
[ "MIT" ]
permissive
SunilRao01/SpaceSim
d387f5273f3450687eb328997efcbb3837961aa2
f7dcd44b5f80ab8d34955c2c7e1d21dc2c144f74
refs/heads/master
2021-01-22T05:16:33.258105
2015-03-30T13:28:59
2015-03-30T13:28:59
27,149,572
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
#include "solarsystem.h" void solarsystem::renderSolarSystem() { if (!changingParameters) { glPushMatrix(); // Center solar system glTranslatef(centerX, centerY, 0.0f); // Render sun sun.renderPlanet(0, 0); // Render planets for (int i = 0; i < numPlanets; i++) { // Rotate planets //glTranslatef(centerX, centerY, 0.0f); glRotatef(planets[i].angle, 0.0f, 0.0f, 1.0f); if (i == 0) { planets[i].renderPlanet(0, -60); } else { planets[i].renderPlanet(0, (i+1) * (-60)); } } glPopMatrix(); } } // TODO: Change rotation so it doesn't always rotate around (0, 0) void solarsystem::rotatePlanets() { if (!changingParameters) { for(int i = 0; i < numPlanets; i++) { planets[i].angle += (360.0f / 60) * (getRotationSpeed()); // Cap angle if (planets[i].angle >= 360.0f) { planets[i].angle -= 360.0f; } } } } void solarsystem::shuffle() { changingParameters = true; free(planets); numPlanets = rand() % maxNumPlanets + minNumPlanets; planets = (planet *) malloc(numPlanets * 100); rotationSpeed = 0.05f + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(0.5f-0.05f))); for (int i = 0; i < numPlanets; i++) { planet tempPlanet(5, 15); planets[i] = tempPlanet; } changingParameters = false; } float solarsystem::getRotationSpeed() { return rotationSpeed; }
[ "slysunil101@gmail.com" ]
slysunil101@gmail.com
33408a23097072f760f0534104fa50728e5dd28e
92c0f53e43881f8c384ab344a44a16fd5eac54fd
/packetWin7/NPFInstall/NPFInstall/LoopbackRecord.cpp
7312c53f56fd6f755d5fb2f3200d6b91db1251f9
[ "LicenseRef-scancode-unknown-license-reference", "HPND", "BSD-4-Clause-UC", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-carnegie-mellon", "BSD-4.3TAHOE", "BSD-2-Clause", "LicenseRef-scancode-bsd-new-tcpdump" ]
permissive
vaginessa/npcap
65301289cfb8c25872695824d90267392562e675
391e71e54f72aadd41f5556174c7324af0047c73
refs/heads/master
2021-01-18T08:51:30.985915
2016-06-04T18:26:14
2016-06-04T18:26:14
60,437,309
0
0
NOASSERTION
2019-01-18T08:41:12
2016-06-05T01:09:20
C
UTF-8
C++
false
false
7,092
cpp
/*++ Copyright (c) Nmap.org. All rights reserved. Module Name: LoopbackRecord.cpp Abstract: This is used for enumerating our "Npcap Loopback Adapter" using NetCfg API, if found, we changed its name from "Ethernet X" or "Local Network Area" to "Npcap Loopback Adapter". Also, we need to make a flag in registry to let the Npcap driver know that "this adapter is ours", so send the loopback traffic to it. --*/ #pragma warning(disable: 4311 4312) #include <Netcfgx.h> #include <iostream> #include <atlbase.h> // CComPtr #include <devguid.h> // GUID_DEVCLASS_NET, ... #include "LoopbackRecord.h" #include "LoopbackRename.h" #include "RegUtil.h" #define NPCAP_LOOPBACK_ADAPTER_NAME NPF_DRIVER_NAME_NORMAL_WIDECHAR L" Loopback Adapter" #define NPCAP_LOOPBACK_APP_NAME NPF_DRIVER_NAME_NORMAL_WIDECHAR L"_Loopback" int g_NpcapAdapterID = -1; // RAII helper class class COM { public: COM(); ~COM(); }; COM::COM() { HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: CoInitializeEx() failed. Error code: 0x%08x\n"), hr); } } COM::~COM() { CoUninitialize(); } // RAII helper class class NetCfg { CComPtr<INetCfg> m_pINetCfg; CComPtr<INetCfgLock> m_pLock; public: NetCfg(); ~NetCfg(); // Displays all network adapters, clients, transport protocols and services. // For each client, transport protocol and service (network features) // shows adpater(s) they are bound to. BOOL GetNetworkConfiguration(); }; NetCfg::NetCfg() : m_pINetCfg(0) { HRESULT hr = S_OK; hr = m_pINetCfg.CoCreateInstance(CLSID_CNetCfg); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: CoCreateInstance() failed. Error code: 0x%08x\n"), hr); throw 1; } hr = m_pINetCfg.QueryInterface(&m_pLock); if (!SUCCEEDED(hr)) { _tprintf(_T("QueryInterface(INetCfgLock) 0x%08x\n"), hr); throw 2; } // Note that this call can block. hr = m_pLock->AcquireWriteLock(INFINITE, NPCAP_LOOPBACK_APP_NAME, NULL); if (!SUCCEEDED(hr)) { _tprintf(_T("INetCfgLock::AcquireWriteLock 0x%08x\n"), hr); throw 3; } hr = m_pINetCfg->Initialize(NULL); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: Initialize() failed. Error code: 0x%08x\n"), hr); throw 4; } } NetCfg::~NetCfg() { HRESULT hr = S_OK; if(m_pINetCfg) { hr = m_pINetCfg->Uninitialize(); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: Uninitialize() failed. Error code: 0x%08x\n"), hr); } hr = m_pLock->ReleaseWriteLock(); if (!SUCCEEDED(hr)) { _tprintf(_T("INetCfgLock::ReleaseWriteLock 0x%08x\n"), hr); } } } BOOL EnumerateComponents(CComPtr<INetCfg>& pINetCfg, const GUID* pguidClass) { /* cout << "\n\nEnumerating " << GUID2Str(pguidClass) << " class:\n" << endl;*/ // IEnumNetCfgComponent provides methods that enumerate the INetCfgComponent interfaces // for network components of a particular type installed on the operating system. // Types of network components include network cards, protocols, services, and clients. CComPtr<IEnumNetCfgComponent> pIEnumNetCfgComponent; // get enumeration containing network components of the provided class (GUID) HRESULT hr = pINetCfg->EnumComponents(pguidClass, &pIEnumNetCfgComponent); if(!SUCCEEDED(hr)) { _tprintf(_T("ERROR: Failed to get IEnumNetCfgComponent interface pointer\n")); throw 1; } // INetCfgComponent interface provides methods that control and retrieve // information about a network component. CComPtr<INetCfgComponent> pINetCfgComponent; unsigned int nIndex = 1; BOOL bFound = FALSE; BOOL bFailed = FALSE; // retrieve the next specified number of INetCfgComponent interfaces in the enumeration sequence. while(pIEnumNetCfgComponent->Next(1, &pINetCfgComponent, 0) == S_OK) { /* cout << GUID2Desc(pguidClass) << " "<< nIndex++ << ":\n";*/ // LPWSTR pszDisplayName = NULL; // pINetCfgComponent->GetDisplayName(&pszDisplayName); // wcout << L"\tDisplay name: " << wstring(pszDisplayName) << L'\n'; // CoTaskMemFree(pszDisplayName); LPWSTR pszBindName = NULL; pINetCfgComponent->GetBindName(&pszBindName); // wcout << L"\tBind name: " << wstring(pszBindName) << L'\n'; // DWORD dwCharacteristics = 0; // pINetCfgComponent->GetCharacteristics(&dwCharacteristics); // cout << "\tCharacteristics: " << dwCharacteristics << '\n'; // // GUID guid; // pINetCfgComponent->GetClassGuid(&guid); // cout << "\tClass GUID: " << guid.Data1 << '-' << guid.Data2 << '-' // << guid.Data3 << '-' << (unsigned int) guid.Data4 << '\n'; // // ULONG ulDeviceStatus = 0; // pINetCfgComponent->GetDeviceStatus(&ulDeviceStatus); // cout << "\tDevice Status: " << ulDeviceStatus << '\n'; // // LPWSTR pszHelpText = NULL; // pINetCfgComponent->GetHelpText(&pszHelpText); // wcout << L"\tHelp Text: " << wstring(pszHelpText) << L'\n'; // CoTaskMemFree(pszHelpText); // // LPWSTR pszID = NULL; // pINetCfgComponent->GetId(&pszID); // wcout << L"\tID: " << wstring(pszID) << L'\n'; // CoTaskMemFree(pszID); // // pINetCfgComponent->GetInstanceGuid(&guid); // cout << "\tInstance GUID: " << guid.Data1 << '-' << guid.Data2 << '-' // << guid.Data3 << '-' << (unsigned int) guid.Data4 << '\n'; LPWSTR pszPndDevNodeId = NULL; pINetCfgComponent->GetPnpDevNodeId(&pszPndDevNodeId); // wcout << L"\tPNP Device Node ID: " << wstring(pszPndDevNodeId) << L'\n'; int iDevID = getIntDevID(pszPndDevNodeId); if (g_NpcapAdapterID == iDevID) { bFound = TRUE; hr = pINetCfgComponent->SetDisplayName(NPCAP_LOOPBACK_ADAPTER_NAME); if (hr != S_OK) { bFailed = TRUE; } if (!AddFlagToRegistry(pszBindName)) { bFailed = TRUE; } // if (!AddFlagToRegistry_Service(pszBindName)) // { // bFailed = TRUE; // } if (!RenameLoopbackNetwork(pszBindName)) { bFailed = TRUE; } } CoTaskMemFree(pszBindName); CoTaskMemFree(pszPndDevNodeId); pINetCfgComponent.Release(); if (bFound) { if (bFailed) { return FALSE; } else { return TRUE; } } } return FALSE; } BOOL NetCfg::GetNetworkConfiguration() { // get enumeration containing GUID_DEVCLASS_NET class of network components return EnumerateComponents(m_pINetCfg, &GUID_DEVCLASS_NET); } int getIntDevID(TCHAR strDevID[]) //DevID is in form like: "ROOT\\NET\\0008" { int iDevID; _stscanf_s(strDevID, _T("ROOT\\NET\\%04d"), &iDevID); return iDevID; } BOOL AddFlagToRegistry(tstring strDeviceName) { return WriteStrToRegistry(NPCAP_REG_KEY_NAME, NPCAP_REG_LOOPBACK_VALUE_NAME, tstring(_T("\\Device\\") + strDeviceName).c_str(), KEY_WRITE | KEY_WOW64_32KEY); } BOOL AddFlagToRegistry_Service(tstring strDeviceName) { return WriteStrToRegistry(NPCAP_SERVICE_REG_KEY_NAME, NPCAP_REG_LOOPBACK_VALUE_NAME, tstring(_T("\\Device\\") + strDeviceName).c_str(), KEY_WRITE); } BOOL RecordLoopbackDevice(int iNpcapAdapterID) { g_NpcapAdapterID = iNpcapAdapterID; try { COM com; NetCfg netCfg; if (!netCfg.GetNetworkConfiguration()) { return FALSE; } } catch(...) { _tprintf(_T("ERROR: main() caught exception\n")); return FALSE; } return TRUE; }
[ "hsluoyz@qq.com" ]
hsluoyz@qq.com
aef07905830e29af2c7e6550a0e2cfdfdd56aad8
d86aedd0eb141b8d5fbaf30f41425ff97c17d6f4
/src/utiltime.h
96332926f2a3aaaf50ba2779cd7d0855dc2a6d50
[ "MIT" ]
permissive
catscoinofficial/src
277f6d4458e8ee3332ea415e0ed8b5253d22071b
eb9053362c3e9c90fe2cac09a65fad7d64d5f417
refs/heads/master
2023-02-28T10:39:10.685012
2021-02-07T10:54:28
2021-02-07T10:54:28
336,761,478
0
2
null
null
null
null
UTF-8
C++
false
false
666
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The CATSCOIN developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTILTIME_H #define BITCOIN_UTILTIME_H #include <stdint.h> #include <string> int64_t GetTime(); int64_t GetTimeMillis(); int64_t GetTimeMicros(); void SetMockTime(int64_t nMockTimeIn); void MilliSleep(int64_t n); std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); std::string DurationToDHMS(int64_t nDurationTime); #endif // BITCOIN_UTILTIME_H
[ "64649630+catscoinofficial@users.noreply.github.com" ]
64649630+catscoinofficial@users.noreply.github.com
4e1eb034bb57014b4a7c62aee8eb1f41584c5b80
37464ad43bcd0e263e1bf50c248a1e13e4ba8cf6
/MrRipPlug/FMT/0wwmix/misc/xif_file.h
ae0ba7b9b7bdc7e086d1b48d71d9f36fccc25e26
[]
no_license
crom83/cromfarplugs
5d3a65273433c655d63ef649ac3a3f3618d2ca82
666c3cafa35d8c7ca84a6ca5fc3ff7c69430bf0e
refs/heads/master
2021-01-21T04:26:34.123420
2016-08-11T14:47:51
2016-08-11T14:47:51
54,393,015
3
2
null
2016-08-11T14:47:51
2016-03-21T13:54:32
C++
UTF-8
C++
false
false
922
h
// xif_file.h: interface for the Cxif_file class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_XIF_FILE_H__93731940_3FA3_11D4_B606_0000B4936994__INCLUDED_) #define AFX_XIF_FILE_H__93731940_3FA3_11D4_B606_0000B4936994__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "cc_file_sh.h" #include "cc_structures.h" #include "xif_key.h" class Cxif_file: public Ccc_file_sh<t_xif_header> { public: bool is_valid() const { int size = get_size(); const t_xif_header& header = *get_header(); return !(sizeof(t_xif_header) > size || header.id != file_id || header.version != file_version_old && header.version != file_version_new); } int decode(Cxif_key& key) { return key.load_key(get_data(), get_size()); } }; #endif // !defined(AFX_XIF_FILE_H__93731940_3FA3_11D4_B606_0000B4936994__INCLUDED_)
[ "crom83@mail.ru" ]
crom83@mail.ru
c4040d99ddf76fa5f8bbf6c60e2c31d9d0241927
91b19ebb15c3f07785929b7f7a4972ca8f89c847
/Classes/HatGacha.cpp
aea8c69e18c32821e23ec745e8501daa4597d657
[]
no_license
droidsde/DrawGirlsDiary
85519ac806bca033c09d8b60fd36624f14d93c2e
738e3cee24698937c8b21bd85517c9e10989141e
refs/heads/master
2020-04-08T18:55:14.160915
2015-01-07T05:33:16
2015-01-07T05:33:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,724
cpp
#include "HatGacha.h" #include <random> #include "GachaShowReward.h" const int kFakeItemTag = 0x43534; class CCNodeFrames : public CCNode { protected: std::vector<CCNode*> m_nodes; int m_currentIndex; float m_delay; float m_timer; public: void runAnimation(float delay) { m_timer = 0; m_delay = delay; for(auto i : m_nodes) { i->setVisible(false); } scheduleUpdate(); } void update(float dt) { m_timer += dt; if(m_timer > m_delay) { m_nodes[m_currentIndex]->setVisible(false); m_currentIndex++; if(m_nodes.size() == m_currentIndex) { m_currentIndex = 0; } m_nodes[m_currentIndex]->setVisible(true); while(m_timer > m_delay) { m_timer -= m_delay; } } } void appendNode(CCNode* n) { m_nodes.push_back(n); addChild(n); } static CCNodeFrames* create() { CCNodeFrames* nf = new CCNodeFrames(); nf->init(); nf->autorelease(); return nf; } }; bool HatGachaSub::init(KSAlertView* av, std::function<void(void)> callback, const vector<RewardSprite*>& rs, GachaPurchaseStartMode gsm, GachaCategory gc) { CCLayer::init(); m_gachaCategory = gc; m_gachaMode = gsm; m_fakeRewards = rs; setTouchEnabled(true); CCSprite* dimed = CCSprite::create(); dimed->setTextureRect(CCRectMake(0, 0, 600, 400)); dimed->setColor(ccc3(0, 0, 0)); dimed->setOpacity(180); dimed->setPosition(ccp(240, 160)); addChild(dimed, 0); CCSprite* commonBack = CCSprite::create("hat_stage.png"); commonBack->setPosition(ccp(240, 140)); addChild(commonBack, 0); m_parent = av; m_callback = callback; // setContentSize(av->getViewSize()); m_internalMenu = CCMenuLambda::create(); m_internalMenu->setPosition(ccp(0, 0)); m_internalMenu->setTouchPriority(INT_MIN); m_internalMenu->setTouchEnabled(true); addChild(m_internalMenu); m_menu = CCMenuLambda::create(); m_menu->setPosition(ccp(0, 0)); m_menu->setTouchPriority(INT_MIN); m_menu->setTouchEnabled(false); addChild(m_menu); m_disableMenu = CCMenuLambda::create(); m_disableMenu->setPosition(ccp(0, 0)); addChild(m_disableMenu); for(int i=0; i<360; i+=45) { // 모자 추가 CCMenuItemImageLambda* hatTopOpen = CCMenuItemImageLambda::create("hat_open_01.png", "hat_open_01.png", nullptr); CCMenuItemImageLambda* hatBottomOpen = CCMenuItemImageLambda::create("hat_open_02.png", "hat_open_02.png", nullptr); CCMenuItemImageLambda* hatTopClose = CCMenuItemImageLambda::create("hat_close_01.png", "hat_close_01.png", nullptr); CCMenuItemImageLambda* hatBottomClose = CCMenuItemImageLambda::create("hat_close_02.png", "hat_close_02.png", nullptr); ((CCSprite*)hatTopOpen->getNormalImage())->getTexture()->setAliasTexParameters(); ((CCSprite*)hatBottomOpen->getNormalImage())->getTexture()->setAliasTexParameters(); ((CCSprite*)hatTopClose->getNormalImage())->getTexture()->setAliasTexParameters(); ((CCSprite*)hatBottomClose->getNormalImage())->getTexture()->setAliasTexParameters(); // CCSprite* t; // t->getTexture()->set CCMenuItemToggleWithTopHatLambda* hatBottom = CCMenuItemToggleWithTopHatLambda::createWithTarget ( [=](CCObject* _item) { m_menu->setTouchEnabled(false); CCMenuItemToggleWithTopHatLambda* item = dynamic_cast<CCMenuItemToggleWithTopHatLambda*>(_item); CCLOG("%d", item->getSelectedIndex()); if(m_state == SceneState::kStopHat) { m_selectComment->removeFromParent(); item->m_hatTop->setSelectedIndex(0); item->setSelectedIndex(0); m_state = SceneState::kSelectedHatMoving; m_selectedHat = item; CCPoint centerPosition; if(m_parent) centerPosition = ccp(m_parent->getViewSize().width / 2.f, m_parent->getViewSize().height / 2.f) + ccp(0, 50); else centerPosition = ccp(240, 160); this->addChild(KSGradualValue<CCPoint>::create (m_selectedHat->getPosition(), centerPosition, 0.8f, [=](CCPoint pt) { m_selectedHat->setPosition(pt); topFollowBottom(); // 모자 위가 모자 밑둥을 따라감 }, [=](CCPoint pt) { // 상품을 모자에 맞추고 모자를 열고 상품을 보여줌. addChild(KSTimer::create(1.f, [=]() { for(auto i : m_hats) { i.first->m_reward->setScale(i.first->getScale()); i.first->m_reward->setPosition(i.first->getPosition()); i.first->setSelectedIndex(1); i.first->m_hatTop->setSelectedIndex(1); i.first->m_reward->setVisible(true); if(i.first == m_selectedHat) { // KS::KSLog("kind % value %", (int)i.first->m_reward->m_kind, ); m_state = SceneState::kShowReward1; this->addChild(KSGradualValue<float>::create (1.f, 2.f, 1.f, [=](float t) { i.first->m_reward->setScale(t); }, [=](float t) { CCLOG("end!!"); m_state = SceneState::kShowReward2; // content->addChild(CCSprite::create(i.first->m_reward->m_spriteStr.c_str())); // // // 가격 표시 // content->addChild(CCLabelTTF::create // (CCString::createWithFormat // ("+%d", // i.first->m_reward->m_value)->getCString(), mySGD->getFont().c_str(), 25)); RewardKind kind = i.first->m_reward->m_kind; int selectedItemValue = i.first->m_reward->m_value; std::function<void(void)> replayFunction; CCNode* parentPointer = getParent(); if(m_gachaMode == kGachaPurchaseStartMode_select){ // 선택으로 들어온 거라면 다시 하기가 가능함. replayFunction = [=]() { auto retryGame = [=](){ auto tempKind = i.first->m_reward->m_kind; auto value = i.first->m_reward->m_value; auto spriteStr = i.first->m_reward->m_spriteStr; auto weight = i.first->m_reward->m_weight; std::vector<RewardSprite*> rewards; for(auto i : m_rewards) { rewards.push_back(RewardSprite::create(tempKind, value, spriteStr, weight)); } parentPointer->addChild(HatGachaSub::create(m_callback, rewards, m_gachaMode, m_gachaCategory), this->getZOrder()); this->removeFromParent(); }; // 선택으로 들어온 거라면 다시 하기가 가능함. if(m_gachaCategory == GachaCategory::kRubyGacha) { if(mySGD->getGoodsValue(kGoodsType_ruby) >= mySGD->getGachaRubyFeeRetry()) { // mySGD->setStar(mySGD->getGoodsValue(kGoodsType_ruby) - mySGD->getGachaRubyFeeRetry()); // myDSH->saveUserData({kSaveUserData_Key_star}, [=](Json::Value v) { // // }); retryGame(); } else { CCLOG("돈 없음"); } } else if(m_gachaCategory == GachaCategory::kGoldGacha) { if(mySGD->getGoodsValue(kGoodsType_gold) >= mySGD->getGachaGoldFeeRetry()) { // mySGD->setGold(mySGD->getGoodsValue(kGoodsType_gold) - mySGD->getGachaGoldFeeRetry()); // myDSH->saveUserData({kSaveUserData_Key_gold}, [=](Json::Value v) { // // }); retryGame(); } else { CCLOG("돈 없음"); } } }; }else{ replayFunction = nullptr; }; std::string againFileName; if(m_gachaCategory == GachaCategory::kRubyGacha) { againFileName = "Ruby"; } else if(m_gachaCategory == GachaCategory::kGoldGacha) { againFileName = "Gold"; } GachaShowReward* gachaShowReward = GachaShowReward::create(replayFunction, m_callback, CCSprite::create(i.first->m_reward->m_spriteStr.c_str()), CCString::createWithFormat("%d", i.first->m_reward->m_value)->getCString(), kind, selectedItemValue, againFileName, m_gachaCategory ); addChild(gachaShowReward, 30); })); CCSprite* hatBack = CCSprite::create("hat_back.png"); hatBack->setScale(2.f); CCPoint centerPosition; if(m_parent) centerPosition = ccp(m_parent->getViewSize().width / 2.f, m_parent->getViewSize().height / 2.f) + ccp(0, 50); else centerPosition = ccp(240, 160); hatBack->setPosition(centerPosition); this->addChild(hatBack, 0); this->addChild(KSGradualValue<float>::create (0, 180.f * 99999.f, 99999.f, [=](float t) { hatBack->setRotation(t); }, [=](float t) { CCLOG("qq"); })); } topFollowBottom(); // 모자 위가 모자 밑둥을 따라감 } })); })); } // if(m_state == SceneState::kStopHat) // { // item->m_reward->setVisible(true); // } CCLOG("open!!"); }, hatBottomClose, hatBottomOpen, 0); CCMenuItemToggleLambda* hatTop = CCMenuItemToggleLambda::createWithTarget (nullptr, hatTopClose, hatTopOpen, 0); m_menu->addChild(hatBottom); m_disableMenu->addChild(hatTop); //// m_menu hatBottom->setPosition(retOnTheta(i * M_PI / 180.f)); hatBottom->m_hatTop = hatTop; hatTop->setAnchorPoint(ccp(0.5f, 0.0f)); hatTop->setPosition(ccp(hatBottom->getPositionX(), hatBottom->getPositionY() + hatBottom->getContentSize().height / 2.f)); m_hats.push_back(std::make_pair(hatBottom, i)); } ProbSelector ps; for(auto i : m_fakeRewards) { ps.pushProb(i->m_weight); } for(int i=0; i<8; i++) { int index = ps.getResult(); RewardSprite* temp_rs = m_fakeRewards[index]; RewardSprite* rs = RewardSprite::create(temp_rs->m_kind, temp_rs->m_value, temp_rs->m_spriteStr, temp_rs->m_weight); std::string valueStr = CCString::createWithFormat("%d", temp_rs->m_value)->getCString(); valueStr = std::string("+") + KS::insert_separator(valueStr); CCLabelBMFont* value = CCLabelBMFont::create(valueStr.c_str(), "allfont.fnt"); rs->addChild(value); value->setPosition(ccp(rs->getContentSize().width, rs->getContentSize().height) / 2.f); // rs->setColor(ccc3(255, 0, 0)); KS::setOpacity(rs, 0); // rs->setOpacity(0); addChild(rs, 20); m_rewards.push_back(rs); CCNodeFrames* nf = CCNodeFrames::create(); std::vector<int> randomIndex; for(int i=0; i<m_fakeRewards.size(); i++) { randomIndex.push_back(i); } random_device rd; mt19937 rEngine(rd()); random_shuffle(randomIndex.begin(), randomIndex.end(), [&rEngine](int n) { uniform_int_distribution<> distribution(0, n-1); return distribution(rEngine); }); // 페이크 에니메이션 돌림. for(auto iter : randomIndex) { RewardSprite* temp_rs = m_fakeRewards[iter]; RewardSprite* fakeItem = RewardSprite::create(temp_rs->m_kind, temp_rs->m_value, temp_rs->m_spriteStr, temp_rs->m_weight); std::string valueStr = CCString::createWithFormat("%d", temp_rs->m_value)->getCString(); valueStr = std::string("+") + KS::insert_separator(valueStr); CCLabelBMFont* value = CCLabelBMFont::create(valueStr.c_str(), "allfont.fnt"); fakeItem->addChild(value); value->setPosition(ccp(rs->getContentSize().width, fakeItem->getContentSize().height) / 2.f); nf->appendNode(fakeItem); } nf->runAnimation(0.05f); nf->setTag(kFakeItemTag); rs->addChild(nf); // nf->setPosition(rs->getPosition()); nf->setPosition(ccp(rs->getContentSize().width, rs->getContentSize().height) / 2.f); } // 모자와 똑같은 위치에 상품 넣음. { // 상품 연결 std::random_shuffle(m_rewards.begin(), m_rewards.end(), [=](int i) { return m_well512.GetValue(0, i-1); }); for(int i=0; i<m_hats.size(); i++) { m_hats[i].first->m_reward = m_rewards[i]; } } repositionHat(); for(auto i : m_hats) { i.first->setSelectedIndex(1); // 다 열음 i.first->m_hatTop->setSelectedIndex(1); } // m_rewardFollowHat = false; CCMenuItemImageLambda* startBtn = CCMenuItemImageLambda::create("gacha4_stop.png", "gacha4_stop.png"); startBtn->setPosition(ccp(240, 40)); // startBtn->setVisible(false); startBtn->setTarget([=](CCObject*) { // m_state = SceneState::kRun; startBtn->setVisible(false); for(auto i : m_rewards) { KS::setOpacity(i, 255); i->getChildByTag(kFakeItemTag)->removeFromParent(); } addChild(KSTimer::create(2.f, [=]() { m_state = SceneState::kCoveringHat; })); }); m_state = SceneState::kBeforeCoveringHat; m_internalMenu->addChild(startBtn); scheduleUpdate(); return true; } //HatGacha::HatGacha() //{ //} //HatGacha::~HatGacha() //{ //CCLOG("~hatgacha"); //} ////void HatGacha::registerWithTouchDispatcher() ////{ //// CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, false); ////} ////bool HatGacha::ccTouchBegan(CCTouch* pTouch, CCEvent* pEvent) ////{ //// CCTouch* touch = pTouch; //// //// CCPoint location(ccp(0, 0)); //// location = CCDirector::sharedDirector()->convertToGL(touch->locationInView()); //// //// return true; ////} //bool HatGacha::init(std::function<void(void)> closeCallback) //{ //CCLayer::init(); //KSAlertView* av = KSAlertView::create(); //HatGachaSub* gs = HatGachaSub::create(av, { //RewardSprite::create(RewardKind::kRuby, 20, "price_ruby_img.png", 1), //RewardSprite::create(RewardKind::kGold, 500, "price_gold_img.png", 2), //RewardSprite::create(RewardKind::kSpecialAttack, 1, "item1.png", 5), //RewardSprite::create(RewardKind::kDash, 1, "item4.png", 5), //RewardSprite::create(RewardKind::kSlience, 1, "item8.png", 5), //RewardSprite::create(RewardKind::kRentCard, 1, "item16.png", 5), //RewardSprite::create(RewardKind::kSubMonsterOneKill, 1, "item9.png", 5), //RewardSprite::create(RewardKind::kGold, 1000, "price_gold_img.png", 5) //}); //av->setContentNode(gs); //av->setBack9(CCScale9Sprite::create("popup2_case_back.png", CCRectMake(0,0, 150, 150), CCRectMake(13, 45, 122, 92))); //// av->setContentBorder(CCScale9Sprite::create("popup2_content_back.png", CCRectMake(0,0, 150, 150), CCRectMake(6, 6, 144-6, 144-6))); //av->setBorderScale(0.9f); //av->setButtonHeight(0); //av->setCloseOnPress(false); //// av->setTitleStr("지금 열기"); //addChild(av, 1); //// con2->alignItemsVerticallyWithPadding(30); //av->show(closeCallback); //av->getContainerScrollView()->setTouchEnabled(false); //return true; //}
[ "seo88youngho@gmail.com" ]
seo88youngho@gmail.com
dab6e471f3dc6a3d0fd52432a1c94d113f63333f
52a3c93c38bef127eaee4420f36a89d929a321c5
/SDK/SoT_BP_SmallShipNetProxy_classes.hpp
e394e766d8552097eb57e693973fc443d964f472
[]
no_license
RDTCREW/SoT-SDK_2_0_7_reserv
8e921275508d09e5f81b10f9a43e47597223cb35
db6a5fc4cdb9348ddfda88121ebe809047aa404a
refs/heads/master
2020-07-24T17:18:40.537329
2019-09-11T18:53:58
2019-09-11T18:53:58
207,991,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_SmallShipNetProxy_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_SmallShipNetProxy.BP_SmallShipNetProxy_C // 0x0018 (0x0538 - 0x0520) class ABP_SmallShipNetProxy_C : public AShipNetProxy { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0520(0x0008) (ZeroConstructor, Transient, DuplicateTransient) TArray<class UMaterialInstanceDynamic*> Dynamic_Materials; // 0x0528(0x0010) (Edit, BlueprintVisible, ZeroConstructor) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_SmallShipNetProxy.BP_SmallShipNetProxy_C")); return ptr; } void Set_Colour_on_All_Materials(const struct FName& ParameterName, const struct FLinearColor& Value); void Set_Value_on_All_Materials(const struct FName& Variable_Name, float Value); void Apply_Bits_to_Lanterns(int Bits); void Create_Dynamic_Materials(); void UserConstructionScript(); void ReceiveBeginPlay(); void OnLanternStateChanged(int LanternStateBits); void ExecuteUbergraph_BP_SmallShipNetProxy(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
de2aaada0095602ec0fedbb7de08324b8f32de68
5a51deb838cbb865a4f3f5206da3b686032e6f84
/cpp/open3d/visualization/rendering/filament/FilamentGeometryBuffersBuilder.cpp
ce170f45cc3ddef92ee013cc8886b2a41bee9509
[ "MIT" ]
permissive
sujitahirrao/Open3D
0d49ca59c3b933e63c98d9e37703529fe91587bd
aa29e5a38cf4f15351e7f8aefe3d9ecd71e67f88
refs/heads/master
2023-08-29T01:00:44.982177
2021-10-10T08:54:20
2021-10-10T08:54:20
301,184,341
0
0
NOASSERTION
2021-10-04T17:15:57
2020-10-04T17:18:16
C++
UTF-8
C++
false
false
11,583
cpp
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/visualization/rendering/filament/FilamentGeometryBuffersBuilder.h" #include "open3d/geometry/BoundingVolume.h" #include "open3d/geometry/LineSet.h" #include "open3d/geometry/Octree.h" #include "open3d/geometry/PointCloud.h" #include "open3d/geometry/TriangleMesh.h" #include "open3d/geometry/VoxelGrid.h" namespace open3d { namespace visualization { namespace rendering { namespace { static const Eigen::Vector3d kDefaultVoxelColor(0.5, 0.5, 0.5); // Coordinates of 8 vertices in a cuboid (assume origin (0,0,0), size 1) const static std::vector<Eigen::Vector3i> kCuboidVertexOffsets{ Eigen::Vector3i(0, 0, 0), Eigen::Vector3i(1, 0, 0), Eigen::Vector3i(0, 1, 0), Eigen::Vector3i(1, 1, 0), Eigen::Vector3i(0, 0, 1), Eigen::Vector3i(1, 0, 1), Eigen::Vector3i(0, 1, 1), Eigen::Vector3i(1, 1, 1), }; // Vertex indices of 12 triangles in a cuboid, for right-handed manifold mesh const static std::vector<Eigen::Vector3i> kCuboidTrianglesVertexIndices{ Eigen::Vector3i(0, 2, 1), Eigen::Vector3i(0, 1, 4), Eigen::Vector3i(0, 4, 2), Eigen::Vector3i(5, 1, 7), Eigen::Vector3i(5, 7, 4), Eigen::Vector3i(5, 4, 1), Eigen::Vector3i(3, 7, 1), Eigen::Vector3i(3, 1, 2), Eigen::Vector3i(3, 2, 7), Eigen::Vector3i(6, 4, 7), Eigen::Vector3i(6, 7, 2), Eigen::Vector3i(6, 2, 4), }; // Vertex indices of 12 lines in a cuboid const static std::vector<Eigen::Vector2i> kCuboidLinesVertexIndices{ Eigen::Vector2i(0, 1), Eigen::Vector2i(0, 2), Eigen::Vector2i(0, 4), Eigen::Vector2i(3, 1), Eigen::Vector2i(3, 2), Eigen::Vector2i(3, 7), Eigen::Vector2i(5, 1), Eigen::Vector2i(5, 4), Eigen::Vector2i(5, 7), Eigen::Vector2i(6, 2), Eigen::Vector2i(6, 4), Eigen::Vector2i(6, 7), }; static void AddVoxelFaces(geometry::TriangleMesh& mesh, const std::vector<Eigen::Vector3d>& vertices, const Eigen::Vector3d& color) { for (const Eigen::Vector3i& triangle_vertex_indices : kCuboidTrianglesVertexIndices) { int n = int(mesh.vertices_.size()); mesh.triangles_.push_back({n, n + 1, n + 2}); mesh.vertices_.push_back(vertices[triangle_vertex_indices(0)]); mesh.vertices_.push_back(vertices[triangle_vertex_indices(1)]); mesh.vertices_.push_back(vertices[triangle_vertex_indices(2)]); mesh.vertex_colors_.push_back(color); mesh.vertex_colors_.push_back(color); mesh.vertex_colors_.push_back(color); } } static void AddLineFace(geometry::TriangleMesh& mesh, const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& half_width, const Eigen::Vector3d& color) { int n = int(mesh.vertices_.size()); mesh.triangles_.push_back({n, n + 1, n + 3}); mesh.triangles_.push_back({n, n + 3, n + 2}); mesh.vertices_.push_back(start - half_width); mesh.vertices_.push_back(start + half_width); mesh.vertices_.push_back(end - half_width); mesh.vertices_.push_back(end + half_width); mesh.vertex_colors_.push_back(color); mesh.vertex_colors_.push_back(color); mesh.vertex_colors_.push_back(color); mesh.vertex_colors_.push_back(color); } static std::shared_ptr<geometry::TriangleMesh> CreateTriangleMeshFromVoxelGrid( const geometry::VoxelGrid& voxel_grid) { auto mesh = std::make_shared<geometry::TriangleMesh>(); auto num_voxels = voxel_grid.voxels_.size(); mesh->vertices_.reserve(36 * num_voxels); mesh->vertex_colors_.reserve(36 * num_voxels); std::vector<Eigen::Vector3d> vertices; // putting outside loop enables reuse for (auto& it : voxel_grid.voxels_) { vertices.clear(); const geometry::Voxel& voxel = it.second; // 8 vertices in a voxel Eigen::Vector3d base_vertex = voxel_grid.origin_ + voxel.grid_index_.cast<double>() * voxel_grid.voxel_size_; for (const Eigen::Vector3i& vertex_offset : kCuboidVertexOffsets) { vertices.push_back(base_vertex + vertex_offset.cast<double>() * voxel_grid.voxel_size_); } // Voxel color (applied to all points) Eigen::Vector3d voxel_color; if (voxel_grid.HasColors()) { voxel_color = voxel.color_; } else { voxel_color = kDefaultVoxelColor; } AddVoxelFaces(*mesh, vertices, voxel_color); } return mesh; } static std::shared_ptr<geometry::TriangleMesh> CreateTriangleMeshFromOctree( const geometry::Octree& octree) { auto mesh = std::make_shared<geometry::TriangleMesh>(); // We cannot have a real line with a width in pixels, we can only fake a // line as rectangles. This value works nicely on the assumption that the // octree fills about 80% of the viewing area. double line_half_width = 0.0015 * octree.size_; auto f = [&mesh = *mesh, line_half_width]( const std::shared_ptr<geometry::OctreeNode>& node, const std::shared_ptr<geometry::OctreeNodeInfo>& node_info) -> bool { Eigen::Vector3d base_vertex = node_info->origin_.cast<double>(); std::vector<Eigen::Vector3d> vertices; for (const Eigen::Vector3i& vertex_offset : kCuboidVertexOffsets) { vertices.push_back(base_vertex + vertex_offset.cast<double>() * double(node_info->size_)); } auto leaf_node = std::dynamic_pointer_cast<geometry::OctreeColorLeafNode>(node); if (leaf_node) { AddVoxelFaces(mesh, vertices, leaf_node->color_); } else { // We cannot have lines in a TriangleMesh, obviously, so fake them // with two crossing planes. for (const Eigen::Vector2i& line_vertex_indices : kCuboidLinesVertexIndices) { auto& start = vertices[line_vertex_indices(0)]; auto& end = vertices[line_vertex_indices(1)]; Eigen::Vector3d w(line_half_width, 0.0, 0.0); // if (end - start).dot({1, 0, 0}) ~= 0, then use z, not x if (std::abs(end.y() - start.y()) < 0.1 && std::abs(end.z() - start.z()) < 0.1) { w = {0.0, 0.0, line_half_width}; } AddLineFace(mesh, start, end, w, {0.0, 0.0, 0.0}); w = {0.0, line_half_width, 0.0}; // if (end - start).dot({0, 1, 0}) ~= 0, then use z, not y if (std::abs(end.x() - start.x()) < 0.1 && std::abs(end.z() - start.z()) < 0.1) { w = {0.0, 0.0, line_half_width}; } AddLineFace(mesh, start, end, w, {0.0, 0.0, 0.0}); } } return false; }; octree.Traverse(f); return mesh; } } // namespace class TemporaryLineSetBuilder : public LineSetBuffersBuilder { public: explicit TemporaryLineSetBuilder(std::shared_ptr<geometry::LineSet> lines) : LineSetBuffersBuilder(*lines), lines_(lines) {} private: std::shared_ptr<geometry::LineSet> lines_; }; class TemporaryMeshBuilder : public TriangleMeshBuffersBuilder { public: explicit TemporaryMeshBuilder(std::shared_ptr<geometry::TriangleMesh> mesh) : TriangleMeshBuffersBuilder(*mesh), mesh_(mesh) {} private: std::shared_ptr<geometry::TriangleMesh> mesh_; }; std::unique_ptr<GeometryBuffersBuilder> GeometryBuffersBuilder::GetBuilder( const geometry::Geometry3D& geometry) { using GT = geometry::Geometry::GeometryType; switch (geometry.GetGeometryType()) { case GT::TriangleMesh: return std::make_unique<TriangleMeshBuffersBuilder>( static_cast<const geometry::TriangleMesh&>(geometry)); case GT::PointCloud: return std::make_unique<PointCloudBuffersBuilder>( static_cast<const geometry::PointCloud&>(geometry)); case GT::LineSet: return std::make_unique<LineSetBuffersBuilder>( static_cast<const geometry::LineSet&>(geometry)); case GT::OrientedBoundingBox: { auto obb = static_cast<const geometry::OrientedBoundingBox&>(geometry); auto lines = geometry::LineSet::CreateFromOrientedBoundingBox(obb); lines->PaintUniformColor(obb.color_); return std::make_unique<TemporaryLineSetBuilder>(lines); } case GT::AxisAlignedBoundingBox: { auto aabb = static_cast<const geometry::AxisAlignedBoundingBox&>( geometry); auto lines = geometry::LineSet::CreateFromAxisAlignedBoundingBox(aabb); lines->PaintUniformColor(aabb.color_); return std::make_unique<TemporaryLineSetBuilder>(lines); } case GT::VoxelGrid: { auto voxel_grid = static_cast<const geometry::VoxelGrid&>(geometry); auto mesh = CreateTriangleMeshFromVoxelGrid(voxel_grid); return std::make_unique<TemporaryMeshBuilder>(mesh); } case GT::Octree: { auto octree = static_cast<const geometry::Octree&>(geometry); auto mesh = CreateTriangleMeshFromOctree(octree); return std::make_unique<TemporaryMeshBuilder>(mesh); } default: break; } return nullptr; } std::unique_ptr<GeometryBuffersBuilder> GeometryBuffersBuilder::GetBuilder( const t::geometry::PointCloud& geometry) { return std::make_unique<TPointCloudBuffersBuilder>(geometry); } void GeometryBuffersBuilder::DeallocateBuffer(void* buffer, size_t size, void* user_ptr) { free(buffer); } } // namespace rendering } // namespace visualization } // namespace open3d
[ "noreply@github.com" ]
sujitahirrao.noreply@github.com
ccac8e7a659f19ab9e5195acc2908eab162e211a
8af716c46074aabf43d6c8856015d8e44e863576
/src/qt/privacydialog.cpp
d95d965639e6ed7984f1693667db622905ce598c
[ "MIT" ]
permissive
coinwebfactory/acrecore
089bc945becd76fee47429c20be444d7b2460f34
cba71d56d2a3036be506a982f23661e9de33b03b
refs/heads/master
2020-03-23T06:44:27.396884
2018-07-17T03:32:27
2018-07-17T03:32:27
141,226,622
0
0
null
null
null
null
UTF-8
C++
false
false
28,237
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privacydialog.h" #include "ui_privacydialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "libzerocoin/Denominations.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "coincontrol.h" #include "zcivcontroldialog.h" #include "spork.h" #include <QClipboard> #include <QSettings> #include <utilmoneystr.h> #include <QtWidgets> PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent), ui(new Ui::PrivacyDialog), walletModel(0), currentBalance(-1) { nDisplayUnit = 0; // just make sure it's not unitialized ui->setupUi(this); // "Spending 999999 zACRE ought to be enough for anybody." - Bill Gates, 2017 ui->zACREpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) ); ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) ); // Default texts for (mini-) coincontrol ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); ui->labelzACRESyncStatus->setText("(" + tr("out of sync") + ")"); // Sunken frame for minting messages ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui->TEMintStatus->setLineWidth (2); ui->TEMintStatus->setMidLineWidth (2); ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Coin Control signals connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); // Denomination labels ui->labelzDenom1Text->setText("Denom. with value <b>1</b>:"); ui->labelzDenom2Text->setText("Denom. with value <b>5</b>:"); ui->labelzDenom3Text->setText("Denom. with value <b>10</b>:"); ui->labelzDenom4Text->setText("Denom. with value <b>50</b>:"); ui->labelzDenom5Text->setText("Denom. with value <b>100</b>:"); ui->labelzDenom6Text->setText("Denom. with value <b>500</b>:"); ui->labelzDenom7Text->setText("Denom. with value <b>1000</b>:"); ui->labelzDenom8Text->setText("Denom. with value <b>5000</b>:"); // Acre settings QSettings settings; if (!settings.contains("nSecurityLevel")){ nSecurityLevel = 42; settings.setValue("nSecurityLevel", nSecurityLevel); } else{ nSecurityLevel = settings.value("nSecurityLevel").toInt(); } if (!settings.contains("fMinimizeChange")){ fMinimizeChange = false; settings.setValue("fMinimizeChange", fMinimizeChange); } else{ fMinimizeChange = settings.value("fMinimizeChange").toBool(); } ui->checkBoxMinimizeChange->setChecked(fMinimizeChange); // Start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // Hide those placeholder elements needed for CoinControl interaction ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator ui->dummyHideWidget->hide(); // Dummy widget with elements to hide //temporary disable for maintenance if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { ui->pushButtonMintzACRE->setEnabled(false); ui->pushButtonMintzACRE->setToolTip(tr("zACRE is currently disabled due to maintenance.")); ui->pushButtonSpendzACRE->setEnabled(false); ui->pushButtonSpendzACRE->setToolTip(tr("zACRE is currently disabled due to maintenance.")); } } PrivacyDialog::~PrivacyDialog() { delete ui; } void PrivacyDialog::setModel(WalletModel* walletModel) { this->walletModel = walletModel; if (walletModel && walletModel->getOptionsModel()) { // Keep up to date with wallet setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); ui->securityLevel->setValue(nSecurityLevel); } } void PrivacyDialog::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void PrivacyDialog::on_addressBookButton_clicked() { if (!walletModel) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(walletModel->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->zACREpayAmount->setFocus(); } } void PrivacyDialog::on_pushButtonMintzACRE_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zACRE is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Reset message text ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first.")); return; } } QString sAmount = ui->labelMintAmountValue->text(); CAmount nAmount = sAmount.toInt() * COIN; // Minting amount must be > 0 if(nAmount <= 0){ ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0.")); return; } ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zACRE..."); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); CWalletTx wtx; vector<CZerocoinMint> vMints; string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); // Return if something went wrong during minting if (strError != ""){ ui->TEMintStatus->setPlainText(QString::fromStdString(strError)); return; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; // Minting successfully finished. Show some stats for entertainment. QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zACRE in ") + QString::number(fDuration) + tr(" sec. Used denominations:\n"); // Clear amount to avoid double spending when accidentally clicking twice ui->labelMintAmountValue->setText ("0"); QString strStats = ""; ui->TEMintStatus->setPlainText(strStatsHeader); for (CZerocoinMint mint : vMints) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); strStats = strStats + QString::number(mint.GetDenomination()) + " "; ui->TEMintStatus->setPlainText(strStatsHeader + strStats); ui->TEMintStatus->repaint (); } // Available balance isn't always updated, so force it. setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); coinControlUpdateLabels(); return; } void PrivacyDialog::on_pushButtonMintReset_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware. \nPlease be patient...")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetMintResult = pwalletMain->ResetMintZerocoin(false); // do not do the extended search from GUI double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); return; } void PrivacyDialog::on_pushButtonSpentReset_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: ")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); return; } void PrivacyDialog::on_pushButtonSpendzACRE_clicked() { if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zACRE is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled return; } // Wallet is unlocked now, sedn zACRE sendzACRE(); return; } // Wallet already unlocked or not encrypted at all, send zACRE sendzACRE(); } void PrivacyDialog::on_pushButtonZCivControl_clicked() { ZCivControlDialog* zCivControl = new ZCivControlDialog(this); zCivControl->setModel(walletModel); zCivControl->exec(); } void PrivacyDialog::setZCivControlLabels(int64_t nAmount, int nQuantity) { ui->labelzCivSelected_int->setText(QString::number(nAmount)); ui->labelQuantitySelected_int->setText(QString::number(nQuantity)); } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } void PrivacyDialog::sendzACRE() { QSettings settings; // Handle 'Pay To' address options CBitcoinAddress address(ui->payTo->text().toStdString()); if(ui->payTo->text().isEmpty()){ QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok); } else{ if (!address.IsValid()) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Acre Address"), QMessageBox::Ok, QMessageBox::Ok); ui->payTo->setFocus(); return; } } // Double is allowed now double dAmount = ui->zACREpayAmount->text().toDouble(); CAmount nAmount = roundint64(dAmount* COIN); // Check amount validity if (!MoneyRange(nAmount) || nAmount <= 0.0) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok); ui->zACREpayAmount->setFocus(); return; } // Convert change to zACRE bool fMintChange = ui->checkBoxMintChange->isChecked(); // Persist minimize change setting fMinimizeChange = ui->checkBoxMinimizeChange->isChecked(); settings.setValue("fMinimizeChange", fMinimizeChange); // Warn for additional fees if amount is not an integer and change as zACRE is requested bool fWholeNumber = floor(dAmount) == dAmount; double dzFee = 0.0; if(!fWholeNumber) dzFee = 1.0 - (dAmount - floor(dAmount)); if(!fWholeNumber && fMintChange){ QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>"; strFeeWarning += QString::number(dzFee, 'f', 8) + " ACRE </b>will be added to the standard transaction fees!<br />"; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"), strFeeWarning, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled ui->zACREpayAmount->setFocus(); return; } } // Persist Security Level for next start nSecurityLevel = ui->securityLevel->value(); settings.setValue("nSecurityLevel", nSecurityLevel); // Spend confirmation message box // Add address info if available QString strAddressLabel = ""; if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){ strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") "; } // General info QString strQuestionString = tr("Are you sure you want to send?<br /><br />"); QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zACRE</b>"; QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />"; if(ui->payTo->text().isEmpty()){ // No address provided => send to local address strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />"); } QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?"; strQuestionString += strAmount + strAddress + strSecurityLevel; // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), strQuestionString, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled return; } int64_t nTime = GetTimeMillis(); ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware. \nPlease be patient...")); ui->TEMintStatus->repaint(); // use mints from zCiv selector if applicable vector<CZerocoinMint> vMintsSelected; if (!ZCivControlDialog::listSelectedMints.empty()) { vMintsSelected = ZCivControlDialog::GetSelectedMints(); } // Spend zACRE CWalletTx wtxNew; CZerocoinSpendReceipt receipt; bool fSuccess = false; if(ui->payTo->text().isEmpty()){ // Spend to newly generated local address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange); } else { // Spend to supplied destination address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address); } // Display errors during spend if (!fSuccess) { int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zACRE transaction if (nNeededSpends > nMaxSpends) { QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed. \nMaximum allowed: ") + QString::number(nMaxSpends, 10); strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend."); QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString())); } else { QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage())); } ui->zACREpayAmount->setFocus(); ui->TEMintStatus->repaint(); return; } // Clear zciv selector in case it was used ZCivControlDialog::listSelectedMints.clear(); // Some statistics for entertainment QString strStats = ""; CAmount nValueIn = 0; int nCount = 0; for (CZerocoinSpend spend : receipt.GetSpends()) { strStats += tr("zCiv Spend #: ") + QString::number(nCount) + ", "; strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", "; strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n"; strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n"; nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination()); } CAmount nValueOut = 0; for (const CTxOut& txout: wtxNew.vout) { strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " Civ, "; nValueOut += txout.nValue; strStats += tr("address: "); CTxDestination dest; if(txout.scriptPubKey.IsZerocoinMint()) strStats += tr("zCiv Mint"); else if(ExtractDestination(txout.scriptPubKey, dest)) strStats += tr(CBitcoinAddress(dest).ToString().c_str()); strStats += "\n"; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"); strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n"; QString strReturn; strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n"; strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n"; strReturn += strStats; // Clear amount to avoid double spending when accidentally clicking twice ui->zACREpayAmount->setText ("0"); ui->TEMintStatus->setPlainText(strReturn); ui->TEMintStatus->repaint(); } void PrivacyDialog::on_payTo_textChanged(const QString& address) { updateLabel(address); } // Coin Control: copy label "Quantity" to clipboard void PrivacyDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void PrivacyDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: button inputs -> show actual coin control dialog void PrivacyDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(walletModel); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: update labels void PrivacyDialog::coinControlUpdateLabels() { if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); if (CoinControlDialog::coinControl->HasSelected()) { // Actual coin control calculation CoinControlDialog::updateLabels(walletModel, this); } else { ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); } } bool PrivacyDialog::updateLabel(const QString& address) { if (!walletModel) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; } void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentZerocoinBalance = zerocoinBalance; currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance; currentImmatureZerocoinBalance = immatureZerocoinBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true); std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances; std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; std::map<libzerocoin::CoinDenomination, int> mapImmature; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapDenomBalances.insert(make_pair(denom, 0)); mapUnconfirmed.insert(make_pair(denom, 0)); mapImmature.insert(make_pair(denom, 0)); } int nBestHeight = chainActive.Height(); for (auto& mint : listMints){ // All denominations mapDenomBalances.at(mint.GetDenomination())++; if (!mint.GetHeight() || chainActive.Height() - mint.GetHeight() <= Params().Zerocoin_MintRequiredConfirmations()) { // All unconfirmed denominations mapUnconfirmed.at(mint.GetDenomination())++; } else { // After a denomination is confirmed it might still be immature because < 1 of the same denomination were minted after it CBlockIndex *pindex = chainActive[mint.GetHeight() + 1]; int nHeight2CheckpointsDeep = nBestHeight - (nBestHeight % 10) - 20; int nMintsAdded = 0; while (pindex->nHeight < nHeight2CheckpointsDeep) { //at least 2 checkpoints from the top block nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination()); if (nMintsAdded >= Params().Zerocoin_RequiredAccumulation()) break; pindex = chainActive[pindex->nHeight + 1]; } if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()){ // Immature denominations mapImmature.at(mint.GetDenomination())++; } } } int64_t nCoins = 0; int64_t nSumPerCoin = 0; int64_t nUnconfirmed = 0; int64_t nImmature = 0; QString strDenomStats, strUnconfirmed = ""; for (const auto& denom : libzerocoin::zerocoinDenomList) { nCoins = libzerocoin::ZerocoinDenominationToInt(denom); nSumPerCoin = nCoins * mapDenomBalances.at(denom); nUnconfirmed = mapUnconfirmed.at(denom); nImmature = mapImmature.at(denom); strUnconfirmed = ""; if (nUnconfirmed) { strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. "); } if(nImmature) { strUnconfirmed += QString::number(nImmature) + QString(" immature "); } if(nImmature || nUnconfirmed) { strUnconfirmed = QString("( ") + strUnconfirmed + QString(") "); } strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " + QString::number(nCoins) + " = <b>" + QString::number(nSumPerCoin) + " zACRE </b>"; switch (nCoins) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelzDenom1Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelzDenom2Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelzDenom3Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelzDenom4Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelzDenom5Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelzDenom6Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelzDenom7Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelzDenom8Amount->setText(strDenomStats); break; default: // Error Case: don't update display break; } } CAmount matureZerocoinBalance = zerocoinBalance - immatureZerocoinBalance; CAmount nLockedBalance = 0; if (walletModel) { nLockedBalance = walletModel->getLockedBalance(); } ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zACRE ")); ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zACRE ")); ui->labelzACREAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways)); } void PrivacyDialog::updateDisplayUnit() { if (walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if (currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); } } void PrivacyDialog::showOutOfSyncWarning(bool fShow) { ui->labelzACRESyncStatus->setVisible(fShow); } void PrivacyDialog::keyPressEvent(QKeyEvent* event) { if (event->key() != Qt::Key_Escape) // press esc -> ignore { this->QDialog::keyPressEvent(event); } else { event->ignore(); } }
[ "root@vultr.guest" ]
root@vultr.guest
343f663010a279fe57586156eb3c2aa1840d4084
594e646453b7255104f721a9f9da84f752a733b8
/labs/kurs/samples/02_raytrace_plane/FrameBuffer.cpp
fc0988097c03e93b0b7c47146540d9e90b369ba3
[]
no_license
alexey-malov/cg
50068a19b8dc5d8259092e14ce2fdfa45400eac9
ca189f7e850a4d6f94103eabdb7840679f366d93
refs/heads/master
2020-12-30T15:41:35.575926
2018-06-19T11:26:35
2018-06-19T11:26:35
91,160,585
1
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include "stdafx.h" #include "FrameBuffer.h" CFrameBuffer::CFrameBuffer(unsigned width, unsigned height) :m_pixels(width * height) ,m_width(width) ,m_height(height) { } void CFrameBuffer::Clear(boost::uint32_t color) { std::fill(m_pixels.begin(), m_pixels.end(), color); }
[ "alexey.malov@cpslabs.net" ]
alexey.malov@cpslabs.net
c90db25310eb3414b659e6dc8ada7ecdd37b32db
79546e9feb03644ba7b99e26e2cfb4e34341712a
/obj.cpp
2dc39df39032dd6646565cc9640d7d3e4cdaef6c
[]
no_license
kagasan/cg
f261a793e327cb263c5e135d678d274efaa320f8
64179c65e086f6184417bfb5b271cbfff7562bca
refs/heads/master
2020-03-11T03:01:27.305331
2018-04-17T04:34:23
2018-04-17T04:34:23
129,734,697
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include "obj.h" #include <sstream> OBJ::OBJ(const std::string &filename){ read(filename); } void OBJ::read(const std::string &filename){ vertex.resize(1); face.clear(); ifs.open(filename); for (std::string line; getline(ifs, line);){ if (line[0] == '#')continue; else if (line[0] == 'v'){ std::stringstream ss; ss << line; char keyword; Point3d p; ss >> keyword >> p.x >> p.y >> p.z; vertex.push_back(p); } else if (line[0] == 'f'){ std::stringstream ss; ss << line; char keyword; Point3i p; ss >> keyword >> p.x >> p.y >> p.z; face.push_back(p); } } }
[ "ghghkaja@gmail.com" ]
ghghkaja@gmail.com
579bda5db9646c8e96b42221f422a0f52fb7230f
c75feeaa3f66d56c81b319648c210cd84caa403f
/InverseKinematic/src/Texture.h
165b72192407355e5dc6132f6656c90215d5191a
[]
no_license
hachihao792001/InverseKinematicOpenGL
2ef6da7203640dd82306c775ceee236d5a4ffa32
228993ff38d724f718357d7c3c2c36c473f9e735
refs/heads/master
2023-07-22T21:55:39.048705
2021-09-03T03:35:48
2021-09-03T03:35:48
402,010,870
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#pragma once #include "Renderer.h" class Texture { private: unsigned int m_RendererID; std::string m_FilePath; unsigned char* m_LocalBuffer; int m_Width, m_Height, m_BPP; //bits per pixel public: Texture(const std::string& path); ~Texture(); void Bind(unsigned int slot = 0) const; void Unbind() const; inline int GetWitdth() const { return m_Width; } inline int GetHeight() const { return m_Height; } };
[ "40560981+hachihao792001@users.noreply.github.com" ]
40560981+hachihao792001@users.noreply.github.com
11667f7a97a70b3d0a3a4a68df2dab613128c891
f6695e04d3188c96f0e8f08b8bfdcd362056b451
/xtwse/FT/source/bxDR/backup/bxRptWorker.cpp
b0973626b5d639ede0e47d4b54de1f9b7eadf030
[]
no_license
sp557371/TwseNewFix
28772048ff9150ba978ec591aec22b855ae6250a
5ed5146f221a0e38512e4056c2c4ea52dbd32dcd
refs/heads/master
2020-04-17T03:18:03.493560
2019-01-17T08:40:46
2019-01-17T08:40:46
166,175,913
0
0
null
null
null
null
BIG5
C++
false
false
4,459
cpp
#ifdef __BORLANDC__ #pragma hdrstop #pragma package(smart_init) #endif //--------------------------------------------------------------------------- #include "bxRptWorker.h" #include "bxRpt.h" #include "TwStk.h" #include "bxRptSes.h" //--------------------------------------------------------------------------- using namespace Kway::Tw::Bx; using namespace Kway::Tw::Bx::Rpt; ///////////////////////////////////////////////////////////////////////////// K_mf(int) TWork_RPT::GetPacketSize(TbxSesBase& aSes, const TbxData& aPkt) { switch(aPkt.GetFun()) { case ckRPTLink: switch(aPkt.GetMsg()) { case mgR1: // same as R2 case mgR2: return sizeof(TR1R2); case mgR4: // same as R5 case mgR5: return sizeof(TR4R5); } break; case ckRPTData: return sizeof(TControlHead) + sizeof(TLength); case ckRPTEnd: return sizeof(TR6); } return 0; } //--------------------------------------------------------------------------- K_mf(int) TWork_RPT::BeforeAPacket(TbxSesBase& aSes, const TbxData& aPkt) { if(aPkt.GetFun() == ckRPTData) { const TControlHead* head = static_cast<const TControlHead*>(&aPkt); const TR3 *r3 = static_cast<const TR3*>(head); return szTR3_Head + r3->BodyLength_.as_int(); } return 0; } //--------------------------------------------------------------------------- K_mf(bool) TWork_RPT::APacket(TbxSesBase& aSes, const TbxData& aPkt) { TbxRptSes* ses = dynamic_cast<TbxRptSes*>(&aSes); const TControlHead* head = static_cast<const TControlHead*>(&aPkt); size_t sz = GetPacketSize(aSes, aPkt); ses->WriteLog(reinterpret_cast<const char*>(&aPkt), sz, ses->GetPvcID()); return OnRptPkt(*ses, *head); } //--------------------------------------------------------------------------- K_mf(bool) TWork_RPT::DoReq(TbxSesBase& aSes, const TBxMsg aMsg, const TControlHead& aPkt) { TbxRptSes* ses = dynamic_cast<TbxRptSes*>(&aSes); return DoRptReq(*ses, aMsg, aPkt); } ///////////////////////////////////////////////////////////////////////////// K_mf(bool) TWork_R5000::OnRptPkt(TbxRptSes& aSes, const TControlHead& aPkt) { switch(aPkt.GetMsg()) { case mgR2: // R2 起始作業訊息 aSes.SetState(TbxRptSes::rpt_RptReply, "R2"); aSes.StartRptTimer(); break; case mgR4: // R4 連線作業訊息 if(aSes.DoWorker(aSes.GetWorkKey(ckRPTLink), mgR5, aPkt)) //送出 R5 { aSes.SetState(TbxRptSes::rpt_LinkChk, "R5"); aSes.StartRptTimer(); } break; default: return false; } return true; } //--------------------------------------------------------------------------- K_mf(bool) TWork_R5000::DoRptReq(TbxRptSes& aSes, const TBxMsg aMsg, const TControlHead& aPkt) { TR1R2 r1; TR4R5 r5; switch(aMsg) { case mgR1: r1.SetHead(GetWorkKey(), aMsg, aPkt.GetCode()); r1.BrkID_ = aSes.GetBrokerID(); r1.StartSeq_ = aSes.GetNextSeqNo(); return aSes.SendPkt(r1); case mgR5: r5.SetHead(GetWorkKey(), aMsg, aPkt.GetCode()); return aSes.SendPkt(r5); } return false; } ///////////////////////////////////////////////////////////////////////////// K_mf(bool) TWork_R5010::OnRptPkt(TbxRptSes& aSes, const TControlHead& aPkt) { // 如果STATE是rpt_Starting, 表示在重新要求R1, 此時放棄該成交資料 if(aSes.GetSesState() == TbxRptSes::rpt_Starting) return true; if(aPkt.GetMsg() == mgR3) { aSes.SetState(TbxRptSes::rpt_Data, "R3"); const TR3* r3 = static_cast<const TR3*>(&aPkt); int count = r3->BodyCount_.as_int(); for(int i=0;i<count;i++) aSes.WritePmach(r3->Body_[i]); return true; } return false; } ///////////////////////////////////////////////////////////////////////////// K_mf(bool) TWork_R5020::OnRptPkt(TbxRptSes& aSes, const TControlHead& aPkt) { if(aPkt.GetFun() == mgR6) { TRptBody body; const TR6* r6 = static_cast<const TR6*>(&aPkt); aSes.StopRptTimer(); aSes.SetState(TbxRptSes::rpt_Logout, "R6"); body.ExcCode_.assign("0"); body.OrdNo_.assign(" "); body.StkNo_.assign(" "); body.BSCode_.assign(" "); body.OrdType_.assign("0"); body.SeqNo_.assign(r6->TotalRec_.as_string()); body.BrkID_.assign(" "); aSes.WritePmach(body); aSes.CheckRptCount(r6->TotalRec_.as_int()); } return false; } //---------------------------------------------------------------------------
[ "xtwse@mail.kway.com.tw" ]
xtwse@mail.kway.com.tw
907a7d0e2be12d3a1289668c4cefc629e9d306ce
b9bd8a0bb3e107acdc61de13e18777c6045adfdf
/src/mail.cpp
ff77c908a2d057ff5497432dc7443e7cbd74cd9e
[]
no_license
Chrps/super-pack
8765f4a64f4d08055b9b7afa849349efab5a1638
78680ebe5e5e9ab6368b794507dfe1c7ef6b5be3
refs/heads/master
2021-01-10T18:20:24.376175
2015-10-29T07:53:18
2015-10-29T07:53:18
45,168,669
0
0
null
null
null
null
UTF-8
C++
false
false
47
cpp
void main (void){ // Nothing happens return; }
[ "Christoffer.chrps@gmail.com" ]
Christoffer.chrps@gmail.com
a155374aa950a76ad976b6339a071c30b3a691f5
713c3e5f7b4126bb5d57edf795580320d0b72e66
/App/ATFGenerator/src/CPU/SimpsonHalfIterateIntegrator.cpp
e6c4d315375b05b3f7f95d9e330518d15e2b1808
[]
no_license
rustanitu/TFG
b40ed59295e9d490dbd2724a5e86ee3697d6c787
0570d8cfe0d48edc19cf76c9771b14beb03f9fc4
refs/heads/master
2020-04-04T06:12:18.445176
2016-09-15T18:37:06
2016-09-15T18:37:06
54,929,706
0
0
null
null
null
null
UTF-8
C++
false
false
46,542
cpp
//Internal Error Half, External Half #include "SimpsonHalfIterateIntegrator.h" #include "VolumeEvaluator.h" #include "SimpsonEvaluation.h" #include <iostream> #include <fstream> #include <cmath> #include <cerrno> #include <cfenv> #include <cstring> #ifdef ANALYSIS__RGBA_ALONG_THE_RAY void SimpsonHalfIterateIntegrator::PrintExternalStepSize (double h) { if (file_ext) { (*file_ext) << std::setprecision (30) << anchor << '\t' << std::setprecision (30) << anchor + h << '\t' << std::setprecision (30) << h << '\t' << std::setprecision (30) << color.x << '\t' << std::setprecision (30) << color.y << '\t' << std::setprecision (30) << color.z << '\t' << std::setprecision (30) << color.w << '\n'; } } void SimpsonHalfIterateIntegrator::PrintInternalStepSize (double h) { if (file_int) { (*file_int) << std::setprecision (30) << anchor << '\t' << std::setprecision (30) << anchor + h << '\t' << std::setprecision (30) << h << '\t'; } } void SimpsonHalfIterateIntegrator::PrintInternalColor () { if (file_int) { (*file_int) << std::setprecision (30) << pre_integrated << '\n'; } } #endif SimpsonHalfIterateIntegrator::SimpsonHalfIterateIntegrator (VolumeEvaluator* veva) : SimpsonIntegrator (veva) {} SimpsonHalfIterateIntegrator::~SimpsonHalfIterateIntegrator () { Reset (); } void SimpsonHalfIterateIntegrator::Reset () { #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[0] = 0; m_steps_evaluation[1] = 0; m_steps_evaluation[2] = 0; m_steps_evaluation[3] = 0; m_steps_evaluation[4] = 0; m_steps_evaluation[5] = 0; m_steps_evaluation[6] = 0; m_steps_evaluation[7] = 0; m_steps_evaluation[8] = 0; m_steps_evaluation[9] = 0; m_steps_evaluation[10] = 0; #endif } void SimpsonHalfIterateIntegrator::PrintStepsEvaluation () { #ifdef COMPUTE_STEPS_ALONG_EVALUATION printf ("Steps evaluation:\n"); for (int i = 0; i < 11; i++) printf ("%d h < %d\n", m_steps_evaluation[i], i + 1); #endif } void SimpsonHalfIterateIntegrator::Init (lqc::Vector3d minp, lqc::Vector3d maxp, vr::Volume* vol, vr::TransferFunction* tf) { SimpsonIntegrator::Init (minp, maxp, vol, tf); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY file_ext = file_int = NULL; #endif } void SimpsonHalfIterateIntegrator::IntegrateSimple (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif double se1 = anchor + h; h_6 = h / 6.00; h_12 = h_6 * 0.5; tol = tol_multiplier * h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 == anchor) break; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; h_6 = h / 6.00; h_12 = h_6 * 0.5; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateSimpleExtStep (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double hext = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif double se1 = anchor + h; if (h <= hext) { hext = h; } else h = hext; h_6 = h / 6.00; h_12 = h_6 * 0.5; tol = tol_multiplier * h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 == anchor) break; hext = 2.0 * h; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; h_6 = h / 6.00; h_12 = h_6 * 0.5; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateComplexExtStep (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double hext = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif double se1 = anchor + h; //O passo que deve ser integrado deve ser igual ao passo // feito na integral interna if (h <= hext) { hext = hproj; if (S2alfa == 0.0) { #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); } else { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; pre_integrated = pre_integrated + (S2alfa + (S2alfa - Salfa) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } else { double se1 = anchor + h; do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_6 = h / 6.00; h_12 = h_6 * 0.5; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 <= anchor) break; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } } } } //O passo que deve ser integrado deve ser menor ao passo // feito na integral interna else { h = hext; h_6 = h / 6.00; h_12 = h_6 * 0.5; tol = tol_multiplier * h; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 == anchor) break; hext = 2.0 * h; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; h_6 = h / 6.00; h_12 = h_6 * 0.5; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateExp (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; pre_integrated = 1.0; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol && h > hmin); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif if (anchor_color.w + tf_d.w + tf_c.w + tf_e.w + tf_b.w == 0.0) { anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); } else { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluationApprox (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluationApprox (c, tf_c, tf_d.w); F_e = ExternalEvaluationApprox (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluationApprox (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; double x = -h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated * (1.0 + x + (x*x) / 2.0 + (x*x*x) / 6.0); anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } else { double se1 = anchor + h; h = h * 0.5; tol = tol * 0.5; while (se1 > anchor) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluationApprox (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluationApprox (c, tf_c, tf_d.w); F_e = ExternalEvaluationApprox (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluationApprox (b, tf_b, tf_c.w); h_6 = h / 6.00; h_12 = h_6 * 0.5; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; double x = -h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated * (1.0 + x + (x*x) / 2.0 + (x*x*x) / 6.0); anchor_color = tf_b; anchor = anchor + h; F_a = F_b; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; } else { do { h = h * 0.5; tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluationApprox (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluationApprox (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin)); color += S2 + S2S / 15.0; double x = -h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated * (1.0 + x + (x*x) / 2.0 + (x*x*x) / 6.0); anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } } } } } } void SimpsonHalfIterateIntegrator::IntegrateSeparated (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, hext = h0, hint = h0, hproj = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); lqc::Vector4d F_a = ExternalEvaluationAnchor (); double tol_int_multiplier = tol_int / s1; double tol_ext_multiplier = tol_ext / s1; double b, c, d, e, h_6, h_12, Salfa, S2alfa, S2left; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, F_d, F_c, F_e, F_b, S, S2, S2S, S2Eleft; while (s1 > anchor) { ///////////////////////////////////////////////// //Integral Interna { hint = std::max (hproj, hmin); hint = std::min (std::min (hint, hmax), s1 - anchor); tol = tol_int_multiplier * hint; tf_d = GetFromTransferFunction (anchor + hint * 0.25); tf_c = GetFromTransferFunction (anchor + hint * 0.50); tf_e = GetFromTransferFunction (anchor + hint * 0.75); tf_b = GetFromTransferFunction (anchor + hint); h_6 = hint / 6.0; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || hint <= hmin) hproj = 2.0 * hint; else { do { hint = hint * 0.5; if (hint <= hmin) { hint = hmin; tol = tol_int_multiplier * hint; tf_d = GetFromTransferFunction (anchor + hint * 0.25); tf_c = GetFromTransferFunction (anchor + hint * 0.50); tf_e = GetFromTransferFunction (anchor + hint * 0.75); tf_b = GetFromTransferFunction (anchor + hint); h_12 = hint / 12.0; Salfa = (h_12 * 2.0) * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); break; } tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + hint * 0.25); tf_e = GetFromTransferFunction (anchor + hint * 0.75); Salfa = S2left; S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol); hproj = hint; } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (hint); #endif ///////////////////////////////////////////////// //Integral Externa { double h = hext; //Caso o intervalo da integral externa for maior // que o intervalo da integral interna if (hint <= h) { h = hint; if (S2alfa == 0.0) { #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); hext = std::max (hext, hproj); continue; } else { h_6 = h_12 * 2.0; b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; pre_integrated = pre_integrated + (S2alfa + (S2alfa - Salfa) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = std::max (hext, hproj); continue; } } h = h * 0.5; } //O passo que deve ser integrado deve ser menor ao passo // feito na integral interna tol = tol_ext_multiplier * h; h_6 = h / 6.0; h_12 = h_6 * 0.5; double s1 = anchor + hint; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; double S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (s1 <= anchor) break; double h_2 = 2.0 * h; double s1_anchor = s1 - anchor; hext = h_2; h = std::min (h_2, s1_anchor); h_6 = h / 6.0; h_12 = h_6 * 0.5; tol = tol_ext_multiplier * h; } else { do { h = h * 0.5; if (h <= hmin) { h = hmin; tol = tol_ext_multiplier * h; b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_12 = h / 12.0; S = (h_12 * 2.0) * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; break; } tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)))); color += S2 + S2S / 15.0; h_6 = h_12 * 2.0; double S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; hext = h; } } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } } void SimpsonHalfIterateIntegrator::IntegrateScount (double s0, double s1, double tol, double h0, double hmin, double hmax) { tol = 15.0 * tol; double tol_int = tol, tol_ext = tol, h = h0; anchor = s0; anchor_color = GetFromTransferFunction (anchor); float Salfa, S2alfa; lqc::Vector4d S, S2; float b, c, d, e; lqc::Vector4d tf_d, tf_c, tf_e, tf_b, S2S; lqc::Vector4d tf_ad, tf_ae; lqc::Vector4d F_d, F_c, F_e, F_b; lqc::Vector4d F_a = lqc::Vector4d (anchor_color.w * anchor_color.x, anchor_color.w * anchor_color.y, anchor_color.w * anchor_color.z, anchor_color.w); double hproj = h; double h_6, h_12, S2left; lqc::Vector4d S2Eleft; double tol_multiplier = tol_int / s1; while (s1 > anchor) { h = std::max (hproj, hmin); h = std::min (std::min (h, hmax), s1 - anchor); tol = tol_multiplier * h; //Integral Interna tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_6 = h / 6.00; h_12 = h_6 * 0.5; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); if (abs (S2alfa - Salfa) <= tol || h <= hmin) hproj = 2.0 * h; else { do { h = h * 0.5; if (h <= hmin) { h = hmin; tol = tol_multiplier * h; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_c = GetFromTransferFunction (anchor + h * 0.50); tf_e = GetFromTransferFunction (anchor + h * 0.75); tf_b = GetFromTransferFunction (anchor + h); h_12 = h / 12.0; h_6 = h_12 * 2.0; Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); break; } tol = tol * 0.5; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; tf_d = GetFromTransferFunction (anchor + h * 0.25); tf_e = GetFromTransferFunction (anchor + h * 0.75); Salfa = h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w); S2left = h_12 * (anchor_color.w + 4.0 * tf_d.w + tf_c.w); S2alfa = S2left + (h_12 * (tf_c.w + 4.0 * tf_e.w + tf_b.w)); } while (abs (S2alfa - Salfa) > tol); hproj = h; h_6 = h_12 * 2.0; } #ifdef COMPUTE_STEPS_ALONG_EVALUATION m_steps_evaluation[(int)h]++; #endif #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalStepSize (h); #endif if (anchor_color.w + tf_d.w + tf_c.w + tf_e.w + tf_b.w == 0.0) { #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = lqc::Vector4d (0.0); } else { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; pre_integrated = pre_integrated + (S2alfa + (S2alfa - Salfa) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } else { double se1 = anchor + h; h = h * 0.5; tol = tol * 0.5; while (true) { b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_6 = h / 6.00; h_12 = h_6 * 0.5; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; if ((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)) || h <= hmin) { color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; if (se1 <= anchor) break; h = std::min (h * 2.0, se1 - anchor); tol = tol_multiplier * h; } else { do { h = h * 0.5; if (h <= hmin) { h = hmin; tol = tol_multiplier * h; b = anchor + h; c = anchor + h * 0.5; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_c = GetFromTransferFunction (c); tf_e = GetFromTransferFunction (e); tf_b = GetFromTransferFunction (b); F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction (anchor + h * 0.125).w); F_c = ExternalEvaluation (c, tf_c, tf_d.w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction (anchor + h * 0.375).w); F_b = ExternalEvaluation (b, tf_b, tf_c.w); h_12 = h / 12.0; h_6 = h_12 * 2.0; S = h_6 * (F_a + 4.0 * F_c + F_b); S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; break; } tol = tol * 0.5; h_6 = h_12; h_12 = h_12 * 0.5; tf_b = tf_c; tf_c = tf_d; d = anchor + h * 0.25; e = anchor + h * 0.75; tf_d = GetFromTransferFunction (d); tf_e = GetFromTransferFunction (e); F_b = F_c; F_c = F_d; F_d = ExternalEvaluation (d, tf_d, GetFromTransferFunction ((anchor + d) * 0.5).w); F_e = ExternalEvaluation (e, tf_e, GetFromTransferFunction ((anchor + e) * 0.5).w); S = S2Eleft; S2Eleft = h_12 * (F_a + 4.0 * F_d + F_c); S2 = S2Eleft + h_12 * (F_c + 4.0 * F_e + F_b); S2S = S2 - S; } while (!((tol >= abs (S2S.w) && tol >= abs (S2S.x) && tol >= abs (S2S.y) && tol >= abs (S2S.z)))); color += S2 + S2S / 15.0; S2alfa = h_12 * (anchor_color.w + 4.0 * tf_d.w + 2.0 * tf_c.w + 4.0 * tf_e.w + tf_b.w); pre_integrated = pre_integrated + (S2alfa + (S2alfa - h_6 * (anchor_color.w + 4.0 * tf_c.w + tf_b.w)) / 15.0); #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintExternalStepSize (h); #endif anchor_color = tf_b; anchor = anchor + h; F_a = F_b; } } } } #ifdef ANALYSIS__RGBA_ALONG_THE_RAY PrintInternalColor (); #endif } }
[ "rustanitus@gmail.com" ]
rustanitus@gmail.com
d1f913c328321f6f2d4f523934632f9ef08fd825
ba34acc11d45cf644d7ce462c5694ce9662c34c2
/Classes/gesture/PathWriter.h
119c62dbe67c0eae9f12e021b2242195a7a2810e
[]
no_license
mspenn/Sketch2D
acce625c4631313ba2ef47a5c8f8eadcd332719b
ae7d9f00814ac68fbd8e3fcb39dfac34edfc9883
refs/heads/master
2021-01-12T13:26:35.864853
2019-01-09T12:45:11
2019-01-09T12:45:11
69,162,221
8
7
null
null
null
null
UTF-8
C++
false
false
885
h
#ifndef _PathWriterIncluded_ #define _PathWriterIncluded_ #include <fstream> #include <string> #include "GeometricRecognizerTypes.h" using namespace std; namespace DollarRecognizer { class PathWriter { public: static bool writeToFile( Path2D path, const string fileName = "savedPath.txt", const string gestureName = "DefaultName") { fstream file(fileName.c_str(), ios::out); file << "Path2D getGesture" << gestureName << "()" << endl; file << "{" << endl; file << "\t" << "Path2D path;" << endl; Path2D::const_iterator i; for (i = path.begin(); i != path.end(); i++) { Point2D point = *i; file << "\t" << "path.push_back(Point2D(" << point.x << "," << point.y << "));" << endl; } file << endl; file << "\t" << "return path;" << endl; file << "}" << endl; file.close(); return true; } }; } #endif
[ "microsmadio@hotmail.com" ]
microsmadio@hotmail.com
5f1175bc34336a949304ecb72472445e6a1954b5
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir35435/dir35536/dir35859/dir36113/dir36250/file36306.cpp
70084755b8420d5ef4fd5e8c3d7a6f51bc3c5de5
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file36306 #error "macro file36306 must be defined" #endif static const char* file36306String = "file36306";
[ "tgeng@google.com" ]
tgeng@google.com
1d8e4feaeaf84034162c44d42bc2d8cc0a3684d4
bdda98f269400b13dfb277d52da4cb234fd4305c
/CVGCom/Units/Devices/dev_CVGx48.cpp
d87e2b2b5837aa06555dd2f308aa7db09d1bd47c
[]
no_license
fangxuetian/sources_old
75883b556c2428142e3323e676bea46a1191c775
7b1b0f585c688cb89bd4a23d46067f1dca2a17b2
refs/heads/master
2021-05-11T01:26:02.180353
2012-09-05T20:20:16
2012-09-05T20:20:16
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,528
cpp
//=========================================================================== #include "pmPCH.h" #pragma hdrstop //=========================================================================== #include "dev_CVGx48.h" //=========================================================================== CCVGx48::CCVGx48() { // ----- Частоты на которых работаем в непрерывном режиме выдачи информации ------ SamplingFreqsRate.Clear( ); SamplingFreqsRate.Add( 1); SamplingFreqsRate.Add( 5); SamplingFreqsRate.Add( 10); SamplingFreqsRate.Add( 20); SamplingFreqsRate.Add( 50); SamplingFreqsRate.Add(100); SamplingFreqsRate.Add(200); SerialPort->BaudRate = 115200; SerialPort->ByteSize = 8; ExtendedParamCount = 0; ExtendedParamValues[0] = 200; ExtendedParamNames[0] = strdup("UART_Frequncy:"); ExtendedParamValues[2] = 48; //ExtendedParamValues[2] = 64; Parent_ThreadType = 1; // -------- LoadFromRegistry("CVGx48"); } //=========================================================================== CCVGx48::~CCVGx48() { SaveDataToRegistry("CVGx48"); } //=========================================================================== int CCVGx48::Start() { // ---------- SaveDataToRegistry("CVGx48"); // ---------- UART_Frequency = ExtendedParamValues[0]; PackedLength = ExtendedParamValues[2]; InfoPackedLength = ExtendedParamValues[2]; SummationCount = UART_Frequency / SamplingFreq; if ( SummationCount < 1 ) SummationCount = 1; SummationCount_invert = 1.0 / (double)SummationCount; CurrentSummationPoint = 0; Storage->file_Param.StorageT0[0] = SummationCount / (double) UART_Frequency; // ---- Сэтапю каналы ---- CountUARTValues = 11; Storage->SetItemsCount(CountUARTValues + 0); //Storage->SetItemsCount(11); Storage->Items[ 0]->SetName("GyroOut"); Storage->Items[ 1]->SetName("Temperature"); Storage->Items[ 2]->SetName("AntiNodePeriod"); Storage->Items[ 3]->SetName("ExcitationDelay"); Storage->Items[ 4]->SetName("AntiNodeAmplitude"); Storage->Items[ 5]->SetName("ExcitationAmpl"); Storage->Items[ 6]->SetName("QuadratureAmpl"); Storage->Items[ 7]->SetName("QuadratureError"); Storage->Items[ 8]->SetName("CoriolisError"); Storage->Items[ 9]->SetName("NodeAmplitude"); Storage->Items[10]->SetName("GyroOut_RAW"); memset(fSliderBuffer, 0, sizeof(fSliderBuffer)); SliderArraySize = 120 * SamplingFreq; isSliderBufferInited = false; // ------------- if ( CBaseDevice::Start() == -1 ) return -1; if( OpenDataSaveFile( &h_file[0], Storage ) == -1 ) return -2; // ----- return 0; } //=========================================================================== void CCVGx48::Stop() { CBaseDevice::Stop(); } //=========================================================================== void CCVGx48::DeCompositeData() { // ---- в ---- gd->LastGoodReadValue[i] --- Находяться последние прочитанные данные с пакета ---- // ---- в ---- gd->SumValues [i] --- Находиться сумма на временном пакете ---- // ---- в ---- CountSumPoint --- Находиться количкство сумм ---- if ( Storage->Items[0]->ValuesCount >= SliderArraySize && isSliderBufferInited == false ) { if ( h_file[0] != NULL) fclose( h_file[0] ); h_file[0] = NULL; OpenDataSaveFile( &h_file[0], Storage ); Sleep(300); isSliderBufferInited = true; for (int i = 0; i < Storage->ItemsCount; i++) Storage->Items[i]->Clear(); } // ------- for (int i = 0; i < Storage->ItemsCount; i++) { memmove(&fSliderBuffer[i][1], &fSliderBuffer[i][0], SliderArraySize*sizeof(double)); fSliderBuffer[i][0] = ParentSummValues[i] / float(SummationCount); if ( isSliderBufferInited == true ) { double SumVal = 0; for ( int k = 0; k < SliderArraySize; k++) SumVal = SumVal + fSliderBuffer[i][k]; Storage->Items[i]->Add( SumVal / SliderArraySize ); } else Storage->Items[i]->Add(fSliderBuffer[i][0]); } }
[ "pm@pm.(none)" ]
pm@pm.(none)
51bba36cd257c80659870e36bd9a94a3acbdc1ac
6721651e2340b4936101744cc59f2e512815136f
/Activities/Session 48 - 23 April/PTKStudentCopy.cpp
1c2d362b48145965f4fd88715845d426877c539a
[]
no_license
compscisi/Programming-Fundamentals-1-SI
5859b60296f868d94faff2e02dc7d18735859ccb
d20311d09b85aaeb9621d04260cc104a011be35f
refs/heads/master
2020-04-16T12:38:20.189966
2019-05-09T16:07:50
2019-05-09T16:07:50
165,589,457
3
2
null
null
null
null
UTF-8
C++
false
false
1,814
cpp
//The following program skeleton, when complete, asks the user to enter these data //about his or her favorite movie : // Name of movie // Name of the movie’s director // Name of the movie’s producer // The year the movie was released //Complete the program by declaring the structure that holds this data, defining a //structure variable, and writing the individual statements necessary. //NOTE: This is the one students worked out in session #include <iostream> #include <string> using namespace std; // Write the structure declaration here to hold the movie data. struct MovieData { string movieName; string movieDir; string moviePro; string movieRel; }; int main() { // define the structure variable here. MovieData movie; cout << "Enter the following data about your\n"; cout << "favorite movie.\n"; cout << "Name: "; cin >> movie.movieName; // Write a statement here that lets the user enter the // name of a favorite movie. Store the name in the // structure variable. cout << "Director: "; cin >> movie.movieDir; // Write a statement here that lets the user enter the // name of the movie's director. Store the name in the // structure variable. cout << "Producer: "; cin >> movie.moviePro; // Write a statement here that lets the user enter the // name of the movie's producer. Store the name in the // structure variable. cout << "Year of release: "; cin >> movie.movieRel; // Write a statement here that lets the user enter the // year the movie was released. Store the year in the // structure variable. cout << "Here is data on your favorite movie:\n"; // Write statements here that display the data. cout << movie.movieName; cout << movie.movieDir; cout << movie.moviePro; cout << movie.movieRel; // just entered into the structure variable. return 0; }
[ "noreply@github.com" ]
compscisi.noreply@github.com
1a80c0e537b2db3edb3866fea5fb0462a60f5491
8c8820fb84dea70d31c1e31dd57d295bd08dd644
/Online/BuildPatchServices/Private/Generation/ChunkMatchProcessor.h
f542b09eeb6d28177bd1b41832353bb39b05010b
[]
no_license
redisread/UE-Runtime
e1a56df95a4591e12c0fd0e884ac6e54f69d0a57
48b9e72b1ad04458039c6ddeb7578e4fc68a7bac
refs/heads/master
2022-11-15T08:30:24.570998
2020-06-20T06:37:55
2020-06-20T06:37:55
274,085,558
3
0
null
null
null
null
UTF-8
C++
false
false
815
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreTypes.h" #include "Containers/Array.h" #include "Templates/Tuple.h" #include "Core/BlockRange.h" #include "Core/BlockStructure.h" #include "Generation/DataScanner.h" namespace BuildPatchServices { struct FMatchEntry { FChunkMatch ChunkMatch; FBlockStructure BlockStructure; }; class IChunkMatchProcessor { public: virtual ~IChunkMatchProcessor() {} virtual void ProcessMatch(const int32 Layer, const FChunkMatch& Match, FBlockStructure BuildSpace) = 0; virtual void FlushLayer(const int32 Layer, const uint64 UpToByteOffset) = 0; virtual FBlockRange CollectLayer(const int32 Layer, TArray<FMatchEntry>& OutData) = 0; }; class FChunkMatchProcessorFactory { public: static IChunkMatchProcessor* Create(); }; }
[ "wujiahong19981022@outlook.com" ]
wujiahong19981022@outlook.com
8c6b01bbcbc12ef85dde52892409c76cd8a5ef5c
ad780787315490d1deb31c2d550fe671c8d9777e
/GameLogic.cpp
2a8a55c0b33aee7fe164713316dfa91d03694e75
[]
no_license
nkwleroux/Proftaak2.4_A1_Word_Raiders
369c27989cbc7a12ba990e439f89b470125cb188
bc413dadb4d1d81be70fabce15588c2ca6e7a072
refs/heads/master
2023-05-29T11:49:50.951100
2021-06-14T08:45:33
2021-06-14T08:45:33
366,298,443
0
0
null
null
null
null
UTF-8
C++
false
false
4,204
cpp
#include "GameLogic.h" #include "WordLoader.h" #include "Scene.h" #include "LetterModelComponent.h" GameLogic::GameLogic() { // Initiate variables to standard values gameStarted = false; reset = false; currentWordLength = 5; currentWordAmount = 3; currentWordIndex = -1; // Initiate timers gameTimer = new Timer(90); oneSecondTimer = new Timer(1); // Load words from json file wordLoader = new WordLoader(); checkForStartingConditions(); } GameLogic::~GameLogic() {} void GameLogic::checkForStartingConditions() { //check if it is the start of the game if (!gameStarted) { gameStarted = true; wordsToGuess = wordLoader->loadWords(currentWordLength, currentWordAmount); currentWord = wordsToGuess[chosenWordsAmount]; gameTimer->start(); oneSecondTimer->start(); correctLetters = std::vector<char>(currentWordLength); shotLetters = std::vector<char>(currentWordLength); } } bool GameLogic::update(bool* redDetected) { checkForStartingConditions(); // If the currentWordIndex == -1 we know a new word is the current word if (currentWordIndex == -1) { fillVector(); currentWordIndex = 0; // todo remove for debugging std::cout << currentWord->getWord() << std::endl; return false; } //TODO --> check for lives //TODO --> check for timer // Check if the player want to fire if (*redDetected) { *redDetected = false; // Check if the player can fire if (oneSecondTimer->hasFinished()) { oneSecondTimer->start(); // Check if an objcet is selected if (selectedObject != nullptr) { // If the object is a letter model if (selectedObject->getComponent<LetterModelComponent>()) { // Get the letter of that lettermodel and shoot it char shotLetter = selectedObject->getComponent<LetterModelComponent>()->getLetter(); shootLetter(shotLetter); } } // If we have shot as many letters as the wordLength if (currentWordIndex == currentWordLength) { // Check the word if it is correct if (checkWord()) { // If it is correct we delete the word and set the new current word wordsToGuess.pop_back(); if (wordsToGuess.size() > 0) { currentWord = wordsToGuess[wordsToGuess.size() - 1]; reset = true; } // If there are no words left we are done and return true else { return true; } } // We remove all the shot characters else { currentWordIndex = 0; shotWord = ""; clearVector(&shotLetters); } } } } shotWord = ""; //clear the shotWord string for (int i = 0; i < shotLetters.size(); i++) { shotWord += shotLetters[i]; //fill the string with the letters of the vector } correctWord = ""; //clear the correctWord string for (int i = 0; i < correctLetters.size(); i++) { correctWord += correctLetters[i]; //fill the string with the letters of the vector } return false; } std::string GameLogic::getShotWord() { return shotWord; } std::string GameLogic::getCorrectWord() { return correctWord; } Word* GameLogic::getCurrentWord() { return currentWord; } Timer* GameLogic::getGameTimer() { return gameTimer; } void GameLogic::clearVector(std::vector<char>* vector) { for (int i = 0; i < vector->size(); i++) { vector->at(i) = '_'; } } /* * This function fills 2 vectors with letters or an _ */ void GameLogic::fillVector() { for (int i = 0; i < correctLetters.size(); i++) { shotLetters.at(i) = '_'; //fill the shotLetter vector with _ if (i == 0) { correctLetters.at(i) = currentWord->getFirstLetter(); //fill the vector with the first letter of the current word } else { correctLetters.at(i) = '_'; //fill the other indexes with an _ } } } bool GameLogic::checkWord() { int correctLettersAmount = 0; for (int i = 0; i < currentWordLength; i++) { if (currentWord->getWord()[i] == shotLetters.at(i)) { correctLetters.at(i) = currentWord->getWord()[i]; correctLettersAmount++; } } if (correctLettersAmount == currentWordLength) { clearVector(&correctLetters); currentWordIndex = -1; return true; } else { return false; } } void GameLogic::shootLetter(char shotLetter) { shotLetters.at(currentWordIndex) = shotLetter; currentWordIndex++; }
[ "rik.vos01@gmail.com" ]
rik.vos01@gmail.com
cecc114659f5dfed4ee527cb83e30191f3554955
2769085a50899819e8af0c0f28020cd42bbb5ed3
/src/ui_interface.h
bd67f38c5b831fda2aafe3c30d8adc609264a0af
[ "MIT" ]
permissive
CarbonTradingcoin/CarbonTradingcoin
ec188762cc06e1d1d963c10650e0427352c830af
0f824ee580b0ec7042abd607f581055bf68db0f9
refs/heads/master
2016-08-07T20:08:30.010797
2014-06-01T03:08:15
2014-06-01T03:08:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,375
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2012 The Carbonemissiontradecoin developers // Copyright (c) 2013-2079 CT DEV // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CARBONEMISSIONTRADECOIN_UI_INTERFACE_H #define CARBONEMISSIONTRADECOIN_UI_INTERFACE_H #include <string> #include "util.h" // for int64 #include <boost/signals2/signal.hpp> #include <boost/signals2/last_value.hpp> class CBasicKeyStore; class CWallet; class uint256; /** General change type (added, updated, removed). */ enum ChangeType { CT_NEW, CT_UPDATED, CT_DELETED }; /** Signals for UI communication. */ class CClientUIInterface { public: /** Flags for CClientUIInterface::ThreadSafeMessageBox */ enum MessageBoxFlags { ICON_INFORMATION = 0, ICON_WARNING = (1U << 0), ICON_ERROR = (1U << 1), /** * Mask of all available icons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when icons are changed there! */ ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR), /** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */ BTN_OK = 0x00000400U, // QMessageBox::Ok BTN_YES = 0x00004000U, // QMessageBox::Yes BTN_NO = 0x00010000U, // QMessageBox::No BTN_ABORT = 0x00040000U, // QMessageBox::Abort BTN_RETRY = 0x00080000U, // QMessageBox::Retry BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore BTN_CLOSE = 0x00200000U, // QMessageBox::Close BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel BTN_DISCARD = 0x00800000U, // QMessageBox::Discard BTN_HELP = 0x01000000U, // QMessageBox::Help BTN_APPLY = 0x02000000U, // QMessageBox::Apply BTN_RESET = 0x04000000U, // QMessageBox::Reset /** * Mask of all available buttons in CClientUIInterface::MessageBoxFlags * This needs to be updated, when buttons are changed there! */ BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE | BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET), /** Force blocking, modal message box dialog (not just OS notification) */ MODAL = 0x10000000U, /** Predefined combinations for certain default usage cases */ MSG_INFORMATION = ICON_INFORMATION, MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL), MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL) }; /** Show message box. */ boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox; /** Ask the user whether they want to pay a fee or not. */ boost::signals2::signal<bool (int64 nFeeRequired), boost::signals2::last_value<bool> > ThreadSafeAskFee; /** Handle a URL passed at the command line. */ boost::signals2::signal<void (const std::string& strURI)> ThreadSafeHandleURI; /** Progress message during initialization. */ boost::signals2::signal<void (const std::string &message)> InitMessage; /** Translate a message to the native language of the user. */ boost::signals2::signal<std::string (const char* psz)> Translate; /** Block chain changed. */ boost::signals2::signal<void ()> NotifyBlocksChanged; /** Number of network connections changed. */ boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged; /** * New, updated or cancelled alert. * @note called with lock cs_mapAlerts held. */ boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged; boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyNewsMessageChanged; }; extern CClientUIInterface uiInterface; /** * Translation function: Call Translate signal on UI interface, which returns a boost::optional result. * If no translation slot is registered, nothing is returned, and simply return the input. */ inline std::string _(const char* psz) { boost::optional<std::string> rv = uiInterface.Translate(psz); return rv ? (*rv) : psz; } #endif
[ "CarbonTradingcoin@gmail.com" ]
CarbonTradingcoin@gmail.com
b907c3601688af6a76a4ca679b60b446ba2766a1
ff444613472c57836e0f92ae404871f586639059
/inc/vhwd/collection/detail/bst_tree_node.h
dae1c45af740a5d447edda7b619708f62f743442
[ "Apache-2.0" ]
permissive
akirayu101/vhwd_base
1959cf1ebf065e669f89b54b3841a10923464023
fb694676bab13d4258c0031769e9aac0baa37b55
refs/heads/master
2020-12-11T03:33:23.650707
2014-09-16T09:08:37
2014-09-16T09:08:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,357
h
#ifndef __H_VHWD_COLLECTION_BST_TREE_NODE__ #define __H_VHWD_COLLECTION_BST_TREE_NODE__ #include "vhwd/collection/detail/collection_base.h" VHWD_ENTER template<typename K,typename V,typename E> class bst_node { public: typedef bst_node<K,V,E> node_type; typedef K key_type; typedef V mapped_type; typedef E extra_type; typedef typename kv_trait<K,V>::value_type value_type; node_type* parent; node_type* child1; node_type* child2; value_type value; extra_type extra; bst_node() { parent=child1=child2=NULL; } bst_node(const value_type& v):value(v) { parent=child1=child2=NULL; } bst_node(const bst_node& n):value(n.value),extra(n.extra) { parent=child1=child2=NULL; } #ifdef VHWD_C11 bst_node(value_type&& v):value(std::move(v)) { parent=child1=child2=NULL; } bst_node(bst_node&& n):value(n.value),extra(n.extra) { parent=child1=child2=NULL; } #endif }; template<typename K,typename V,typename C,typename E> class bst_trait_base { public: typedef bst_node<K,V,E> node_type; typedef K key_type; typedef V mapped_type; typedef typename node_type::value_type value_type; typedef const key_type& const_key_reference; typedef C key_compare; static size_t nd_count(node_type* p) { if(!p) return 0; return 1+nd_count(p->child1)+nd_count(p->child2); } static node_type* nd_min(node_type* n) { if(!n) return NULL; while(n->child1) n=n->child1; return n; } static node_type* nd_max(node_type* n) { if(!n) return NULL; while(n->child2) n=n->child2; return n; } static node_type* nd_inc(node_type* n) { wassert(n!=NULL); if(n->child2) { n=n->child2; while(n->child1) n=n->child1; return n; } for(;;) { node_type* p=n->parent; if(!p) { return NULL; } if(p->child1==n) { return p; } n=p; } } static node_type* nd_dec(node_type* n) { wassert(n!=NULL); if(n->child1) { n=n->child1; while(n->child2) n=n->child2; return n; } for(;;) { node_type* p=n->parent; if(!p) { return NULL; } if(p->child2==n) { return p; } n=p; } } }; template<typename K,typename V,typename C,typename E> class bst_trait : public bst_trait_base<K,V,C,E> { public: typedef bst_trait_base<K,V,C,E> basetype; typedef typename basetype::key_type key_type; typedef typename basetype::value_type value_type; typedef typename basetype::node_type node_type; static const key_type& key(const key_type& v) { return v; } static const key_type& key(const value_type& v) { return v.first; } static const key_type& key(node_type* node) { wassert(node!=NULL); return key(node->value); } }; template<typename K,typename C,typename E> class bst_trait<K,void,C,E> : public bst_trait_base<K,void,C,E> { public: typedef bst_trait_base<K,void,C,E> basetype; typedef typename basetype::key_type key_type; typedef typename basetype::value_type value_type; typedef typename basetype::node_type node_type; static const key_type& key(const key_type& v) { return v; } static const key_type& key(node_type* node) { wassert(node!=NULL); return node->value; } }; VHWD_LEAVE #endif
[ "wendahan@qq.com" ]
wendahan@qq.com
70e93d28b595a156c551dcadffc943bf47ec9e66
64440f30282c87b47b314e348957780d49e0d59d
/include/feature_birl.hpp
71689a514c1ee4d8f5eefe59a050aea7160b5568
[ "MIT" ]
permissive
dsbrown1331/aaai-2018-code
9f7eb75b431c37e3ac798bf085dc795692d5960b
303fe4e1c8c2d4cfae70100b5d2eb73efe121393
refs/heads/master
2021-04-30T05:30:59.060939
2018-03-07T15:18:58
2018-03-07T15:18:58
121,417,536
6
1
null
null
null
null
UTF-8
C++
false
false
18,657
hpp
#ifndef feature_birl_h #define feature_birl_h #include <cmath> #include <stdlib.h> #include <vector> #include <numeric> #include <math.h> #include "mdp.hpp" #include "../include/unit_norm_sampling.hpp" using namespace std; class FeatureBIRL { // BIRL process protected: double r_min, r_max, step_size; unsigned int chain_length; unsigned int grid_height, grid_width; double alpha; unsigned int iteration; int sampling_flag; bool mcmc_reject; //If false then it uses Yuchen's sample until accept method, if true uses normal MCMC sampling procedure int num_steps; //how many times to change current to get proposal void initializeMDP(); vector<pair<unsigned int,unsigned int> > positive_demonstration; vector<pair<unsigned int,unsigned int> > negative_demonstration; void modifyFeatureWeightsRandomly(FeatureGridMDP * gmdp, double step_size); void sampleL1UnitBallRandomly(FeatureGridMDP * gmdp); void updownL1UnitBallWalk(FeatureGridMDP * gmdp, double step); void manifoldL1UnitBallWalk(FeatureGridMDP * gmdp, double step, int num_steps); void manifoldL1UnitBallWalkAllSteps(FeatureGridMDP * gmdp, double step); double* posteriors = nullptr; FeatureGridMDP* MAPmdp = nullptr; double MAPposterior; public: FeatureGridMDP* mdp = nullptr; //original MDP FeatureGridMDP** R_chain = nullptr; //storing the rewards along the way ~FeatureBIRL(){ if(R_chain != nullptr) { for(unsigned int i=0; i<chain_length; i++) delete R_chain[i]; delete []R_chain; } if(posteriors != nullptr) delete []posteriors; delete MAPmdp; } double getAlpha(){return alpha;} FeatureBIRL(FeatureGridMDP* init_mdp, double min_reward, double max_reward, unsigned int chain_len, double step, double conf, int samp_flag=0, bool reject=false, int num_step=1): r_min(min_reward), r_max(max_reward), step_size(step), chain_length(chain_len), alpha(conf), sampling_flag(samp_flag), mcmc_reject(reject), num_steps(num_step){ unsigned int grid_height = init_mdp -> getGridHeight(); unsigned int grid_width = init_mdp -> getGridWidth(); bool* initStates = init_mdp -> getInitialStates(); bool* termStates = init_mdp -> getTerminalStates(); unsigned int nfeatures = init_mdp -> getNumFeatures(); double* fweights = init_mdp -> getFeatureWeights(); double** sfeatures = init_mdp -> getStateFeatures(); bool stochastic = init_mdp -> isStochastic(); double gamma = init_mdp -> getDiscount(); //copy init_mdp mdp = new FeatureGridMDP(grid_width, grid_height, initStates, termStates, nfeatures, fweights, sfeatures, stochastic, gamma); mdp->setWallStates(init_mdp->getWallStates()); initializeMDP(); //set weights to (r_min+r_max)/2 MAPmdp = new FeatureGridMDP(grid_width, grid_height, initStates, termStates, nfeatures, fweights, sfeatures, stochastic, gamma); MAPmdp->setWallStates(init_mdp->getWallStates()); MAPmdp->setFeatureWeights(mdp->getFeatureWeights()); MAPposterior = 0; R_chain = new FeatureGridMDP*[chain_length]; posteriors = new double[chain_length]; iteration = 0; }; FeatureGridMDP* getMAPmdp(){return MAPmdp;} double getMAPposterior(){return MAPposterior;} void addPositiveDemo(pair<unsigned int,unsigned int> demo) { positive_demonstration.push_back(demo); }; // (state,action) pair void addNegativeDemo(pair<unsigned int,unsigned int> demo) { negative_demonstration.push_back(demo); }; void addPositiveDemos(vector<pair<unsigned int,unsigned int> > demos); void addNegativeDemos(vector<pair<unsigned int,unsigned int> > demos); void run(double eps=0.001); void displayPositiveDemos(); void displayNegativeDemos(); void displayDemos(); double getMinReward(){return r_min;}; double getMaxReward(){return r_max;}; double getStepSize(){return step_size;}; unsigned int getChainLength(){return chain_length;}; vector<pair<unsigned int,unsigned int> >& getPositiveDemos(){ return positive_demonstration; }; vector<pair<unsigned int,unsigned int> >& getNegativeDemos(){ return negative_demonstration; }; FeatureGridMDP** getRewardChain(){ return R_chain; }; FeatureGridMDP* getMeanMDP(int burn, int skip); double* getPosteriorChain(){ return posteriors; }; FeatureGridMDP* getMDP(){ return mdp;}; double calculatePosterior(FeatureGridMDP* gmdp); double logsumexp(double* nums, unsigned int size); bool isDemonstration(pair<double,double> s_a); }; void FeatureBIRL::run(double eps) { //cout.precision(10); //cout << "itr: " << iteration << endl; //clear out previous values if they exist if(iteration > 0) for(unsigned int i=0; i<chain_length-1; i++) delete R_chain[i]; iteration++; MAPposterior = 0; R_chain[0] = mdp; // so that it can be deleted with R_chain!!!! //vector<unsigned int> policy (mdp->getNumStates()); //cout << "testing" << endl; mdp->valueIteration(eps);//deterministicPolicyIteration(policy); //cout << "value iter" << endl; mdp->calculateQValues(); mdp->displayFeatureWeights(); double posterior = calculatePosterior(mdp); //cout << "init posterior: " << posterior << endl; posteriors[0] = exp(posterior); int reject_cnt = 0; //BIRL iterations for(unsigned int itr=1; itr < chain_length; itr++) { //cout << "itr: " << itr << endl; FeatureGridMDP* temp_mdp = new FeatureGridMDP (mdp->getGridWidth(),mdp->getGridHeight(), mdp->getInitialStates(), mdp->getTerminalStates(), mdp->getNumFeatures(), mdp->getFeatureWeights(), mdp->getStateFeatures(), mdp->isStochastic(), mdp->getDiscount()); //set the walls temp_mdp->setWallStates(mdp->getWallStates()); temp_mdp->setFeatureWeights(mdp->getFeatureWeights()); if(sampling_flag == 0) { //random grid walk modifyFeatureWeightsRandomly(temp_mdp,step_size); } else if(sampling_flag == 1) { //cout << "sampling randomly from L1 unit ball" << endl; sampleL1UnitBallRandomly(temp_mdp); } //updown sampling on L1 ball else if(sampling_flag == 2) { //cout << "before step" << endl; //temp_mdp->displayFeatureWeights(); updownL1UnitBallWalk(temp_mdp, step_size); //cout << "after step" << endl; //temp_mdp->displayFeatureWeights(); //check if norm is right assert(isEqual(l1_norm(temp_mdp->getFeatureWeights(), temp_mdp->getNumFeatures()),1.0)); } //random manifold walk sampling else if(sampling_flag == 3) { manifoldL1UnitBallWalk(temp_mdp, step_size, num_steps); assert(isEqual(l1_norm(temp_mdp->getFeatureWeights(), temp_mdp->getNumFeatures()),1.0)); } else if(sampling_flag == 4) { manifoldL1UnitBallWalkAllSteps(temp_mdp, step_size); assert(isEqual(l1_norm(temp_mdp->getFeatureWeights(), temp_mdp->getNumFeatures()),1.0)); } //cout << "trying out" << endl; //temp_mdp->displayFeatureWeights(); temp_mdp->valueIteration(eps, mdp->getValues()); //temp_mdp->deterministicPolicyIteration(policy);//valueIteration(0.05); temp_mdp->calculateQValues(); double new_posterior = calculatePosterior(temp_mdp); //cout << "posterior: " << new_posterior << endl; double probability = min((double)1.0, exp(new_posterior - posterior)); //cout << probability << endl; //transition with probability double r = ((double) rand() / (RAND_MAX)); if ( r < probability ) //policy_changed && { //temp_mdp->displayFeatureWeights(); //cout << "accept" << endl; mdp = temp_mdp; posterior = new_posterior; R_chain[itr] = temp_mdp; posteriors[itr] = exp(new_posterior); //if (itr%100 == 0) cout << itr << ": " << posteriors[itr] << endl; if(posteriors[itr] > MAPposterior) { MAPposterior = posteriors[itr]; //TODO remove set terminals, right? why here in first place? MAPmdp->setFeatureWeights(mdp->getFeatureWeights()); } }else { //delete temp_mdp delete temp_mdp; //keep previous reward in chain //cout << "reject!!!!" << endl; reject_cnt++; if(mcmc_reject) { //TODO can I make this more efficient by adding a count variable? //make a copy of mdp FeatureGridMDP* mdp_copy = new FeatureGridMDP (mdp->getGridWidth(),mdp->getGridHeight(), mdp->getInitialStates(), mdp->getTerminalStates(), mdp->getNumFeatures(), mdp->getFeatureWeights(), mdp->getStateFeatures(), mdp->isStochastic(), mdp->getDiscount()); mdp_copy->setValues(mdp->getValues()); mdp_copy->setQValues(mdp->getQValues()); mdp_copy->setWallStates(mdp->getWallStates()); R_chain[itr] = mdp_copy; } //sample until you get accept and then add that -- doesn't repeat old reward in chain else { assert(reject_cnt < 100000); itr--; //delete temp_mdp; } } } cout << "rejects: " << reject_cnt << endl; } //TODO check that this follows guidance for softmax double FeatureBIRL::logsumexp(double* nums, unsigned int size) { double max_exp = nums[0]; double sum = 0.0; unsigned int i; for (i = 1 ; i < size ; i++) { if (nums[i] > max_exp) max_exp = nums[i]; } for (i = 0; i < size ; i++) sum += exp(nums[i] - max_exp); return log(sum) + max_exp; } double FeatureBIRL::calculatePosterior(FeatureGridMDP* gmdp) //assuming uniform prior { double posterior = 0; //add in a zero norm (non-zero count) double prior = 0; // int count = 0; // double* weights = gmdp->getFeatureWeights(); // for(int i=0; i < gmdp->getNumFeatures(); i++) // if(abs(weights[i]) > 0.0001) // count += 1; // prior = -1 * alpha * log(count-1); posterior += prior; unsigned int state, action; unsigned int numActions = gmdp->getNumActions(); // "-- Positive Demos --" for(unsigned int i=0; i < positive_demonstration.size(); i++) { pair<unsigned int,unsigned int> demo = positive_demonstration[i]; state = demo.first; action = demo.second; double Z [numActions]; // for(unsigned int a = 0; a < numActions; a++) Z[a] = alpha*(gmdp->getQValue(state,a)); posterior += alpha*(gmdp->getQValue(state,action)) - logsumexp(Z, numActions); //cout << state << "," << action << ": " << posterior << endl; } // "-- Negative Demos --" for(unsigned int i=0; i < negative_demonstration.size(); i++) { pair<unsigned int,unsigned int> demo = negative_demonstration[i]; state = demo.first; action = demo.second; double Z [numActions]; // for(unsigned int a = 0; a < numActions; a++) Z[a] = alpha*(gmdp->getQValue(state,a)); unsigned int ct = 0; double Z2 [numActions - 1]; for(unsigned int a = 0; a < numActions; a++) { if(a != action) Z2[ct++] = alpha*(gmdp->getQValue(state,a)); } posterior += logsumexp(Z2, numActions-1) - logsumexp(Z, numActions); } //cout << "posterior" << posterior << endl; return posterior; } void FeatureBIRL::modifyFeatureWeightsRandomly(FeatureGridMDP * gmdp, double step) { unsigned int state = rand() % gmdp->getNumFeatures(); double change = pow(-1,rand()%2)*step; //cout << "before " << gmdp->getReward(state) << endl; //cout << "change " << change << endl; double weight = max(min(gmdp->getWeight(state) + change, r_max), r_min); //if(gmdp->isTerminalState(state)) reward = max(min(gmdp->getReward(state) + change, r_max), 0.0); //else reward = max(min(gmdp->getReward(state) + change, 0.0), r_min); //cout << "after " << reward << endl; gmdp->setFeatureWeight(state, weight); } void FeatureBIRL::sampleL1UnitBallRandomly(FeatureGridMDP * gmdp) { unsigned int numFeatures = gmdp->getNumFeatures(); double* newWeights = sample_unit_L1_norm(numFeatures); gmdp->setFeatureWeights(newWeights); delete [] newWeights; } void FeatureBIRL::updownL1UnitBallWalk(FeatureGridMDP * gmdp, double step) { unsigned int numFeatures = gmdp->getNumFeatures(); double* newWeights = updown_l1_norm_walk(gmdp->getFeatureWeights(), numFeatures, step); gmdp->setFeatureWeights(newWeights); delete [] newWeights; } void FeatureBIRL::manifoldL1UnitBallWalk(FeatureGridMDP * gmdp, double step, int num_steps) { unsigned int numFeatures = gmdp->getNumFeatures(); double* newWeights = random_manifold_l1_step(gmdp->getFeatureWeights(), numFeatures, step, num_steps); gmdp->setFeatureWeights(newWeights); delete [] newWeights; } void FeatureBIRL::manifoldL1UnitBallWalkAllSteps(FeatureGridMDP * gmdp, double step) { unsigned int numFeatures = gmdp->getNumFeatures(); double* newWeights = take_all_manifold_l1_steps(gmdp->getFeatureWeights(), numFeatures, step); gmdp->setFeatureWeights(newWeights); delete [] newWeights; } void FeatureBIRL::addPositiveDemos(vector<pair<unsigned int,unsigned int> > demos) { for(unsigned int i=0; i < demos.size(); i++) positive_demonstration.push_back(demos[i]); //positive_demonstration.insert(positive_demonstration.end(), demos.begin(), demos.end()); } void FeatureBIRL::addNegativeDemos(vector<pair<unsigned int,unsigned int> > demos) { for(unsigned int i=0; i < demos.size(); i++) negative_demonstration.push_back(demos[i]); //negative_demonstration.insert(negative_demonstration.end(), demos.begin(), demos.end()); } void FeatureBIRL::displayDemos() { displayPositiveDemos(); displayNegativeDemos(); } void FeatureBIRL::displayPositiveDemos() { if(positive_demonstration.size() !=0 ) cout << "\n-- Positive Demos --" << endl; for(unsigned int i=0; i < positive_demonstration.size(); i++) { pair<unsigned int,unsigned int> demo = positive_demonstration[i]; cout << " (" << demo.first << "," << demo.second << ") "; } cout << endl; } void FeatureBIRL::displayNegativeDemos() { if(negative_demonstration.size() != 0) cout << "\n-- Negative Demos --" << endl; for(unsigned int i=0; i < negative_demonstration.size(); i++) { pair<unsigned int,unsigned int> demo = negative_demonstration[i]; cout << " (" << demo.first << "," << demo.second << ") "; } cout << endl; } void FeatureBIRL::initializeMDP() { // if(sampling_flag == 0) // { // double* weights = new double[mdp->getNumFeatures()]; // for(unsigned int s=0; s<mdp->getNumFeatures(); s++) // { // weights[s] = (r_min+r_max)/2; // } // mdp->setFeatureWeights(weights); // delete [] weights; // } // else if (sampling_flag == 1) //sample randomly from L1 unit ball // { // double* weights = sample_unit_L1_norm(mdp->getNumFeatures()); // mdp->setFeatureWeights(weights); // delete [] weights; // } // else if(sampling_flag == 2) // { unsigned int numDims = mdp->getNumFeatures(); double* weights = new double[numDims]; for(unsigned int s=0; s<numDims; s++) weights[s] = -1.0 / numDims; // { // if((rand() % 2) == 0) // weights[s] = 1.0 / numDims; // else // weights[s] = -1.0 / numDims; //// if(s == 0) //// weights[s] = 1.0; //// else //// weights[s] = 0.0; // } // weights[0] = 0.2; // weights[1] = 0.2; // weights[2] = -0.2; // weights[3] = 0.2; // weights[4] = 0.2; //weights[0] = 1.0; mdp->setFeatureWeights(weights); delete [] weights; // } // else if(sampling_flag == 3) // { // unsigned int numDims = mdp->getNumFeatures(); // double* weights = new double[numDims]; // for(unsigned int s=0; s<numDims; s++) // weights[s] = 0.0; //// { //// if((rand() % 2) == 0) //// weights[s] = 1.0 / numDims; //// else //// weights[s] = -1.0 / numDims; ////// if(s == 0) ////// weights[s] = 1.0; ////// else ////// weights[s] = 0.0; //// } //// weights[0] = 0.2; //// weights[1] = 0.2; //// weights[2] = -0.2; //// weights[3] = 0.2; //// weights[4] = 0.2; // weights[0] = 1.0; // mdp->setFeatureWeights(weights); // delete [] weights; // } } bool FeatureBIRL::isDemonstration(pair<double,double> s_a) { for(unsigned int i=0; i < positive_demonstration.size(); i++) { if(positive_demonstration[i].first == s_a.first && positive_demonstration[i].second == s_a.second) return true; } for(unsigned int i=0; i < negative_demonstration.size(); i++) { if(negative_demonstration[i].first == s_a.first && negative_demonstration[i].second == s_a.second) return true; } return false; } FeatureGridMDP* FeatureBIRL::getMeanMDP(int burn, int skip) { //average rewards in chain int nFeatures = mdp->getNumFeatures(); double aveWeights[nFeatures]; for(int i=0;i<nFeatures;i++) aveWeights[i] = 0; int count = 0; for(unsigned int i=burn; i<chain_length; i+=skip) { count++; //(*(R_chain + i))->displayFeatureWeights(); //cout << "weights" << endl; double* w = (*(R_chain + i))->getFeatureWeights(); for(int f=0; f < nFeatures; f++) aveWeights[f] += w[f]; } for(int f=0; f < nFeatures; f++) aveWeights[f] /= count; // //create new MDP with average weights as features FeatureGridMDP* mean_mdp = new FeatureGridMDP(MAPmdp->getGridWidth(),MAPmdp->getGridHeight(), MAPmdp->getInitialStates(), MAPmdp->getTerminalStates(), MAPmdp->getNumFeatures(), aveWeights, MAPmdp->getStateFeatures(), MAPmdp->isStochastic(), MAPmdp->getDiscount()); mean_mdp->setWallStates(MAPmdp->getWallStates()); return mean_mdp; } #endif
[ "dsbrown1331@gmail.com" ]
dsbrown1331@gmail.com
bd906faaf244c2c79671bc7dbe48351b2f229369
33d55fd020dfa888c4b81c524ec10f27cacc31fe
/Tarde/main.cpp
e7dcb360f1009e3a4d963879712f43453d74ad95
[]
no_license
Melchyore/softwares
a24933da06dc70d20d4d408b5fb093aa06aaf6c3
4ab94ca88003a2ba62b720a581c91a7f827ca366
refs/heads/master
2021-05-28T04:21:54.443121
2014-05-22T19:58:09
2014-05-22T19:58:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
#include <QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication application(argc, argv); MainWindow window; QPalette* palette = new QPalette(); QLinearGradient linearGradient(0, 0, 0, window.height()); linearGradient.setColorAt(0, "#242424"); linearGradient.setColorAt(1, "#090808"); palette->setBrush(QPalette::Window, *(new QBrush(linearGradient))); window.setPalette(*palette); window.show(); return application.exec(); }
[ "rider-2000@hotmail.com" ]
rider-2000@hotmail.com
918cc665e564bdd2c1c9251e03f210a7b5f39b38
0efb71923c02367a1194a9b47779e8def49a7b9f
/Oblig1/les/0.26/uniform/time
a9c9de75ed607099f405984fdd0c64ff6341f5eb
[]
no_license
andergsv/blandet
bbff505e8663c7547b5412700f51e3f42f088d78
f648b164ea066c918e297001a8049dd5e6f786f9
refs/heads/master
2021-01-17T13:23:44.372215
2016-06-14T21:32:00
2016-06-14T21:32:00
41,495,450
0
0
null
null
null
null
UTF-8
C++
false
false
982
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.26/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.26; name "0.26"; index 2600; deltaT 0.0001; deltaT0 0.0001; // ************************************************************************* //
[ "g.svenn@online.no" ]
g.svenn@online.no
dfa16b76f2c626b10138e6f5b0b0f33885843470
19b14d0280be480be7f4642079419c3a584db2b0
/programa 8/main.cpp
a74cd1d68f92da42483cdbd2646f3a64268e77e6
[]
no_license
juanfernandorl/ProgramacionII-Codeblocks
2664f4e6c7e22a099401c9ca8f709ef45db6554b
a515252d320ac2acb45ae0afa11c21466befbb0c
refs/heads/master
2021-01-10T22:07:22.539437
2013-10-17T17:34:33
2013-10-17T17:34:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
915
cpp
#include <iostream> using namespace std; /* Se tiene que ingresar el nombre, la nota y el progreso del alumno con las siguientes observaciones 1-59 reprobado 60-80 bueno 81-90 muy bueno 91-100 sobresaliente. usar condiciones donde apliquemos el and */ int main() { char nombre[30]; int nota; cout<<"Ingresar nombre del alumno:"; cin.getline(nombre,30); cout<<"Nota del alumno:>"; cin>>nota; if ((nota>=0)and (nota<60)) { cout<<"Reprobado"<<"\n"; } else if ((nota>060) and (nota <=80)) { cout<<"Bueno"<<"\n"; } else if ((nota>=81) and (nota<=90)) { cout<<"Muy bueno"<<"\n"; } else if ((nota>=91) and (nota<=100)) { cout<<"Sobresaliente"<<"\n"; } else { cout<<"nota incorrecta"; } return 0; }
[ "juanfernando.rl@unitec.edu" ]
juanfernando.rl@unitec.edu
76dfc035bec9a230417ea7a0e0428900c674b874
ff0cf0bedd68db20da2dfe1c613bf684588e68a5
/lab3Q24.cpp
799af5d60769743852a76266131157a631ecb29f
[]
no_license
DeepakNayak0165/cs141lab3
22891d9bfacdab61d81a76273d51933584bbf320
8f400e274f69d4089e9f9a9a946535977e8963e9
refs/heads/master
2021-06-27T20:52:16.807900
2017-09-15T18:26:07
2017-09-15T18:26:07
103,657,458
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
#include<iostream> using namespace std; int main() { char i='a'; while(i<='z') { cout<<i<<endl; i=i+1; } return 0; }
[ "noreply@github.com" ]
DeepakNayak0165.noreply@github.com
b8925239c800c1578c44c147f72797d706baa31b
f4b88022a4ef061383b93260c3c76bf5ecf2407a
/src/gui/MainWindow.cpp
904de02879112bc225fa4d68723792a78a578c17
[]
no_license
SylvanHuang/mknap_pso
bc03b11841c1c16ae579a3f5e16355d56d2f824d
2624080a204781bafb18230fc90ae6f98bf97826
refs/heads/master
2020-04-01T14:48:24.257639
2014-06-26T08:22:38
2014-06-26T08:22:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,082
cpp
#include "MainWindow.h" #include <QMessageBox> #include <QFileDialog> #include <QTableWidgetItem> #include <QTableWidget> #include <QTime> #include <stdexcept> #include <iostream> #include <ctime> namespace mknap_pso { MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setupUi(this); connect(actionOpen_mknap_file, SIGNAL(triggered()), this, SLOT(openFile())); connect(actionExit, SIGNAL(triggered()), this, SLOT(close())); connect(actionAbout, SIGNAL(triggered()), this, SLOT(about())); connect(solveBtn, SIGNAL(clicked()), this, SLOT(solveBtnClicked())); connect(table, SIGNAL(itemClicked(QTableWidgetItem *)), this, SLOT(tableItemClicked(QTableWidgetItem *))); connect(actionSet_parameter, SIGNAL(triggered()), this, SLOT(openSettingsDialog())); connect(actionStart, SIGNAL(triggered()), this, SLOT(toolbarStart())); connect(actionStop, SIGNAL(triggered()), this, SLOT(toolbarStop())); connect(actionNext_Iteration, SIGNAL(triggered()), this, SLOT(toolbarNext())); connect(actionDo_pre_defined_test, SIGNAL(triggered()), this, SLOT(preDefinedTestClicked())); consoleEdit->append("> Choose file with multidimensional (multi-constraint) knapsack problem to solve."); settingsDialog = new SettingsDialog(); plot = new minotaur::MouseMonitorPlot(); plot->init(Qt::blue, "Global best fitness value", "Iteration", "Fitness value"); graphLayout->layout()->addWidget(plot); swarmPlot = new minotaur::MouseMonitorPlot(); swarmPlot->init(Qt::blue, "Particle best fitness value", "Iteration", "Fitness value"); swarmTab->layout()->addWidget(swarmPlot); swarmPlot->setDotStyle(); future = QtConcurrent::run(this, &MainWindow::runFunction); } MainWindow::~MainWindow() { delete settingsDialog; delete plot; } int MainWindow::runFunction() { return solver.solveProblemIteration(); } void MainWindow::toolbarStart() { if (parser.getProblemsReference().size() == 0) { consoleEdit->append("> No problems selected to solve."); return; } plot->clear(); consoleEdit->clear(); solver.setParameters(settingsDialog->getParameters()); swarmPlot->clearCurves(); std::srand(std::time(0)); for (int i = 0; i < settingsDialog->getParameters().getNumberOfParticles(); ++i) { swarmPlot->addCurve(QColor((std::rand() % (255 + 1)), (std::rand() % (255 + 1)), (std::rand() % (255 + 1)))); } QList<QTableWidgetItem *> items = table->selectedItems(); if (items.size() >= 1) { int row = items.at(0)->row(); solver.startSolveProblem(parser.getProblemsReference().at(row)); consoleEdit->append("=================================="); QString outTxt = "> Solving problem " + QString::number(row) + ":"; consoleEdit->append(outTxt); printSwarmToConsole(solver.getSwarmReference()); consoleEdit->append("=================================="); printSwarmToTable(solver.getSwarmReference()); } } int MainWindow::toolbarStop() { if (!solver.isSolving()) return -1; int gBest = solver.stopSolveProblem(); QString outTxt = "> FINAL SOLUTION VALUE: " + QString::number(gBest); consoleEdit->append(outTxt); consoleEdit->append("=================================="); return gBest; } void MainWindow::toolbarNext() { if (!solver.isSolving()) return; consoleEdit->append("----------------------------------"); int gBest = runFunction();//future.result(); printSwarmToTable(solver.getSwarmReference()); printSwarmToConsole(solver.getSwarmReference()); QString outTxt = "> gBest value: " + QString::number(gBest); consoleEdit->append(outTxt); QVector<double> data; data.append(gBest); plot->updatePlot(data); QVector<double> dataSwarm; for (auto &i : solver.getSwarmReference().getParticles()) dataSwarm.append(i.getBestValue()); swarmPlot->updatePlot(dataSwarm); } void MainWindow::solveBtnClicked() { if (parser.getProblemsReference().size() == 0) { consoleEdit->append("> No problems selected to solve."); return; } toolbarStart(); for (int i = 0; i < settingsDialog->getParameters().getIterations(); ++i) { QString outTxt = "> Iteration: " + QString::number(i); consoleEdit->append(outTxt); toolbarNext(); } toolbarStop(); } void MainWindow::openFile() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open mknap problem file"), "", tr("Problem files (*.txt)")); if (fileName == "") return; parser.parseFile(fileName.toStdString()); consoleEdit->append("> Parsed mknap problem file"); nrOfProblemsEdit->setText(QString::number(parser.getProblemsReference().size())); fileNameEdit->setText(fileName); table->clear(); table->setRowCount(0); table->setColumnCount(0); tableDetail->clear(); tableDetail->setRowCount(0); tableDetail->setColumnCount(0); QStringList headerLabels; headerLabels << "Problem" << "Elements" << "Constraints" << "Solution"; table->setColumnCount(4); table->setHorizontalHeaderLabels(headerLabels); table->setEditTriggers(QAbstractItemView::NoEditTriggers); table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); int counter = 0; for (auto i : parser.getProblemsReference()) { table->insertRow(table->rowCount()); table->setItem(table->rowCount() - 1, 0, new QTableWidgetItem(QString::number(counter++))); table->setItem(table->rowCount() - 1, 1, new QTableWidgetItem(QString::number(i->n))); table->setItem(table->rowCount() - 1, 2, new QTableWidgetItem(QString::number(i->m))); table->setItem(table->rowCount() - 1, 3, new QTableWidgetItem(QString::number(i->solution))); } } void MainWindow::tableItemClicked(QTableWidgetItem *item) { tableDetail->clear(); tableDetail->setRowCount(0); tableDetail->setColumnCount(0); std::shared_ptr<KnapsackProblem> problem = parser.getProblemsReference().at(item->row()); tableDetail->setRowCount(problem->m + 1); QStringList headerLabels; headerLabels << "Profit"; for (int i = 0; i < (problem->m); i++) { QString label = "Constraint " + QString::number(i) + " (Capacity: " + QString::number(problem->capacity.at(i)) + ")"; headerLabels << label; } tableDetail->setVerticalHeaderLabels(headerLabels); int j = 0; for (auto &profit : problem->profit) { tableDetail->insertColumn(tableDetail->columnCount()); tableDetail->setItem(0, tableDetail->columnCount() - 1, new QTableWidgetItem(QString::number(profit))); int i = 0; for (auto &constraint : problem->constraint) { tableDetail->setItem(i + 1, tableDetail->columnCount() - 1, new QTableWidgetItem(QString::number(constraint.at(j)))); ++i; } ++j; } } void MainWindow::openSettingsDialog() { settingsDialog->setVisible(true); } void MainWindow::about() { QMessageBox::about(this, tr("About mknap_pso"), "This application solves the mknap problem with discrete binary Particle Swarm Optimization.\n\n" "Author: JeGa\n" "Github: https://github.com/JeGa/mknap_pso"); } void MainWindow::printSwarmToConsole(Swarm &swarm) { int counter = 0; for (auto &i : swarm.getParticles()) { QString outTxt = "> Particle " + QString::number(counter) + ":"; consoleEdit->append(outTxt); consoleEdit->append(getPositionString(i.getPosition())); consoleEdit->append("Velocity: "); consoleEdit->append(getVelocityString(i.getVelocity())); outTxt = "=> pBest " + QString::number(i.getBestValue()); consoleEdit->append(outTxt); ++counter; } } void MainWindow::initSwarmtable() { swarmTable->clear(); swarmTable->setRowCount(0); swarmTable->setColumnCount(0); QStringList headerLabels; headerLabels << "Particle" << "pBest" << "pBest position" << "Position" << "Velocity"; swarmTable->setColumnCount(5); swarmTable->setHorizontalHeaderLabels(headerLabels); swarmTable->setEditTriggers(QAbstractItemView::NoEditTriggers); } void MainWindow::printSwarmToTable(Swarm &swarm) { initSwarmtable(); swarmParticlesEdit->setText(QString::number(swarm.getParticles().size())); swarmPBestEdit->setText(QString::number(swarm.getBestValue())); QString outText; Solution &position = swarm.getBestPosition(); for (auto i : position) outText += QString::number(i); swarmPBestPositionEdit->setText(outText); int counter = 0; for (auto &i : swarm.getParticles()) { swarmTable->insertRow(swarmTable->rowCount()); swarmTable->setItem(swarmTable->rowCount() - 1, 0, new QTableWidgetItem(QString::number(counter++))); swarmTable->setItem(swarmTable->rowCount() - 1, 1, new QTableWidgetItem(QString::number(i.getBestValue()))); swarmTable->setItem(swarmTable->rowCount() - 1, 2, new QTableWidgetItem(getPositionString(i.getBestPosition()))); swarmTable->setItem(swarmTable->rowCount() - 1, 3, new QTableWidgetItem(getPositionString(i.getPosition()))); swarmTable->setItem(swarmTable->rowCount() - 1, 4, new QTableWidgetItem(getVelocityString(i.getVelocity()))); } } QString MainWindow::getPositionString(Solution &position) { QString outText; for (auto i : position) outText += QString::number(i); return outText; } QString MainWindow::getVelocityString(Velocity &velocity) { QString outText; for (auto i : velocity) outText += QString::number(i) + ","; return outText; } //================================================================ void MainWindow::preDefinedTestClicked() { if (parser.getProblemsReference().size() == 0) { consoleEdit->append("> No problems selected to solve."); return; } consoleEdit->clear(); // Problem 1 consoleEdit->append("==================================="); consoleEdit->append("Problem 1"); consoleEdit->append("==================================="); // Change particle number consoleEdit->append(doTest(0, 5, 500, 1.0, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 10, 500, 1.0, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 15, 500, 1.0, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 25, 500, 1.0, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 30, 500, 1.0, 2.0, 2.0, 6.0)); // Change inertia consoleEdit->append(doTest(0, 20, 500, 0.1, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 0.5, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 0.8, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 0.9, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.1, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.2, 2.0, 2.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.5, 2.0, 2.0, 6.0)); // Change c1 / c2 consoleEdit->append(doTest(0, 20, 500, 1.0, 0.1, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 0.5, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 1.0, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 3.0, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 5.0, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 10.0, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 1.0, 0.1, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 1.0, 1.0, 6.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 1.0, 5.0, 6.0)); // Change vMax consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 0.1)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 0.5)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 1.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 2.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 3.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 4.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 5.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 10.0)); consoleEdit->append(doTest(0, 20, 500, 1.0, 2.0, 2.0, 20.0)); } QString MainWindow::doTest(int problem, int particles, int iterations, double inertia, double c1, double c2, double vMax) { int globalIt = 30; int gBest, best = INT32_MIN, worse = INT32_MAX; int meanOptimumSum = 0, meanTimeSum = 0; QString str; QTime t; Parameters p; p.set(particles, iterations, inertia, c1, c2, vMax); solver.setParameters(p); for (int j = 0; j < globalIt; ++j) { t.start(); solver.startSolveProblem(parser.getProblemsReference().at(problem)); for (int i = 0; i < p.getIterations(); ++i) runFunction(); gBest = solver.stopSolveProblem(); if (gBest > best) best = gBest; if (gBest < worse) worse = gBest; meanOptimumSum += gBest; meanTimeSum += t.elapsed(); } str = "Mean of " + QString::number(globalIt) + " iterations -> (" + p.toString() + ") " + "Best value: " + QString::number(best) + ", Worst value: " + QString::number(worse) + " Mean Optimum: " + QString::number((double) meanOptimumSum / globalIt) + " Mean Time (ms): " + QString::number((double) meanTimeSum / globalIt); return str; } }
[ "jega@win" ]
jega@win
ab01748f9808456d5dbf17d2b31506413196483a
e798cbc98fba4eda3c51f956f54e03d2ba310f91
/interface/ExpressionNtuple.h
362e0fe4662ac53201899c645504ca4aa14b940f
[]
no_license
jjbuchanan/CaloLayer1Calibrations
eb329583714a3ea6306e8bad3db755453b713427
3264c802bd9c04c2595a6b09f97d7d4d84823d7e
refs/heads/master
2021-09-10T01:24:20.084231
2018-03-20T14:15:16
2018-03-20T14:15:16
92,431,299
0
1
null
2018-03-20T14:14:08
2017-05-25T18:14:51
Python
UTF-8
C++
false
false
2,635
h
/* * Tool to build a TTree of columns of from StringObjectFunctions. * * Author: Evan K. Friis, UW Madison * */ #ifndef EXPRESSIONNTUPLE_E32UGXK7 #define EXPRESSIONNTUPLE_E32UGXK7 #include "boost/utility.hpp" #include <boost/ptr_container/ptr_vector.hpp> #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "CommonTools/Utils/interface/TFileDirectory.h" #include "TTree.h" #include "L1Trigger/CaloLayer1Calibrations/interface/ExpressionNtupleColumn.h" // so we don't conflict with FinalStateAnalysis namespace uct { template<class T> class ExpressionNtuple : private boost::noncopyable { public: ExpressionNtuple(const edm::ParameterSet& pset); ~ExpressionNtuple(); // Setup the tree in the given TFile void initialize(TFileDirectory& fs); // Fill the tree with an element with given index. void fill(const T& element, int idx = -1); // Get access to the internal tree TTree* tree() const { return tree_; } private: TTree* tree_; std::vector<std::string> columnNames_; edm::ParameterSet pset_; boost::ptr_vector<ExpressionNtupleColumn<T> > columns_; boost::shared_ptr<Int_t> idxBranch_; }; template<class T> ExpressionNtuple<T>::ExpressionNtuple(const edm::ParameterSet& pset): pset_(pset) { tree_ = NULL; typedef std::vector<std::string> vstring; // Double check no column already exists columnNames_ = pset.getParameterNames(); std::set<std::string> enteredAlready; for (size_t i = 0; i < columnNames_.size(); ++i) { const std::string& colName = columnNames_[i]; if (enteredAlready.count(colName)) { throw cms::Exception("DuplicatedBranch") << " The ntuple branch with name " << colName << " has already been registered!" << std::endl; } enteredAlready.insert(colName); } idxBranch_.reset(new Int_t); } template<class T> ExpressionNtuple<T>::~ExpressionNtuple() {} template<class T> void ExpressionNtuple<T>::initialize(TFileDirectory& fs) { tree_ = fs.make<TTree>("Ntuple", "Expression Ntuple"); // Build branches for (size_t i = 0; i < columnNames_.size(); ++i) { columns_.push_back(buildColumn<T>(columnNames_[i], pset_, tree_)); } // A special branch so we know which subrow we are on. tree_->Branch("idx", idxBranch_.get(), "idx/I"); } template<class T> void ExpressionNtuple<T>::fill(const T& element, int idx) { for (size_t i = 0; i < columns_.size(); ++i) { // Compute the function and load the value into the column. columns_[i].compute(element); } *idxBranch_ = idx; tree_->Fill(); } } #endif /* end of include guard: EXPRESSIONNTUPLE_E32UGXK7 */
[ "jjbuchanan42@gmail.com" ]
jjbuchanan42@gmail.com
b6c6832b2a70463a80978150dd6e79de3dcd2ce4
c57819bebe1a3e1d305ae0cb869cdcc48c7181d1
/src/qt/src/gui/widgets/qtoolbar.h
daa14fd77a9f595547f576b31fc47c833e24a386
[ "LGPL-2.1-only", "Qt-LGPL-exception-1.1", "LicenseRef-scancode-generic-exception", "GPL-3.0-only", "GPL-1.0-or-later", "GFDL-1.3-only", "BSD-3-Clause" ]
permissive
blowery/phantomjs
255829570e90a28d1cd597192e20314578ef0276
f929d2b04a29ff6c3c5b47cd08a8f741b1335c72
refs/heads/master
2023-04-08T01:22:35.426692
2012-10-11T17:43:24
2012-10-11T17:43:24
6,177,895
1
0
BSD-3-Clause
2023-04-03T23:09:40
2012-10-11T17:39:25
C++
UTF-8
C++
false
false
6,257
h
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QDYNAMICTOOLBAR_H #define QDYNAMICTOOLBAR_H #include <QtGui/qwidget.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_TOOLBAR class QToolBarPrivate; class QAction; class QIcon; class QMainWindow; class QStyleOptionToolBar; class Q_GUI_EXPORT QToolBar : public QWidget { Q_OBJECT Q_PROPERTY(bool movable READ isMovable WRITE setMovable DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) != 0) NOTIFY movableChanged) Q_PROPERTY(Qt::ToolBarAreas allowedAreas READ allowedAreas WRITE setAllowedAreas DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) != 0) NOTIFY allowedAreasChanged) Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation DESIGNABLE (qobject_cast<QMainWindow *>(parentWidget()) == 0) NOTIFY orientationChanged) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize NOTIFY iconSizeChanged) Q_PROPERTY(Qt::ToolButtonStyle toolButtonStyle READ toolButtonStyle WRITE setToolButtonStyle NOTIFY toolButtonStyleChanged) Q_PROPERTY(bool floating READ isFloating) Q_PROPERTY(bool floatable READ isFloatable WRITE setFloatable) public: explicit QToolBar(const QString &title, QWidget *parent = 0); explicit QToolBar(QWidget *parent = 0); ~QToolBar(); void setMovable(bool movable); bool isMovable() const; void setAllowedAreas(Qt::ToolBarAreas areas); Qt::ToolBarAreas allowedAreas() const; inline bool isAreaAllowed(Qt::ToolBarArea area) const { return (allowedAreas() & area) == area; } void setOrientation(Qt::Orientation orientation); Qt::Orientation orientation() const; void clear(); #ifdef Q_NO_USING_KEYWORD inline void addAction(QAction *action) { QWidget::addAction(action); } #else using QWidget::addAction; #endif QAction *addAction(const QString &text); QAction *addAction(const QIcon &icon, const QString &text); QAction *addAction(const QString &text, const QObject *receiver, const char* member); QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char* member); QAction *addSeparator(); QAction *insertSeparator(QAction *before); QAction *addWidget(QWidget *widget); QAction *insertWidget(QAction *before, QWidget *widget); QRect actionGeometry(QAction *action) const; QAction *actionAt(const QPoint &p) const; inline QAction *actionAt(int x, int y) const; QAction *toggleViewAction() const; QSize iconSize() const; Qt::ToolButtonStyle toolButtonStyle() const; QWidget *widgetForAction(QAction *action) const; bool isFloatable() const; void setFloatable(bool floatable); bool isFloating() const; public Q_SLOTS: void setIconSize(const QSize &iconSize); void setToolButtonStyle(Qt::ToolButtonStyle toolButtonStyle); Q_SIGNALS: void actionTriggered(QAction *action); void movableChanged(bool movable); void allowedAreasChanged(Qt::ToolBarAreas allowedAreas); void orientationChanged(Qt::Orientation orientation); void iconSizeChanged(const QSize &iconSize); void toolButtonStyleChanged(Qt::ToolButtonStyle toolButtonStyle); void topLevelChanged(bool topLevel); void visibilityChanged(bool visible); protected: void actionEvent(QActionEvent *event); void changeEvent(QEvent *event); void childEvent(QChildEvent *event); void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *event); bool event(QEvent *event); void initStyleOption(QStyleOptionToolBar *option) const; #ifdef QT3_SUPPORT public: QT3_SUPPORT_CONSTRUCTOR QToolBar(QWidget *parent, const char *name); inline QT3_SUPPORT void setLabel(const QString &label) { setWindowTitle(label); } inline QT3_SUPPORT QString label() const { return windowTitle(); } #endif private: Q_DECLARE_PRIVATE(QToolBar) Q_DISABLE_COPY(QToolBar) Q_PRIVATE_SLOT(d_func(), void _q_toggleView(bool)) Q_PRIVATE_SLOT(d_func(), void _q_updateIconSize(const QSize &)) Q_PRIVATE_SLOT(d_func(), void _q_updateToolButtonStyle(Qt::ToolButtonStyle)) friend class QMainWindow; friend class QMainWindowLayout; friend class QToolBarLayout; friend class QToolBarAreaLayout; }; inline QAction *QToolBar::actionAt(int ax, int ay) const { return actionAt(QPoint(ax, ay)); } #endif // QT_NO_TOOLBAR QT_END_NAMESPACE QT_END_HEADER #endif // QDYNAMICTOOLBAR_H
[ "ariya.hidayat@gmail.com" ]
ariya.hidayat@gmail.com
4f94d5e77d3b5c4a69717f6acbccdbe31fe67713
0615fd17ae28bdb62918b8b275b72e098f9d1078
/Classes/DB_Emoji.h
08325aac95951ffdb3f5c8e6076c8b416d08b810
[ "MIT" ]
permissive
InternationalDefy/AdvenTri-Cocos
7c7f072af3f6872fae9e430714de16de80f0f1f9
966ef8112a350b6ddb0ed22f33c14abed35b51b5
refs/heads/main
2022-12-30T04:11:24.554959
2020-10-26T13:02:38
2020-10-26T13:02:38
307,361,154
1
0
null
null
null
null
UTF-8
C++
false
false
454
h
#ifndef __DB_EMOJI__ #define __DB_EMOJI__ #include "Ref_DataBase.h" class SD_Emoji; using namespace cocos2d; class DB_Emoji :public DB { private: SD_Emoji* tempSD; std::string tempName; Map<std::string, SD_Emoji*> _table; public: std::string useString(){ return "Table_Emoji.csv"; } void getLine(const std::string& data); static DB_Emoji* create(); static DB_Emoji* getInstance(); SD_Emoji* getEmojiSD(const std::string& name); }; #endif
[ "DTEye1533014901@126.com" ]
DTEye1533014901@126.com
70d0cc99258adda5afe687dbceb14ee0aca9235b
c73422c07bff58108ff9cc528c71c22533263f99
/src/proxy_handler.cc
4095ee291efeb918761e64331bbdb1e3d471a9c0
[]
no_license
UCLA-CS130/Just-Enough
6b048b8bf48223a9bcb7afd9505d7f139d270ea7
66d2d50af6e6796c40a97e6ce7af9cfb273db7d6
refs/heads/master
2021-01-20T12:06:23.871282
2017-03-13T18:10:53
2017-03-13T18:10:53
79,513,574
0
4
null
2017-03-13T18:10:54
2017-01-20T01:37:03
C++
UTF-8
C++
false
false
5,771
cc
#include "proxy_handler.h" #include <string> RequestHandler::Status ProxyHandler::Init(const std::string& uri_prefix, const NginxConfig& config) { uri_prefix_ = uri_prefix; /* * We can accept one of two formats inside of the ProxyHandler's block. * Format 1: * remote_host website.com; * remote_port 80; * Format 2: * remote_port 80; * remote_host website.com; * The variable server_location specifies which format in terms of the * server-specifying statement's location in config.statements_. */ int server_location = 0; if (config.statements_[0]->tokens_[0] == "remote_port") { server_location = 1; } remote_host_ = config.statements_[server_location]->tokens_[1]; remote_port_ = config.statements_[1-server_location]->tokens_[1]; return RequestHandler::OK; } RequestHandler::Status ProxyHandler::HandleRequest(const Request& request, Response* response) { if (!redirect_) { mtx_.lock(); } else { redirect_ = false; } std::string host; if (remote_host_.size() == 0 || remote_port_.size() == 0) { std::cerr << "ProxyHandler::HandleRequest: remote_host_ or "; std::cerr << "remote_port_ are empty. Cannot serve request."; std::cerr << std::endl; mtx_.unlock(); return RequestHandler::Error; } if (redirect_host_.size() > 0) { host = redirect_host_; redirect_host_ = ""; } else { host = remote_host_; } Request proxied_req(request); proxied_req.set_uri(request.uri().substr(uri_prefix_.size())); if (proxied_req.uri().size() == 0) { proxied_req.set_uri("/"); } // make sure keep alive is off proxied_req.remove_header("Connection"); proxied_req.add_header("Connection", "Close"); // update host proxied_req.remove_header("Host"); proxied_req.add_header("Host", host + ":" + remote_port_); if (!client_->Connect(host, remote_port_)) { std::cerr << "ProxyHandler::HandleRequest failed to connect to "; std::cerr << host << ":" << remote_port_ << std::endl; mtx_.unlock(); return RequestHandler::Error; } if (!client_->Write(proxied_req.raw_request())) { std::cerr << "ProxyHandler::HandleRequest failed to write to "; std::cerr << host << ":" << remote_port_ << std::endl; mtx_.unlock(); return RequestHandler::Error; } std::string response_str(1024, 0); if (!client_->Read(response_str)) { std::cerr << "ProxyHandler::HandleRequest failed to read from "; std::cerr << host << ":" << remote_port_ << std::endl; mtx_.unlock(); return RequestHandler::Error; } // copy parsed response into given response *response = ParseRawResponse(response_str); if (redirect_) { Request redirect_request(request); redirect_request.set_uri(redirect_uri_); redirect_request.remove_header("Host"); redirect_request.add_header("Host", redirect_host_header_); uri_prefix_ = ""; // sub-call will unlock mtx_ return HandleRequest(redirect_request, response); } mtx_.unlock(); return RequestHandler::OK; } // TODO: this assume raw_response is valid HTTP // TODO: factor this out into a more appropriate location Response ProxyHandler::ParseRawResponse(const std::string& raw_response) { Response response; // for a given substring, start points to first char, end points to 1 // position past the end size_t start = 0, end; // get response code start = raw_response.find(" ") + 1; // skip version end = raw_response.find(" ", start); int raw_response_code = std::stoi(raw_response.substr(start, end - start)); auto rc = (Response::ResponseCode) raw_response_code; response.SetStatus(rc); // get all headers std::string header_name, header_value; end = raw_response.find("\r\n", start); while (true) { start = end + 2; // if next \r\n is right after current one, we're done with the headers if (raw_response.find("\r\n", start) == start) { start += 2; break; } end = raw_response.find(":", start); header_name = raw_response.substr(start, end - start); start = end + 1; // skip over whitespace while (raw_response[start] == ' ') { start++; } end = raw_response.find("\r\n", start); header_value = raw_response.substr(start, end - start); if ((rc == Response::code_302_found || rc == Response::code_301_moved) && header_name == "Location") { redirect_ = true; if (header_value[0] == '/') { // new URI on same host redirect_uri_ = header_value; } else { // new host // extract new host, uri size_t uri_pos = 0; redirect_host_ = header_value; if (redirect_host_.find("http://") == 0) { redirect_host_ = redirect_host_.substr(strlen("http://")); uri_pos += strlen("http://"); } uri_pos = header_value.find("/", uri_pos); redirect_host_header_ = header_value.substr(0, uri_pos); redirect_uri_ = header_value.substr(uri_pos); redirect_host_ = redirect_host_.substr( 0, redirect_host_.find(redirect_uri_)); } } response.AddHeader(header_name, header_value); } response.SetBody(raw_response.substr(start, raw_response.size() - start)); return response; }
[ "jevbburton@gmail.com" ]
jevbburton@gmail.com
d3ce376cee6653517b6ef1f3b8ce07fd643fb42b
fd7f2eacb173116501e981ffc3638e7940802c15
/OOP/school/2018-09-18/input.cpp
7b0e2e4fb02709b2f0b67669d2edbea9f2c5677c
[]
no_license
mikirov/Elsys-2018-2019
543759c32b74f40a965a36dc15d1747ba9a4811d
0dc3536e66eb314f56dec124a859228dce905e26
refs/heads/master
2023-01-27T17:18:31.631899
2019-05-30T03:54:12
2019-05-30T03:54:12
149,159,617
0
0
null
2023-01-19T09:44:37
2018-09-17T17:05:05
C++
UTF-8
C++
false
false
201
cpp
#include<iostream> using namespace std; int main(){ int value; while(true){ cin >> value; if(!cin){ cout<<"bad input"<< endl; break; }else{ cout << value << endl; } } return 0; }
[ "shimonchick@gmail.com" ]
shimonchick@gmail.com
873af766bdbf16eae30c97c5712ec7ae777df87e
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/quic/chromium/quic_chromium_alarm_factory.h
e033de183657c37ef82dcd012c0d1abe51bba30d
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
1,525
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // The Chrome-specific helper for QuicConnection which uses // a TaskRunner for alarms, and uses a DatagramClientSocket for writing data. #ifndef NET_QUIC_CHROMIUM_QUIC_CHROMIUM_ALARM_FACTORY_H_ #define NET_QUIC_CHROMIUM_QUIC_CHROMIUM_ALARM_FACTORY_H_ #include <set> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "net/base/net_export.h" #include "net/quic/core/quic_alarm_factory.h" #include "net/quic/core/quic_packets.h" #include "net/quic/core/quic_time.h" #include "net/quic/platform/api/quic_clock.h" namespace base { class TaskRunner; } // namespace base namespace net { class NET_EXPORT_PRIVATE QuicChromiumAlarmFactory : public QuicAlarmFactory { public: QuicChromiumAlarmFactory(base::TaskRunner* task_runner, const QuicClock* clock); ~QuicChromiumAlarmFactory() override; // QuicAlarmFactory QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override; QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override; private: base::TaskRunner* task_runner_; const QuicClock* clock_; base::WeakPtrFactory<QuicChromiumAlarmFactory> weak_factory_; DISALLOW_COPY_AND_ASSIGN(QuicChromiumAlarmFactory); }; } // namespace net #endif // NET_QUIC_CHROMIUM_QUIC_CHROMIUM_ALARM_FACTORY_H_
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
fa33cd4750a7a0eadfdd405168ba7ab65b42aef8
7cffa9b29f855c68ec5efcf049f596dc7be6bff6
/src/color/xyz/make/ivory.hpp
e704719c9f2884fbef19b0f1daac5db9da8bdd22
[ "Apache-2.0" ]
permissive
lzs4073/color
c4e12e26cfe96022e0a5e6736a7abaadf9912c14
290c2c1550c499465f814ba89a214cbec19a72df
refs/heads/master
2020-04-03T07:16:33.120894
2016-02-02T16:18:25
2016-02-02T16:18:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,614
hpp
#ifndef color_xyz_make_ivory #define color_xyz_make_ivory // ::color::make::ivory( c ) namespace color { namespace make { //RGB equivalents: std::array<double,3>( { 1, 1, 0.941176 } ) - rgb(255,255,240) - #fffff0 inline void ivory( ::color::_internal::model< color::category::xyz_uint8 > & color_parameter ) { color_parameter.container() = 0xff; } inline void ivory( ::color::_internal::model< color::category::xyz_uint16 > & color_parameter ) { color_parameter.container() = 0x3ded; } inline void ivory( ::color::_internal::model< color::category::xyz_uint32 > & color_parameter ) { color_parameter.container() = 0xff4da08fu; } inline void ivory( ::color::_internal::model< color::category::xyz_uint64 > & color_parameter ) { color_parameter.container() = 0xffff524fa5a59588ul; } inline void ivory( ::color::_internal::model< color::category::xyz_float > & color_parameter ) { color_parameter.container() = std::array<float,3>( { 31.5545, 31.9102, 30.0707 } ); } inline void ivory( ::color::_internal::model< color::category::xyz_double> & color_parameter ) { color_parameter.container() = std::array<double,3>( { 31.5545, 31.9102, 30.0707 } ); } inline void ivory( ::color::_internal::model< color::category::xyz_ldouble> & color_parameter ) { color_parameter.container() = std::array<long double,3>( { 31.5545, 31.9102, 30.0707 } ); } } } #endif
[ "dmilos@gmail.com" ]
dmilos@gmail.com
9a8191b068970c19ce29466c9fd653bddf09ab51
e1eb7280a262852015288c05f4a45370d99b039e
/Source/rotation/Rotation.cpp
f97979584e455c144a6d9f58733b5b573b04137e
[ "BSD-3-Clause-LBNL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
shardi2/Castro
e2e90656617a5e4c0ce191bd0e4c2065a76bf232
4d30cba1cafda080cb2c3459f1645d5f30a8ed0c
refs/heads/main
2022-12-09T12:50:27.245602
2020-07-02T12:09:47
2020-07-02T12:09:47
283,568,009
0
0
NOASSERTION
2020-08-28T01:07:50
2020-07-29T18:01:06
null
UTF-8
C++
false
false
6,032
cpp
#include "Castro.H" #include "Castro_F.H" #include "math.H" #include "Rotation.H" AMREX_GPU_HOST_DEVICE void Castro::rotational_acceleration(GpuArray<Real, 3>& r, GpuArray<Real, 3>& v, GpuArray<Real, 3> const& omega, const bool coriolis, Real* Sr) { // Given a position and velocity, calculate // the rotational acceleration. This is the sum of: // the Coriolis force (-2 omega x v), // the centrifugal force (- omega x ( omega x r)), // and a changing rotation rate (-d(omega)/dt x r). Sr[0] = 0.0; Sr[1] = 0.0; Sr[2] = 0.0; if (state_in_rotating_frame == 1) { // Allow the various terms to be turned off. This is often used // for diagnostic purposes, but there are genuine science cases // for disabling certain terms in some cases (in particular, when // obtaining a system in rotational equilibrium through a // relaxation process involving damping or sponging, one may want // to turn off the Coriolis force during the relaxation process, // on the basis that the true equilibrium state will have zero // velocity anyway). bool c1 = (rotation_include_centrifugal == 1) ? true : false; bool c2 = (rotation_include_coriolis == 1 && coriolis) ? true : false; GpuArray<Real, 3> omega_cross_v; cross_product(omega, v, omega_cross_v); if (c1) { GpuArray<Real, 3> omega_cross_r; cross_product(omega, r, omega_cross_r); GpuArray<Real, 3> omega_cross_omega_cross_r; cross_product(omega, omega_cross_r, omega_cross_omega_cross_r); for (int idir = 0; idir < 3; idir++) { Sr[idir] -= omega_cross_omega_cross_r[idir]; } } if (c2) { for (int idir = 0; idir < 3; idir++) { Sr[idir] -= 2.0_rt * omega_cross_v[idir]; } } } else { // The source term for the momenta when we're not measuring state // variables in the rotating frame is not strictly the traditional // Coriolis force, but we'll still allow it to be disabled with // the same parameter. bool c2 = (rotation_include_coriolis == 1 && coriolis) ? true : false; if (c2) { GpuArray<Real, 3> omega_cross_v; cross_product(omega, v, omega_cross_v); for (int idir = 0; idir < 3; idir++) { Sr[idir] -= omega_cross_v[idir]; } } } } void Castro::fill_rotational_acceleration(const Box& bx, Array4<Real> const& rot, Array4<Real const> const& state) { GpuArray<Real, 3> center; ca_get_center(center.begin()); auto problo = geom.ProbLoArray(); auto dx = geom.CellSizeArray(); auto coord_type = geom.Coord(); GpuArray<Real, 3> omega; get_omega(omega.begin()); amrex::ParallelFor(bx, [=] AMREX_GPU_HOST_DEVICE (int i, int j, int k) noexcept { GpuArray<Real, 3> r; r[0] = problo[0] + dx[0] * (static_cast<Real>(i) + 0.5_rt) - center[0]; #if AMREX_SPACEDIM >= 2 r[1] = problo[1] + dx[1] * (static_cast<Real>(j) + 0.5_rt) - center[1]; #else r[1] = 0.0_rt; #endif #if AMREX_SPACEDIM == 3 r[2] = problo[2] + dx[2] * (static_cast<Real>(k) + 0.5_rt) - center[2]; #else r[2] = 0.0_rt; #endif GpuArray<Real, 3> v; v[0] = state(i,j,k,UMX) / state(i,j,k,URHO); v[1] = state(i,j,k,UMY) / state(i,j,k,URHO); v[2] = state(i,j,k,UMZ) / state(i,j,k,URHO); bool coriolis = true; Real Sr[3]; rotational_acceleration(r, v, omega, coriolis, Sr); for (int idir = 0; idir < 3; idir++) { rot(i,j,k,idir) = Sr[idir]; } }); } void Castro::fill_rotational_potential(const Box& bx, Array4<Real> const& phi, const Real time) { auto coord_type = geom.Coord(); GpuArray<Real, 3> omega; get_omega(omega.begin()); GpuArray<Real, 3> center; ca_get_center(center.begin()); auto problo = geom.ProbLoArray(); auto dx = geom.CellSizeArray(); amrex::ParallelFor(bx, [=] AMREX_GPU_HOST_DEVICE (int i, int j, int k) noexcept { GpuArray<Real, 3> r; r[0] = problo[0] + dx[0] * (static_cast<Real>(i) + 0.5_rt) - center[0]; #if AMREX_SPACEDIM >= 2 r[1] = problo[1] + dx[1] * (static_cast<Real>(j) + 0.5_rt) - center[1]; #else r[1] = 0.0_rt; #endif #if AMREX_SPACEDIM == 3 r[2] = problo[2] + dx[2] * (static_cast<Real>(k) + 0.5_rt) - center[2]; #else r[2] = 0.0_rt; #endif phi(i,j,k) = rotational_potential(r, omega); }); } void Castro::fill_rotational_psi(const Box& bx, Array4<Real> const& psi, const Real time) { // Construct psi, which is the distance-related part of the rotation // law. See e.g. Hachisu 1986a, Equation 15. For rigid-body // rotation, psi = -R^2 / 2, where R is the distance orthogonal to // the rotation axis. There are also v-constant and j-constant // rotation laws that we do not implement here. We will construct // this as potential / omega**2, so that the rotational_potential // routine uniquely determines the rotation law. For the other // rotation laws, we would simply divide by v_0^2 or j_0^2 instead. auto coord_type = geom.Coord(); GpuArray<Real, 3> omega; get_omega(omega.begin()); Real denom = omega[0] * omega[0] + omega[1] * omega[1] + omega[2] * omega[2]; auto problo = geom.ProbLoArray(); GpuArray<Real, 3> center; ca_get_center(center.begin()); auto dx = geom.CellSizeArray(); amrex::ParallelFor(bx, [=] AMREX_GPU_HOST_DEVICE (int i, int j, int k) noexcept { GpuArray<Real, 3> r; r[0] = problo[0] + dx[0] * (static_cast<Real>(i) + 0.5_rt) - center[0]; #if AMREX_SPACEDIM >= 2 r[1] = problo[1] + dx[1] * (static_cast<Real>(j) + 0.5_rt) - center[1]; #else r[1] = 0.0_rt; #endif #if AMREX_SPACEDIM == 3 r[2] = problo[2] + dx[2] * (static_cast<Real>(k) + 0.5_rt) - center[2]; #else r[2] = 0.0_rt; #endif psi(i,j,k) = rotational_potential(r, omega) / denom; }); }
[ "noreply@github.com" ]
shardi2.noreply@github.com
4305dc81cd4783205187d4004e84ef1f178e2872
ff9cf2d81ffcbed6b43efdcf0f551393888275a5
/Easy/Trap.cpp
4a2d04fdc6c1fa57db52f44459cc0e9ac3361584
[ "MIT" ]
permissive
pranshu98/LeetCode-Problems
0bad7c5b388fe5052f960f642402578a7b1add24
73c6e56caf6323b95e1ad3403f3635064287ece8
refs/heads/main
2023-08-15T23:23:27.389210
2021-10-05T15:26:16
2021-10-05T15:26:16
413,874,017
0
0
MIT
2021-10-05T15:25:38
2021-10-05T15:25:37
null
UTF-8
C++
false
false
624
cpp
class Solution { public: int trap(int A[], int n) { int left=0; int right=n-1; int res=0; int maxleft=0, maxright=0; while(left<=right){ if(A[left]<=A[right]){ if(A[left]>=maxleft) maxleft=A[left]; else res+=maxleft-A[left]; left++; } else{ if(A[right]>=maxright) maxright= A[right]; else res+=maxright-A[right]; right--; } } return res; } }; //Question is from leetcode //https://leetcode.com/problems/trapping-rain-water/
[ "noreply@github.com" ]
pranshu98.noreply@github.com
4d134aa688d5f1e1e81db196d9f6388e736f376d
53c31ea2d780bb501790e559cf0934ed3f58e3b0
/Hungre Jelly/Classes/Native/System_Core_U3CPrivateImplementationDetailsU3E3053238933.h
f64dfef5ba860fd4e339ac8df4bebbfa42c88286
[]
no_license
rezajebeli97/Hungry-Jelly
15765ce08c06c986808d5a16a69c06186f1a458b
3f4cd88904ec292ca939877df226d8115060b567
refs/heads/master
2020-04-06T03:36:30.910871
2018-06-12T13:20:26
2018-06-12T13:20:26
64,659,937
2
0
null
null
null
null
UTF-8
C++
false
false
8,100
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object837106420.h" #include "System_Core_U3CPrivateImplementationDetailsU3E_U242366141818.h" #include "System_Core_U3CPrivateImplementationDetailsU3E_U242366142878.h" #include "System_Core_U3CPrivateImplementationDetailsU3E_U24A335950518.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails> struct U3CPrivateImplementationDetailsU3E_t3053238934 : public Il2CppObject { public: public: }; struct U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields { public: // <PrivateImplementationDetails>/$ArrayType$120 <PrivateImplementationDetails>::$$field-1 U24ArrayTypeU24120_t2366141819 ___U24U24fieldU2D1_0; // <PrivateImplementationDetails>/$ArrayType$256 <PrivateImplementationDetails>::$$field-2 U24ArrayTypeU24256_t2366142879 ___U24U24fieldU2D2_1; // <PrivateImplementationDetails>/$ArrayType$256 <PrivateImplementationDetails>::$$field-3 U24ArrayTypeU24256_t2366142879 ___U24U24fieldU2D3_2; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-4 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D4_3; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-5 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D5_4; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-6 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D6_5; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-7 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D7_6; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-8 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D8_7; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-9 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D9_8; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-10 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D10_9; // <PrivateImplementationDetails>/$ArrayType$1024 <PrivateImplementationDetails>::$$field-11 U24ArrayTypeU241024_t335950519 ___U24U24fieldU2D11_10; public: inline static int32_t get_offset_of_U24U24fieldU2D1_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D1_0)); } inline U24ArrayTypeU24120_t2366141819 get_U24U24fieldU2D1_0() const { return ___U24U24fieldU2D1_0; } inline U24ArrayTypeU24120_t2366141819 * get_address_of_U24U24fieldU2D1_0() { return &___U24U24fieldU2D1_0; } inline void set_U24U24fieldU2D1_0(U24ArrayTypeU24120_t2366141819 value) { ___U24U24fieldU2D1_0 = value; } inline static int32_t get_offset_of_U24U24fieldU2D2_1() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D2_1)); } inline U24ArrayTypeU24256_t2366142879 get_U24U24fieldU2D2_1() const { return ___U24U24fieldU2D2_1; } inline U24ArrayTypeU24256_t2366142879 * get_address_of_U24U24fieldU2D2_1() { return &___U24U24fieldU2D2_1; } inline void set_U24U24fieldU2D2_1(U24ArrayTypeU24256_t2366142879 value) { ___U24U24fieldU2D2_1 = value; } inline static int32_t get_offset_of_U24U24fieldU2D3_2() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D3_2)); } inline U24ArrayTypeU24256_t2366142879 get_U24U24fieldU2D3_2() const { return ___U24U24fieldU2D3_2; } inline U24ArrayTypeU24256_t2366142879 * get_address_of_U24U24fieldU2D3_2() { return &___U24U24fieldU2D3_2; } inline void set_U24U24fieldU2D3_2(U24ArrayTypeU24256_t2366142879 value) { ___U24U24fieldU2D3_2 = value; } inline static int32_t get_offset_of_U24U24fieldU2D4_3() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D4_3)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D4_3() const { return ___U24U24fieldU2D4_3; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D4_3() { return &___U24U24fieldU2D4_3; } inline void set_U24U24fieldU2D4_3(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D4_3 = value; } inline static int32_t get_offset_of_U24U24fieldU2D5_4() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D5_4)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D5_4() const { return ___U24U24fieldU2D5_4; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D5_4() { return &___U24U24fieldU2D5_4; } inline void set_U24U24fieldU2D5_4(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D5_4 = value; } inline static int32_t get_offset_of_U24U24fieldU2D6_5() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D6_5)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D6_5() const { return ___U24U24fieldU2D6_5; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D6_5() { return &___U24U24fieldU2D6_5; } inline void set_U24U24fieldU2D6_5(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D6_5 = value; } inline static int32_t get_offset_of_U24U24fieldU2D7_6() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D7_6)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D7_6() const { return ___U24U24fieldU2D7_6; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D7_6() { return &___U24U24fieldU2D7_6; } inline void set_U24U24fieldU2D7_6(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D7_6 = value; } inline static int32_t get_offset_of_U24U24fieldU2D8_7() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D8_7)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D8_7() const { return ___U24U24fieldU2D8_7; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D8_7() { return &___U24U24fieldU2D8_7; } inline void set_U24U24fieldU2D8_7(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D8_7 = value; } inline static int32_t get_offset_of_U24U24fieldU2D9_8() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D9_8)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D9_8() const { return ___U24U24fieldU2D9_8; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D9_8() { return &___U24U24fieldU2D9_8; } inline void set_U24U24fieldU2D9_8(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D9_8 = value; } inline static int32_t get_offset_of_U24U24fieldU2D10_9() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D10_9)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D10_9() const { return ___U24U24fieldU2D10_9; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D10_9() { return &___U24U24fieldU2D10_9; } inline void set_U24U24fieldU2D10_9(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D10_9 = value; } inline static int32_t get_offset_of_U24U24fieldU2D11_10() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3053238934_StaticFields, ___U24U24fieldU2D11_10)); } inline U24ArrayTypeU241024_t335950519 get_U24U24fieldU2D11_10() const { return ___U24U24fieldU2D11_10; } inline U24ArrayTypeU241024_t335950519 * get_address_of_U24U24fieldU2D11_10() { return &___U24U24fieldU2D11_10; } inline void set_U24U24fieldU2D11_10(U24ArrayTypeU241024_t335950519 value) { ___U24U24fieldU2D11_10 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "rezajebeli97@yahoo.com" ]
rezajebeli97@yahoo.com
5d2824a810075602d6fea9dab22abce2e51ae6f6
596ed8d5d8e53ef7961af976f7a8449a6b591f18
/src/output/workspace-impl.cpp
f78e76e84f0a55bdc5b225d49f8cbd6d5e5e01f8
[ "MIT" ]
permissive
junglerobba/wayfire
7938361336ef3cd48880adf597325b685d8151b3
26d00712590d219ac4aae12f2061dd9f5a39a2b4
refs/heads/master
2020-11-24T01:35:55.767021
2019-12-10T11:25:30
2019-12-10T11:25:30
227,907,498
0
0
MIT
2019-12-13T19:22:00
2019-12-13T19:21:59
null
UTF-8
C++
false
false
22,341
cpp
#include <view.hpp> #include <debug.hpp> #include <output.hpp> #include <core.hpp> #include <workspace-manager.hpp> #include <render-manager.hpp> #include <signal-definitions.hpp> #include <opengl.hpp> #include <list> #include <algorithm> #include <nonstd/reverse.hpp> namespace wf { /** * output_layer_manager_t is a part of the workspace_manager module. It provides * the functionality related to layers. */ class output_layer_manager_t { struct view_layer_data_t : public wf::custom_data_t { uint32_t layer = 0; }; using layer_container = std::list<wayfire_view>; layer_container layers[TOTAL_LAYERS]; public: constexpr int layer_index_from_mask(uint32_t layer_mask) const { return __builtin_ctz(layer_mask); } uint32_t& get_view_layer(wayfire_view view) { return view->get_data_safe<view_layer_data_t>()->layer; } void remove_view(wayfire_view view) { auto& view_layer = get_view_layer(view); if (!view_layer) return; view->damage(); auto& layer_container = layers[layer_index_from_mask(view_layer)]; auto it = std::remove( layer_container.begin(), layer_container.end(), view); layer_container.erase(it, layer_container.end()); view_layer = 0; } /** * Add or move the view to the given layer */ void add_view_to_layer(wayfire_view view, layer_t layer) { view->damage(); auto& current_layer = get_view_layer(view); if (current_layer) remove_view(view); auto& layer_container = layers[layer_index_from_mask(layer)]; layer_container.push_front(view); current_layer = layer; view->damage(); } void bring_to_front(wayfire_view view) { uint32_t view_layer = get_view_layer(view); assert(view_layer > 0); // checked in workspace_manager::impl remove_view(view); add_view_to_layer(view, static_cast<layer_t>(view_layer)); } wayfire_view get_front_view(wf::layer_t layer) { auto& container = layers[layer_index_from_mask(layer)]; if (container.empty()) return nullptr; return container.front(); } void restack_above(wayfire_view view, wayfire_view below) { remove_view(view); auto layer = get_view_layer(below); auto& container = layers[layer_index_from_mask(layer)]; auto it = std::find(container.begin(), container.end(), below); container.insert(it, view); get_view_layer(view) = layer; } void restack_below(wayfire_view view, wayfire_view above) { remove_view(view); auto layer = get_view_layer(above); auto& container = layers[layer_index_from_mask(layer)]; auto it = std::find(container.begin(), container.end(), above); assert(it != container.end()); container.insert(std::next(it), view); get_view_layer(view) = layer; } std::vector<wayfire_view> get_views_in_layer(uint32_t layers_mask) { std::vector<wayfire_view> views; for (int i = TOTAL_LAYERS - 1; i >= 0; i--) { if ((1 << i) & layers_mask) { views.insert(views.end(), layers[i].begin(), layers[i].end()); } } return views; } }; struct default_workspace_implementation_t : public workspace_implementation_t { bool view_movable (wayfire_view view) { return true; } bool view_resizable(wayfire_view view) { return true; } virtual ~default_workspace_implementation_t() {} }; /** * The output_viewport_manager_t provides viewport-related functionality in * workspace_manager */ class output_viewport_manager_t { private: int vwidth; int vheight; int current_vx; int current_vy; output_t *output; public: output_viewport_manager_t(output_t *output) { this->output = output; auto section = wf::get_core().config->get_section("core"); vwidth = *section->get_option("vwidth", "3"); vheight = *section->get_option("vheight", "3"); vwidth = clamp(vwidth, 1, 20); vheight = clamp(vheight, 1, 20); current_vx = 0; current_vy = 0; } /** * @param use_bbox When considering view visibility, whether to use the * bounding box or the wm geometry. * * @return true if the view is visible on the workspace vp */ bool view_visible_on(wayfire_view view, wf_point vp, bool use_bbox) { auto g = output->get_relative_geometry(); if (view->role != VIEW_ROLE_SHELL_VIEW) { g.x += (vp.x - current_vx) * g.width; g.y += (vp.y - current_vy) * g.height; } if (view->has_transformer() & use_bbox) { return view->intersects_region(g); } else { return g & view->get_wm_geometry(); } } /** * Moves view geometry so that it is visible on the given workspace */ void move_to_workspace(wayfire_view view, wf_point ws) { if (view->get_output() != output) { log_error("Cannot ensure view visibility for a view from a different output!"); return; } auto box = view->get_wm_geometry(); auto visible = output->get_relative_geometry(); visible.x += (ws.x - current_vx) * visible.width; visible.y += (ws.y - current_vy) * visible.height; if (!(box & visible)) { /* center of the view */ int cx = box.x + box.width / 2; int cy = box.y + box.height / 2; int width = visible.width, height = visible.height; /* compute center coordinates when moved to the current workspace */ int local_cx = (cx % width + width) % width; int local_cy = (cy % height + height) % height; /* finally, calculate center coordinates in the target workspace */ int target_cx = local_cx + visible.x; int target_cy = local_cy + visible.y; view->move(box.x + target_cx - cx, box.y + target_cy - cy); } } std::vector<wayfire_view> get_views_on_workspace(wf_point vp, uint32_t layers_mask, bool wm_only) { /* get all views in the given layers */ std::vector<wayfire_view> views = output->workspace->get_views_in_layer(layers_mask); /* remove those which aren't visible on the workspace */ auto it = std::remove_if(views.begin(), views.end(), [&] (wayfire_view view) { return !view_visible_on(view, vp, !wm_only); }); views.erase(it, views.end()); return views; } wf_point get_current_workspace() { return {current_vx, current_vy}; } wf_size_t get_workspace_grid_size() { return {vwidth, vheight}; } void set_workspace(wf_point nws) { if(nws.x >= vwidth || nws.y >= vheight || nws.x < 0 || nws.y < 0) { log_error("Attempt to set invalid workspace: %d,%d," " workspace grid size is %dx%d", nws.x, nws.y, vwidth, vheight); return; } if (nws.x == current_vx && nws.y == current_vy) { output->refocus(); return; } change_viewport_signal data; data.old_viewport = {current_vx, current_vy}; data.new_viewport = {nws.x, nws.y}; /* The part below is tricky, because with the current architecture * we cannot make the viewport change look atomic, i.e the workspace * is changed first, and then all views are moved. * * We first change the viewport, and then adjust the position of the * views. */ current_vx = nws.x; current_vy = nws.y; auto screen = output->get_screen_size(); auto dx = (data.old_viewport.x - nws.x) * screen.width; auto dy = (data.old_viewport.y - nws.y) * screen.height; for (auto& v : output->workspace->get_views_in_layer(MIDDLE_LAYERS)) { v->move(v->get_wm_geometry().x + dx, v->get_wm_geometry().y + dy); } output->emit_signal("viewport-changed", &data); /* unfocus view from last workspace */ output->focus_view(nullptr); /* we iterate through views on current viewport from bottom to top * that way we ensure that they will be focused before all others */ auto views = get_views_on_workspace(get_current_workspace(), MIDDLE_LAYERS, true); for (auto& view : wf::reverse(views)) { if (view->is_mapped()) output->workspace->bring_to_front(view); } /* Focus last window */ if (!views.empty()) output->focus_view(views.front()); } }; /** * output_workarea_manager_t provides workarea-related functionality from the * workspace_manager module */ class output_workarea_manager_t { wf_geometry current_workarea; std::vector<workspace_manager::anchored_area*> anchors; output_t *output; public: output_workarea_manager_t(output_t *output) { this->output = output; this->current_workarea = output->get_relative_geometry(); } wf_geometry get_workarea() { return current_workarea; } wf_geometry calculate_anchored_geometry(const workspace_manager::anchored_area& area) { auto wa = get_workarea(); wf_geometry target; if (area.edge <= workspace_manager::ANCHORED_EDGE_BOTTOM) { target.width = wa.width; target.height = area.real_size; } else { target.height = wa.height; target.width = area.real_size; } target.x = wa.x; target.y = wa.y; if (area.edge == workspace_manager::ANCHORED_EDGE_RIGHT) target.x = wa.x + wa.width - target.width; if (area.edge == workspace_manager::ANCHORED_EDGE_BOTTOM) target.y = wa.y + wa.height - target.height; return target; } void add_reserved_area(workspace_manager::anchored_area *area) { anchors.push_back(area); } void remove_reserved_area(workspace_manager::anchored_area *area) { auto it = std::remove(anchors.begin(), anchors.end(), area); anchors.erase(it, anchors.end()); } void reflow_reserved_areas() { auto old_workarea = current_workarea; current_workarea = output->get_relative_geometry(); for (auto a : anchors) { auto anchor_area = calculate_anchored_geometry(*a); if (a->reflowed) a->reflowed(anchor_area, current_workarea); switch(a->edge) { case workspace_manager::ANCHORED_EDGE_TOP: current_workarea.y += a->reserved_size; // fallthrough case workspace_manager::ANCHORED_EDGE_BOTTOM: current_workarea.height -= a->reserved_size; break; case workspace_manager::ANCHORED_EDGE_LEFT: current_workarea.x += a->reserved_size; // fallthrough case workspace_manager::ANCHORED_EDGE_RIGHT: current_workarea.width -= a->reserved_size; break; } } reserved_workarea_signal data; data.old_workarea = old_workarea; data.new_workarea = current_workarea; if (data.old_workarea != data.new_workarea) output->emit_signal("reserved-workarea", &data); } }; class workspace_manager::impl { wf::output_t *output; wf_geometry output_geometry; signal_callback_t output_geometry_changed = [&] (void*) { auto old_w = output_geometry.width, old_h = output_geometry.height; auto new_size = output->get_screen_size(); for (auto& view : layer_manager.get_views_in_layer(MIDDLE_LAYERS)) { if (!view->is_mapped()) continue; auto wm = view->get_wm_geometry(); float px = 1. * wm.x / old_w; float py = 1. * wm.y / old_h; float pw = 1. * wm.width / old_w; float ph = 1. * wm.height / old_h; view->set_geometry({ int(px * new_size.width), int(py * new_size.height), int(pw * new_size.width), int(ph * new_size.height) }); } output_geometry = output->get_relative_geometry(); workarea_manager.reflow_reserved_areas(); }; signal_callback_t view_changed_viewport = [=] (signal_data_t *data) { check_autohide_panels(); }; bool sent_autohide = false; std::unique_ptr<workspace_implementation_t> workspace_impl; public: output_layer_manager_t layer_manager; output_viewport_manager_t viewport_manager; output_workarea_manager_t workarea_manager; impl(output_t *o) : layer_manager(), viewport_manager(o), workarea_manager(o) { output = o; output_geometry = output->get_relative_geometry(); o->connect_signal("view-change-viewport", &view_changed_viewport); o->connect_signal("output-configuration-changed", &output_geometry_changed); } workspace_implementation_t* get_implementation() { static default_workspace_implementation_t default_impl; return workspace_impl ? workspace_impl.get() : &default_impl; } bool set_implementation(std::unique_ptr<workspace_implementation_t> impl, bool overwrite) { bool replace = overwrite || !workspace_impl; if (replace) workspace_impl = std::move(impl); return replace; } void check_autohide_panels() { auto fs_views = viewport_manager.get_views_on_workspace( viewport_manager.get_current_workspace(), wf::LAYER_FULLSCREEN, true); if (fs_views.size() && !sent_autohide) { sent_autohide = 1; output->emit_signal("autohide-panels", reinterpret_cast<signal_data_t*> (1)); log_debug("autohide panels"); } else if (fs_views.empty() && sent_autohide) { sent_autohide = 0; output->emit_signal("autohide-panels", reinterpret_cast<signal_data_t*> (0)); log_debug("restore panels"); } } void set_workspace(wf_point ws) { viewport_manager.set_workspace(ws); check_autohide_panels(); } layer_t get_target_layer(wayfire_view view, layer_t current_target) { /* A view which is fullscreen should go directly to the fullscreen layer * when it is raised */ if ((current_target & MIDDLE_LAYERS) && view->fullscreen) { return LAYER_FULLSCREEN; } else { return current_target; } } void check_lower_fullscreen_layer(wayfire_view top_view, uint32_t top_view_layer) { /* We need to lower fullscreen layer only if we are focusing a regular * view, which isn't fullscreen */ if (top_view_layer != LAYER_WORKSPACE || top_view->fullscreen) return; auto views = viewport_manager.get_views_on_workspace( viewport_manager.get_current_workspace(), LAYER_FULLSCREEN, true); for (auto& v : wf::reverse(views)) layer_manager.add_view_to_layer(v, LAYER_WORKSPACE); } void add_view_to_layer(wayfire_view view, layer_t layer) { uint32_t view_layer_before = layer_manager.get_view_layer(view); layer_t target_layer = get_target_layer(view, layer); /* First lower fullscreen layer, then make the view on top of all lowered * fullscreen views */ check_lower_fullscreen_layer(view, target_layer); layer_manager.add_view_to_layer(view, target_layer); if (view_layer_before == 0) { _view_signal data; data.view = view; output->emit_signal("attach-view", &data); } check_autohide_panels(); } void bring_to_front(wayfire_view view) { uint32_t view_layer = layer_manager.get_view_layer(view); if (!view_layer) { log_error ("trying to bring_to_front a view without a layer!"); return; } uint32_t target_layer = get_target_layer(view, static_cast<layer_t>(view_layer)); /* First lower fullscreen layer, then make the view on top of all lowered * fullscreen views */ check_lower_fullscreen_layer(view, target_layer); if (view_layer == target_layer) { layer_manager.bring_to_front(view); } else { layer_manager.add_view_to_layer(view, static_cast<layer_t>(target_layer)); } check_autohide_panels(); } void restack_above(wayfire_view view, wayfire_view below) { if (!view || !below || view == below) { log_error("Cannot restack a view on top of itself"); return; } uint32_t view_layer = layer_manager.get_view_layer(view); uint32_t below_layer = layer_manager.get_view_layer(below); if (view_layer == 0 || below_layer == 0 || view_layer != below_layer) { log_error("restacking views from different layers(%d vs %d!)", view_layer, below_layer); return; } log_info("restack %s on top of %s", view->get_title().c_str(), below->get_title().c_str()); /* If we restack on top of the front-most view, then this can * potentially change fullscreen state. So in this case use the * bring_to_front() path */ auto front_view = layer_manager.get_front_view(static_cast<wf::layer_t>(below_layer)); if (front_view == below) { bring_to_front(view); } else { layer_manager.restack_above(view, below); } } void restack_below(wayfire_view view, wayfire_view above) { if (!view || !above || view == above) { log_error("Cannot restack a view on top of itself"); return; } uint32_t view_layer = layer_manager.get_view_layer(view); uint32_t below_layer = layer_manager.get_view_layer(above); if (view_layer == 0 || below_layer == 0 || view_layer != below_layer) { log_error("restacking views from different layers(%d vs %d!)", view_layer, below_layer); return; } layer_manager.restack_below(view, above); } void remove_view(wayfire_view view) { uint32_t view_layer = layer_manager.get_view_layer(view); layer_manager.remove_view(view); _view_signal data; data.view = view; output->emit_signal("detach-view", &data); /* Check if the next focused view is fullscreen. If so, then we need * to make sure it is in the fullscreen layer */ if (view_layer & MIDDLE_LAYERS) { auto views = viewport_manager.get_views_on_workspace( viewport_manager.get_current_workspace(), LAYER_WORKSPACE | LAYER_FULLSCREEN, true); if (views.size() && views[0]->fullscreen) layer_manager.add_view_to_layer(views[0], LAYER_FULLSCREEN); } check_autohide_panels(); } }; workspace_manager::workspace_manager(output_t *wo) : pimpl(new impl(wo)) {} workspace_manager::~workspace_manager() = default; /* Just pass to the appropriate function from above */ bool workspace_manager::view_visible_on(wayfire_view view, wf_point ws) { return pimpl->viewport_manager.view_visible_on(view, ws, true); } std::vector<wayfire_view> workspace_manager::get_views_on_workspace(wf_point ws, uint32_t layer_mask, bool wm_only) { return pimpl->viewport_manager.get_views_on_workspace(ws, layer_mask, wm_only); } void workspace_manager::move_to_workspace(wayfire_view view, wf_point ws) { return pimpl->viewport_manager.move_to_workspace(view, ws); } void workspace_manager::add_view(wayfire_view view, layer_t layer) { return pimpl->add_view_to_layer(view, layer); } void workspace_manager::bring_to_front(wayfire_view view) { return pimpl->bring_to_front(view); } void workspace_manager::restack_above(wayfire_view view, wayfire_view below) { return pimpl->restack_above(view, below); } void workspace_manager::restack_below(wayfire_view view, wayfire_view below) { return pimpl->restack_below(view, below); } void workspace_manager::remove_view(wayfire_view view) { return pimpl->remove_view(view); } uint32_t workspace_manager::get_view_layer(wayfire_view view) { return pimpl->layer_manager.get_view_layer(view); } std::vector<wayfire_view> workspace_manager::get_views_in_layer(uint32_t layers_mask) { return pimpl->layer_manager.get_views_in_layer(layers_mask); } workspace_implementation_t* workspace_manager::get_workspace_implementation() { return pimpl->get_implementation(); } bool workspace_manager::set_workspace_implementation(std::unique_ptr<workspace_implementation_t> impl, bool overwrite) { return pimpl->set_implementation(std::move(impl), overwrite); } void workspace_manager::set_workspace(wf_point ws) { return pimpl->set_workspace(ws); } wf_point workspace_manager::get_current_workspace() { return pimpl->viewport_manager.get_current_workspace(); } wf_size_t workspace_manager::get_workspace_grid_size() { return pimpl->viewport_manager.get_workspace_grid_size(); } void workspace_manager::add_reserved_area(anchored_area *area) { return pimpl->workarea_manager.add_reserved_area(area); } void workspace_manager::remove_reserved_area(anchored_area *area) { return pimpl->workarea_manager.remove_reserved_area(area); } void workspace_manager::reflow_reserved_areas() { return pimpl->workarea_manager.reflow_reserved_areas(); } wf_geometry workspace_manager::get_workarea() { return pimpl->workarea_manager.get_workarea(); } } // namespace wf
[ "ammen99@gmail.com" ]
ammen99@gmail.com
bc9b483ccf96b56559b22a7b68a0c9d1ae4696ff
d4ab7ac90d19c8c71647091013813ac65489ffbc
/ex3/Matrix.hpp
bfd1fb5f8ec07448c5f1749a542c522fab159440
[]
no_license
oribro/C-Plus-Plus
d275271025319189ae0cde8caa45a6fb1f00a47c
f29cc9dd4d5f9676bf2c60ab81baac7810e5f06a
refs/heads/master
2021-01-12T14:06:22.713676
2016-09-29T12:25:43
2016-09-29T12:25:43
69,565,035
0
0
null
null
null
null
UTF-8
C++
false
false
25,686
hpp
// // Created by OriB on 06/09/2015. // #ifndef MATRIX_HPP #define MATRIX_HPP #include "Complex.h" #include <iostream> #include <thread> #include <mutex> #include <vector> #include "TraceException.h" #include "AdditionException.h" #include "MultiplicationException.h" #include "SubtractionException.h" #include "MatrixAllocException.h" #include "MoveException.h" #include "MatrixAssignmentException.h" #define MULT "MULT" #define SUM "SUM" #define TAB "\t" /** * A generic matrix class. * This class represents a matrix with a type that supports ‫‪ ‬‬ operations: * ‫‪==,= ,* ,+= ,­-= ,­ -, << and the zero constructor.‬‬ */ template <class T> class Matrix { public: // The const iterator for the matrix is a const iterator for vector. typedef typename std::vector<T>::const_iterator VectorConstIterator; // A vector of threads for multithreading. typedef std::vector<std::thread> Threads; // Iterator for the threads vector. typedef typename std::vector<std::thread>::iterator ThreadsIterator; /** * Default constructor. * Initiate a matrix of dimension 0 as null matrix. * This constructor is used to construct a matrix object with no values. * @return a copy of the constructed matrix. */ // -------------------------------- Declarations ------------------------- /** * Default constructor. * Initializes the matrix as 1x1 matrix with zero value. */ Matrix(); /** * Sets the corresponding static data member value to the value indicated * by indicator. * @param indicator - true for using parallel mode, false for using sequential mode. */ static void setParallel(bool indicator); /** * Constructor that receives the matrix dimensions and initializes a matrix with * zero values. * @rows - the rows of the matrix. * @cols - the cols of the matrix. */ Matrix(unsigned int rows, unsigned int cols); /** * Copy constructor. * @param other - the other matrix to copy. */ Matrix(const Matrix<T>& other); /** * Move constructor. * @param other - the other matrix to move. */ Matrix(Matrix<T> && other); /** * Constructor that initializes the matrix according to the const iterator of the class. * @param rows - the rows of the matrix. * @param cols - the cols of the matrix. * @param cells - the cells of the matrix to initialize to. */ Matrix(unsigned int rows, unsigned int cols, const std::vector<T>& cells); /** * Destructor. */ ~Matrix(); /** * Operator for matrix assignment. * @param other the second matrix operand. * @return the assigned matrix. We change the object! * @throws invalid_argument if a dimension is 0. */ Matrix<T>& operator=(const Matrix<T>& other); /** * Operator for matrix addition. * @param other the second matrix operand. * @return a copy matrix of the addition. * @throws invalid_argument if a dimension is 0. */ const Matrix<T> operator+(const Matrix<T>& other) const; /** * Operator for matrix substraction. * @param other the second matrix operand. * @return a copy of the difference matrix. * @throws invalid_argument if a dimension is 0. */ const Matrix<T> operator-(const Matrix<T>& other) const; /** * Operator for matrix multiplication. * @param other the second matrix operand. * @return a copy of the mult matrix. * @throws invalid_argument if a dimension is 0. */ const Matrix<T> operator*(const Matrix<T>& other) const; /** * Operator for comparing matrices. * @param other - the matrix to compare. * @return true if the matrices are equal and false otherwise. */ bool operator==(const Matrix<T>& other) const; /** * Operator for comparing matrices. * @param other - the matrix to compare. * @return true if the matrices are different and false otherwise. */ bool operator!=(const Matrix<T>& other) const; /** * Returns the transpose of the given matrix. * @return the matrix transpose. * @throws invalid_argument if a dimension is 0. */ const Matrix<T> trans() const; /** * Returns the trace of the matrix. * @return the trace. * @throws invalid_argument if a dimension is 0. */ const T trace() const; /** * Const operator for indexing the matrix. * @param row - the row to look for the value. * @param col - the col to look for the value. * @return The value at the given row and col, as const value * (read only). */ const T& operator()(unsigned int row, unsigned int col) const; /** * Operator for indexing the matrix. * @param row - the row to look for the value. * @param col - the col to look for the value. * @return The value at the given row and col, as const value */ T& operator()(unsigned int row, unsigned int col); /** * Prints the matrix. * @param out - the object to write to. * @param matrix - the matrix to print. * @return reference to the printing object. */ template <typename K> friend std::ostream& operator<<(std::ostream& out, const Matrix<K>& matrix); /** * @return the size of the rows of the matrix. */ unsigned int rows() const; /** * @return the size of the columns of the matrix. */ unsigned int cols() const; /** * @return true if the matrix is square, false otherwise. */ bool isSquareMatrix() const; /** * This class represents a const iterator for the matrix. * The iterator iterates the matrix for read only purposes. */ class const_iterator { public: /** * Constructor for the iterator. * @param it - the iterator of the matrix, sets by defult to be defaultly * constructed by vector constructor. */ const_iterator(VectorConstIterator it = VectorConstIterator()) : _it(it) { } /** * Copy constructor. * @param other - the other iterator to copy. */ const_iterator(const const_iterator& other) { _it = other._it; } /** * Assignment operator. * @param other the other iterator to assign. */ const_iterator& operator=(const const_iterator& other) { _it = other._it; return *this; } /** * Dereference operator. * @return reference to the value the iterator points to. */ const T& operator*() { return *_it; } /** * @returns the iterator. */ T* operator->() { return _it; } /** *@return returns the incremented operator. */ const_iterator& operator++() { ++_it; return *this; } /** * @return the operator before increment. */ const_iterator operator++(int) { const_iterator tmp = *this; _it++; return tmp; } /** * @return reference to the operator after decrement. */ const_iterator& operator--() { --_it; return *this; } /** * @return reference to the operator before decrement. */ const_iterator operator--(int) { const_iterator tmp = *this; _it--; return tmp; } /** * @param other iterator to compare. * @return true if the operators are equal, false otherwise. */ bool operator==(const_iterator const& other) const { return _it == other._it; } /** * @param other iterator to compare. * @return false if the operators are equal, true otherwise. */ bool operator!=(const_iterator const& other) const { return _it != other._it; } private: // The iterator for the matrix. VectorConstIterator _it; }; /** * @return iterator to the beginning of the matrix. */ const_iterator begin() const { return const_iterator(_pMatrix.begin()); } /** * @return iterator to the end of the matrix. */ const_iterator end() const { return const_iterator(_pMatrix.end()); } private: unsigned int _rows; // The number of rows in the matrix. unsigned int _cols; // The number of columns in the matrix. std::vector<T> _pMatrix; // Vector containing the matrix values. // Static variable to indicate the mode we use - parallel or sequential. static bool s_useParallel; /** * This is how we index the matrix. Every row is defined as a sequence of * values in the vector. * @param row - the row for the value. * @param col - the column for the value. * @return the position in the matrix which the value is found at. */ inline unsigned int _matrixIndex(unsigned int row, unsigned int col) const { return (row * _cols) + col; } /** * Method for multiplying creating a line using multiplication in the parallel mode. * @param lineNumber - the line in the result matrix we currently compute. * @param multMatrix - the result matrix to be created. * @param firstM - the first matrix to multiply. * @param secondM - the second matrix to multiply. */ static void _multLine(int lineNumber, Matrix<T>& multMatrix, const Matrix<T>& firstM, const Matrix<T>& secondM); /** * Method for summing creating a line using summation in the parallel mode. * @param lineNumber - the line in the result matrix we currently compute. * @param multMatrix - the result matrix to be created. * @param firstM - the first matrix to multiply. * @param secondM - the second matrix to multiply. */ static void _sumLine(int lineNumber, Matrix<T>& sumMatrix, const Matrix<T>& firstM, const Matrix<T>& secondM); /** * Performs a parallel operation. * @param operation- an indicator to tell us which operation to perform (mult or sum). * @param resultMatrix - the result matrix to be created. * @param other - the other matrix to perform the action on. */ void _parallelOperation(const std::string& operation, Matrix<T>& resultMatrix, const Matrix<T>& other) const; }; // ---------------------------------------- Implementations ------------------------------ /** * Sets the corresponding static data member value to the value indicated * by indicator. * @param indicator - true for using parallel mode, false for using sequential mode. */ template <class T> bool Matrix<T>::s_useParallel = false; template <class T> inline void Matrix<T>::setParallel(bool indicator) { // Print only if the indicator changes the state of the program. if (indicator != s_useParallel) { s_useParallel = indicator; if (indicator == true) { std::cout << "Generic Matrix mode changed to parallel mode" << std::endl; } else { std::cout << "Generic Matrix mode changed to non-parallel mode" << std::endl; } } } /** * Default constructor. * Initializes the matrix as 1x1 matrix with zero value. * @throws MatrixAllocException if the memory could not be allocated. */ template <class T> inline Matrix<T>::Matrix() : _rows(1), _cols(1) { try { // The zero value of the type is the default constructed type. _pMatrix.push_back(T()); } catch(std::bad_alloc& e) { throw MatrixAllocException(); } } /** * Constructor that receives the matrix dimensions and initializes a matrix with * zero values. * @rows - the rows of the matrix. * @cols - the cols of the matrix. * @throws MatrixAllocException if the memory could not be allocated. */ template <class T> inline Matrix<T>::Matrix(unsigned int rows, unsigned int cols) : _rows(rows), _cols(cols) { try { // Initialize the matrix with zero values. for (unsigned int i = 0; i < rows * cols; i++) { _pMatrix.push_back(T()); } } catch(std::bad_alloc& e) { throw MatrixAllocException(); } } /** * Copy constructor. * @param other - the other matrix to copy. */ template <typename T> inline Matrix<T>::Matrix(const Matrix<T>& other) : _rows(other._rows), _cols(other._cols), _pMatrix(other._pMatrix) { } /** * Move constructor. * @param other - the other matrix to move. * @throws MoveException if the matrix could not be moved. */ template <typename T> inline Matrix<T>::Matrix(Matrix<T> && other) : _rows(other._rows), _cols(other._cols) { try { _pMatrix = std::move(other._pMatrix); } catch(...) { throw MoveException(); } } /** * Constructor that initializes the matrix according to the const iterator of the class. * @param rows - the rows of the matrix. * @param cols - the cols of the matrix. * @param cells - the cells of the matrix to initialize to. * @throws MatrixAllocException if the memory could not be allocated. */ template <class T> inline Matrix<T>::Matrix(unsigned int rows, unsigned int cols, const std::vector<T>& cells) : _rows(rows), _cols(cols) { try { for (VectorConstIterator it = cells.begin(); it != cells.end(); ++it) { _pMatrix.push_back(*it); } } catch(std::bad_alloc& e) { throw MatrixAllocException(); } } /** * Destructor. */ template <class T> inline Matrix<T>::~Matrix() { } /** * Const operator for indexing the matrix. * @param row - the row to look for the value. * @param col - the col to look for the value. * @return The value at the given row and col, as const value * (read only). */ template <typename T> inline const T& Matrix<T>::operator()(unsigned int row, unsigned int col) const { return _pMatrix.at(_matrixIndex(row, col)); } /** * Operator for indexing the matrix. * @param row - the row to look for the value. * @param col - the col to look for the value. * @return The value at the given row and col, as const value */ template <typename T> inline T& Matrix<T>::operator()(unsigned int row, unsigned int col) { return _pMatrix[_matrixIndex(row, col)]; } /** * Operator for matrix addition. * @param other the second matrix operand. * @return a copy matrix of the addition. * @throws AdditionException if the dimensions are different. */ template <typename T> inline const Matrix<T> Matrix<T>::operator+(const Matrix<T>& other) const { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if ((other._rows != other._cols) && (other._rows == 0 || other._cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if(!((_rows == other._rows) && (_cols == other._cols))) { throw AdditionException("cannot addition matrices of different sizes."); } Matrix<T> sumMatrix = Matrix<T>(other._rows, other._cols); // use regular programming (serialized) if (!s_useParallel) { // Create the left summand object. for (unsigned int i = 0; i < sumMatrix._rows; ++i) { for (unsigned int j = 0; j < sumMatrix._cols; ++j) { sumMatrix(i, j) = (*this)(i, j) + other(i, j); } } } // Use multithreading (parallel). else { _parallelOperation(SUM, sumMatrix, other); } return sumMatrix; } /** * Operator for matrix substraction. * @param other the second matrix operand. * @return a copy of the difference matrix. * @throws SubtractionException if the dimensions are different. */ template <typename T> inline const Matrix<T> Matrix<T>::operator-(const Matrix<T>& other) const { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if ((other._rows != other._cols) && (other._rows == 0 || other._cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if(!((_rows == other._rows) && (_cols == other._cols))) { throw SubtractionException("Cannot subtract matrices of different sizes."); } // The result matrix. Matrix<T> minusMatrix = Matrix<T>(_rows, _cols); for (unsigned int i = 0; i < minusMatrix._rows; ++i) { for (unsigned int j = 0; j < minusMatrix._cols; ++j) { minusMatrix(i, j) = (*this)(i, j) - other(i, j); } } return minusMatrix; } /** * Operator for matrix multiplication. * @param other the second matrix operand. * @return a copy of the mult matrix. * @throws MultiplicationException if the dimensions are different. */ template <typename T> inline const Matrix<T> Matrix<T>::operator*(const Matrix<T>& other) const { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if ((other._rows != other._cols) && (other._rows == 0 || other._cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if(_cols != other._rows) { throw MultiplicationException("Cannot multiply matrices of different sizes."); } Matrix<T> multMatrix = Matrix<T>(_rows, other._cols); if (!s_useParallel) { for (unsigned int i = 0; i < multMatrix._rows; ++i) { for (unsigned int j = 0; j < multMatrix._cols; ++j) { // Multiply the first matrix row by the second matrix column. multMatrix(i, j) = T(); for (unsigned int k = 0; k < _cols; ++k) { multMatrix(i, j) += ((*this)(i, k)) * (other(k, j)); } } } } else { _parallelOperation(MULT, multMatrix, other); } return multMatrix; } /** * Operator for matrix assignment. * @param other the second matrix operand. * @return the assigned matrix. We change the object! * @throws AssignmentException if could not assign matrix. */ template <typename T> inline Matrix<T>& Matrix<T>::operator=(const Matrix<T>& other) { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if ((other._rows != other._cols) && (other._rows == 0 || other._cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } // We try to copy the same object, we don't want to lose the pointer. if (this == &other) { return *this; } try { _rows = other._rows; _cols = other._cols; _pMatrix = other._pMatrix; } catch(...) { throw MatrixAssignmentException("Could not assign matrix."); } return *this; } /** * Operator for comparing matrices. * @param other - the matrix to compare. * @return true if the matrices are equal and false otherwise. */ template <typename T> inline bool Matrix<T>::operator==(const Matrix<T>& other) const { // The matrices are from different dimensions and cant be equal. if(!((_rows == other._rows) && (_cols == other._cols))) { return false; } return _pMatrix == other._pMatrix; } /** * Operator for comparing matrices. * @param other - the matrix to compare. * @return true if the matrices are different and false otherwise. */ template <typename T> inline bool Matrix<T>::operator!=(const Matrix<T>& other) const { return !(*this == other); } /** * Matrix transpose. * @return a copy of the transposed matrix. */ template <typename T> inline const Matrix<T> Matrix<T>::trans() const { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } Matrix<T> transMatrix; transMatrix._rows = _cols; transMatrix._cols = _rows; transMatrix._pMatrix.resize(transMatrix._rows * transMatrix._cols); for (unsigned int i = 0; i < transMatrix._rows; ++i) { for (unsigned int j = 0; j < transMatrix._cols; ++j) { // Substitute between cols and rows. transMatrix(i, j) = (*this)(j, i); } } return transMatrix; } /** * Specialization method for matrix complex transpose. * @return a copy of the transposed matrix. */ template <> inline const Matrix<Complex> Matrix<Complex>::trans() const { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } Matrix<Complex> conjugateM; conjugateM._rows = _cols; conjugateM._cols = _rows; conjugateM._pMatrix.resize(conjugateM._rows * conjugateM._cols); for (unsigned int i = 0; i < conjugateM._rows; ++i) { for (unsigned int j = 0; j < conjugateM._cols; ++j) { // Change the values to their conjugates. conjugateM(i, j) = ((*this)(j, i)).conj(); } } return conjugateM; } /** * Prints the matrix. * @param out - the object to write to. * @param matrix - the matrix to print. * @return reference to the printing object. */ template <typename K> inline std::ostream& operator<<(std::ostream& out, const Matrix<K>& matrix) { unsigned int j; for (unsigned int i = 0; i < matrix._rows; i++) { for (j = 0; j < matrix._cols; j++) { out << matrix(i, j) << TAB; } out << std::endl; } return out; } /** * calculates the trace of the matrix. * @return the trace of the matrix. * @throws TraceException if the matrix isn't square. */ template <typename T> inline const T Matrix<T>::trace() const { if ((_rows != _cols) && (_rows == 0 || _cols == 0)) { throw std::invalid_argument("Matrix with dimension 0 is illegal."); } if(_rows != _cols) { throw TraceException("Matrix isn't square"); } T mTrace = T(); for (unsigned int i = 0; i < _rows; i++) { mTrace += (*this)(i, i); } return mTrace; } /** * @return the rows of the matrix. */ template <typename T> inline unsigned int Matrix<T>::rows() const { return _rows; } /** * @return the cols of the matrix. */ template <typename T> unsigned int Matrix<T>::cols() const { return _cols; } /** * @return true if the matrix is square, false otherwise. */ template <typename T> inline bool Matrix<T>::isSquareMatrix() const { return (_rows == _cols); } /** * Performs a parallel operation. * @param operation- an indicator to tell us which operation to perform (mult or sum). * @param resultMatrix - the result matrix to be created. * @param other - the other matrix to perform the action on. */ template <typename T> inline void Matrix<T>::_parallelOperation(const std::string& operation, Matrix<T>& resultMatrix, const Matrix<T>& other) const { // The threads for the matrix lines. Threads matrixRowsThreads(_rows); // Create threads for the matrix rows. if (operation.compare(SUM) == 0) { for (unsigned int i = 0; i < resultMatrix._rows; ++i) { matrixRowsThreads[i] = std::thread(&Matrix<T>::_sumLine, i, std::ref(resultMatrix), std::ref(*this), std::ref(other)); } } else if (operation.compare(MULT) == 0) { for (unsigned int i = 0; i < resultMatrix._rows; ++i) { matrixRowsThreads[i] = std::thread(&Matrix<T>::_multLine, i, std::ref(resultMatrix), std::ref(*this), std::ref(other)); } } // Wait for the threads to calculate the matrix lines. for (ThreadsIterator it = matrixRowsThreads.begin(); it != matrixRowsThreads.end(); ++it) { (*it).join(); } } /** * Method for multiplying creating a line using multiplication in the parallel mode. * @param lineNumber - the line in the result matrix we currently compute. * @param multMatrix - the result matrix to be created. * @param firstM - the first matrix to multiply. * @param secondM - the second matrix to multiply. */ std::mutex m; template <typename T> inline void Matrix<T>::_multLine(int lineNumber, Matrix<T>& multMatrix, const Matrix<T>& firstM, const Matrix<T>& secondM) { for (unsigned int j = 0; j < multMatrix._cols; ++j) { // Multiply the first matrix row by the second matrix column. multMatrix(lineNumber, j) = T(); T tempCellVal = T(); for (unsigned int k = 0; k < firstM._cols; ++k) { tempCellVal += (firstM(lineNumber, k)) * (secondM(k, j)); } m.lock(); multMatrix(lineNumber, j) = tempCellVal; m.unlock(); } } /** * Method for summing creating a line using summation in the parallel mode. * @param lineNumber - the line in the result matrix we currently compute. * @param multMatrix - the result matrix to be created. * @param firstM - the first matrix to multiply. * @param secondM - the second matrix to multiply. */ template <typename T> inline void Matrix<T>::_sumLine(int lineNumber, Matrix<T>& sumMatrix, const Matrix<T>& firstM, const Matrix<T>& secondM) { std::lock_guard<std::mutex> lk(m); for (unsigned int j = 0; j < sumMatrix._cols; ++j) { sumMatrix(lineNumber, j) = (firstM(lineNumber, j)) + (secondM(lineNumber, j)); } } #endif //MATRIX_HPP
[ "orib@cs.huji.ac.il" ]
orib@cs.huji.ac.il
9b9fee3ac0f9e6c297c105cab18f1c29b0494dcd
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/gdb/gdb-7.8.2/gdb/cp-abi.h
7d4b7f309026bcd0e58ff8cb4329a137f8d2e1e3
[ "GPL-3.0-or-later", "GPL-1.0-or-later", "BSD-3-Clause", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "AGPL-3.0-or-later", "LGPL-3.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-other-copyleft", "GPL-2.0-only", "LGPL-2.0-only", ...
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
9,714
h
/* Abstraction of various C++ ABI's we support, and the info we need to get from them. Contributed by Daniel Berlin <dberlin@redhat.com> Copyright (C) 2001-2014 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CP_ABI_H_ #define CP_ABI_H_ 1 struct fn_field; struct type; struct value; struct ui_file; struct frame_info; /* The functions here that attempt to determine what sort of thing a mangled name refers to may well be revised in the future. It would certainly be cleaner to carry this information explicitly in GDB's data structures than to derive it from the mangled name. */ /* Kinds of constructors. All these values are guaranteed to be non-zero. */ enum ctor_kinds { /* Initialize a complete object, including virtual bases, using memory provided by caller. */ complete_object_ctor = 1, /* Initialize a base object of some larger object. */ base_object_ctor, /* An allocating complete-object constructor. */ complete_object_allocating_ctor }; /* Return non-zero iff NAME is the mangled name of a constructor. Actually, return an `enum ctor_kind' value describing what *kind* of constructor it is. */ extern enum ctor_kinds is_constructor_name (const char *name); /* Kinds of destructors. All these values are guaranteed to be non-zero. */ enum dtor_kinds { /* A destructor which finalizes the entire object, and then calls `delete' on its storage. */ deleting_dtor = 1, /* A destructor which finalizes the entire object, but does not call `delete'. */ complete_object_dtor, /* A destructor which finalizes a subobject of some larger object. */ base_object_dtor }; /* Return non-zero iff NAME is the mangled name of a destructor. Actually, return an `enum dtor_kind' value describing what *kind* of destructor it is. */ extern enum dtor_kinds is_destructor_name (const char *name); /* Return non-zero iff NAME is the mangled name of a vtable. */ extern int is_vtable_name (const char *name); /* Return non-zero iff NAME is the un-mangled name of an operator, perhaps scoped within some class. */ extern int is_operator_name (const char *name); /* Return an object's virtual function as a value. VALUEP is a pointer to a pointer to a value, holding the object whose virtual function we want to invoke. If the ABI requires a virtual function's caller to adjust the `this' pointer by an amount retrieved from the vtable before invoking the function (i.e., we're not using "vtable thunks" to do the adjustment automatically), then this function may set *VALUEP to point to a new object with an appropriately tweaked address. The J'th element of the overload set F is the virtual function of *VALUEP we want to invoke. TYPE is the base type of *VALUEP whose method we're invoking --- this is the type containing F. OFFSET is the offset of that base type within *VALUEP. */ extern struct value *value_virtual_fn_field (struct value **valuep, struct fn_field *f, int j, struct type *type, int offset); /* Try to find the run-time type of VALUE, using C++ run-time type information. Return the run-time type, or zero if we can't figure it out. If we do find the run-time type: - Set *FULL to non-zero if VALUE already contains the complete run-time object, not just some embedded base class of the object. - Set *TOP and *USING_ENC to indicate where the enclosing object starts relative to VALUE: - If *USING_ENC is zero, then *TOP is the offset from the start of the complete object to the start of the embedded subobject VALUE represents. In other words, the enclosing object starts at VALUE_ADDR (VALUE) + VALUE_OFFSET (VALUE) + value_embedded_offset (VALUE) + *TOP - If *USING_ENC is non-zero, then *TOP is the offset from the address of the complete object to the enclosing object stored in VALUE. In other words, the enclosing object starts at VALUE_ADDR (VALUE) + VALUE_OFFSET (VALUE) + *TOP. If VALUE's type and enclosing type are the same, then these two cases are equivalent. FULL, TOP, and USING_ENC can each be zero, in which case we don't provide the corresponding piece of information. */ extern struct type *value_rtti_type (struct value *value, int *full, int *top, int *using_enc); /* Compute the offset of the baseclass which is the INDEXth baseclass of class TYPE, for value at VALADDR (in host) at ADDRESS (in target), offset by EMBEDDED_OFFSET. VALADDR points to the raw contents of VAL. The result is the offset of the baseclass value relative to (the address of)(ARG) + OFFSET. */ extern int baseclass_offset (struct type *type, int index, const gdb_byte *valaddr, int embedded_offset, CORE_ADDR address, const struct value *val); /* Describe the target of a pointer to method. CONTENTS is the byte pattern representing the pointer to method. TYPE is the pointer to method type. STREAM is the stream to print it to. */ void cplus_print_method_ptr (const gdb_byte *contents, struct type *type, struct ui_file *stream); /* Return the size of a pointer to member function of type TO_TYPE. */ int cplus_method_ptr_size (struct type *to_type); /* Return the method which should be called by applying METHOD_PTR to *THIS_P, and adjust *THIS_P if necessary. */ struct value *cplus_method_ptr_to_value (struct value **this_p, struct value *method_ptr); /* Create the byte pattern in CONTENTS representing a pointer of type TYPE to member function at ADDRESS (if IS_VIRTUAL is 0) or with virtual table offset ADDRESS (if IS_VIRTUAL is 1). This is the opposite of cplus_method_ptr_to_value. */ void cplus_make_method_ptr (struct type *type, gdb_byte *CONTENTS, CORE_ADDR address, int is_virtual); /* Print the vtable for VALUE, if there is one. If there is no vtable, print a message, but do not throw. */ void cplus_print_vtable (struct value *value); /* Implement 'typeid': find the type info for VALUE, if possible. If the type info cannot be found, throw an exception. */ extern struct value *cplus_typeid (struct value *value); /* Return the type of 'typeid' for the current C++ ABI on the given architecture. */ extern struct type *cplus_typeid_type (struct gdbarch *gdbarch); /* Given a value which holds a pointer to a std::type_info, return the type which that type_info represents. Throw an exception if the type cannot be found. */ extern struct type *cplus_type_from_type_info (struct value *value); /* Given a value which holds a pointer to a std::type_info, return the name of the type which that type_info represents. Throw an exception if the type name cannot be found. The result is xmalloc'd and must be freed by the caller. */ extern char *cplus_typename_from_type_info (struct value *value); /* Determine if we are currently in a C++ thunk. If so, get the address of the routine we are thunking to and continue to there instead. */ CORE_ADDR cplus_skip_trampoline (struct frame_info *frame, CORE_ADDR stop_pc); /* Return non-zero if an argument of type TYPE should be passed by reference instead of value. */ extern int cp_pass_by_reference (struct type *type); struct cp_abi_ops { const char *shortname; const char *longname; const char *doc; /* ABI-specific implementations for the functions declared above. */ enum ctor_kinds (*is_constructor_name) (const char *name); enum dtor_kinds (*is_destructor_name) (const char *name); int (*is_vtable_name) (const char *name); int (*is_operator_name) (const char *name); struct value *(*virtual_fn_field) (struct value **arg1p, struct fn_field * f, int j, struct type * type, int offset); struct type *(*rtti_type) (struct value *v, int *full, int *top, int *using_enc); int (*baseclass_offset) (struct type *type, int index, const bfd_byte *valaddr, int embedded_offset, CORE_ADDR address, const struct value *val); void (*print_method_ptr) (const gdb_byte *contents, struct type *type, struct ui_file *stream); int (*method_ptr_size) (struct type *); void (*make_method_ptr) (struct type *, gdb_byte *, CORE_ADDR, int); struct value * (*method_ptr_to_value) (struct value **, struct value *); void (*print_vtable) (struct value *); struct value *(*get_typeid) (struct value *value); struct type *(*get_typeid_type) (struct gdbarch *gdbarch); struct type *(*get_type_from_type_info) (struct value *value); char *(*get_typename_from_type_info) (struct value *value); CORE_ADDR (*skip_trampoline) (struct frame_info *, CORE_ADDR); int (*pass_by_reference) (struct type *type); }; extern int register_cp_abi (struct cp_abi_ops *abi); extern void set_cp_abi_as_auto_default (const char *short_name); #endif
[ "lihuibin705@163.com" ]
lihuibin705@163.com
a1facb1de91d572574c28f6ff760903f9b5ab46f
879dc5681a36a3df9ae5a7244fa2d9af6bd346d7
/EUS/boole_22_34.cpp
f0850a5a88d11d4760851801fce2469ea8002b5c
[ "BSD-3-Clause" ]
permissive
gachet/booledeusto
9defdba424a64dc7cf7ccd3938d412e3e797552b
fdc110a9add4a5946fabc2055a533593932a2003
refs/heads/master
2022-01-18T21:27:26.810810
2014-01-30T15:20:23
2014-01-30T15:20:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,404
cpp
// Do not edit. This file is machine generated by the Resource DLL Wizard. //--------------------------------------------------------------------------- #define PACKAGE __declspec(package) #define USERC(FileName) extern PACKAGE _Dummy #define USERES(FileName) extern PACKAGE _Dummy #define USEFORMRES(FileName, FormName, AncestorName) extern PACKAGE _Dummy #pragma hdrstop int _turboFloat; //--------------------------------------------------------------------------- /*ITE*/ /*LCID:00000C0A:0000042D*/ /**/ /*ITE*/ /*DFMFileType*/ /*src\Boole2\V_Boole2.dfm*/ /*ITE*/ /*RCFileType*/ /*exe\boole_DRC.rc*/ /*ITE*/ /*RCFileType*/ /*src\res\mensajes.rc*/ //--------------------------------------------------------------------------- #pragma resource "src\Boole1\app.dfm" #pragma resource "src\Boole1\calc.dfm" #pragma resource "src\Boole1\uKarnaugh.dfm" #pragma resource "src\Boole1\ExpBool.dfm" #pragma resource "src\Boole1\FormasN.dfm" #pragma resource "src\Boole1\FormSimp.dfm" #pragma resource "src\Boole1\Main.dfm" #pragma resource "src\Boole1\NandNor.dfm" #pragma resource "src\Boole1\NuevoSC.dfm" #pragma resource "src\Boole1\SCCompac.dfm" #pragma resource "src\Boole1\TVComple.dfm" #pragma resource "src\Boole1\TVManual.dfm" #pragma resource "src\Boole2\FCalculando.dfm" #pragma resource "src\Boole2\ayuda.dfm" #pragma resource "src\Boole2\uLog.dfm" #pragma resource "src\Boole2\Unit15.dfm" #pragma resource "src\Boole2\Unit11.dfm" #pragma resource "src\Boole2\Unit12.dfm" #pragma resource "src\Boole2\Unit13.dfm" #pragma resource "src\Boole2\Unit14.dfm" #pragma resource "src\Boole2\Unit10.dfm" USEFORMRES("src\Boole2\V_Boole2.dfm", TForm); #pragma resource "src\Boole2\V_Boole2.dfm" #pragma resource "src\Boole2\Unit2.dfm" #pragma resource "src\Boole2\Unit3.dfm" #pragma resource "src\Boole2\Unit4.dfm" #pragma resource "src\Boole2\Unit5.dfm" #pragma resource "src\Boole2\Unit6.dfm" #pragma resource "src\Boole2\Unit8.dfm" #pragma resource "src\Boole2\Unit9.dfm" #pragma resource "src\Boole2\uSimulacion.dfm" #pragma resource "src\Boole2\Unit16.dfm" #pragma resource "src\Circuito\V_Imprimir.dfm" #pragma resource "src\Circuito\V_Circuito.dfm" #pragma resource "src\Comun\uTextoAsoc.dfm" USERC("exe\boole_DRC.rc"); USERC("src\res\mensajes.rc"); //--------------------------------------------------------------------------- #define DllEntryPoint
[ "luis.rodriguez@opendeusto.es" ]
luis.rodriguez@opendeusto.es
598c51e9415b85d7e488c6fabfb6c97ae7115f6a
d3f28e804167124ea95a208dabd82d32c7599b0c
/Func.cpp
d93491eb7f59d63995db79a37625fbc6d4b7e17e
[]
no_license
Vlad-ole/Parser_signal_finder
2912219e0fd361641f1771c3501536befa4f16d4
c378e514ddd4f2a0081ad5755090bd9fb2a3ca80
refs/heads/master
2020-05-29T08:46:04.440580
2017-06-30T08:01:29
2017-06-30T08:01:29
69,550,531
0
0
null
null
null
null
UTF-8
C++
false
false
3,261
cpp
#include <iostream> #include <vector> #include <sstream> #include "TF1.h" #include "TGraph.h" #include "Func.h" using namespace std; TGraph* gr0 = 0; double fit_exp(double *x, double *par) { double time = x[0] - par[2]; double fitval; if (time > 0) { fitval = par[0] + par[1] * exp(-time / par[3]); } else { fitval = par[0]; } return fitval; } //integral of signal vector<double> integral_vs_time(vector<double> yv, vector<double> baseline, double time_scale) { vector<double> yv_result; yv_result.resize(yv.size()); double summ = 0; for (int i = 0; i < yv.size(); i++) { summ += (yv[i] - baseline[i]); yv_result[i] = summ * time_scale; } return yv_result; } //find start and stop for future fitting vector< vector<double> > find_start_and_stop(vector<double> yv_der, double th, double time_scale, double dead_time) { vector<double> t_start_V; vector<double> t_stop_V; t_start_V.push_back(1000); // range 0 - 1000 ns is noisy double time_max = 60000; //ns double time_trigg = 0;//??? bool flag = true; double shift = 0;//ns int point_max = (int)(time_max / time_scale); for (int i = 0; i < point_max; i++) { if (yv_der[i] > th && flag) { t_stop_V.push_back(time_scale * i - shift); //[ns] flag = false; time_trigg = time_scale * i; } if (i * time_scale > (time_trigg + dead_time) && !flag) { flag = true; t_start_V.push_back(time_scale * i - shift); } if (yv_der[i] < th && flag && (i == point_max - 1)) { t_stop_V.push_back(time_scale * i); } } vector< vector<double> > result_v; result_v.push_back(t_start_V); result_v.push_back(t_stop_V); return result_v; } vector<double> find_s1_area(vector<double> xv, vector<double> yv, vector< vector<double> > t_start_stop_V, vector<double> baselineV_single) { vector<double> t_start_V = t_start_stop_V[0]; vector<double> t_stop_V = t_start_stop_V[1]; vector<double> result; result.resize(4); //cout << t_start_V.size() << "\t" << t_stop_V.size() << endl; //fit S1 signal if (t_stop_V[0] < 59000) { //cout << "gr0 in find_s1_area before creation" << gr0 << endl; gr0 = new TGraph(yv.size(), &xv[0], &yv[0]); TF1 fitFcn("fitFcn", fit_exp, t_stop_V[0], t_start_V[1], 4); //cout << "gr0 in find_s1_area after creation" << gr0 << endl; fitFcn.SetLineColor(3); fitFcn.SetParLimits(0, baselineV_single[0], baselineV_single[0]); fitFcn.SetParLimits(1, 0, 10); fitFcn.SetParLimits(2, t_stop_V[0], t_start_V[1]); fitFcn.SetParLimits(3, 150, 400);//ns fitFcn.SetParameter(0, baselineV_single[0]); fitFcn.SetParameter(1, 0.5); fitFcn.SetParameter(2, t_stop_V[0]); fitFcn.SetParameter(3, 100); //gr0.Fit("fitFcn", "R+"); gr0->Fit("fitFcn", "RQ"); result[0] = fitFcn.GetParameter(0); result[1] = fitFcn.GetParameter(1); result[2] = fitFcn.GetParameter(2); result[3] = fitFcn.GetParameter(3); //return fitFcn.GetParameter(1) * fitFcn.GetParameter(3); } return result; } double find_s2_area(vector<double> yv_integral, double time_scale) { //rough estimate of S2 double integral_max = 0; for (int i = (int)(60000 / time_scale); i < (int)(100000 / time_scale); i++) { if (yv_integral[i] > integral_max) integral_max = yv_integral[i]; } return integral_max; }
[ "Vlad-ole@mail.ru" ]
Vlad-ole@mail.ru
ffa754ad604b86a1c43fd641bb6f2e5e7d0b1558
eb017064e9d0e109c050942967e9863bd8589002
/Client/src/Client.cpp
8ad4417258984ddd240c261cfcfbe56f3f3d4c4d
[]
no_license
talkad/SPLASS3
5b265fab6bb645b12756d77a9e39b7b65250d8d3
04f6e053ff768de2ad71fed2db025bbf4929744c
refs/heads/master
2020-12-05T12:54:19.882261
2020-01-19T13:46:17
2020-01-19T13:46:17
232,116,699
0
0
null
2020-01-19T13:46:18
2020-01-06T14:21:45
Java
UTF-8
C++
false
false
1,621
cpp
#include <connectionHandler.h> #include <UserData.h> #include <thread> //#include <boost/asio.hpp> using std::string; void writeTask(ConnectionHandler* connectionHandler){ while (connectionHandler->isRunning()) { const short bufsize = 1024; char buf[bufsize]; std::cin.getline(buf, bufsize); string line(buf); string frameOut=connectionHandler->toStompFrame(line); connectionHandler->sendFrame(frameOut); if(line=="logout") { connectionHandler->terminate(); connectionHandler->close(); } } } void readTask(ConnectionHandler* connectionHandler){ while (connectionHandler->isRunning()) { if(connectionHandler->isConnected()) { string answer; if (!connectionHandler->getFrame(answer)) { break; } string sendMsg = connectionHandler->process(answer); if (sendMsg.length() > 0) { //there is a response to the server if (!connectionHandler->sendFrame(sendMsg)) { break; } } } } } using namespace boost; int main (int argc, char *argv[]) { ConnectionHandler* connection = new ConnectionHandler(); std::thread thread_1 = std::thread(writeTask, connection); std::thread thread_2 = std::thread(readTask, connection); thread_2.join(); thread_1.join(); delete connection; if(UserData::getInstance()!=nullptr) delete UserData::getInstance(); return 0; }
[ "talkad@post.bgu.ac.il" ]
talkad@post.bgu.ac.il
0e6cd347f1a37b5d49b1968c302f6c4e65c0828d
92ff6acf7f099a1511833a734898988990b5090c
/Program_Framework/Core/subSystem/Timer.h
8a414c3b1bdcf33845d9b6c33746e8e481c7ad87
[]
no_license
king1495/My_OpenGL_Program_Framework
db1fd023f7ada028d90955d69265a83b07520870
65f7d5ca1a0e0f42d3655f8d743c2f2bf1d33360
refs/heads/master
2020-08-27T00:15:39.880734
2020-02-19T09:25:21
2020-02-19T09:25:21
217,189,654
0
0
null
null
null
null
UTF-8
C++
false
false
664
h
#pragma once #include "ISubSystem.h" class Timer final : public ISubSystem { public: static Timer& GetInstance() { static Timer* _instance = new Timer(); return *_instance; } void Update() { _currentTime = glfwGetTime(); _elapsedTime = _currentTime - _oldTime; _oldTime = _currentTime; }; inline float GetElapsedTime(void) const { return _elapsedTime; } inline float GetTime(void) const { return _currentTime; } inline float GetFPS(void) { return 1.f / _elapsedTime; } private: double _oldTime; double _currentTime; double _elapsedTime; Timer() :_oldTime(0), _elapsedTime(0), _currentTime(0) {}; }; #define _Timer Timer::GetInstance()
[ "king1495@naver.com" ]
king1495@naver.com
9b545ce6494d85856b759a91647c36bb118a820e
59b45f9f8960084fe8247860ddfc584237f87066
/frameworks/runtime-src/Classes/AppDelegate.cpp
f61ae26d264debd909aa8a4c20df91431f42dea4
[]
no_license
zhengqiangzi/pai
e6756db7b8ef8e9a4ee7bb41433b9848aac936dc
183030f6d7dc29f84404ff797ebad98d769c90e9
refs/heads/master
2021-01-19T22:29:44.704723
2015-07-04T10:46:57
2015-07-04T10:46:57
38,530,689
0
0
null
null
null
null
UTF-8
C++
false
false
3,788
cpp
#include "AppDelegate.h" #include "SimpleAudioEngine.h" #include "jsb_cocos2dx_auto.hpp" #include "jsb_cocos2dx_ui_auto.hpp" #include "jsb_cocos2dx_studio_auto.hpp" #include "jsb_cocos2dx_builder_auto.hpp" #include "jsb_cocos2dx_spine_auto.hpp" #include "jsb_cocos2dx_extension_auto.hpp" #include "ui/jsb_cocos2dx_ui_manual.h" #include "cocostudio/jsb_cocos2dx_studio_manual.h" #include "cocosbuilder/js_bindings_ccbreader.h" #include "spine/jsb_cocos2dx_spine_manual.h" #include "extension/jsb_cocos2dx_extension_manual.h" #include "localstorage/js_bindings_system_registration.h" #include "chipmunk/js_bindings_chipmunk_registration.h" #include "jsb_opengl_registration.h" #include "network/XMLHTTPRequest.h" #include "network/jsb_websocket.h" #include "network/jsb_socketio.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/CCJavascriptJavaBridge.h" #endif USING_NS_CC; using namespace CocosDenshion; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { ScriptEngineManager::destroyInstance(); } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = GLView::createWithRect("xiaoxiong", Rect(0,0,900,640)); director->setOpenGLView(glview); } // turn on display FPS director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_all_cocos2dx_extension); sc->addRegisterCallback(register_cocos2dx_js_extensions); sc->addRegisterCallback(register_all_cocos2dx_extension_manual); sc->addRegisterCallback(jsb_register_chipmunk); sc->addRegisterCallback(jsb_register_system); sc->addRegisterCallback(JSB_register_opengl); sc->addRegisterCallback(register_all_cocos2dx_builder); sc->addRegisterCallback(register_CCBuilderReader); sc->addRegisterCallback(register_all_cocos2dx_ui); sc->addRegisterCallback(register_all_cocos2dx_ui_manual); sc->addRegisterCallback(register_all_cocos2dx_studio); sc->addRegisterCallback(register_all_cocos2dx_studio_manual); sc->addRegisterCallback(register_all_cocos2dx_spine); sc->addRegisterCallback(register_all_cocos2dx_spine_manual); sc->addRegisterCallback(MinXmlHttpRequest::_js_register); sc->addRegisterCallback(register_jsb_websocket); sc->addRegisterCallback(register_jsb_socketio); #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) sc->addRegisterCallback(JavascriptJavaBridge::_js_register); #endif sc->start(); ScriptEngineProtocol *engine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); ScriptingCore::getInstance()->runScript("main.js"); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { auto director = Director::getInstance(); director->stopAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_hide"); SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); SimpleAudioEngine::getInstance()->pauseAllEffects(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { auto director = Director::getInstance(); director->startAnimation(); director->getEventDispatcher()->dispatchCustomEvent("game_on_show"); SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); SimpleAudioEngine::getInstance()->resumeAllEffects(); }
[ "zhengqiangzi123@163.com" ]
zhengqiangzi123@163.com
525f5a4142042821bdb80d4c695abd7bfa50e825
93ad5d825d1f40a4080c33ba728951f4a36c9a21
/src/midi/tests/02-midi/05-notes/03-event-multicaster-tests.cpp
fe183c63ddb5673a97aa58c19c702e90bcd0c53b
[]
no_license
UCLeuvenLimburg/midi-project-student
38f4971529b9e4d1d0e4a8346fa11844e8b3dc41
dd19ca859073f0778ab9578d1545fc22383afdbd
refs/heads/master
2022-05-11T03:50:37.067059
2022-03-28T12:16:07
2022-03-28T12:16:07
171,903,152
1
11
null
2020-06-07T18:08:12
2019-02-21T16:08:13
Objective-C
UTF-8
C++
false
false
7,937
cpp
#ifdef TEST_BUILD #define CATCH_CONFIG_PREFIX_ALL #define TEST_CASE CATCH_TEST_CASE #include "tests/tests-util.h" #include <vector> #include <functional> using namespace testutils; std::unique_ptr<uint8_t[]> copy_string_to_char_array(const std::string& string) { auto result = std::make_unique<uint8_t[]>(string.size() + 1); for (size_t i = 0; i != string.size(); ++i) { result[i] = string[i]; } result[string.size()] = 0; return std::move(result); } TEST_CASE("Multicaster test, one receiver, one event (note on)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().note_on(midi::Duration(1), midi::Channel(2), midi::NoteNumber(3), 4).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.note_on(midi::Duration(1), midi::Channel(2), midi::NoteNumber(3), 4); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (note off)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().note_off(midi::Duration(1), midi::Channel(2), midi::NoteNumber(3), 4).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.note_off(midi::Duration(1), midi::Channel(2), midi::NoteNumber(3), 4); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (polyphonic key pressure)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().polyphonic_key_pressure(midi::Duration(10), midi::Channel(5), midi::NoteNumber(20), 30).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.polyphonic_key_pressure(midi::Duration(10), midi::Channel(5), midi::NoteNumber(20), 30); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (control change)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().control_change(midi::Duration(5), midi::Channel(6), 7, 8).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.control_change(midi::Duration(5), midi::Channel(6), 7, 8); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (program change)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().program_change(midi::Duration(9), midi::Channel(6), midi::Instrument(3)).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.program_change(midi::Duration(9), midi::Channel(6), midi::Instrument(3)); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (channel pressure)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().channel_pressure(midi::Duration(8), midi::Channel(5), 2).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.channel_pressure(midi::Duration(8), midi::Channel(5), 2); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (pitch wheel change)") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().pitch_wheel_change(midi::Duration(1), midi::Channel(5), 9).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.pitch_wheel_change(midi::Duration(1), midi::Channel(5), 9); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, one event (meta)") { std::string data = "fjlsaq"; auto create_receiver = [&data]() { return std::shared_ptr<TestEventReceiver>(Builder().meta(midi::Duration(1), 9, data).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.meta(midi::Duration(1), 9, copy_string_to_char_array(data), data.size()); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, one receiver, two events") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>( Builder() .note_on(midi::Duration(0), midi::Channel(0), midi::NoteNumber(0), 255) .note_off(midi::Duration(10), midi::Channel(0), midi::NoteNumber(0), 255) .build() .release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.note_on(midi::Duration(0), midi::Channel(0), midi::NoteNumber(0), 255); multicaster.note_off(midi::Duration(10), midi::Channel(0), midi::NoteNumber(0), 255); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, two receivers, one event") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().note_on(midi::Duration(0), midi::Channel(0), midi::NoteNumber(0), 255).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver(), create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.note_on(midi::Duration(0), midi::Channel(0), midi::NoteNumber(0), 255); for (auto receiver : receivers) { receiver->check_finished(); } } TEST_CASE("Multicaster test, five receivers, one event") { auto create_receiver = []() { return std::shared_ptr<TestEventReceiver>(Builder().note_on(midi::Duration(1000), midi::Channel(1), midi::NoteNumber(0), 255).build().release()); }; std::vector<std::shared_ptr<TestEventReceiver>> receivers{ create_receiver(), create_receiver(), create_receiver(), create_receiver(), create_receiver() }; midi::EventMulticaster multicaster(std::vector<std::shared_ptr<midi::EventReceiver>>(receivers.begin(), receivers.end())); multicaster.note_on(midi::Duration(1000), midi::Channel(1), midi::NoteNumber(0), 255); for (auto receiver : receivers) { receiver->check_finished(); } } #endif
[ "frederic.vogels@ucll.be" ]
frederic.vogels@ucll.be
9faf5de5cf5d5dce915aad2b0cbb105757b57dc1
73109b10cf5b40d704978914cd84bdc1800a4072
/security.cpp
87f7984691f6f9dd6ffd3cd44576c8a9256be15e
[]
no_license
TejaSaiInala/Elevator-Simulator
ac91d104e4f1469be8be7be1e31f3b5e5769515e
552fb59e4b9c874107b17886da5094e9ab8791c4
refs/heads/main
2023-02-19T05:09:16.911591
2021-01-16T22:28:20
2021-01-16T22:28:20
330,269,814
0
0
null
null
null
null
UTF-8
C++
false
false
820
cpp
#include "security.h" int security::cntSec = 0; security::security() { counterIncrementor(); securityID = "SE" + to_string(cntSec); } void security::introduce() { cout << "Security function called \n"; cout << "Security ID: " << securityID << endl; cout << "Current Floor: " << getCurrFloor() << endl; cout << "Destination Floor: " << getDesFloor() << endl; cout << "Weightage: " << getWeightage() << endl; //cout << "Creation Time: " << 1 + getCreationTime().tm_hour << ":"; //cout << 1 + getCreationTime().tm_min << ":"; //cout << 1 + getCreationTime().tm_sec << endl << endl; } void security::evacuate() { } void security::counterIncrementor() { cntSec++; } int security::getCounter() { //cout << "Idhar kya value hai " << cntSec << endl; return cntSec; }
[ "noreply@github.com" ]
TejaSaiInala.noreply@github.com
4d10e57b526720f420efb3e61da679acbc90ae7a
469176a1cbce6090f2a168862442eb0277403f75
/faceSwap/src/main/jni/dlib/dnn/cudnn_dlibapi.cpp
80fecaef663ce36bc40e5e3a421b0f056444ad51
[ "Apache-2.0", "BSL-1.0" ]
permissive
adunye/Face-Swap-Android
a208798743c55f4f3c5f249cc8b6f52c02977057
7c203d6ef17dbff9d8be538dbfb2c2757ee446ae
refs/heads/master
2020-03-28T03:44:26.905917
2018-09-06T17:30:41
2018-09-06T17:30:41
147,667,717
0
0
Apache-2.0
2018-09-06T12:07:30
2018-09-06T12:07:30
null
UTF-8
C++
false
false
58,677
cpp
// Copyright (C) 2015 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_DNN_CuDNN_CPP_ #define DLIB_DNN_CuDNN_CPP_ #ifdef DLIB_USE_CUDA #include "cudnn_dlibapi.h" #include "tensor.h" #include <cudnn.h> #include <iostream> #include <string> #include "cuda_utils.h" #include "cpu_dlib.h" #include "cuda_dlib.h" #include "tensor_tools.h" static const char* cudnn_get_error_string(cudnnStatus_t s) { switch(s) { case CUDNN_STATUS_NOT_INITIALIZED: return "CUDA Runtime API initialization failed."; case CUDNN_STATUS_ALLOC_FAILED: return "CUDA Resources could not be allocated."; case CUDNN_STATUS_BAD_PARAM: return "CUDNN_STATUS_BAD_PARAM"; case CUDNN_STATUS_EXECUTION_FAILED: return "CUDNN_STATUS_EXECUTION_FAILED"; case CUDNN_STATUS_NOT_SUPPORTED: return "CUDNN_STATUS_NOT_SUPPORTED"; default: return "A call to cuDNN failed"; } } // Check the return value of a call to the cuDNN runtime for an error condition. #define CHECK_CUDNN(call) \ do{ \ const cudnnStatus_t error = call; \ if (error != CUDNN_STATUS_SUCCESS) \ { \ std::ostringstream sout; \ sout << "Error while calling " << #call << " in file " << __FILE__ << ":" << __LINE__ << ". ";\ sout << "code: " << error << ", reason: " << cudnn_get_error_string(error);\ throw dlib::cudnn_error(sout.str()); \ } \ }while(false) namespace dlib { namespace cuda { // ------------------------------------------------------------------------------------ static cudnnTensorDescriptor_t descriptor(const tensor& t) { return (const cudnnTensorDescriptor_t)t.get_cudnn_tensor_descriptor().get_handle(); } static cudnnTensorDescriptor_t descriptor(const tensor_descriptor& t) { return (const cudnnTensorDescriptor_t)t.get_handle(); } // ------------------------------------------------------------------------------------ class cudnn_context { public: // not copyable cudnn_context(const cudnn_context&) = delete; cudnn_context& operator=(const cudnn_context&) = delete; cudnn_context() { CHECK_CUDNN(cudnnCreate(&handle)); CHECK_CUDA(cudaGetDevice(&device_id)); } ~cudnn_context() { cudnnDestroy(handle); } cudnnHandle_t get_handle ( ) { // Check if the active device for the current thread changed. If so then // regenerate our cuDNN handle so it will use the currently selected // device. int new_device_id; CHECK_CUDA(cudaGetDevice(&new_device_id)); if (new_device_id != device_id) { CHECK_CUDNN(cudnnDestroy(handle)); CHECK_CUDNN(cudnnCreate(&handle)); } return handle; } private: cudnnHandle_t handle; int device_id; }; static cudnnHandle_t context() { thread_local cudnn_context c; return c.get_handle(); } // ------------------------------------------------------------------------------------ class cudnn_activation_descriptor { public: // not copyable cudnn_activation_descriptor(const cudnn_activation_descriptor&) = delete; cudnn_activation_descriptor& operator=(const cudnn_activation_descriptor&) = delete; cudnn_activation_descriptor( cudnnActivationMode_t mode, cudnnNanPropagation_t reluNanOpt, double reluCeiling ) { CHECK_CUDNN(cudnnCreateActivationDescriptor(&handle)); CHECK_CUDNN(cudnnSetActivationDescriptor(handle, mode, reluNanOpt, reluCeiling)); } ~cudnn_activation_descriptor() { cudnnDestroyActivationDescriptor(handle); } cudnnActivationDescriptor_t get_handle ( ) { return handle; } private: cudnnActivationDescriptor_t handle; }; static cudnnActivationDescriptor_t relu_activation_descriptor() { thread_local cudnn_activation_descriptor des(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN,0); return des.get_handle(); } static cudnnActivationDescriptor_t sigmoid_activation_descriptor() { thread_local cudnn_activation_descriptor des(CUDNN_ACTIVATION_SIGMOID, CUDNN_PROPAGATE_NAN,0); return des.get_handle(); } static cudnnActivationDescriptor_t tanh_activation_descriptor() { thread_local cudnn_activation_descriptor des(CUDNN_ACTIVATION_TANH, CUDNN_PROPAGATE_NAN,0); return des.get_handle(); } // ------------------------------------------------------------------------------------ tensor_descriptor:: tensor_descriptor( ) : handle(nullptr) { } tensor_descriptor:: ~tensor_descriptor() { set_size(0,0,0,0); } void tensor_descriptor:: set_size( int n, int k, int nr, int nc ) { if (n == 0 || nr == 0 || nc == 0 || k == 0) { if (handle) { cudnnDestroyTensorDescriptor((cudnnTensorDescriptor_t)handle); handle = nullptr; } } else { cudnnTensorDescriptor_t h; CHECK_CUDNN(cudnnCreateTensorDescriptor(&h)); handle = h; CHECK_CUDNN(cudnnSetTensor4dDescriptor((cudnnTensorDescriptor_t)handle, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, k, nr, nc)); } } void tensor_descriptor:: get_size ( int& n, int& k, int& nr, int& nc ) const { if (handle) { int nStride, cStride, hStride, wStride; cudnnDataType_t datatype; CHECK_CUDNN(cudnnGetTensor4dDescriptor((cudnnTensorDescriptor_t)handle, &datatype, &n, &k, &nr, &nc, &nStride, &cStride, &hStride, &wStride)); } else { n = 0; k = 0; nr = 0; nc = 0; } } // ------------------------------------------------------------------------------------ void add( float beta, tensor& dest, float alpha, const tensor& src ) { DLIB_CASSERT( (have_same_dimensions(src, dest) || (src.num_samples()==1 && src.k()==dest.k() && src.nr()==1 && src.nc()==1) || (src.num_samples()==1 && src.k()==dest.k() && src.nr()==dest.nr() && src.nc()==dest.nc()) || (src.num_samples()==1 && src.k()==1 && src.nr()==dest.nr() && src.nc()==dest.nc())) && is_same_object(src,dest) == false , "\n\t dest.num_samples(): " << dest.num_samples() <<"\n\t dest.k(): " << dest.k() <<"\n\t dest.nr(): " << dest.nr() <<"\n\t dest.nc(): " << dest.nc() <<"\n\t src.num_samples(): " << src.num_samples() <<"\n\t src.k(): " << src.k() <<"\n\t src.nr(): " << src.nr() <<"\n\t src.nc(): " << src.nc() ); if (dest.size() == src.size() && beta == 1) { // Call the dlib function in this case since it's faster than the one that // comes with cuDNN (at least as of cuDNN v4). add_scaled(dest, alpha, src); return; } CHECK_CUDNN(cudnnAddTensor(context(), &alpha, descriptor(src), src.device(), &beta, descriptor(dest), dest.device())); } void set_tensor ( tensor& t, float value ) { if (t.size() == 0) return; CHECK_CUDNN(cudnnSetTensor(context(), descriptor(t), t.device_write_only(), &value)); } void scale_tensor ( tensor& t, float value ) { if (t.size() == 0) return; CHECK_CUDNN(cudnnScaleTensor(context(), descriptor(t), t.device(), &value)); } void assign_conv_bias_gradient ( tensor& grad, const tensor& gradient_input ) { DLIB_CASSERT( grad.num_samples() == 1 && grad.k() >= 1 && grad.nr() == 1 && grad.nc() == 1 && gradient_input.k() == grad.k() && gradient_input.size() > 0 && is_same_object(grad,gradient_input) == false ,""); const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnConvolutionBackwardBias(context(), &alpha, descriptor(gradient_input), gradient_input.device(), &beta, descriptor(grad), grad.device())); } // ------------------------------------------------------------------------------------ void batch_normalize_inference ( const double eps, resizable_tensor& dest, const tensor& src, const tensor& gamma, const tensor& beta, const tensor& running_means, const tensor& running_variances ) { DLIB_CASSERT( gamma.num_samples() == 1 && gamma.nr() == src.nr() && gamma.nc() == src.nc() && gamma.k() == src.k() && have_same_dimensions(gamma, beta) && have_same_dimensions(gamma, running_means) && have_same_dimensions(gamma, running_variances) && eps > 0, "\ngamma.num_samples(): " << gamma.num_samples() << "\ngamma.k(): " << gamma.k() << "\ngamma.nr(): " << gamma.nr() << "\ngamma.nc(): " << gamma.nc() << "\nbeta.num_samples(): " << beta.num_samples() << "\nbeta.k(): " << beta.k() << "\nbeta.nr(): " << beta.nr() << "\nbeta.nc(): " << beta.nc() << "\nrunning_means.num_samples(): " << running_means.num_samples() << "\nrunning_means.k(): " << running_means.k() << "\nrunning_means.nr(): " << running_means.nr() << "\nrunning_means.nc(): " << running_means.nc() << "\nrunning_variances.num_samples(): " << running_variances.num_samples() << "\nrunning_variances.k(): " << running_variances.k() << "\nrunning_variances.nr(): " << running_variances.nr() << "\nrunning_variances.nc(): " << running_variances.nc() << "\nsrc.k(): " << src.k() << "\nsrc.nr(): " << src.nr() << "\nsrc.nc(): " << src.nc() << "\neps: " << eps ); const float in_scale = 1; const float out_scale = 0; dest.copy_size(src); CHECK_CUDNN(cudnnBatchNormalizationForwardInference( context(), CUDNN_BATCHNORM_PER_ACTIVATION, &in_scale, &out_scale, descriptor(src), src.device(), descriptor(dest), dest.device(), descriptor(gamma), gamma.device(), beta.device(), running_means.device(), running_variances.device(), eps)); } void batch_normalize ( const double eps, resizable_tensor& dest, resizable_tensor& means, resizable_tensor& invstds, const double averaging_factor, resizable_tensor& running_means, resizable_tensor& running_variances, const tensor& src, const tensor& gamma, const tensor& beta ) { DLIB_CASSERT(0 <= averaging_factor && averaging_factor <= 1, "averaging_factor: " << averaging_factor); DLIB_CASSERT(averaging_factor==1 || have_same_dimensions(running_means,means),""); DLIB_CASSERT(averaging_factor==1 || have_same_dimensions(running_variances,invstds),""); DLIB_CASSERT( src.num_samples() > 1 && gamma.num_samples() == 1 && beta.num_samples() == 1 && gamma.nr() == beta.nr() && beta.nr() == src.nr() && gamma.nc() == beta.nc() && beta.nc() == src.nc() && gamma.k() == beta.k() && beta.k() == src.k() && eps > 0, "\ngamma.num_samples(): " << gamma.num_samples() << "\ngamma.k(): " << gamma.k() << "\ngamma.nr(): " << gamma.nr() << "\ngamma.nc(): " << gamma.nc() << "\nbeta.num_samples(): " << beta.num_samples() << "\nbeta.k(): " << beta.k() << "\nbeta.nr(): " << beta.nr() << "\nbeta.nc(): " << beta.nc() << "\nsrc.k(): " << src.k() << "\nsrc.nr(): " << src.nr() << "\nsrc.nc(): " << src.nc() << "\neps: " << eps ); const float in_scale = 1; const float out_scale = 0; dest.copy_size(src); means.set_size(1, src.k(), src.nr(), src.nc()); invstds.copy_size(means); running_means.copy_size(means); running_variances.copy_size(means); CHECK_CUDNN(cudnnBatchNormalizationForwardTraining( context(), CUDNN_BATCHNORM_PER_ACTIVATION, &in_scale, &out_scale, descriptor(src), src.device(), descriptor(dest), dest.device(), descriptor(gamma), gamma.device(), beta.device(), averaging_factor, running_means.device(), running_variances.device(), eps, means.device(), invstds.device())); } void batch_normalize_gradient( const double eps, const tensor& gradient_input, const tensor& means, const tensor& invstds, const tensor& src, const tensor& gamma, tensor& src_grad, tensor& gamma_grad, tensor& beta_grad ) { const long num = src.k()*src.nr()*src.nc(); DLIB_CASSERT(src.num_samples() > 1, ""); DLIB_CASSERT(num == means.size(),""); DLIB_CASSERT(num == invstds.size(),""); DLIB_CASSERT(num == gamma.size(),""); DLIB_CASSERT(num == gamma_grad.size(),""); DLIB_CASSERT(num == beta_grad.size(),""); DLIB_CASSERT(have_same_dimensions(gradient_input, src),""); DLIB_CASSERT(have_same_dimensions(gradient_input, src_grad),""); DLIB_CASSERT(eps > 0,""); const float in_scale = 1; const float out_scale = 1; const float in_scale_params = 1; const float out_scale_params = 0; CHECK_CUDNN(cudnnBatchNormalizationBackward( context(), CUDNN_BATCHNORM_PER_ACTIVATION, &in_scale, &out_scale, &in_scale_params, &out_scale_params, descriptor(src), src.device(), descriptor(gradient_input), gradient_input.device(), descriptor(src_grad), src_grad.device(), descriptor(gamma), gamma.device(), gamma_grad.device(), beta_grad.device(), eps, means.device(), invstds.device())); } // ------------------------------------------------------------------------------------ void batch_normalize_conv_inference ( const double eps, resizable_tensor& dest, const tensor& src, const tensor& gamma, const tensor& beta, const tensor& running_means, const tensor& running_variances ) { DLIB_CASSERT( gamma.num_samples() == 1 && gamma.nr() == 1 && gamma.nc() == 1 && gamma.k() == src.k() && have_same_dimensions(gamma, beta) && have_same_dimensions(gamma, running_means) && have_same_dimensions(gamma, running_variances) && eps > 0, "\ngamma.num_samples(): " << gamma.num_samples() << "\ngamma.k(): " << gamma.k() << "\ngamma.nr(): " << gamma.nr() << "\ngamma.nc(): " << gamma.nc() << "\nbeta.num_samples(): " << beta.num_samples() << "\nbeta.k(): " << beta.k() << "\nbeta.nr(): " << beta.nr() << "\nbeta.nc(): " << beta.nc() << "\nrunning_means.num_samples(): " << running_means.num_samples() << "\nrunning_means.k(): " << running_means.k() << "\nrunning_means.nr(): " << running_means.nr() << "\nrunning_means.nc(): " << running_means.nc() << "\nrunning_variances.num_samples(): " << running_variances.num_samples() << "\nrunning_variances.k(): " << running_variances.k() << "\nrunning_variances.nr(): " << running_variances.nr() << "\nrunning_variances.nc(): " << running_variances.nc() << "\nsrc.k(): " << src.k() << "\nsrc.nr(): " << src.nr() << "\nsrc.nc(): " << src.nc() << "\neps: " << eps ); const float in_scale = 1; const float out_scale = 0; dest.copy_size(src); CHECK_CUDNN(cudnnBatchNormalizationForwardInference( context(), CUDNN_BATCHNORM_SPATIAL, &in_scale, &out_scale, descriptor(src), src.device(), descriptor(dest), dest.device(), descriptor(gamma), gamma.device(), beta.device(), running_means.device(), running_variances.device(), eps)); } void batch_normalize_conv ( const double eps, resizable_tensor& dest, resizable_tensor& means, resizable_tensor& invstds, const double averaging_factor, resizable_tensor& running_means, resizable_tensor& running_variances, const tensor& src, const tensor& gamma, const tensor& beta ) { DLIB_CASSERT(0 <= averaging_factor && averaging_factor <= 1, "averaging_factor: " << averaging_factor); DLIB_CASSERT(averaging_factor==1 || have_same_dimensions(running_means,means),""); DLIB_CASSERT(averaging_factor==1 || have_same_dimensions(running_variances,invstds),""); DLIB_CASSERT( src.num_samples() > 1 && gamma.num_samples() == 1 && beta.num_samples() == 1 && gamma.nr() == 1 && beta.nr() == 1 && gamma.nc() == 1 && beta.nc() == 1 && gamma.k() == beta.k() && beta.k() == src.k() && eps > 0, "\ngamma.num_samples(): " << gamma.num_samples() << "\ngamma.k(): " << gamma.k() << "\ngamma.nr(): " << gamma.nr() << "\ngamma.nc(): " << gamma.nc() << "\nbeta.num_samples(): " << beta.num_samples() << "\nbeta.k(): " << beta.k() << "\nbeta.nr(): " << beta.nr() << "\nbeta.nc(): " << beta.nc() << "\nsrc.k(): " << src.k() << "\nsrc.nr(): " << src.nr() << "\nsrc.nc(): " << src.nc() << "\neps: " << eps ); const float in_scale = 1; const float out_scale = 0; dest.copy_size(src); means.set_size(1, src.k()); invstds.copy_size(means); running_means.copy_size(means); running_variances.copy_size(means); CHECK_CUDNN(cudnnBatchNormalizationForwardTraining( context(), CUDNN_BATCHNORM_SPATIAL, &in_scale, &out_scale, descriptor(src), src.device(), descriptor(dest), dest.device(), descriptor(gamma), gamma.device(), beta.device(), averaging_factor, running_means.device(), running_variances.device(), eps, means.device(), invstds.device())); } void batch_normalize_conv_gradient( const double eps, const tensor& gradient_input, const tensor& means, const tensor& invstds, const tensor& src, const tensor& gamma, tensor& src_grad, tensor& gamma_grad, tensor& beta_grad ) { const long num = src.nr()*src.nc(); DLIB_CASSERT(src.k() == means.size(),""); DLIB_CASSERT(src.k() == invstds.size(),""); DLIB_CASSERT(src.k() == gamma.size(),""); DLIB_CASSERT(src.k() == gamma_grad.size(),""); DLIB_CASSERT(src.k() == beta_grad.size(),""); DLIB_CASSERT(have_same_dimensions(gradient_input, src),""); DLIB_CASSERT(have_same_dimensions(gradient_input, src_grad),""); DLIB_CASSERT(eps > 0,""); const float in_scale = 1; const float out_scale = 1; const float in_scale_params = 1; const float out_scale_params = 0; CHECK_CUDNN(cudnnBatchNormalizationBackward( context(), CUDNN_BATCHNORM_SPATIAL, &in_scale, &out_scale, &in_scale_params, &out_scale_params, descriptor(src), src.device(), descriptor(gradient_input), gradient_input.device(), descriptor(src_grad), src_grad.device(), descriptor(gamma), gamma.device(), gamma_grad.device(), beta_grad.device(), eps, means.device(), invstds.device())); } // ------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------ tensor_conv:: tensor_conv( ) : filter_handle(nullptr), conv_handle(nullptr), forward_algo(0), forward_workspace_size_in_bytes(0), forward_workspace(nullptr), backward_data_algo(0), backward_data_workspace_size_in_bytes(0), backward_data_workspace(nullptr), backward_filters_algo(0), backward_filters_workspace_size_in_bytes(0), backward_filters_workspace(nullptr) { clear(); } void tensor_conv:: clear ( ) { if (filter_handle) cudnnDestroyFilterDescriptor((cudnnFilterDescriptor_t)filter_handle); if (conv_handle) cudnnDestroyConvolutionDescriptor((cudnnConvolutionDescriptor_t)conv_handle); filter_handle = nullptr; conv_handle = nullptr; out_num_samples = 0; out_k = 0; out_nr = 0; out_nc = 0; if (forward_workspace) cudaFree(forward_workspace); forward_workspace = nullptr; forward_algo = 0; forward_workspace_size_in_bytes = 0; if (backward_data_workspace) cudaFree(backward_data_workspace); backward_data_workspace = nullptr; backward_data_algo = 0; backward_data_workspace_size_in_bytes = 0; if (backward_filters_workspace) cudaFree(backward_filters_workspace); backward_filters_workspace = nullptr; backward_filters_algo = 0; backward_filters_workspace_size_in_bytes = 0; stride_y = 0; stride_x = 0; padding_y = 0; padding_x = 0; data_num_samples = 0; data_k = 0; data_nr = 0; data_nc = 0; filters_num_samples = 0; filters_k = 0; filters_nr = 0; filters_nc = 0; } void tensor_conv:: setup( const tensor& data, const tensor& filters, int stride_y_, int stride_x_, int padding_y_, int padding_x_ ) { DLIB_CASSERT(data.k() == filters.k(),""); // if the last call to setup gave the same exact settings then don't do // anything. if (stride_y_ == stride_y && stride_x_ == stride_x && padding_y_ == padding_y && padding_x_ == padding_x && data_num_samples == data.num_samples() && data_k == data.k() && data_nr == data.nr() && data_nc == data.nc() && filters_num_samples == filters.num_samples() && filters_k == filters.k() && filters_nr == filters.nr() && filters_nc == filters.nc()) { return; } clear(); try { stride_y = stride_y_; stride_x = stride_x_; padding_y = padding_y_; padding_x = padding_x_; data_num_samples = data.num_samples(); data_k = data.k(); data_nr = data.nr(); data_nc = data.nc(); filters_num_samples = filters.num_samples(); filters_k = filters.k(); filters_nr = filters.nr(); filters_nc = filters.nc(); CHECK_CUDNN(cudnnCreateFilterDescriptor((cudnnFilterDescriptor_t*)&filter_handle)); CHECK_CUDNN(cudnnSetFilter4dDescriptor((cudnnFilterDescriptor_t)filter_handle, CUDNN_DATA_FLOAT, CUDNN_TENSOR_NCHW, filters.num_samples(), filters.k(), filters.nr(), filters.nc())); CHECK_CUDNN(cudnnCreateConvolutionDescriptor((cudnnConvolutionDescriptor_t*)&conv_handle)); CHECK_CUDNN(cudnnSetConvolution2dDescriptor((cudnnConvolutionDescriptor_t)conv_handle, padding_y, // vertical padding padding_x, // horizontal padding stride_y, stride_x, 1, 1, // must be 1,1 CUDNN_CROSS_CORRELATION)); // could also be CUDNN_CONVOLUTION CHECK_CUDNN(cudnnGetConvolution2dForwardOutputDim( (const cudnnConvolutionDescriptor_t)conv_handle, descriptor(data), (const cudnnFilterDescriptor_t)filter_handle, &out_num_samples, &out_k, &out_nr, &out_nc)); tensor_descriptor dest_desc; dest_desc.set_size(out_num_samples,out_k,out_nr,out_nc); // Pick which forward algorithm we will use and allocate the necessary // workspace buffer. cudnnConvolutionFwdAlgo_t forward_best_algo; CHECK_CUDNN(cudnnGetConvolutionForwardAlgorithm( context(), descriptor(data), (const cudnnFilterDescriptor_t)filter_handle, (const cudnnConvolutionDescriptor_t)conv_handle, descriptor(dest_desc), dnn_prefer_fastest_algorithms()?CUDNN_CONVOLUTION_FWD_PREFER_FASTEST:CUDNN_CONVOLUTION_FWD_NO_WORKSPACE, std::numeric_limits<size_t>::max(), &forward_best_algo)); forward_algo = forward_best_algo; CHECK_CUDNN(cudnnGetConvolutionForwardWorkspaceSize( context(), descriptor(data), (const cudnnFilterDescriptor_t)filter_handle, (const cudnnConvolutionDescriptor_t)conv_handle, descriptor(dest_desc), forward_best_algo, &forward_workspace_size_in_bytes)); CHECK_CUDA(cudaMalloc(&forward_workspace, forward_workspace_size_in_bytes)); // Pick which backward data algorithm we will use and allocate the // necessary workspace buffer. cudnnConvolutionBwdDataAlgo_t backward_data_best_algo; CHECK_CUDNN(cudnnGetConvolutionBackwardDataAlgorithm( context(), (const cudnnFilterDescriptor_t)filter_handle, descriptor(dest_desc), (const cudnnConvolutionDescriptor_t)conv_handle, descriptor(data), dnn_prefer_fastest_algorithms()?CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST:CUDNN_CONVOLUTION_BWD_DATA_NO_WORKSPACE, std::numeric_limits<size_t>::max(), &backward_data_best_algo)); backward_data_algo = backward_data_best_algo; CHECK_CUDNN(cudnnGetConvolutionBackwardDataWorkspaceSize( context(), (const cudnnFilterDescriptor_t)filter_handle, descriptor(dest_desc), (const cudnnConvolutionDescriptor_t)conv_handle, descriptor(data), backward_data_best_algo, &backward_data_workspace_size_in_bytes)); CHECK_CUDA(cudaMalloc(&backward_data_workspace, backward_data_workspace_size_in_bytes)); // Pick which backward filters algorithm we will use and allocate the // necessary workspace buffer. cudnnConvolutionBwdFilterAlgo_t backward_filters_best_algo; CHECK_CUDNN(cudnnGetConvolutionBackwardFilterAlgorithm( context(), descriptor(data), descriptor(dest_desc), (const cudnnConvolutionDescriptor_t)conv_handle, (const cudnnFilterDescriptor_t)filter_handle, dnn_prefer_fastest_algorithms()?CUDNN_CONVOLUTION_BWD_FILTER_PREFER_FASTEST:CUDNN_CONVOLUTION_BWD_FILTER_NO_WORKSPACE, std::numeric_limits<size_t>::max(), &backward_filters_best_algo)); backward_filters_algo = backward_filters_best_algo; CHECK_CUDNN(cudnnGetConvolutionBackwardFilterWorkspaceSize( context(), descriptor(data), descriptor(dest_desc), (const cudnnConvolutionDescriptor_t)conv_handle, (const cudnnFilterDescriptor_t)filter_handle, backward_filters_best_algo, &backward_filters_workspace_size_in_bytes)); CHECK_CUDA(cudaMalloc(&backward_filters_workspace, backward_filters_workspace_size_in_bytes)); } catch(...) { clear(); throw; } } tensor_conv:: ~tensor_conv ( ) { clear(); } void tensor_conv::operator() ( resizable_tensor& output, const tensor& data, const tensor& filters, int stride_y, int stride_x, int padding_y, int padding_x ) { DLIB_CASSERT(is_same_object(output,data) == false,""); DLIB_CASSERT(is_same_object(output,filters) == false,""); DLIB_CASSERT(filters.k() == data.k(),""); DLIB_CASSERT(stride_y > 0 && stride_x > 0,""); DLIB_CASSERT(filters.nc() <= data.nc() + 2*padding_x, "Filter windows must be small enough to fit into the padded image." << "\n\t filters.nc(): " << filters.nc() << "\n\t data.nc(): " << data.nc() << "\n\t padding_x: " << padding_x ); DLIB_CASSERT(filters.nr() <= data.nr() + 2*padding_y, "Filter windows must be small enough to fit into the padded image." << "\n\t filters.nr(): " << filters.nr() << "\n\t data.nr(): " << data.nr() << "\n\t padding_y: " << padding_y ); setup(data,filters,stride_y,stride_x,padding_y,padding_x); output.set_size(out_num_samples, out_k, out_nr, out_nc); DLIB_ASSERT(output.num_samples() == data.num_samples(),out_num_samples << " " << data.num_samples()); DLIB_ASSERT(output.k() == filters.num_samples(),""); DLIB_ASSERT(output.nr() == 1+(data.nr()+2*padding_y-filters.nr())/stride_y,""); DLIB_ASSERT(output.nc() == 1+(data.nc()+2*padding_x-filters.nc())/stride_x,""); const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnConvolutionForward( context(), &alpha, descriptor(data), data.device(), (const cudnnFilterDescriptor_t)filter_handle, filters.device(), (const cudnnConvolutionDescriptor_t)conv_handle, (cudnnConvolutionFwdAlgo_t)forward_algo, forward_workspace, forward_workspace_size_in_bytes, &beta, descriptor(output), output.device())); } void tensor_conv::get_gradient_for_data ( const tensor& gradient_input, const tensor& filters, tensor& data_gradient ) { const float alpha = 1; const float beta = 1; CHECK_CUDNN(cudnnConvolutionBackwardData(context(), &alpha, (const cudnnFilterDescriptor_t)filter_handle, filters.device(), descriptor(gradient_input), gradient_input.device(), (const cudnnConvolutionDescriptor_t)conv_handle, (cudnnConvolutionBwdDataAlgo_t)backward_data_algo, backward_data_workspace, backward_data_workspace_size_in_bytes, &beta, descriptor(data_gradient), data_gradient.device())); } void tensor_conv:: get_gradient_for_filters ( const tensor& gradient_input, const tensor& data, tensor& filters_gradient ) { const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnConvolutionBackwardFilter(context(), &alpha, descriptor(data), data.device(), descriptor(gradient_input), gradient_input.device(), (const cudnnConvolutionDescriptor_t)conv_handle, (cudnnConvolutionBwdFilterAlgo_t)backward_filters_algo, backward_filters_workspace, backward_filters_workspace_size_in_bytes, &beta, (const cudnnFilterDescriptor_t)filter_handle, filters_gradient.device())); } // ------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------ pooling::pooling ( ) : handle(nullptr),window_height(0),window_width(0),stride_y(0),stride_x(0),padding_y(0), padding_x(0) { } pooling::~pooling( ) { clear(); } void pooling:: clear( ) { if (handle) cudnnDestroyPoolingDescriptor((cudnnPoolingDescriptor_t)handle); handle = nullptr; window_height = 0; window_width = 0; stride_y = 0; stride_x = 0; padding_y = 0; padding_x = 0; } void pooling:: setup_max_pooling( int window_height_, int window_width_, int stride_y_, int stride_x_, int padding_y_, int padding_x_ ) { setup(window_height_, window_width_, stride_y_, stride_x_, padding_y_, padding_x_, CUDNN_POOLING_MAX); do_max_pooling = true; } void pooling:: setup_avg_pooling( int window_height_, int window_width_, int stride_y_, int stride_x_, int padding_y_, int padding_x_ ) { setup(window_height_, window_width_, stride_y_, stride_x_, padding_y_, padding_x_, CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING); do_max_pooling = false; } void pooling:: setup( int window_height_, int window_width_, int stride_y_, int stride_x_, int padding_y_, int padding_x_, int pooling_mode ) { DLIB_CASSERT (window_height_ > 0 && window_width_ > 0 && stride_y_ > 0 && stride_x_ > 0 , "window_height_: " << window_height_ << "\t\n window_width_: " << window_width_ << "\t\n stride_y_: " << stride_y_ << "\t\n stride_x_: " << stride_x_ ); DLIB_CASSERT( 0 <= padding_y_ && padding_y_ < window_height_ && 0 <= padding_x_ && padding_x_ < window_width_, "window_height_: " << window_height_ << "\t\n window_width_: " << window_width_ << "\t\n padding_y_: " << padding_y_ << "\t\n padding_x_: " << padding_x_ ); if (window_height == window_height_ && window_width == window_width_ && stride_y == stride_y_ && stride_x == stride_x_ && padding_y == padding_y_ && padding_x == padding_x_ ) { return; } clear(); try { window_height = window_height_; window_width = window_width_; stride_x = stride_x_; stride_y = stride_y_; padding_y = padding_y_; padding_x = padding_x_; cudnnPoolingDescriptor_t poolingDesc; CHECK_CUDNN(cudnnCreatePoolingDescriptor(&poolingDesc)); handle = poolingDesc; CHECK_CUDNN(cudnnSetPooling2dDescriptor(poolingDesc, (cudnnPoolingMode_t)pooling_mode, CUDNN_PROPAGATE_NAN, window_height, window_width, padding_y, padding_x, stride_y, stride_x)); } catch(...) { clear(); throw; } } void pooling:: operator() ( resizable_tensor& dest, const tensor& src ) { DLIB_CASSERT(window_width <= src.nc() + 2*padding_x, "Pooling windows must be small enough to fit into the padded image." << "\n\t window_width: " << window_width << "\n\t src.nc(): " << src.nc() << "\n\t padding_x: " << padding_x ); DLIB_CASSERT(window_height <= src.nr() + 2*padding_y, "Pooling windows must be small enough to fit into the padded image." << "\n\t window_height: " << window_height << "\n\t src.nr(): " << src.nr() << "\n\t padding_y: " << padding_y ); const float alpha = 1; const float beta = 0; int outN; int outC; int outH; int outW; CHECK_CUDNN(cudnnGetPooling2dForwardOutputDim((const cudnnPoolingDescriptor_t)handle, descriptor(src), &outN, &outC, &outH, &outW)); dest.set_size(outN,outC,outH,outW); DLIB_CASSERT(dest.num_samples() == src.num_samples(),""); DLIB_CASSERT(dest.k() == src.k(),""); DLIB_CASSERT(dest.nr() == 1 + (src.nr() + 2*padding_y - window_height)/stride_y, "\n stride_y: " << stride_y << "\n padding_y: " << padding_y << "\n window_height: " << window_height << "\n src.nr(): " << src.nr() << "\n dest.nr(): " << dest.nr() << "\n src.nr()/stride_y: " << src.nr()/stride_y); DLIB_CASSERT(dest.nc() == 1 + (src.nc() + 2*padding_x - window_width)/stride_x, "\n stride_x: " << stride_x << "\n padding_x: " << padding_x << "\n window_width: " << window_width << "\n src.nc(): " << src.nc() << "\n dest.nc(): " << dest.nc() << "\n src.nc()/stride_x: " << src.nc()/stride_x); CHECK_CUDNN(cudnnPoolingForward(context(), (const cudnnPoolingDescriptor_t)handle, &alpha, descriptor(src), src.device(), &beta, descriptor(dest), dest.device())); } void pooling::get_gradient( const tensor& gradient_input, const tensor& dest, const tensor& src, tensor& grad ) { DLIB_CASSERT(have_same_dimensions(gradient_input,dest),""); DLIB_CASSERT(have_same_dimensions(src,grad),""); const float alpha = 1; const float beta = 1; CHECK_CUDNN(cudnnPoolingBackward(context(), (const cudnnPoolingDescriptor_t)handle, &alpha, descriptor(dest), dest.device(), descriptor(gradient_input), gradient_input.device(), descriptor(src), src.device(), &beta, descriptor(grad), grad.device())); } // ------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------ void softmax ( tensor& dest, const tensor& src ) { DLIB_CASSERT(have_same_dimensions(dest,src),""); if (src.size() == 0) return; const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnSoftmaxForward(context(), CUDNN_SOFTMAX_ACCURATE, CUDNN_SOFTMAX_MODE_CHANNEL, &alpha, descriptor(src), src.device(), &beta, descriptor(dest), dest.device())); } void softmax_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ) { DLIB_CASSERT( have_same_dimensions(dest,gradient_input) == true && have_same_dimensions(dest,grad) == true , ""); if (dest.size() == 0) return; const float alpha = 1; const float beta = is_same_object(grad,gradient_input) ? 0 : 1; CHECK_CUDNN(cudnnSoftmaxBackward(context(), CUDNN_SOFTMAX_ACCURATE, CUDNN_SOFTMAX_MODE_CHANNEL, &alpha, descriptor(dest), dest.device(), descriptor(gradient_input), gradient_input.device(), &beta, descriptor(grad), grad.device())); } // ------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------ void sigmoid ( tensor& dest, const tensor& src ) { DLIB_CASSERT(have_same_dimensions(dest,src),""); if (src.size() == 0) return; const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnActivationForward(context(), sigmoid_activation_descriptor(), &alpha, descriptor(src), src.device(), &beta, descriptor(dest), dest.device())); } void sigmoid_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ) { DLIB_CASSERT( have_same_dimensions(dest,gradient_input) == true && have_same_dimensions(dest,grad) == true , ""); if (dest.size() == 0) return; const float alpha = 1; const float beta = is_same_object(grad,gradient_input) ? 0 : 1; CHECK_CUDNN(cudnnActivationBackward(context(), sigmoid_activation_descriptor(), &alpha, descriptor(dest), dest.device(), descriptor(gradient_input), gradient_input.device(), descriptor(dest), dest.device(), &beta, descriptor(grad), grad.device())); } // ------------------------------------------------------------------------------------ void relu ( tensor& dest, const tensor& src ) { DLIB_CASSERT(have_same_dimensions(dest,src),""); if (src.size() == 0) return; const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnActivationForward(context(), relu_activation_descriptor(), &alpha, descriptor(src), src.device(), &beta, descriptor(dest), dest.device())); } void relu_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ) { DLIB_CASSERT( have_same_dimensions(dest,gradient_input) == true && have_same_dimensions(dest,grad) == true , ""); if (dest.size() == 0) return; const float alpha = 1; const float beta = is_same_object(grad,gradient_input) ? 0 : 1; CHECK_CUDNN(cudnnActivationBackward(context(), relu_activation_descriptor(), &alpha, descriptor(dest), dest.device(), descriptor(gradient_input), gradient_input.device(), descriptor(dest), dest.device(), &beta, descriptor(grad), grad.device())); } // ------------------------------------------------------------------------------------ void tanh ( tensor& dest, const tensor& src ) { DLIB_CASSERT(have_same_dimensions(dest,src),""); if (src.size() == 0) return; const float alpha = 1; const float beta = 0; CHECK_CUDNN(cudnnActivationForward(context(), tanh_activation_descriptor(), &alpha, descriptor(src), src.device(), &beta, descriptor(dest), dest.device())); } void tanh_gradient ( tensor& grad, const tensor& dest, const tensor& gradient_input ) { DLIB_CASSERT( have_same_dimensions(dest,gradient_input) == true && have_same_dimensions(dest,grad) == true, ""); if (dest.size() == 0) return; const float alpha = 1; const float beta = is_same_object(grad,gradient_input) ? 0 : 1; CHECK_CUDNN(cudnnActivationBackward(context(), tanh_activation_descriptor(), &alpha, descriptor(dest), dest.device(), descriptor(gradient_input), gradient_input.device(), descriptor(dest), dest.device(), &beta, descriptor(grad), grad.device())); } // ------------------------------------------------------------------------------------ } } #endif // DLIB_USE_CUDA #endif // DLIB_DNN_CuDNN_CPP_
[ "tn.emre@gmail.com" ]
tn.emre@gmail.com
07e01b5d88b4084bc0813e1fe8a433248e2a2240
3b1b28a7b608de0aaec6318872d18a217dfce2b3
/helper/lte-helper.h
1486b9a4ead65166843e82565f482e660c419b45
[]
no_license
piotrlech/ns-3-LTE-Carrier-Aggregation
e31002f12c57e2bba1f7d02dcc5ef5b396c17daa
e7aa0234efbaaec30dd19712225a64ca89090d1e
refs/heads/master
2021-01-10T06:17:59.825304
2016-04-13T10:01:16
2016-04-13T10:01:16
55,409,334
0
0
null
null
null
null
UTF-8
C++
false
false
28,837
h
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * Copyright (c) 2015 Danilo Abrignani * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Nicola Baldo <nbaldo@cttc.es> * Danilo Abrignani <danilo.abrignani@unibo.it> (Carrier Aggregation - GSoC 2015) */ #ifndef LTE_HELPER_H #define LTE_HELPER_H #include <ns3/config.h> #include <ns3/simulator.h> #include <ns3/names.h> #include <ns3/net-device.h> #include <ns3/net-device-container.h> #include <ns3/node.h> #include <ns3/node-container.h> #include <ns3/eps-bearer.h> #include <ns3/phy-stats-calculator.h> #include <ns3/phy-tx-stats-calculator.h> #include <ns3/phy-rx-stats-calculator.h> #include <ns3/mac-stats-calculator.h> #include <ns3/radio-bearer-stats-calculator.h> #include <ns3/radio-bearer-stats-connector.h> #include <ns3/epc-tft.h> #include <ns3/mobility-model.h> #include <ns3/component-carrier-enb.h> #include <map> namespace ns3 { class LteUePhy; class LteEnbPhy; class SpectrumChannel; class EpcHelper; class PropagationLossModel; class SpectrumPropagationLossModel; /** * \ingroup lte * * Creation and configuration of LTE entities. One LteHelper instance is * typically enough for an LTE simulation. To create it: * * Ptr<LteHelper> lteHelper = CreateObject<LteHelper> (); * * The general responsibility of the helper is to create various LTE objects * and arrange them together to make the whole LTE system. The overall * arrangement would look like the following: * - Downlink spectrum channel * + Path loss model * + Fading model * - Uplink spectrum channel * + Path loss model * + Fading model * - eNodeB node(s) * + Mobility model * + eNodeB device(s) * * Antenna model * * eNodeB PHY (includes spectrum PHY, interference model, HARQ model) * * eNodeB MAC * * eNodeB RRC (includes RRC protocol) * * Scheduler * * Handover algorithm * * FFR (frequency reuse) algorithm * * ANR (automatic neighbour relation) * * CCS (Carrier Component Selection) algorithm * + EPC related models (EPC application, Internet stack, X2 interface) * - UE node(s) * + Mobility model * + UE device(s) * * Antenna model * * UE PHY (includes spectrum PHY, interference model, HARQ model) * * UE MAC * * UE RRC (includes RRC protocol) * * NAS * - EPC helper * - Various statistics calculator objects * * Spetrum channels are created automatically: one for DL, and one for UL. * eNodeB devices are created by calling InstallEnbDevice(), while UE devices * are created by calling InstallUeDevice(). EPC helper can be set by using * SetEpcHelper(). */ class LteHelper : public Object { public: LteHelper (void); virtual ~LteHelper (void); /** * Register this type. * \return The object TypeId. */ static TypeId GetTypeId (void); virtual void DoDispose (void); /** * Set the EpcHelper to be used to setup the EPC network in * conjunction with the setup of the LTE radio access network. * * \note if no EpcHelper is ever set, then LteHelper will default * to creating an LTE-only simulation with no EPC, using LteRlcSm as * the RLC model, and without supporting any IP networking. In other * words, it will be a radio-level simulation involving only LTE PHY * and MAC and the FF Scheduler, with a saturation traffic model for * the RLC. * * \param h a pointer to the EpcHelper to be used */ void SetEpcHelper (Ptr<EpcHelper> h); /** * Set the type of path loss model to be used for both DL and UL channels. * * \param type type of path loss model, must be a type name of any class * inheriting from ns3::PropagationLossModel, for example: * "ns3::FriisPropagationLossModel" */ void SetPathlossModelType (std::string type); /** * Set an attribute for the path loss models to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetPathlossModelAttribute (std::string n, const AttributeValue &v); /** * Set the type of scheduler to be used by eNodeB devices. * * \param type type of scheduler, must be a type name of any class * inheriting from ns3::FfMacScheduler, for example: * "ns3::PfFfMacScheduler" * * Equivalent with setting the `Scheduler` attribute. */ void SetSchedulerType (std::string type); /** * * \return the scheduler type */ std::string GetSchedulerType () const; /** * Set an attribute for the scheduler to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetSchedulerAttribute (std::string n, const AttributeValue &v); /** * Set the type of FFR algorithm to be used by eNodeB devices. * * \param type type of FFR algorithm, must be a type name of any class * inheriting from ns3::LteFfrAlgorithm, for example: * "ns3::LteFrNoOpAlgorithm" * * Equivalent with setting the `FfrAlgorithm` attribute. */ void SetFfrAlgorithmType (std::string type); /** * * \return the FFR algorithm type */ std::string GetFfrAlgorithmType () const; /** * Set an attribute for the FFR algorithm to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetFfrAlgorithmAttribute (std::string n, const AttributeValue &v); /** * Set the type of handover algorithm to be used by eNodeB devices. * * \param type type of handover algorithm, must be a type name of any class * inheriting from ns3::LteHandoverAlgorithm, for example: * "ns3::NoOpHandoverAlgorithm" * * Equivalent with setting the `HandoverAlgorithm` attribute. */ void SetHandoverAlgorithmType (std::string type); /** * * \return the handover algorithm type */ std::string GetHandoverAlgorithmType () const; /** * Set an attribute for the handover algorithm to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetHandoverAlgorithmAttribute (std::string n, const AttributeValue &v); /** * Set an attribute for the eNodeB devices (LteEnbNetDevice) to be created. * * \param n the name of the attribute. * \param v the value of the attribute */ void SetEnbDeviceAttribute (std::string n, const AttributeValue &v); /** * Set the type of antenna model to be used by eNodeB devices. * * \param type type of antenna model, must be a type name of any class * inheriting from ns3::AntennaModel, for example: * "ns3::IsotropicAntennaModel" */ void SetEnbAntennaModelType (std::string type); /** * Set an attribute for the eNodeB antenna model to be created. * * \param n the name of the attribute. * \param v the value of the attribute */ void SetEnbAntennaModelAttribute (std::string n, const AttributeValue &v); /** * Set an attribute for the UE devices (LteUeNetDevice) to be created. * * \param n the name of the attribute. * \param v the value of the attribute */ void SetUeDeviceAttribute (std::string n, const AttributeValue &v); /** * Set the type of antenna model to be used by UE devices. * * \param type type of antenna model, must be a type name of any class * inheriting from ns3::AntennaModel, for example: * "ns3::IsotropicAntennaModel" */ void SetUeAntennaModelType (std::string type); /** * Set an attribute for the UE antenna model to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetUeAntennaModelAttribute (std::string n, const AttributeValue &v); /** * This method is used to send the ComponentCarrier map created with CcHelper * to the helper, the structure will be used within InstallSingleEnbDevice * * \param ccmap, the component carrier map */ void SetEnbCc (std::map< uint8_t, Ptr<ComponentCarrierEnb> > ccmap); /** * Set the type of spectrum channel to be used in both DL and UL. * * \param type type of spectrum channel model, must be a type name of any * class inheriting from ns3::SpectrumChannel, for example: * "ns3::MultiModelSpectrumChannel" */ void SetSpectrumChannelType (std::string type); /** * Set an attribute for the spectrum channel to be created (both DL and UL). * * \param n the name of the attribute * \param v the value of the attribute */ void SetSpectrumChannelAttribute (std::string n, const AttributeValue &v); /** * Set the type of carrier component algorithm to be used by eNodeB devices. * * \param type type of carrier component algorithm, must be a type name of any class * inheriting from ns3::LteCcsAlgorithm, for example: * "ns3::NoOpCcsAlgorithm" * * Equivalent with setting the `CcsAlgorithm` attribute. */ void SetEnbComponentCarrierManagerType (std::string type); /** * * \return the carrier enb component carrier manager type */ std::string GetEnbComponentCarrierManagerType () const; /** * Set an attribute for the enb component carrier manager to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetEnbComponentCarrierManagerAttribute (std::string n, const AttributeValue &v); /** * Set the type of Component Carrier Manager to be used by Ue devices. * * \param type type of Component Carrier Manager, must be a type name of any class * inheriting from ns3::LteCcsAlgorithm, for example: * "ns3::NoOpCcsAlgorithm" * * Equivalent with setting the `CcsAlgorithm` attribute. */ void SetUeComponentCarrierManagerType (std::string type); /** * * \return the carrier ue component carrier manager type */ std::string GetUeComponentCarrierManagerType () const; /** * Set an attribute for the ue component carrier manager to be created. * * \param n the name of the attribute * \param v the value of the attribute */ void SetUeComponentCarrierManagerAttribute (std::string n, const AttributeValue &v); /** * Create a set of eNodeB devices. * * \param c the node container where the devices are to be installed * \return the NetDeviceContainer with the newly created devices */ NetDeviceContainer InstallEnbDevice (NodeContainer c); /** * Create a set of UE devices. * * \param c the node container where the devices are to be installed * \return the NetDeviceContainer with the newly created devices */ NetDeviceContainer InstallUeDevice (NodeContainer c); void test(NodeContainer c); /** * \brief Enables automatic attachment of a set of UE devices to a suitable * cell using Idle mode initial cell selection procedure. * \param ueDevices the set of UE devices to be attached * * By calling this, the UE will start the initial cell selection procedure at * the beginning of simulation. In addition, the function also instructs each * UE to immediately enter CONNECTED mode and activates the default EPS * bearer. * * If this function is called when the UE is in a situation where entering * CONNECTED mode is not possible (e.g. before the simulation begin), then the * UE will attempt to connect at the earliest possible time (e.g. after it * camps to a suitable cell). * * Note that this function can only be used in EPC-enabled simulation. */ void Attach (NetDeviceContainer ueDevices); /** * \brief Enables automatic attachment of a UE device to a suitable cell * using Idle mode initial cell selection procedure. * \param ueDevice the UE device to be attached * * By calling this, the UE will start the initial cell selection procedure at * the beginning of simulation. In addition, the function also instructs the * UE to immediately enter CONNECTED mode and activates the default EPS * bearer. * * If this function is called when the UE is in a situation where entering * CONNECTED mode is not possible (e.g. before the simulation begin), then the * UE will attempt to connect at the earliest possible time (e.g. after it * camps to a suitable cell). * * Note that this function can only be used in EPC-enabled simulation. */ void Attach (Ptr<NetDevice> ueDevice); /** * \brief Manual attachment of a set of UE devices to the network via a given * eNodeB. * \param ueDevices the set of UE devices to be attached * \param enbDevice the destination eNodeB device * * In addition, the function also instructs each UE to immediately enter * CONNECTED mode and activates the default EPS bearer. * * The function can be used in both LTE-only and EPC-enabled simulations. * Note that this function will disable Idle mode initial cell selection * procedure. */ void Attach (NetDeviceContainer ueDevices, Ptr<NetDevice> enbDevice); /** * \brief Manual attachment of a UE device to the network via a given eNodeB. * \param ueDevice the UE device to be attached * \param enbDevice the destination eNodeB device * * In addition, the function also instructs the UE to immediately enter * CONNECTED mode and activates the default EPS bearer. * * The function can be used in both LTE-only and EPC-enabled simulations. * Note that this function will disable Idle mode initial cell selection * procedure. */ void Attach (Ptr<NetDevice> ueDevice, Ptr<NetDevice> enbDevice); /** * \brief Manual attachment of a set of UE devices to the network via the * closest eNodeB (with respect to distance) among those in the set. * \param ueDevices the set of UE devices to be attached * \param enbDevices the set of eNodeB devices to be considered * * This function finds among the eNodeB set the closest eNodeB for each UE, * and then invokes manual attachment between the pair. * * Users are encouraged to use automatic attachment (Idle mode cell selection) * instead of this function. * * \sa LteHelper::Attach(NetDeviceContainer ueDevices); */ void AttachToClosestEnb (NetDeviceContainer ueDevices, NetDeviceContainer enbDevices); /** * \brief Manual attachment of a UE device to the network via the closest * eNodeB (with respect to distance) among those in the set. * \param ueDevice the UE device to be attached * \param enbDevices the set of eNodeB devices to be considered * * This function finds among the eNodeB set the closest eNodeB for the UE, * and then invokes manual attachment between the pair. * * Users are encouraged to use automatic attachment (Idle mode cell selection) * instead of this function. * * \sa LteHelper::Attach(Ptr<NetDevice> ueDevice); */ void AttachToClosestEnb (Ptr<NetDevice> ueDevice, NetDeviceContainer enbDevices); /** * Activate a dedicated EPS bearer on a given set of UE devices. * * \param ueDevices the set of UE devices * \param bearer the characteristics of the bearer to be activated * \param tft the Traffic Flow Template that identifies the traffic to go on this bearer */ uint8_t ActivateDedicatedEpsBearer (NetDeviceContainer ueDevices, EpsBearer bearer, Ptr<EpcTft> tft); /** * Activate a dedicated EPS bearer on a given UE device. * * \param ueDevice the UE device * \param bearer the characteristics of the bearer to be activated * \param tft the Traffic Flow Template that identifies the traffic to go on this bearer. */ uint8_t ActivateDedicatedEpsBearer (Ptr<NetDevice> ueDevice, EpsBearer bearer, Ptr<EpcTft> tft); /** * \brief Manually trigger dedicated bearer de-activation at specific simulation time * \param ueDevice the UE on which dedicated bearer to be de-activated must be of the type LteUeNetDevice * \param enbDevice eNB, must be of the type LteEnbNetDevice * \param bearerId Bearer Identity which is to be de-activated * * \warning Requires the use of EPC mode. See SetEpcHelper() method. */ void DeActivateDedicatedEpsBearer (Ptr<NetDevice> ueDevice, Ptr<NetDevice> enbDevice, uint8_t bearerId); /** * Create an X2 interface between all the eNBs in a given set. * * \param enbNodes the set of eNB nodes */ void AddX2Interface (NodeContainer enbNodes); /** * Create an X2 interface between two eNBs. * * \param enbNode1 one eNB of the X2 interface * \param enbNode2 the other eNB of the X2 interface */ void AddX2Interface (Ptr<Node> enbNode1, Ptr<Node> enbNode2); /** * Manually trigger an X2-based handover. * * \param hoTime when the handover shall be initiated * \param ueDev the UE that hands off, must be of the type LteUeNetDevice * \param sourceEnbDev source eNB, must be of the type LteEnbNetDevice * (originally the UE is attached to this eNB) * \param targetEnbDev target eNB, must be of the type LteEnbNetDevice * (the UE would be connected to this eNB after the * handover) * * \warning Requires the use of EPC mode. See SetEpcHelper() method */ void HandoverRequest (Time hoTime, Ptr<NetDevice> ueDev, Ptr<NetDevice> sourceEnbDev, Ptr<NetDevice> targetEnbDev); /** * Activate a Data Radio Bearer on a given UE devices (for LTE-only simulation). * * \param ueDevices the set of UE devices * \param bearer the characteristics of the bearer to be activated */ void ActivateDataRadioBearer (NetDeviceContainer ueDevices, EpsBearer bearer); /** * Activate a Data Radio Bearer on a UE device (for LTE-only simulation). * This method will schedule the actual activation * the bearer so that it happens after the UE got connected. * * \param ueDevice the UE device * \param bearer the characteristics of the bearer to be activated */ void ActivateDataRadioBearer (Ptr<NetDevice> ueDevice, EpsBearer bearer); /** * Set the type of fading model to be used in both DL and UL. * * \param type type of fading model, must be a type name of any class * inheriting from ns3::SpectrumPropagationLossModel, for * example: "ns3::TraceFadingLossModel" */ void SetFadingModel (std::string type); /** * Set an attribute for the fading model to be created (both DL and UL). * * \param n the name of the attribute * \param v the value of the attribute */ void SetFadingModelAttribute (std::string n, const AttributeValue &v); /** * Enables full-blown logging for major components of the LENA architecture. */ void EnableLogComponents (void); /** * Enables trace sinks for PHY, MAC, RLC and PDCP. To make sure all nodes are * traced, traces should be enabled once all UEs and eNodeBs are in place and * connected, just before starting the simulation. */ void EnableTraces (void); /** * Enable trace sinks for PHY layer. */ void EnablePhyTraces (void); /** * Enable trace sinks for DL PHY layer. */ void EnableDlPhyTraces (void); /** * Enable trace sinks for UL PHY layer. */ void EnableUlPhyTraces (void); /** * Enable trace sinks for DL transmission PHY layer. */ void EnableDlTxPhyTraces (void); /** * Enable trace sinks for UL transmission PHY layer. */ void EnableUlTxPhyTraces (void); /** * Enable trace sinks for DL reception PHY layer. */ void EnableDlRxPhyTraces (void); /** * Enable trace sinks for UL reception PHY layer. */ void EnableUlRxPhyTraces (void); /** * Enable trace sinks for MAC layer. */ void EnableMacTraces (void); /** * Enable trace sinks for DL MAC layer. */ void EnableDlMacTraces (void); /** * Enable trace sinks for UL MAC layer. */ void EnableUlMacTraces (void); /** * Enable trace sinks for RLC layer. */ void EnableRlcTraces (void); /** * * \return the RLC stats calculator object */ Ptr<RadioBearerStatsCalculator> GetRlcStats (void); /** * Enable trace sinks for PDCP layer */ void EnablePdcpTraces (void); /** * * \return the PDCP stats calculator object */ Ptr<RadioBearerStatsCalculator> GetPdcpStats (void); /** * Assign a fixed random variable stream number to the random variables used. * * The InstallEnbDevice() or InstallUeDevice method should have previously * been called by the user on the given devices. * * If TraceFadingLossModel has been set as the fading model type, this method * will also assign a stream number to it, if none has been assigned before. * * \param c NetDeviceContainer of the set of net devices for which the * LteNetDevice should be modified to use a fixed stream * \param stream first stream index to use * \return the number of stream indices (possibly zero) that have been assigned */ int64_t AssignStreams (NetDeviceContainer c, int64_t stream); protected: // inherited from Object virtual void DoInitialize (void); private: /** * Create an eNodeB device (LteEnbNetDevice) on the given node. * \param n the node where the device is to be installed * \return pointer to the created device */ Ptr<NetDevice> InstallSingleEnbDevice (Ptr<Node> n); /** * Create a UE device (LteUeNetDevice) on the given node * \param n the node where the device is to be installed * \return pointer to the created device */ Ptr<NetDevice> InstallSingleUeDevice (Ptr<Node> n); /** * The actual function to trigger a manual handover. * \param ueDev the UE that hands off, must be of the type LteUeNetDevice * \param sourceEnbDev source eNB, must be of the type LteEnbNetDevice * (originally the UE is attached to this eNB) * \param targetEnbDev target eNB, must be of the type LteEnbNetDevice * (the UE would be connected to this eNB after the * handover) * * This method is normally scheduled by HandoverRequest() to run at a specific * time where a manual handover is desired by the simulation user. */ void DoHandoverRequest (Ptr<NetDevice> ueDev, Ptr<NetDevice> sourceEnbDev, Ptr<NetDevice> targetEnbDev); /** * \brief The actual function to trigger a manual bearer de-activation * \param ueDevice the UE on which bearer to be de-activated must be of the type LteUeNetDevice * \param enbDevice eNB, must be of the type LteEnbNetDevice * \param bearerId Bearer Identity which is to be de-activated * * This method is normally scheduled by DeActivateDedicatedEpsBearer() to run at a specific * time when a manual bearer de-activation is desired by the simulation user. */ void DoDeActivateDedicatedEpsBearer (Ptr<NetDevice> ueDevice, Ptr<NetDevice> enbDevice, uint8_t bearerId); void ChannelModelInitialized (void); /** * \brief This function just create the enb ComponentCarrierMap when CA is not enabled */ void DoCreateEnbComponentCarrierMap (uint16_t ulearfc, uint16_t dlearfcn, uint8_t ulbw, uint8_t dlbw); /// The downlink LTE channel used in the simulation. std::vector <Ptr<SpectrumChannel> > m_downlinkChannel; /// The uplink LTE channel used in the simulation. std::vector< Ptr<SpectrumChannel> > m_uplinkChannel; /// The path loss model used in the downlink channel. std::vector< Ptr<Object> > m_downlinkPathlossModel; /// The path loss model used in the uplink channel. std::vector< Ptr<Object> > m_uplinkPathlossModel; /// Factory of MAC scheduler object. ObjectFactory m_schedulerFactory; /// Factory of FFR (frequency reuse) algorithm object. ObjectFactory m_ffrAlgorithmFactory; /// Factory of handover algorithm object. ObjectFactory m_handoverAlgorithmFactory; /// Factory of enb component carrier manager object. ObjectFactory m_enbComponentCarrierManagerFactory; /// Factory of ue component carrier manager object. ObjectFactory m_ueComponentCarrierManagerFactory; /// Factory of LteEnbNetDevice objects. ObjectFactory m_enbNetDeviceFactory; /// Factory of antenna object for eNodeB. ObjectFactory m_enbAntennaModelFactory; /// Factory for LteUeNetDevice objects. ObjectFactory m_ueNetDeviceFactory; /// Factory of antenna object for UE. ObjectFactory m_ueAntennaModelFactory; /// Factory of path loss model object for the downlink channel. ObjectFactory m_dlPathlossModelFactory; /// Factory of path loss model object for the uplink channel. ObjectFactory m_ulPathlossModelFactory; /// Factory of both the downlink and uplink LTE channels. ObjectFactory m_channelFactory; /// Name of fading model type, e.g., "ns3::TraceFadingLossModel". std::string m_fadingModelType; /// Factory of fading model object for both the downlink and uplink channels. ObjectFactory m_fadingModelFactory; /// The fading model used in both the downlink and uplink channels. Ptr<SpectrumPropagationLossModel> m_fadingModule; /** * True if a random variable stream number has been assigned for the fading * model. Used to prevent such assignment to be done more than once. */ bool m_fadingStreamsAssigned; /// Container of PHY layer statistics. Ptr<PhyStatsCalculator> m_phyStats; /// Container of PHY layer statistics related to transmission. Ptr<PhyTxStatsCalculator> m_phyTxStats; /// Container of PHY layer statistics related to reception. Ptr<PhyRxStatsCalculator> m_phyRxStats; /// Container of MAC layer statistics. Ptr<MacStatsCalculator> m_macStats; /// Container of RLC layer statistics. Ptr<RadioBearerStatsCalculator> m_rlcStats; /// Container of PDCP layer statistics. Ptr<RadioBearerStatsCalculator> m_pdcpStats; /// Connects RLC and PDCP statistics containers to appropriate trace sources RadioBearerStatsConnector m_radioBearerStatsConnector; /** * Helper which provides implementation of core network. Initially empty * (i.e., LTE-only simulation without any core network) and then might be * set using SetEpcHelper(). */ Ptr<EpcHelper> m_epcHelper; /** * Keep track of the number of IMSI allocated. Increases by one every time a * new UE is installed (by InstallSingleUeDevice()). The first UE will have * an IMSI of 1. The maximum number of UE is 2^64 (~4.2e9). */ uint64_t m_imsiCounter; /** * Keep track of the number of cell ID allocated. Increases by one every time * a new eNodeB is installed (by InstallSingleEnbDevice()). The first eNodeB * will have a cell ID of 1. The maximum number of eNodeB is 65535. */ uint16_t m_cellIdCounter; /** * The `UseIdealRrc` attribute. If true, LteRrcProtocolIdeal will be used for * RRC signaling. If false, LteRrcProtocolReal will be used. */ bool m_useIdealRrc; /** * The `AnrEnabled` attribute. Activate or deactivate Automatic Neighbour * Relation function. */ bool m_isAnrEnabled; /** * The `UsePdschForCqiGeneration` attribute. If true, DL-CQI will be * calculated from PDCCH as signal and PDSCH as interference. If false, * DL-CQI will be calculated from PDCCH as signal and PDCCH as interference. */ bool m_usePdschForCqiGeneration; /** * The `UseCa` attribute. If true, Carrier Aggregation is enable. * Hence, the helper will wait for a valid component carrier map * If it is false, the component carrier will be created within the LteHelper * this is to mantain the backwards compatibility with user script */ bool m_useCa; /** * This contains all the information about each component carrier * Moreover, there is also a pointer to LteEnbPhy Object. */ std::map< uint8_t, Ptr<ComponentCarrierEnb> > m_enbComponentCarrierMap; uint16_t m_noOfCcs; }; // end of `class LteHelper` } // namespace ns3 #endif // LTE_HELPER_H
[ "piotr.lechowicz@gmail.com" ]
piotr.lechowicz@gmail.com
d5f272f2eccc00eeeff24e75c2136b99582dfb75
71ee93e10a94fbfe6375352dc6da5ca2e41e802c
/cmsc341-data_structures/proj2-eurorails/src/Game.cpp
0f50d3594b9840b173014da560d469a035f54c78
[]
no_license
dangbert/college
ef25b08bd16bfb48d514d0668354a01342c9e104
b137658af27f86297ca70665ff5c487be06076ac
refs/heads/master
2022-12-15T19:37:46.603666
2021-11-23T19:30:44
2021-11-23T19:30:44
191,094,083
1
0
null
2022-11-22T02:43:47
2019-06-10T04:01:26
C
UTF-8
C++
false
false
4,457
cpp
#include "Game.h" #include <fstream> #include <sstream> using namespace std; /* * constuctor * @param coms_filename: filename of the commodities text file * @param cards_filename: filename of the cards text file */ Game::Game(std::string cards_filename, std::string coms_filename) { // TODO: check these files exist m_bank.loadCommodities(coms_filename); // initiate m_bank loadDrawPile(cards_filename); // initiate m_drawPile } /* * Destructor */ Game::~Game() { // deallocate cards while (!m_drawPile.empty()) { delete m_drawPile.top(); m_drawPile.pop(); } for (uint i=0; i<m_players.size(); i++) { delete m_players.at(i); } } /* * runs through the simulation of playing the game * * create player objects * deals cards, making sure everyone gets the same amount (some might be unused) * * @param players: number of players for the simulation * @param stategy: strategy to use for the simulation */ void Game::runSimulation(int players, Player::STRATEGY strategy) { // inititate m_players std::ostringstream ss; for (int i=1; i<=players; i++) { ss.str(""); // clear ss ss << "Player " << i; Player* p = new Player(ss.str()); // example name: "Player 3" m_players.push_back(p); // store player pointer in vector } // deal out the cards to the players std::stack<Card*> temp = m_drawPile; // copy of the draw pile // traverse all of m_players as many times as needed for (uint i=0; i<m_drawPile.size()/players; i++) { // cycle through all players for (uint p=0; p<m_players.size(); p++) { // add card at top of stack to current player m_players.at(p)->addCard(temp.top()); temp.pop(); } } // calculate each player's score for (uint p=0; p<m_players.size(); p++) { m_players.at(p)->calculateScore(strategy); } } /* * prints the current state of the drawPile to a given output stream */ void Game::printDrawPile(std::ofstream& fileStream) { std::stack<Card*> temp = m_drawPile; // needed to traverse stack without emptying it fileStream << "---------- Draw Pile ----------" << endl; while (!temp.empty()) { temp.top()->printCard(fileStream); temp.pop(); } } /* * prints the result of the simulation to a given output stream */ void Game::printResults(std::ofstream& fileStream) { fileStream << "\n\n---------- RESULTS ----------" << endl; Player* winner = m_players.at(0); for (uint p=0; p<m_players.size(); p++) { m_players.at(p)->printResults(fileStream); if (m_players.at(p)->getScore() > winner->getScore()) { winner = m_players.at(p); } } fileStream << "--------------------------" << endl; fileStream << "--------------------------" << endl; fileStream << "Winner: " << winner->getName(); fileStream << " Score: " << winner->getScore() << endl; } /* * loads the deck from the provided file * initiates m_drawPile (assume m_bank is already initialized) */ void Game::loadDrawPile(std::string filename) { ifstream ifile(filename.c_str()); string destination[3]; // destinations on one card string com_string[3]; // comodities string pay_string[3]; // payoffs while (!ifile.eof()) { // loop through the 3 objectives on the card for (int i=0; i<3; i++) { ifile >> destination[i]; // store next string in file in destination ifile >> com_string[i]; ifile >> pay_string[i]; if (ifile.eof()) { // check that we haven't reached the end of the file break; } if (i == 2) { // if 3 objectives were found for this card Card* c = new Card(); // create and store each objective for the card for (int k=0; k<3; k++) { int payoff = atoi(pay_string[k].c_str()); // convert to int // find Commodity* in commodity store Commodity* commodity = m_bank.getCommodity(com_string[k]); // add objectives to card Objective* o = new Objective(destination[k], commodity, payoff); c->addObjective(o); // add objective to this card } m_drawPile.push(c); // push card pointer into stack } } } }
[ "end1@umbc.edu" ]
end1@umbc.edu
e3f2d186d74b1eec66e412b99ccfdd54b6435c67
86683a8d36c44321c92e9c9a8ea6f0602c4f8452
/src/good/res/res.h
eb1c2c5bfe480ca4aec2431134d55d42b6652974
[]
no_license
cnyaw/good
157ca8b8c6560f7cd1f56141b93331fb973e95c7
c7a6564c2421e0685790550734cea5194eed619c
refs/heads/master
2023-09-04T11:06:03.035298
2023-08-31T07:57:37
2023-08-31T07:57:37
107,022,657
10
1
null
null
null
null
UTF-8
C++
false
false
4,988
h
// // res.h // Good resource manager. // // Copyright (c) 2007 Waync Cheng. // All Rights Reserved. // // 2007/11/29 Waync created. // #pragma once namespace good { class Traits { public: typedef Sound SoundT; typedef Texture TextureT; typedef Map<Tileset> MapT; typedef Sprite<Tileset> SpriteT; typedef Object ObjectT; typedef Level<Object> LevelT; }; template<class TraitsT = Traits> class Resource { public: typedef typename TraitsT::SoundT SoundT; typedef typename TraitsT::TextureT TextureT; typedef typename TraitsT::MapT MapT; typedef typename TraitsT::SpriteT SpriteT; typedef typename TraitsT::ObjectT ObjectT; typedef typename TraitsT::LevelT LevelT; // // Project property. // std::string mName; std::string mFileName; sw2::ObjectPool<int,32,true> mId; // ID manager pool. // // Settings. // int mWidth, mHeight; // Window size. int mFps; // // Sounds. // std::vector<int> mSndIdx; std::map<int, SoundT> mSnd; // // Textures. // std::vector<int> mTexIdx; std::map<int, TextureT> mTex; // // Maps. // std::vector<int> mMapIdx; std::map<int, MapT> mMap; // // Sprites. // std::vector<int> mSpriteIdx; std::map<int, SpriteT> mSprite; // // Level. // std::vector<int> mLevelIdx; std::map<int, LevelT> mLevel; // // Script. // std::vector<int> mScriptIdx; std::map<int, std::string> mScript; // // STGE script. // std::vector<int> mStgeScriptIdx; std::map<int, std::string> mStgeScript; // // Project dependencies. // std::vector<int> mDepIdx; std::map<int, std::string> mDep; // // Codegen macros. Ex: isSnd, getSnd. // #define IMPL_GET_RESOURCE_ITEM(ResName, ResType) \ bool is ## ResName(int id) const \ { \ return m ## ResName.end() != m ## ResName.find(id); \ } \ ResType& get ## ResName(int id) \ { \ return const_cast<ResType&>(static_cast<Resource const &>(*this).get ## ResName(id)); \ } \ ResType const& get ## ResName(int id) const \ { \ typename std::map<int, ResType>::const_iterator it = m ## ResName.find(id); \ if (m ## ResName.end() == it) { \ throw std::range_error("get" # ResName); \ } else { \ return it->second; \ } \ } IMPL_GET_RESOURCE_ITEM(Snd, SoundT) IMPL_GET_RESOURCE_ITEM(Tex, TextureT) IMPL_GET_RESOURCE_ITEM(Map, MapT) IMPL_GET_RESOURCE_ITEM(Sprite, SpriteT) IMPL_GET_RESOURCE_ITEM(Level, LevelT) IMPL_GET_RESOURCE_ITEM(Script, std::string) IMPL_GET_RESOURCE_ITEM(StgeScript, std::string) IMPL_GET_RESOURCE_ITEM(Dep, std::string) #undef IMPL_GET_RESOURCE_ITEM // // Load resource. // bool load(std::string const& name) { std::ifstream ifs(name.c_str()); if (!ifs) { return false; } if (!load(ifs)) { return false; } mFileName = name; return true; } bool load(std::istream& ins) { // // File. // sw2::Ini ini; if (!ini.load(ins)) { SW2_TRACE_ERROR("bad ini file format"); return false; } if (!ini.find("good")) { SW2_TRACE_ERROR("[good] section not found"); return false; } sw2::Ini sec = ini["good"]; // // Property. // if (GOOD_VERSION != sec["version"].value) { SW2_TRACE_ERROR("version mismatch"); return false; } mName = sec["name"].value; mId.clear(); // // Default settings. // mWidth = 640; mHeight = 480; mFps = GOOD_DEFAULT_TICK_PER_SECOND; std::vector<int> v; assignListFromString(sec["window"].value, v); if (1 <= v.size()) { mWidth = v[0]; } if (2 <= v.size()) { mHeight = v[1]; } if (sec.find("fps")) { mFps = sec["fps"]; } return loadAllResources(sec, ini); } bool loadAllResources(sw2::Ini &sec, const sw2::Ini &ini) { // // Sounds. // if (!loadResources(mId, mSnd, mSndIdx, "snds", sec, ini)) { return false; } // // Textures. // if (!loadResources(mId, mTex, mTexIdx, "texs", sec, ini)) { return false; } // // Maps. // if (!loadResources(mId, mMap, mMapIdx, "maps", sec, ini)) { return false; } // // Sprites. // if (!loadResources(mId, mSprite, mSpriteIdx, "sprites", sec, ini)) { return false; } // // Levels. // if (!loadResources(mId, mLevel, mLevelIdx, "levels", sec, ini)) { return false; } // // Scripts. // if (!loadStringTableResources(mId, mScript, mScriptIdx, "scripts", ini)) { return false; } // // STGE scripts. // if (!loadStringTableResources(mId, mStgeScript, mStgeScriptIdx, "stges", ini)) { return false; } // // Dependencies. // if (!loadStringTableResources(mId, mDep, mDepIdx, "deps", ini)) { return false; } return true; } }; } // namespace good // end of res.h
[ "wayncc@gmail.com" ]
wayncc@gmail.com
c6f514a045e137d961b2fb6c20e57f721714d523
8173234f279a012d0cb813473f2e7ce15573ab5e
/code/classCode/pets/PetsV2/main.cpp
90a34864170f730ff6b3c1c35352a131f5c6e5cb
[]
no_license
Rvansolkem/ESU-SoftwareEngineering
31bb3a4950082d62462927f43c485cc698141540
cbb2b913fc73914c0989b093e210c01be2a277bc
refs/heads/master
2023-01-19T23:34:04.010267
2020-11-24T00:48:35
2020-11-24T00:48:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
// Written by Nick Moukhine, 2006 #include <iostream> #include "PetCat.h" #include "PetDog.h" #include "PetStore.h" using namespace std; int main(void) { //PetStore(new PetDog()); IPet* p = NewPet(); // do the following if you want to keep the console window visible while executing from windows (not .NET or a console window) char temp; cin >> temp; return 0; }
[ "smcrowley8@gmail.com" ]
smcrowley8@gmail.com
f5ec7db8cc5d96eb8702c8b8656426815e1e80a5
8f021f68cd0949afa8d119582c0b419b014919d8
/UVA/uva11906.cpp
e0489cdb19d6dd5f125197ea9b3a13f56e857210
[]
no_license
Jonatankk/codigos
b9c8426c2f33b5142460a84337480b147169b3e6
233ae668bdf6cdd12dbc9ef243fb4ccdab49c933
refs/heads/master
2022-07-22T11:09:27.271029
2020-05-09T20:57:42
2020-05-09T20:57:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,533
cpp
/* * Leonardo Deliyannis Constantin * UVa 11906 - Knight in a War Grid */ #include<stdio.h> #include<string.h> #include<stack> #include<algorithm> #include<vector> using namespace std; #define MAX 112 typedef pair<int, int> ii; int R, C, M, N; bool vis[MAX][MAX]; bool wet[MAX][MAX]; bool isValid(int i, int j){ return 0 <= i && i < R && 0 <= j && j < C && !wet[i][j]; } ii tour(int si, int sj){ ii ret; int i, j, k, i2, j2, cnt; vector<int> di, dj; if(M == 0 || N == 0){ if(M == 0) swap(M, N); di = { -M, 0, 0, M }; dj = { 0, -M, M, 0 }; } else if(M == N){ di = { -M, -M, M, M }; dj = { -M, M, -M, M }; } else{ di = { -M, -M, -N, -N, N, N, M, M }; dj = { -N, N, -M, M, -M, M, -N, N }; } int tam = di.size(); ret.first = ret.second = 0; memset(vis, false, sizeof(vis)); vis[si][sj] = true; stack<ii> q; q.push(ii(si, sj)); while(!q.empty()){ i = q.top().first; j = q.top().second; q.pop(); cnt = 0; for(k = 0; k < tam; k++){ i2 = i+di[k]; j2 = j+dj[k]; if(isValid(i2, j2)){ if(!vis[i2][j2]){ vis[i2][j2] = true; q.push(ii(i2, j2)); } cnt++; } } (cnt&1) ? ret.second++ : ret.first++; } return ret; } int main(){ int T, W, x, y, tc = 0; scanf("%d", &T); while(T--){ scanf("%d %d %d %d", &R, &C, &M, &N); scanf("%d", &W); memset(wet, false, sizeof(wet)); while(W--){ scanf("%d %d", &x, &y); wet[x][y] = true; } ii ans = tour(0,0); printf("Case %d: %d %d\n", ++tc, ans.first, ans.second); } return 0; }
[ "noreply@github.com" ]
Jonatankk.noreply@github.com