hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
263492dab116c7b753b51dea88433e187ac454eb
4,837
cpp
C++
word-hero.cpp
Ad1tyaV/WordHero-solver
034951510fc7f860499a3cce714ead0f5b6a7317
[ "MIT" ]
null
null
null
word-hero.cpp
Ad1tyaV/WordHero-solver
034951510fc7f860499a3cce714ead0f5b6a7317
[ "MIT" ]
null
null
null
word-hero.cpp
Ad1tyaV/WordHero-solver
034951510fc7f860499a3cce714ead0f5b6a7317
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<iostream> #include<vector> #include "trie.h" #include <fstream> #include<unordered_set> #define ROWS 4 #define COLS 4 using namespace std; using namespace Trie; unordered_set<string> elements; vector<vector<bool>> visited; vector<pair<int, int>> directions = { {1,0}, {0,1}, {-1,0}, {0,-1}, {1,1}, {-1,-1}, {1,-1}, {-1,1}}; void generateAllWords(vector<vector<char>> grid, int x, int y, TrieNode* crawl, string word){ if(crawl->isLeaf){ // elements.push_back(word); elements.insert(word); } if(x>=ROWS || x<0) return; if(y<0 || y>=COLS) return; if(visited[x][y]) return; visited[x][y] = true; for(pair<int, int> direction : directions){ int next_x = x+direction.first; int next_y = y+direction.second; if(next_x>=ROWS || next_x < 0) continue; if(next_y<0 || next_y>=COLS) continue; if(visited[next_x][next_y]) continue; if(crawl->next.find(grid[next_x][next_y])==crawl->next.end()){ // NO point going this direction! continue; } else{ word.push_back(grid[next_x][next_y]); generateAllWords(grid, next_x, next_y, crawl->next[grid[next_x][next_y]],word); word.pop_back(); } } visited[x][y] = false; } void readFile(TrieParent* parent){ std::ifstream infile("scrabbleWords.txt"); for(string line; std::getline(infile, line);){ line.pop_back(); // cout<<"word="<<line<<endl; // cout<<"word size="<<line.size()<<endl; insertWord(parent, line); // cout<<line<<endl; } infile.close(); } bool isValidInput(string temp){ if(temp.size()!=1) return false; return isalpha(temp[0]); } string convertToLowerCase(string input){ string lowerCase = ""; for(int index = 0; index<input.size(); index++){ if(input[index]>=65 && input[index]<=91){ lowerCase.push_back(input[index]); } } } char charToUpper(char letter){ if((int) letter >=65 && (int) letter<=91) return letter; return (char)(letter-32); } void printBoard(vector<vector<char>> grid){ for(int row = 0; row<ROWS; row++){ for(int col = 0; col<COLS; col++){ cout<<grid[row][col]<<"\t"; } cout<<endl; } } int main(){ TrieParent* parent = new TrieParent(); visited = vector<vector<bool>>(ROWS, vector<bool>(COLS, false)); cout<<"Do you want to enter the board as input ? Y/N ?"<<endl; string option; cin>>option; transform(option.begin(),option.end(), option.begin(), ::tolower); vector<vector<char>> grid = vector<vector<char>>(ROWS, vector<char>(COLS, '\0')); // Initializing with NULL if(option[0]=='y' || option=="yes"){ cout<<"Enter 16 elements of the board row after row, use space as seperator or next line\n"; for(int row_index = 0; row_index<ROWS; row_index++){ for(int col_index = 0; col_index<COLS; col_index++){ string temp; cin>>temp; if(!isValidInput(temp)){ cout<<"Invalid Input - "<<temp<<endl; return 0; } else{ // grid[row_index][col_index] = temp[0]; grid[row_index][col_index] = charToUpper(temp[0]); } } } } else{ grid = {{'S','S','E','E'}, {'H','P','R','D'}, {'I','A','E','I'}, {'S','D','Y','R'}}; } printBoard(grid); readFile(parent); for(int x = 0; x<ROWS; x++){ for(int y=0; y<COLS; y++){ visited = vector<vector<bool>>(ROWS, vector<bool>(COLS, false)); string temp = ""; temp.push_back(grid[x][y]); generateAllWords(grid, x, y, parent->links[grid[x][y]], temp); temp.pop_back(); } } cout<<"Total number of elements:"<<elements.size()<<endl; for(auto iterator = elements.begin(); iterator!=elements.end(); iterator++){ cout<<*iterator<<"\t"; } cout<<endl; return 0; }
24.064677
112
0.464751
[ "vector", "transform" ]
263a352a57d6aee079de1b057734d1d1b2e92a45
2,292
cc
C++
2203/lab1/window8.cc
rmwhitaker23/schoolwork
e38822fb96bb1e2ac36b0861ffe1d6f6d9280b12
[ "MIT" ]
null
null
null
2203/lab1/window8.cc
rmwhitaker23/schoolwork
e38822fb96bb1e2ac36b0861ffe1d6f6d9280b12
[ "MIT" ]
null
null
null
2203/lab1/window8.cc
rmwhitaker23/schoolwork
e38822fb96bb1e2ac36b0861ffe1d6f6d9280b12
[ "MIT" ]
null
null
null
/* window7.cc -- Repeatedly read a win # and erase its char with windows in a 3 x 3 grid Author: Larry Morell Modification History Date Action 09/10/18 -- Original version ID code: 5AYVK3r3f.ARA */ using namespace std; #include <iostream> #include <iomanip> #include <string> #include <ncurses.h> WINDOW* createWindow(int row, int col, char letter) { WINDOW *w = newwin(5,5,row,col); // Size 5 x 5 at (row,col) wborder(w, '|', '|', '-', '-', '+', '+', '+', '+'); wmove(w,2,2); waddch(w,letter); wrefresh(w); return w; } void updateDisplay(WINDOW *w, char ch) { wmove(w,2,2); waddch(w,ch); wrefresh(w); } int main () { initscr(); cbreak(); // Set up the model -- the data that underlies the display char model[3][3] { {'a', 'b', 'c' }, {'d', 'e', 'f' }, {'g', 'h', 'i' } }; // Set up the 3 x 3 display // There are 3 rows, positioned at 4, 8, and 12 // There are 3 cols, positioned at 4, 8, and 12 WINDOW *display[3][3]; int r, c; for (r=0; r < 3; ++r) { // iterate through the rows for (c=0; c < 3; ++c ) { // iterate through the cols // Place the char at model[r][c] in display [r][c] display[r][c] = createWindow(4*(r+1),4*(c+1), model[r][c]) ; } } // Create a window at the bottom of the screen // LINES == number of lines on the screen, defined in curses.h // COLS == number of columns on the screen, defined in curses.h WINDOW *command = newwin(1,20,LINES-1,0); wprintw(command,"Window: " ); wrefresh(command); // Now repeatedly read a letter to be removed // from the 3 x 3 grid, find that letter, and // remove it from the grid, then redisplay char ch; while ( (ch = wgetch(command)) != 'q' ) { WINDOW *w; // Find the window with c in it; for (r = 0; r < 3; ++r) { for (c = 0; c < 3; ++c) { if ( model[r][c] == ch ) { // found the character model[r][c] = ' '; // Change the model w = display[r][c]; updateDisplay(w,' '); } } } // clear previously typed command wmove(command,0,8); wclrtoeol(command); wrefresh(command); } endwin(); return 0; }
25.752809
89
0.534904
[ "model" ]
2642855606c0e0815a791b45fbcbffd3f04a19fb
4,151
hh
C++
hackt_docker/hackt/src/sim/chpsim/nonmeta_context.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/sim/chpsim/nonmeta_context.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/sim/chpsim/nonmeta_context.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "sim/chpsim/nonmeta_context.hh" This is used to lookup run-time values and references. $Id: nonmeta_context.hh,v 1.8 2010/04/07 00:13:08 fang Exp $ */ #ifndef __HAC_SIM_CHPSIM_NONMETA_CONTEXT_H__ #define __HAC_SIM_CHPSIM_NONMETA_CONTEXT_H__ #include <vector> // only need fwd decl #include "Object/nonmeta_context.hh" #include "Object/nonmeta_variable.hh" // for event_subscribers_type #include "Object/ref/reference_set.hh" #include "sim/common.hh" #include "util/member_saver.hh" #include "util/memory/excl_ptr.hh" namespace HAC { namespace SIM { class state_base; namespace CHPSIM { class EventNode; class State; using entity::footprint; using entity::footprint_frame; using entity::state_manager; using entity::global_offset; using entity::global_entry_context; using entity::nonmeta_state_manager; using entity::nonmeta_context_base; using entity::event_subscribers_type; using util::memory::never_ptr; class TraceManager; //============================================================================= /** Context information for lookup up run-time values from state. This is now tied to CHPSIM data structures. */ class nonmeta_context : public nonmeta_context_base { typedef nonmeta_context this_type; // TODO: is local_event enough, do we need global_event? // these types must correspond to those used in CHPSIM::State! // but I'm too lazy to include its header here... typedef EventNode event_type; typedef std::vector<event_index_type> enqueue_queue_type; typedef std::vector<event_type> event_pool_type; /// for set-insert interface to first_checks typedef event_subscribers_type::const_iterator const_iterator; public: typedef event_subscribers_type::value_type value_type; typedef event_subscribers_type::const_reference const_reference; private: /** Reference to the event in question. */ event_type* event; /** Offset to add to local-event indices to translate to global event indices. Should be set by set_event. */ event_index_type global_event_offset; /** Current process index for this event. Mostly used for diagnostics. */ size_t process_index; /** Successor of a just-executed event to check for the first time, after their respective delays. NOTE: this is a local structure now, not a reference! */ event_subscribers_type first_checks; public: /** List of references modified by the visiting event. */ entity::global_references_set& updates; /** Global pool of events. */ event_pool_type& event_pool; /** Reference to the State's trace_manager. */ never_ptr<TraceManager> trace_manager; typedef util::member_saver<this_type, event_type*, &this_type::event> event_setter_base; /** To be used by only EventExecutor please! */ struct event_setter : public util::member_saver<this_type, event_type*, &this_type::event> { event_setter(const this_type& t, event_type* e) : event_setter_base(const_cast<this_type&>(t), e) { } }; public: nonmeta_context( // const global_entry_context& available from State& // may need to sub-class global_offset to map // offsets of events and other things! State&); ~nonmeta_context(); void set_event(const state_base&, // for frame-cache event_type&, const size_t, const event_index_type); event_type& get_event(void) const { return *event; } /** The distance from the start of the pool is the index. */ size_t get_event_index(void) const; event_index_type get_process_index(void) const { return process_index; } void subscribe_this_event(void) const; void insert_first_checks(const event_index_type); void insert(const event_index_type ei) { insert_first_checks(ei); } const_iterator first_checks_begin(void) const { return first_checks.begin(); } const_iterator first_checks_end(void) const { return first_checks.end(); } void first_check_all_successors(void); }; // end class nonmeta_context //============================================================================= } // end namespace CHPSIM } // end namespace SIM } // end namespace HAC #endif // __HAC_SIM_CHPSIM_NONMETA_CONTEXT_H__
27.309211
79
0.725849
[ "object", "vector" ]
26510f0717f2ddaedd285e712da48dd0d8a0a5bf
9,432
cpp
C++
source/network/network.cpp
keldu/terraria-devoured
105d65fe6319bd655a394a52c64c4af51d3c0243
[ "MIT" ]
2
2020-03-14T22:11:07.000Z
2020-03-26T22:36:02.000Z
source/network/network.cpp
keldu/terraria-devoured
105d65fe6319bd655a394a52c64c4af51d3c0243
[ "MIT" ]
17
2019-11-26T19:42:29.000Z
2020-03-25T19:32:46.000Z
source/network/network.cpp
keldu/terraria-devoured
105d65fe6319bd655a394a52c64c4af51d3c0243
[ "MIT" ]
null
null
null
#include "network.h" #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <sys/stat.h> #include <sys/epoll.h> #include <endian.h> #include <unistd.h> #include <errno.h> #include <cstring> #include <cassert> #include <iostream> const size_t read_buffer_size = 4096; const size_t write_buffer_size = 4096; namespace dvr { IFdObserver::IFdObserver(EventPoll& p, int file_d, uint32_t msk): poll{p}, file_desc{file_d}, event_mask{msk} { poll.subscribe(*this); } IFdObserver::~IFdObserver(){ poll.unsubscribe(*this); } int IFdObserver::fd()const{ return file_desc; } uint32_t IFdObserver::mask()const{ return event_mask; } const size_t max_events = 256; class EventPoll::Impl { private: std::map<int, IFdObserver*> observers; int epoll_fd; bool broken; ::epoll_event events[max_events]; public: Impl(): broken{false} { epoll_fd = epoll_create1(0); if(epoll_fd < 0){ broken = true; } } ~Impl(){ if(epoll_fd > 0){ close(epoll_fd); } } bool poll(){ if(broken){ return true; } int nfds = ::epoll_wait(epoll_fd, events, max_events, -1); if(nfds < 0){ return broken = true; } for(int n = 0; n < nfds; ++n){ int fd_event = events[n].data.fd; auto finder = observers.find(fd_event); if(finder == observers.end()){ return broken = true; } finder->second->notify(events[n].events); } return broken; } void subscribe(IFdObserver& obsv){ if(!broken){ int fd = obsv.fd(); assert(fd >= 0); ::epoll_event event; event.events = obsv.mask(); event.data.fd = fd; if(::epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event)){ broken = true; return; } observers.insert(std::make_pair(fd, &obsv)); } } void unsubscribe(IFdObserver& obsv){ if(!broken){ int fd = obsv.fd(); assert(fd >= 0); ::epoll_event event; event.events = obsv.mask(); event.data.fd = fd; if(::epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &event)){ broken = true; return; } observers.erase(fd); } } }; EventPoll::EventPoll(): impl{std::make_unique<EventPoll::Impl>()} { } EventPoll::~EventPoll(){} bool EventPoll::poll(){ return impl->poll(); } void EventPoll::subscribe(IFdObserver& obv){ impl->subscribe(obv); } void EventPoll::unsubscribe(IFdObserver& obv){ impl->unsubscribe(obv); } UnixSocketAddress::UnixSocketAddress(EventPoll& p, const std::string& unix_addr): poll{p}, bind_address{unix_addr} {} std::unique_ptr<Server> UnixSocketAddress::listen(IServerStateObserver& obsrv){ int file_descriptor = ::socket( AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0 ); //TODO Missing errno check in every state if(file_descriptor < 0){ std::cerr<<"Couldn't create socket: "<<(::strerror(errno))<<std::endl; return nullptr; } int status; struct ::sockaddr_un local; local.sun_family = AF_UNIX; size_t len = (sizeof(local.sun_path)-1) < bind_address.size() ? (sizeof(local.sun_path)-1): bind_address.size(); ::strncpy(local.sun_path, bind_address.c_str(), len); local.sun_path[len] = 0; #ifdef NDEBUG ::unlink(local.sun_path); #endif status = ::bind(file_descriptor, (struct ::sockaddr*)&local, sizeof(local)); if( status != 0){ std::cerr<<"Couldn't bind socket: "<<local.sun_path<<std::endl; return nullptr; } ::listen(file_descriptor, SOMAXCONN); return std::make_unique<Server>(poll, file_descriptor, bind_address, obsrv); } std::unique_ptr<Connection> UnixSocketAddress::connect(IConnectionStateObserver& obsrv){ int file_descriptor = ::socket( AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0 ); if(file_descriptor < 0){ std::cerr<<"Couldn't create socket: "<<(::strerror(errno))<<std::endl; return nullptr; } int status; struct ::sockaddr_un local; local.sun_family = AF_UNIX; size_t len = (sizeof(local.sun_path)-1) < bind_address.size() ? (sizeof(local.sun_path)-1): bind_address.size(); ::strncpy(local.sun_path, bind_address.c_str(), len); local.sun_path[len] = 0; status = ::connect(file_descriptor, (struct ::sockaddr*)&local, sizeof(local)); if( status != 0){ std::cerr<<"Couldn't connect to socket at "<<local.sun_path<<" : "<<(::strerror(errno))<<std::endl; return nullptr; } return std::make_unique<Connection>(poll, file_descriptor, obsrv); } static ConnectionId next_connection_id = 0; Connection::Connection(EventPoll& p, int fd, IConnectionStateObserver& obsrv): IFdObserver(p, fd, EPOLLIN | EPOLLOUT), poll{p}, connection_id{++next_connection_id}, observer{obsrv}, file_desc{fd}, is_broken{false}, write_ready{true}, already_written{0}, read_ready{true}, already_read{0} { read_buffer.resize(read_buffer_size); } Connection::~Connection(){ close(); } void Connection::close(){ if(broken()){ return; } is_broken = true; read_ready = false; write_ready = false; observer.notify(*this, ConnectionState::Broken); } /* * Based on EPoll notification accept, read or write in a non blocking way * and queue reads and/or handle writes */ void Connection::notify(uint32_t mask){ if(broken()){ return; } if( mask & EPOLLOUT ){ write_ready = true; onReadyWrite(); observer.notify(*this, ConnectionState::WriteReady); } if( mask & EPOLLIN ){ read_ready = true; onReadyRead(); observer.notify(*this, ConnectionState::ReadReady); } } void Connection::write(std::vector<uint8_t>&& buffer){ if(write_buffer.empty()){ write_buffer = std::move(buffer); }else /*if (write_buffer.size() + buffer.size() <= write_buffer_size)*/{ write_buffer.insert(std::end(write_buffer), std::begin(buffer),std::end(buffer)); }/*else{ }*/ if(write_ready){ onReadyWrite(); } } bool Connection::hasWriteQueued() const { return !write_buffer.empty(); } void Connection::onReadyWrite(){ while(write_ready && write_buffer.size() > 0){ ssize_t n = ::send(file_desc, write_buffer.data(), write_buffer.size(), MSG_NOSIGNAL); if(n<0){ if(errno != EAGAIN){ close(); } write_ready = false; return; }else if (n==0){ close(); write_ready = false; return; } already_written += n; size_t remaining = write_buffer.size() - already_written; for(size_t i = 0; i < remaining; ++i){ write_buffer[i] = write_buffer[already_written+i]; } write_buffer.resize(remaining); remaining = 0; } } void Connection::onReadyRead(){ if(broken()){ return; } do { // Not yet read into the buffer size_t remaining = read_buffer.size() - already_read; ssize_t n = ::recv(file_desc, &read_buffer[already_read], remaining, 0); if(n < 0){ if(errno != EAGAIN){ close(); } read_ready = false; return; }else if(n == 0){ close(); read_ready = false; } already_read += static_cast<size_t>(n); }while(read_ready); } std::optional<uint8_t*> Connection::read(size_t n){ if(already_read < n){ if( read_ready ){ onReadyRead(); return read(n); } return std::nullopt; } //auto front = std::move(read_reads.front()); //ready_reads.pop(); return read_buffer.data(); } void Connection::consumeRead(size_t n){ size_t remaining = n < read_buffer.size()?(read_buffer.size()-n):(0); for(size_t i = 0; i < remaining; ++i){ read_buffer[i] = read_buffer[i+n]; } assert(already_read>=n); already_read -= n; } bool Connection::hasReadQueued() const{ return !read_buffer.empty(); } bool Connection::broken() const { return is_broken; } const ConnectionId& Connection::id()const{ return connection_id; } Server::Server(EventPoll& p, int fd, const std::string& addr, IServerStateObserver& obs): IFdObserver(p, fd, EPOLLIN), file_desc{fd}, event_poll{p}, address{addr}, observer{obs} { } Server::~Server(){ ::unlink(address.c_str()); } void Server::notify(uint32_t mask){ if(mask & EPOLLIN){ observer.notify(*this, ServerState::Accept); } } std::unique_ptr<Connection> Server::accept(IConnectionStateObserver& obsrv){ struct ::sockaddr_storage addr; socklen_t addr_len = sizeof(addr); int accepted_fd = ::accept4(file_desc, reinterpret_cast<struct ::sockaddr*>(&addr), &addr_len, SOCK_NONBLOCK | SOCK_CLOEXEC); if(accepted_fd<0) { //TODO Error checking //int error = errno; return nullptr; } return std::make_unique<Connection>(event_poll, accepted_fd, obsrv); } const std::string& UnixSocketAddress::getPath()const{ return bind_address; } Network::Network(){ } void Network::poll(){ ev_poll.poll(); } std::unique_ptr<Server> Network::listen(const std::string& address, IServerStateObserver& obsrv){ auto unix_addr = parseUnixAddress(address); if(!unix_addr){ return nullptr; } auto acceptor = unix_addr->listen(obsrv); if(!acceptor){ return nullptr; } return acceptor; } std::unique_ptr<Connection> Network::connect(const std::string& address, IConnectionStateObserver& obsrv){ auto unix_addr = parseUnixAddress(address); if(!unix_addr){ return nullptr; } auto stream = unix_addr->connect(obsrv); if(!stream){ return nullptr; } return stream; } std::unique_ptr<UnixSocketAddress> Network::parseUnixAddress(const std::string& unix_path){ return std::make_unique<UnixSocketAddress>(ev_poll, unix_path); } }
21.986014
127
0.661472
[ "vector" ]
265d0e1eba115d8bf4fa1ac60f04ff8647676588
2,471
cc
C++
out/euler21.cc
FardaleM/metalang
171557c540f3e2c051ec39ea150afb740c1f615f
[ "BSD-2-Clause" ]
22
2017-04-24T10:00:45.000Z
2021-04-01T10:11:05.000Z
out/euler21.cc
FardaleM/metalang
171557c540f3e2c051ec39ea150afb740c1f615f
[ "BSD-2-Clause" ]
12
2017-03-26T18:34:21.000Z
2019-03-21T19:13:03.000Z
out/euler21.cc
FardaleM/metalang
171557c540f3e2c051ec39ea150afb740c1f615f
[ "BSD-2-Clause" ]
7
2017-10-14T13:33:33.000Z
2021-03-18T15:18:50.000Z
#include <iostream> #include <vector> int eratostene(std::vector<int> * t, int max0) { int n = 0; for (int i = 2; i < max0; i++) if (t->at(i) == i) { n++; int j = i * i; while (j < max0 && j > 0) { t->at(j) = 0; j += i; } } return n; } int fillPrimesFactors(std::vector<int> * t, int n, std::vector<int> * primes, int nprimes) { for (int i = 0; i < nprimes; i++) { int d = primes->at(i); while (n % d == 0) { t->at(d)++; n /= d; } if (n == 1) return primes->at(i); } return n; } int sumdivaux2(std::vector<int> * t, int n, int i) { while (i < n && t->at(i) == 0) i++; return i; } int sumdivaux(std::vector<int> * t, int n, int i) { if (i > n) return 1; else if (t->at(i) == 0) return sumdivaux(t, n, sumdivaux2(t, n, i + 1)); else { int o = sumdivaux(t, n, sumdivaux2(t, n, i + 1)); int out0 = 0; int p = i; for (int j = 1; j <= t->at(i); j++) { out0 += p; p *= i; } return (out0 + 1) * o; } } int sumdiv(int nprimes, std::vector<int> * primes, int n) { std::vector<int> *t = new std::vector<int>( n + 1 ); std::fill(t->begin(), t->end(), 0); int max0 = fillPrimesFactors(t, n, primes, nprimes); return sumdivaux(t, max0, 0); } int main() { int maximumprimes = 1001; std::vector<int> *era = new std::vector<int>( maximumprimes ); for (int j = 0; j < maximumprimes; j++) era->at(j) = j; int nprimes = eratostene(era, maximumprimes); std::vector<int> *primes = new std::vector<int>( nprimes ); std::fill(primes->begin(), primes->end(), 0); int l = 0; for (int k = 2; k < maximumprimes; k++) if (era->at(k) == k) { primes->at(l) = k; l++; } std::cout << l << " == " << nprimes << "\n"; int sum = 0; for (int n = 2; n < 1001; n++) { int other = sumdiv(nprimes, primes, n) - n; if (other > n) { int othersum = sumdiv(nprimes, primes, other) - other; if (othersum == n) { std::cout << other << " & " << n << "\n"; sum += other + n; } } } std::cout << "\n" << sum << "\n"; }
23.759615
92
0.418859
[ "vector" ]
2662f178437b6788b7205e0e053cf135d12a3af4
8,426
cpp
C++
src/cudafeatures2d.cpp
manuelvolk/torch-opencv
edcaa452c9698fc0b113d0e0ffbeaa55c18db5c3
[ "MIT" ]
239
2015-10-13T17:19:40.000Z
2021-11-30T11:30:26.000Z
src/cudafeatures2d.cpp
manuelvolk/torch-opencv
edcaa452c9698fc0b113d0e0ffbeaa55c18db5c3
[ "MIT" ]
202
2015-10-24T09:01:57.000Z
2020-07-28T17:20:12.000Z
src/cudafeatures2d.cpp
manuelvolk/torch-opencv
edcaa452c9698fc0b113d0e0ffbeaa55c18db5c3
[ "MIT" ]
69
2015-11-15T15:02:27.000Z
2022-02-12T16:14:52.000Z
#include <cudafeatures2d.hpp> extern "C" struct DescriptorMatcherPtr createBFMatcherCuda(int normType) { return rescueObjectFromPtr(cuda::DescriptorMatcher::createBFMatcher(normType)); } extern "C" bool DescriptorMatcher_isMaskSupportedCuda(struct DescriptorMatcherPtr ptr) { return ptr->isMaskSupported(); } extern "C" void DescriptorMatcher_addCuda( struct DescriptorMatcherPtr ptr, struct TensorArray descriptors) { ptr->add(descriptors.toGpuMatList()); } extern "C" struct TensorArray DescriptorMatcher_getTrainDescriptorsCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr) { std::vector<cuda::GpuMat> retval = ptr->getTrainDescriptors(); return TensorArray(retval, info.state); } extern "C" void DescriptorMatcher_clearCuda(struct DescriptorMatcherPtr ptr) { ptr->clear(); } extern "C" bool DescriptorMatcher_emptyCuda(struct DescriptorMatcherPtr ptr) { return ptr->empty(); } extern "C" void DescriptorMatcher_trainCuda(struct DescriptorMatcherPtr ptr) { ptr->train(); } extern "C" struct TensorWrapper DescriptorMatcher_matchCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, struct TensorWrapper mask) { cuda::GpuMat retval = matches.toGpuMat(); ptr->matchAsync( queryDescriptors.toGpuMat(), trainDescriptors.toGpuMat(), retval, TO_GPUMAT_OR_NOARRAY(mask), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct TensorWrapper DescriptorMatcher_match_masksCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper matches, struct TensorArray masks) { cuda::GpuMat retval = matches.toGpuMat(); ptr->matchAsync( queryDescriptors.toGpuMat(), retval, TO_GPUMAT_LIST_OR_NOARRAY(masks), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct DMatchArray DescriptorMatcher_matchConvertCuda( struct DescriptorMatcherPtr ptr, struct TensorWrapper gpu_matches) { std::vector<cv::DMatch> retval; ptr->matchConvert(gpu_matches.toGpuMat(), retval); return DMatchArray(retval); } extern "C" struct TensorWrapper DescriptorMatcher_knnMatchCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, int k, struct TensorWrapper mask) { cuda::GpuMat retval = matches.toGpuMat(); ptr->knnMatchAsync( queryDescriptors.toGpuMat(), trainDescriptors.toGpuMat(), retval, k, TO_GPUMAT_OR_NOARRAY(mask), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct TensorWrapper DescriptorMatcher_knnMatch_masksCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, int k, struct TensorArray masks) { cuda::GpuMat retval = matches.toGpuMat(); ptr->knnMatchAsync( queryDescriptors.toGpuMat(), trainDescriptors.toGpuMat(), retval, k, TO_GPUMAT_LIST_OR_NOARRAY(masks), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct DMatchArrayOfArrays DescriptorMatcher_knnMatchConvertCuda( struct DescriptorMatcherPtr ptr, struct TensorWrapper gpu_matches, bool compactResult) { std::vector<std::vector<cv::DMatch>> retval; ptr->knnMatchConvert(gpu_matches.toGpuMat(), retval, compactResult); return DMatchArrayOfArrays(retval); } extern "C" struct TensorWrapper DescriptorMatcher_radiusMatchCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, float maxDistance, struct TensorWrapper mask) { cuda::GpuMat retval = matches.toGpuMat(); ptr->radiusMatchAsync( queryDescriptors.toGpuMat(), trainDescriptors.toGpuMat(), retval, maxDistance, TO_GPUMAT_OR_NOARRAY(mask), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct TensorWrapper DescriptorMatcher_radiusMatch_masksCuda( struct cutorchInfo info, struct DescriptorMatcherPtr ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, float maxDistance, struct TensorArray masks) { cuda::GpuMat retval = matches.toGpuMat(); ptr->radiusMatchAsync( queryDescriptors.toGpuMat(), trainDescriptors.toGpuMat(), retval, maxDistance, TO_GPUMAT_LIST_OR_NOARRAY(masks), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct DMatchArrayOfArrays DescriptorMatcher_radiusMatchConvertCuda( struct DescriptorMatcherPtr ptr, struct TensorWrapper gpu_matches, bool compactResult) { std::vector<std::vector<cv::DMatch>> retval; ptr->radiusMatchConvert(gpu_matches.toGpuMat(), retval, compactResult); return DMatchArrayOfArrays(retval); } extern "C" void Feature2DAsync_dtorCuda(struct Feature2DAsyncPtr ptr) { delete static_cast<cuda::Feature2DAsync *>(ptr.ptr); } extern "C" struct TensorWrapper Feature2DAsync_detectAsyncCuda( struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, struct TensorWrapper keypoints, struct TensorWrapper mask) { cuda::GpuMat retval = keypoints.toGpuMat(); ptr->detectAsync(image.toGpuMat(), retval, TO_GPUMAT_OR_NOARRAY(mask), prepareStream(info)); return TensorWrapper(retval, info.state); } extern "C" struct TensorArray Feature2DAsync_computeAsyncCuda( struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, struct TensorWrapper keypoints, struct TensorWrapper descriptors) { std::vector<cuda::GpuMat> retval(2); retval[0] = keypoints.toGpuMat(); retval[1] = descriptors.toGpuMat(); ptr->computeAsync(image.toGpuMat(), retval[0], retval[1], prepareStream(info)); return TensorArray(retval, info.state); } extern "C" struct TensorArray Feature2DAsync_detectAndComputeAsyncCuda( struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, struct TensorWrapper mask, struct TensorWrapper keypoints, struct TensorWrapper descriptors, bool useProvidedKeypoints) { std::vector<cuda::GpuMat> retval(2); retval[0] = keypoints.toGpuMat(); retval[1] = descriptors.toGpuMat(); ptr->detectAndComputeAsync( image.toGpuMat(), mask.toGpuMat(), retval[0], retval[1], useProvidedKeypoints, prepareStream(info)); return TensorArray(retval, info.state); } extern "C" struct KeyPointArray Feature2DAsync_convertCuda( struct Feature2DAsyncPtr ptr, struct TensorWrapper gpu_keypoints) { std::vector<cv::KeyPoint> retval; ptr->convert(gpu_keypoints.toGpuMat(), retval); return KeyPointArray(retval); } extern "C" struct FastFeatureDetectorPtr FastFeatureDetector_ctorCuda( int threshold, bool nonmaxSuppression, int type, int max_npoints) { return rescueObjectFromPtr( cuda::FastFeatureDetector::create(threshold, nonmaxSuppression, type, max_npoints)); } extern "C" void FastFeatureDetector_setMaxNumPointsCuda(struct FastFeatureDetectorPtr ptr, int val) { ptr->setMaxNumPoints(val); } extern "C" int FastFeatureDetector_getMaxNumPointsCuda(struct FastFeatureDetectorPtr ptr) { return ptr->getMaxNumPoints(); } extern "C" struct ORBPtr ORB_ctorCuda( int nfeatures, float scaleFactor, int nlevels, int edgeThreshold, int firstLevel, int WTA_K, int scoreType, int patchSize, int fastThreshold, bool blurForDescriptor) { return rescueObjectFromPtr( cuda::ORB::create(nfeatures, scaleFactor, nlevels, edgeThreshold, firstLevel, WTA_K, scoreType, patchSize, fastThreshold, blurForDescriptor)); } extern "C" void ORB_setBlurForDescriptorCuda(struct ORBPtr ptr, bool val) { ptr->setBlurForDescriptor(val); } extern "C" bool ORB_getBlurForDescriptorCuda(struct ORBPtr ptr) { return ptr->getBlurForDescriptor(); }
34.962656
96
0.748042
[ "vector" ]
2666e0ab109f98c01e5bdcace976c869cd76553f
1,685
cpp
C++
sources/Leetcodes/src/6_zigzag_conversion.cpp
mcoder2014/myNotes
443cf16b1873bb473b7cb6bc1a6ec9c6423333e7
[ "MIT" ]
4
2020-06-22T13:20:26.000Z
2020-06-24T08:43:11.000Z
sources/Leetcodes/src/6_zigzag_conversion.cpp
mcoder2014/DataStructureAndAlgorithms
443cf16b1873bb473b7cb6bc1a6ec9c6423333e7
[ "MIT" ]
null
null
null
sources/Leetcodes/src/6_zigzag_conversion.cpp
mcoder2014/DataStructureAndAlgorithms
443cf16b1873bb473b7cb6bc1a6ec9c6423333e7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; /*** * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I **/ class Solution { public: string convert(string s, int numRows) { vector<vector<char>> list(numRows, vector<char>()); string result = s; int wide = numRows; if(numRows > 2) wide = 2 * numRows - 2; int length = s.length(); for (int i = 0; i < length; i++) { int id = i % wide; if(id < numRows) list[id].push_back(s[i]); else { list[numRows -2 -(id%numRows)].push_back(s[i]); } } int idx = 0; for (int i=0; i<numRows; i++) { for (char c:list[i]) { // cout << c; result[idx] = c; ++idx; } // cout << endl; } return result; } }; int main() { Solution solution; string s = "PAYPALISHIRING"; string res = solution.convert(s, 4); cout << res << endl; return 0; }
20.301205
172
0.525816
[ "vector" ]
2670ea5bd7ea00803b8ad38714dea8662de3004e
3,662
cc
C++
r-kvstore/src/model/DescribeDBInstanceNetInfoResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
r-kvstore/src/model/DescribeDBInstanceNetInfoResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
r-kvstore/src/model/DescribeDBInstanceNetInfoResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/r-kvstore/model/DescribeDBInstanceNetInfoResult.h> #include <json/json.h> using namespace AlibabaCloud::R_kvstore; using namespace AlibabaCloud::R_kvstore::Model; DescribeDBInstanceNetInfoResult::DescribeDBInstanceNetInfoResult() : ServiceResult() {} DescribeDBInstanceNetInfoResult::DescribeDBInstanceNetInfoResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDBInstanceNetInfoResult::~DescribeDBInstanceNetInfoResult() {} void DescribeDBInstanceNetInfoResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allNetInfoItemsNode = value["NetInfoItems"]["InstanceNetInfo"]; for (auto valueNetInfoItemsInstanceNetInfo : allNetInfoItemsNode) { InstanceNetInfo netInfoItemsObject; if(!valueNetInfoItemsInstanceNetInfo["ConnectionString"].isNull()) netInfoItemsObject.connectionString = valueNetInfoItemsInstanceNetInfo["ConnectionString"].asString(); if(!valueNetInfoItemsInstanceNetInfo["IPAddress"].isNull()) netInfoItemsObject.iPAddress = valueNetInfoItemsInstanceNetInfo["IPAddress"].asString(); if(!valueNetInfoItemsInstanceNetInfo["Port"].isNull()) netInfoItemsObject.port = valueNetInfoItemsInstanceNetInfo["Port"].asString(); if(!valueNetInfoItemsInstanceNetInfo["VPCId"].isNull()) netInfoItemsObject.vPCId = valueNetInfoItemsInstanceNetInfo["VPCId"].asString(); if(!valueNetInfoItemsInstanceNetInfo["VSwitchId"].isNull()) netInfoItemsObject.vSwitchId = valueNetInfoItemsInstanceNetInfo["VSwitchId"].asString(); if(!valueNetInfoItemsInstanceNetInfo["DBInstanceNetType"].isNull()) netInfoItemsObject.dBInstanceNetType = valueNetInfoItemsInstanceNetInfo["DBInstanceNetType"].asString(); if(!valueNetInfoItemsInstanceNetInfo["VPCInstanceId"].isNull()) netInfoItemsObject.vPCInstanceId = valueNetInfoItemsInstanceNetInfo["VPCInstanceId"].asString(); if(!valueNetInfoItemsInstanceNetInfo["IPType"].isNull()) netInfoItemsObject.iPType = valueNetInfoItemsInstanceNetInfo["IPType"].asString(); if(!valueNetInfoItemsInstanceNetInfo["ExpiredTime"].isNull()) netInfoItemsObject.expiredTime = valueNetInfoItemsInstanceNetInfo["ExpiredTime"].asString(); if(!valueNetInfoItemsInstanceNetInfo["Upgradeable"].isNull()) netInfoItemsObject.upgradeable = valueNetInfoItemsInstanceNetInfo["Upgradeable"].asString(); if(!valueNetInfoItemsInstanceNetInfo["DirectConnection"].isNull()) netInfoItemsObject.directConnection = std::stoi(valueNetInfoItemsInstanceNetInfo["DirectConnection"].asString()); netInfoItems_.push_back(netInfoItemsObject); } if(!value["InstanceNetworkType"].isNull()) instanceNetworkType_ = value["InstanceNetworkType"].asString(); } std::vector<DescribeDBInstanceNetInfoResult::InstanceNetInfo> DescribeDBInstanceNetInfoResult::getNetInfoItems()const { return netInfoItems_; } std::string DescribeDBInstanceNetInfoResult::getInstanceNetworkType()const { return instanceNetworkType_; }
43.082353
117
0.801202
[ "vector", "model" ]
2677527ed4f1e8ebfe7d5260c01e6fdf2d7c3adc
3,159
hpp
C++
includes/CryptoUtils.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
includes/CryptoUtils.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
includes/CryptoUtils.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
#ifndef CRYPTO_UTILS_HPP #define CRYPTO_UTILS_HPP #include <algorithm> #include <cassert> #include <cstdint> #include <cstring> #include <exception> #include <iomanip> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/obj_mac.h> #include <openssl/ripemd.h> #include <openssl/sha.h> using byte = unsigned char; using const_bytes = const unsigned char*; const int DIGEST_LENGTH = 32; const byte DER_HEADLINE = 0x30; const byte BEGIN_OF_NUM = 0x02; const byte SIGHASH_ALL = 0x01; // signature is valid for all exits // if not static the file is included more than once and occurs multiple // definition static const char* Base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; namespace cu { std::vector<byte> from_hex_to_bytes(const std::string& hex); std::string from_bytes_to_hex(const_bytes bytes, int length); std::string from_bytes_to_hex(const std::vector<byte>& bytes); std::string to_littleendian_format(const std::string& string); void to_littleendian_format(std::vector<byte>& bytes); std::vector<byte> to_varint_byte(size_t n); uint64_t to_varint(size_t size); std::string get_addres_from_script(const std::vector<byte>& bytes); std::string SHA256(const std::string& string); std::string RIPEMD160(const std::string& string); std::vector<byte> SHA256(const std::vector<byte>& string); std::vector<byte> RIPEMD160(const std::vector<byte>& string); std::string to_hex(byte s); std::string to_base58(const_bytes pbegin, const_bytes pend); std::string to_base58(const std::vector<byte>& vch); bool from_base58(const char* psz, std::vector<byte>& vch); bool from_base58(const std::string& str, std::vector<byte>& vchRet); BIGNUM* get_private_key_from_wif(const std::string& private_key_wif); EC_KEY* get_ec_key_from_private(const std::string& private_key_wif); EC_KEY* get_ec_key_from_public(const std::string& public_key); ECDSA_SIG* sign(const std::string& private_key, const std::vector<byte>& text); bool is_validate_signature(const std::string& public_key, const ECDSA_SIG* signature, const std::vector<byte>& text); std::string signature_to_der(const ECDSA_SIG* signature); std::vector<byte> signature_to_der_byted(const ECDSA_SIG* signature); ECDSA_SIG* from_der_to_sig(const std::string& scriptSig); template <typename T> std::vector<byte> to_bytes(T i) { static_assert(std::is_fundamental<T>::value, "not a fundamental type"); std::vector<byte> a(sizeof(i)); std::memcpy(&a[0], &i, sizeof(i)); return a; } template <typename T, class It> T to_type(It begin, It end) { static_assert(std::is_fundamental<T>::value, "not a fundamental type"); using this_type = typename std::remove_reference<decltype(*begin)>::type; using data = typename std::remove_const<this_type>::type; static_assert(std::is_same<data, byte>::value, "not a chunk"); T x; auto size = std::distance(begin, end); std::memcpy(&x, &(*begin), size); return x; } } // namespace cu #endif // CRYPTO_UTILS_HPP
27.955752
79
0.736942
[ "vector" ]
26824f976ff2cd84549d02a223e0d70ec82485e4
529
hh
C++
ParticleID/inc/PIDUtilities.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
ParticleID/inc/PIDUtilities.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
ParticleID/inc/PIDUtilities.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
#ifndef ParticleID_Utilities_hh #define ParticleID_Utilities_hh // // Original author Vadim Rusu // // C++ includes #include <vector> #include <map> //ROOT includes #include "TH1D.h" namespace mu2e { class PIDUtilities{ public: PIDUtilities() {} TH1D *th1dmorph( TH1D *,TH1D *, double par1,double par2,double parinterp, double morphedhistnorm, int idebug) const; }; } // namespace mu2e #endif /* ParticleID_Utilities_hh */
15.114286
61
0.599244
[ "vector" ]
2686ad6213ea0a8c867fa6ae63b742bee574837e
10,464
cxx
C++
PWGLF/SPECTRA/PiKaPr/TestAOD/AliAnalysisTaskSpectraAOD.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGLF/SPECTRA/PiKaPr/TestAOD/AliAnalysisTaskSpectraAOD.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGLF/SPECTRA/PiKaPr/TestAOD/AliAnalysisTaskSpectraAOD.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------- // AliAnalysisTaskSpectraAOD class //----------------------------------------------------------------- #include "TChain.h" #include "TTree.h" #include "TLegend.h" #include "TH1F.h" #include "TH2F.h" #include "TCanvas.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliAODTrack.h" #include "AliAODMCParticle.h" #include "AliVParticle.h" #include "AliAODEvent.h" #include "AliAODInputHandler.h" #include "AliAnalysisTaskSpectraAOD.h" #include "AliAnalysisTaskESDfilter.h" #include "AliAnalysisDataContainer.h" #include "AliSpectraAODHistoManager.h" #include "AliSpectraAODTrackCuts.h" #include "AliSpectraAODEventCuts.h" #include "AliCentrality.h" #include "TProof.h" #include "AliPID.h" #include "AliVEvent.h" #include "AliPIDResponse.h" #include "AliStack.h" #include "AliSpectraAODPID.h" #include <TMCProcess.h> #include <iostream> using namespace AliSpectraNameSpace; using namespace std; ClassImp(AliAnalysisTaskSpectraAOD) // EX1 This stuff tells root to implement the streamer, inspector methods etc (we discussed about it today) //________________________________________________________________________ AliAnalysisTaskSpectraAOD::AliAnalysisTaskSpectraAOD(const char *name) : AliAnalysisTaskSE(name), fAOD(0), fHistMan(0), fTrackCuts(0), fEventCuts(0), fPID(0), fIsMC(0), fNRebin(0) { // Default constructor DefineInput(0, TChain::Class()); DefineOutput(1, AliSpectraAODHistoManager::Class()); DefineOutput(2, AliSpectraAODEventCuts::Class()); DefineOutput(3, AliSpectraAODTrackCuts::Class()); DefineOutput(4, AliSpectraAODPID::Class()); fNRebin=0; } //________________________________________________________________________ //________________________________________________________________________ void AliAnalysisTaskSpectraAOD::UserCreateOutputObjects() { // create output objects fHistMan = new AliSpectraAODHistoManager("SpectraHistos",fNRebin); if (!fTrackCuts) AliFatal("Track Cuts should be set in the steering macro"); if (!fEventCuts) AliFatal("Event Cuts should be set in the steering macro"); if (!fPID) AliFatal("PID object should be set in the steering macro"); PostData(1, fHistMan ); PostData(2, fEventCuts); PostData(3, fTrackCuts); PostData(4, fPID ); } //________________________________________________________________________ void AliAnalysisTaskSpectraAOD::UserExec(Option_t *) { // main event loop //Printf("ALIVE"); fAOD = dynamic_cast<AliAODEvent*>(fInputEvent); if (!fAOD) { AliWarning("ERROR: AliAODEvent not available \n"); return; } if (strcmp(fAOD->ClassName(), "AliAODEvent")) { AliFatal("Not processing AODs"); } if(!fEventCuts->IsSelected(fAOD,fTrackCuts))return;//event selection //AliCentrality fAliCentral*; // if ((fAOD->GetCentrality())->GetCentralityPercentile("V0M") > 5.) return; // First do MC to fill up the MC particle array, such that we can use it later TClonesArray *arrayMC = 0; if (fIsMC) { arrayMC = (TClonesArray*) fAOD->GetList()->FindObject(AliAODMCParticle::StdBranchName()); if (!arrayMC) { AliFatal("Error: MC particles branch not found!\n"); } Int_t nMC = arrayMC->GetEntries(); for (Int_t iMC = 0; iMC < nMC; iMC++) { AliAODMCParticle *partMC = (AliAODMCParticle*) arrayMC->At(iMC); if(!partMC->Charge()) continue;//Skip neutrals //if(partMC->Eta() > fTrackCuts->GetEtaMin() && partMC->Eta() < fTrackCuts->GetEtaMax()){//charged hadron are filled inside the eta acceptance //Printf("%f %f-%f",partMC->Eta(),fTrackCuts->GetEtaMin(),fTrackCuts->GetEtaMax()); if(partMC->Eta() < fTrackCuts->GetEtaMin() || partMC->Eta() > fTrackCuts->GetEtaMax())continue;//ETA CUT ON GENERATED!!!!!!!!!!!!!!!!!!!!!!!!!! fHistMan->GetPtHistogram(kHistPtGen)->Fill(partMC->Pt(),partMC->IsPhysicalPrimary()); //rapidity cut if(TMath::Abs(partMC->Y()) > fTrackCuts->GetY() ) continue; // check for true PID + and fill P_t histos Int_t charge = partMC->Charge() > 0 ? kChPos : kChNeg ; Int_t id = fPID->GetParticleSpecie(partMC); if(id != kSpUndefined) { fHistMan->GetHistogram2D(kHistPtGenTruePrimary,id,charge)->Fill(partMC->Pt(),partMC->IsPhysicalPrimary()); } } } Double_t mass[3]={1.39570000000000000e-01,4.93676999999999977e-01,9.38271999999999995e-01};//FIXME masses to be taken from AliHelperPID //main loop on tracks for (Int_t iTracks = 0; iTracks < fAOD->GetNumberOfTracks(); iTracks++) { AliAODTrack* track = dynamic_cast<AliAODTrack*>(fAOD->GetTrack(iTracks)); if(!track) AliFatal("Not a standard AOD"); if (!fTrackCuts->IsSelected(track,kTRUE)) continue; fPID->FillQAHistos(fHistMan, track, fTrackCuts); //calculate DCA for AOD track Double_t dca=track->DCA(); if(dca==-999.){// track->DCA() does not work in old AOD production Double_t d[2], covd[3]; AliAODTrack* track_clone=(AliAODTrack*)track->Clone("track_clone"); // need to clone because PropagateToDCA updates the track parameters Bool_t isDCA = track_clone->PropagateToDCA(fAOD->GetPrimaryVertex(),fAOD->GetMagneticField(),9999.,d,covd); delete track_clone; if(!isDCA)d[0]=-999.; dca=d[0]; } fHistMan->GetPtHistogram(kHistPtRec)->Fill(track->Pt(),dca); // PT histo // get identity and charge Int_t idRec = fPID->GetParticleSpecie(fHistMan,track, fTrackCuts); Int_t charge = track->Charge() > 0 ? kChPos : kChNeg; // Fill histograms, only if inside y and nsigma acceptance if(idRec != kSpUndefined){ if(fTrackCuts->CheckYCut (mass[idRec]))fHistMan->GetHistogram2D(kHistPtRecSigma,idRec,charge)->Fill(track->Pt(),dca); }//can't put a continue because we still have to fill allcharged primaries, done later /* MC Part */ if (arrayMC) { AliAODMCParticle *partMC = (AliAODMCParticle*) arrayMC->At(TMath::Abs(track->GetLabel())); if (!partMC) { AliError("Cannot get MC particle"); continue; } // Check if it is primary, secondary from material or secondary from weak decay Bool_t isPrimary = partMC->IsPhysicalPrimary(); Bool_t isSecondaryMaterial = kFALSE; Bool_t isSecondaryWeak = kFALSE; if(!isPrimary) { Int_t mfl=-999,codemoth=-999; Int_t indexMoth=partMC->GetMother(); // FIXME ignore fakes? TO BE CHECKED, on ESD is GetFirstMother() if(indexMoth>=0){//is not fake AliAODMCParticle* moth = (AliAODMCParticle*) arrayMC->At(indexMoth); codemoth = TMath::Abs(moth->GetPdgCode()); mfl = Int_t (codemoth/ TMath::Power(10, Int_t(TMath::Log10(codemoth)))); } //Int_t uniqueID = partMC->GetUniqueID(); //cout<<"uniqueID: "<<partMC->GetUniqueID()<<" "<<kPDecay<<endl; //cout<<"status: "<<partMC->GetStatus()<<" "<<kPDecay<<endl; // if(uniqueID == kPDecay)Printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if(mfl==3) isSecondaryWeak = kTRUE; // add if(partMC->GetStatus() & kPDecay)? FIXME else isSecondaryMaterial = kTRUE; } if (isPrimary)fHistMan->GetPtHistogram(kHistPtRecPrimary)->Fill(track->Pt(),dca); // PT histo of primaries //nsigma cut (reconstructed nsigma) if(idRec == kSpUndefined) continue; // rapidity cut (reconstructed pt and identity) if(!fTrackCuts->CheckYCut (mass[idRec])) continue; // Get true ID Int_t idGen = fPID->GetParticleSpecie(partMC); //if(TMath::Abs(partMC->Y()) > fTrackCuts->GetY() ) continue; // FIXME: do we need a rapidity cut on the generated? // Fill histograms for primaries if (idRec == idGen) fHistMan->GetHistogram2D(kHistPtRecTrue, idGen, charge)->Fill(track->Pt(),dca); if (isPrimary) { fHistMan ->GetHistogram2D(kHistPtRecSigmaPrimary, idRec, charge)->Fill(track->Pt(),dca); if(idGen != kSpUndefined) { fHistMan ->GetHistogram2D(kHistPtRecPrimary, idGen, charge)->Fill(track->Pt(),dca); if (idRec == idGen) fHistMan->GetHistogram2D(kHistPtRecTruePrimary, idGen, charge)->Fill(track->Pt(),dca); } } //25th Apr - Muons are added to Pions -- FIXME if ( partMC->PdgCode() == 13 && idRec == kSpPion) { fHistMan->GetPtHistogram(kHistPtRecTrueMuonPlus)->Fill(track->Pt(),dca); if(isPrimary) fHistMan->GetPtHistogram(kHistPtRecTruePrimaryMuonPlus)->Fill(track->Pt(),dca); } if ( partMC->PdgCode() == -13 && idRec == kSpPion) { fHistMan->GetPtHistogram(kHistPtRecTrueMuonMinus)->Fill(track->Pt(),dca); if (isPrimary) { fHistMan->GetPtHistogram(kHistPtRecTruePrimaryMuonMinus)->Fill(track->Pt(),dca); } } ///..... END FIXME // Fill secondaries if(isSecondaryWeak ) fHistMan->GetHistogram2D(kHistPtRecSigmaSecondaryWeakDecay, idRec, charge)->Fill(track->Pt(),dca); if(isSecondaryMaterial) fHistMan->GetHistogram2D(kHistPtRecSigmaSecondaryMaterial , idRec, charge)->Fill(track->Pt(),dca); }//end if(arrayMC) } // end loop on tracks PostData(1, fHistMan ); PostData(2, fEventCuts); PostData(3, fTrackCuts); PostData(4, fPID ); } //_________________________________________________________________ void AliAnalysisTaskSpectraAOD::Terminate(Option_t *) { // Terminate }
41.689243
180
0.65367
[ "object" ]
2689d94a18db93544aa41a3ecb04fd0ce1215016
1,495
hh
C++
include/HCal.hh
freddyox/hcal-dev
cb0cf2830e6f6c1cddad905c1c2fa4a526b061a9
[ "MIT" ]
null
null
null
include/HCal.hh
freddyox/hcal-dev
cb0cf2830e6f6c1cddad905c1c2fa4a526b061a9
[ "MIT" ]
null
null
null
include/HCal.hh
freddyox/hcal-dev
cb0cf2830e6f6c1cddad905c1c2fa4a526b061a9
[ "MIT" ]
null
null
null
#ifndef HCAL_HH #define HCAL_HH #include <SFML/Graphics.hpp> #include <vector> #include <map> #include <set> class HCal : public sf::Drawable, public sf::Transformable { private: float displayx, displayy; sf::Vector2f center_display; // Module Properties float mylar; sf::Vector2f size; float minx, maxx, miny, maxy; int count_modules, count_nodes; int maxclustersize; float hcal_x, hcal_y; int maxrow, maxcol; sf::RectangleShape temp; std::vector<sf::RectangleShape> modules; std::vector<sf::RectangleShape>::iterator modit; std::map<int,sf::RectangleShape> modmap, cluster, final; std::map<int,sf::RectangleShape>::iterator mapit, clustit, clusterit, lastone; std::vector<std::map<int,sf::RectangleShape> > global_logic; std::vector<std::map<int,sf::RectangleShape> >::iterator glit, glit_rest; // Node Properties float nodeR; int increment; sf::CircleShape node; std::vector<sf::CircleShape> nodes; std::vector<sf::CircleShape>::iterator nodit; std::vector<sf::Text> textnodes; sf::Font font; sf::Text textind; // Boarders std::vector<sf::Color> colors, boardercolors; sf::VertexArray lines; std::vector<sf::VertexArray> boarderthelogic; std::vector<std::vector<sf::VertexArray> > manyboarders; public: HCal(float,float); ~HCal() {}; void draw(sf::RenderTarget&, sf::RenderStates) const; void initializeHCal(); void triggerlogic(); void colorthelogic(); void logicinfo(); void indexnodes(); }; #endif
24.112903
80
0.710368
[ "vector" ]
26a5552c8f46ee781faf2708f982a3877b8151e9
2,854
cpp
C++
src/widget/tagselector.cpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
src/widget/tagselector.cpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
src/widget/tagselector.cpp
degarashi/sprinkler
afc6301ae2c7185f514148100da63dcef94d7f00
[ "MIT" ]
null
null
null
#include "tagselector.hpp" #include "../tagselect_model.hpp" #include "../tagvalidator.hpp" #include "../dbtag_if.hpp" #include "../database_sig.hpp" #include "ui_tagselector.h" #include <QSqlTableModel> namespace dg::widget { TagSelector::TagSelector(QWidget* parent): QWidget(parent), _ui(new Ui::TagSelector), _dbTag(nullptr) { _ui->setupUi(this); } void TagSelector::init(const DBTag *const tag, const DatabaseSignal *const sig) { Q_ASSERT(!_dbTag); _dbTag = tag; _tagCand = tag->makeTagModel(this); _tagCand->setSort(1, Qt::AscendingOrder); _ui->candTag->setModel(_tagCand); _ui->candTag->setModelColumn(1); _tagSelected = new TagSelectModel(tag, sig, this); _ui->selectTag->setModel(_tagSelected); _ui->selectTag->setModelColumn(0); const auto refl = [this](auto...){ _refreshCount(); }; connect(_tagSelected, &QAbstractItemModel::rowsRemoved, this, refl); connect(_tagSelected, &QAbstractItemModel::rowsInserted, this, refl); connect(_tagSelected, &QAbstractItemModel::modelReset, this, refl); connect(sig, &DatabaseSignal::endResetImage, this, refl); connect(sig, &DatabaseSignal::endResetLink, this, refl); _refreshCount(); _ui->leTag->setValidator(new TagValidator(tag, this)); connect(_ui->leTag, &QLineEdit::textChanged, this, [this](const QString& text){ // 前方一致で候補を検索 _tagCand->setFilter(QString("name LIKE '%1%'").arg(text)); }); QMetaObject::invokeMethod(_ui->leTag, "textChanged", Q_ARG(QString, "")); connect(_tagSelected, &QAbstractItemModel::modelReset, this, [this](){ emit changed(_tagSelected->getArray()); }); } void TagSelector::_refreshCount() const { // タグ番号配列を取得 const auto tags = _tagSelected->getArray(); const auto c = _dbTag->countImageByTag(tags); // ANDで検索 _ui->lbCount->setText( QString(tr("%1 tags selected\t(%2 images found, %3 images already shown)")) .arg(tags.size()) .arg(c.total) .arg(c.shown) ); } void TagSelector::onAdd() { QString tagName; { const auto sel = _ui->candTag->selectionModel()->selectedIndexes(); if(sel.size() == 1) { tagName = sel[0].data().toString(); } else { const auto le = _ui->leTag->text(); if(!le.isEmpty()) { if(_dbTag->getTagId(le)) { tagName = le; _ui->leTag->selectAll(); } } } } if(!tagName.isEmpty()) { const auto tagId = _dbTag->getTagId(tagName); Q_ASSERT(tagId); _tagSelected->add(*tagId); } } void TagSelector::onRem() { const auto sl = _ui->selectTag->selectionModel()->selectedRows(); std::vector<int> idxv; for(const auto& idx : sl) idxv.emplace_back(idx.row()); std::sort(idxv.begin(), idxv.end()); std::reverse(idxv.begin(), idxv.end()); for(const auto idx : idxv) _tagSelected->rem(idx); } TagIdV TagSelector::getArray() const { return _tagSelected->getArray(); } }
28.828283
82
0.672039
[ "vector" ]
564c04e25d1d224ad4a183f353bd2fe49fc6a61e
12,863
cpp
C++
osm2csv.cpp
TimSC/pgmap-query
02a274172ec651e41db89bffd7b11d1f91eb5488
[ "MIT" ]
2
2018-09-01T00:32:35.000Z
2019-03-24T15:10:41.000Z
osm2csv.cpp
TimSC/pgmap-query
02a274172ec651e41db89bffd7b11d1f91eb5488
[ "MIT" ]
5
2018-02-05T01:53:48.000Z
2019-05-12T20:22:14.000Z
osm2csv.cpp
TimSC/pgmap-query
02a274172ec651e41db89bffd7b11d1f91eb5488
[ "MIT" ]
1
2021-03-18T10:15:41.000Z
2021-03-18T10:15:41.000Z
#include "cppGzip/DecodeGzip.h" #include "cppGzip/EncodeGzip.h" #include "cppo5m/OsmData.h" #include <iostream> #include <fstream> #include <sstream> #include "dbjson.h" #include "util.h" using namespace std; /* select * from pg_stat_activity; SELECT *, ST_X(geom) as lon, ST_Y(geom) AS lat FROM andorra_nodes WHERE geom && ST_MakeEnvelope(1.5020099, 42.5228903, 1.540173, 42.555443, 4326); GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO microcosm; CREATE INDEX nodes_gin ON nodes USING GIN (tags); SELECT * FROM nodes WHERE tags ? 'amenity' LIMIT 10; Import from fosm.org 2015 dump table_name | row_estimate | toast_bytes | table_bytes | total | index | toast | table -------------------------+--------------+-------------+--------------+------------+------------+------------+------------ planet_nodes | 1.36598e+09 | 131072 | 166346784768 | 252 GB | 98 GB | 128 kB | 155 GB planet_ways | 1.23554e+08 | 548945920 | 48414597120 | 48 GB | 2647 MB | 524 MB | 45 GB planet_relations | 1.39281e+06 | 14221312 | 653623296 | 1082 MB | 445 MB | 14 MB | 623 MB planet_way_mems | 1.6108e+09 | | 84069392384 | 112 GB | 34 GB | | 78 GB planet_relation_mems_w | 1.2219e+07 | | 637747200 | 870 MB | 262 MB | | 608 MB planet_relation_mems_r | 112434 | | 5898240 | 8256 kB | 2496 kB | | 5760 kB planet_relation_mems_n | 1.78653e+06 | | 93265920 | 127 MB | 38 MB | | 89 MB COPY planet_relations TO PROGRAM 'gzip > /home/postgres/dumprelations.gz' WITH (FORMAT 'csv', DELIMITER ',', NULL 'NULL'); */ inline string Int64ToStr(int64_t val) { stringstream ss; ss << val; return ss.str(); } class CsvStore : public IDataStreamHandler { private: std::filebuf livenodeFile, livewayFile, liverelationFile, oldnodeFile, oldwayFile, oldrelationFile; std::filebuf nodeIdsFile, wayIdsFile, relationIdsFile; std::filebuf wayMembersFile, relationMemNodesFile, relationMemWaysFile, relationMemRelsFile; std::shared_ptr<class EncodeGzip> livenodeFileGzip, livewayFileGzip, liverelationFileGzip, oldnodeFileGzip, oldwayFileGzip, oldrelationFileGzip; std::shared_ptr<class EncodeGzip> nodeIdsFileGzip, wayIdsFileGzip, relationIdsFileGzip; std::shared_ptr<class EncodeGzip> wayMembersFileGzip, relationMemNodesFileGzip, relationMemWaysFileGzip, relationMemRelsFileGzip; public: CsvStore(const std::string &outPrefix); virtual ~CsvStore(); virtual bool Sync() {return false;}; virtual bool Reset() {return false;}; virtual bool Finish(); virtual bool StoreIsDiff(bool) {return false;}; virtual bool StoreBounds(double x1, double y1, double x2, double y2) {return false;}; virtual bool StoreNode(int64_t objId, const class MetaData &metaData, const TagMap &tags, double lat, double lon); virtual bool StoreWay(int64_t objId, const class MetaData &metaData, const TagMap &tags, const std::vector<int64_t> &refs); virtual bool StoreRelation(int64_t objId, const class MetaData &metaData, const TagMap &tags, const std::vector<std::string> &refTypeStrs, const std::vector<int64_t> &refIds, const std::vector<std::string> &refRoles); }; CsvStore::CsvStore(const std::string &outPrefix) { cout << outPrefix+"livenodes.csv.gz" << endl; livenodeFile.open(outPrefix+"livenodes.csv.gz", std::ios::out | std::ios::binary); if(!livenodeFile.is_open()) throw runtime_error("Error opening output"); livenodeFileGzip.reset(new class EncodeGzip(livenodeFile)); livewayFile.open(outPrefix+"liveways.csv.gz", std::ios::out | std::ios::binary); livewayFileGzip.reset(new class EncodeGzip(livewayFile)); liverelationFile.open(outPrefix+"liverelations.csv.gz", std::ios::out | std::ios::binary); liverelationFileGzip.reset(new class EncodeGzip(liverelationFile)); oldnodeFile.open(outPrefix+"oldnodes.csv.gz", std::ios::out | std::ios::binary); oldnodeFileGzip.reset(new class EncodeGzip(oldnodeFile)); oldwayFile.open(outPrefix+"oldways.csv.gz", std::ios::out | std::ios::binary); oldwayFileGzip.reset(new class EncodeGzip(oldwayFile)); oldrelationFile.open(outPrefix+"oldrelations.csv.gz", std::ios::out | std::ios::binary); oldrelationFileGzip.reset(new class EncodeGzip(oldrelationFile)); nodeIdsFile.open(outPrefix+"nodeids.csv.gz", std::ios::out | std::ios::binary); nodeIdsFileGzip.reset(new class EncodeGzip(nodeIdsFile)); wayIdsFile.open(outPrefix+"wayids.csv.gz", std::ios::out | std::ios::binary); wayIdsFileGzip.reset(new class EncodeGzip(wayIdsFile)); relationIdsFile.open(outPrefix+"relationids.csv.gz", std::ios::out | std::ios::binary); relationIdsFileGzip.reset(new class EncodeGzip(relationIdsFile)); wayMembersFile.open(outPrefix+"waymems.csv.gz", std::ios::out | std::ios::binary); wayMembersFileGzip.reset(new class EncodeGzip(wayMembersFile)); relationMemNodesFile.open(outPrefix+"relationmems-n.csv.gz", std::ios::out | std::ios::binary); relationMemNodesFileGzip.reset(new class EncodeGzip(relationMemNodesFile)); relationMemWaysFile.open(outPrefix+"relationmems-w.csv.gz", std::ios::out | std::ios::binary); relationMemWaysFileGzip.reset(new class EncodeGzip(relationMemWaysFile)); relationMemRelsFile.open(outPrefix+"relationmems-r.csv.gz", std::ios::out | std::ios::binary); relationMemRelsFileGzip.reset(new class EncodeGzip(relationMemRelsFile)); } CsvStore::~CsvStore() { livenodeFileGzip.reset(); livenodeFile.close(); livewayFileGzip.reset(); livewayFile.close(); liverelationFileGzip.reset(); liverelationFile.close(); oldnodeFileGzip.reset(); oldnodeFile.close(); oldwayFileGzip.reset(); oldwayFile.close(); oldrelationFileGzip.reset(); oldrelationFile.close(); nodeIdsFileGzip.reset(); nodeIdsFile.close(); wayIdsFileGzip.reset(); wayIdsFile.close(); relationIdsFileGzip.reset(); relationIdsFile.close(); wayMembersFileGzip.reset(); wayMembersFile.close(); relationMemNodesFileGzip.reset(); relationMemNodesFile.close(); relationMemWaysFileGzip.reset(); relationMemWaysFile.close(); relationMemRelsFileGzip.reset(); relationMemRelsFile.close(); } bool CsvStore::Finish() { return false; } bool CsvStore::StoreNode(int64_t objId, const class MetaData &metaData, const TagMap &tags, double lat, double lon) { string tagsJson; EncodeTags(tags, tagsJson); StrReplaceAll(tagsJson, "\"", "\"\""); string usernameStr = metaData.username; if(metaData.username.size() > 0) { StrReplaceAll(usernameStr, "\"", "\"\""); usernameStr = "\""+usernameStr+"\""; } else usernameStr = "NULL"; string uidStr; if(metaData.uid!=0) uidStr = Int64ToStr(metaData.uid); else uidStr = "NULL"; string changesetStr = Int64ToStr(metaData.changeset); if(metaData.changeset==0) changesetStr="NULL"; string timestampStr = Int64ToStr(metaData.timestamp); if(metaData.timestamp==0) timestampStr="NULL"; string visibleStr = metaData.visible ? "true" : "false"; std::string changesetIndex="NULL"; stringstream ss; ss.precision(9); if(metaData.current and metaData.visible) { ss << objId <<","<< changesetStr <<","<< changesetIndex <<","<< usernameStr <<","<< uidStr <<","<< \ timestampStr <<","<< metaData.version <<",\"" << tagsJson << "\",SRID=4326;POINT("<< fixed << lon<<" "<<lat<<")\n"; string row(ss.str()); this->livenodeFileGzip->sputn(row.c_str(), row.size()); } else { ss << objId <<","<< changesetStr <<","<< changesetIndex <<","<< usernameStr <<","<< uidStr <<","<< visibleStr <<","<<\ timestampStr <<","<< metaData.version <<",\"" << tagsJson << "\",SRID=4326;POINT("<< fixed << lon<<" "<<lat<<")\n"; string row(ss.str()); this->oldnodeFileGzip->sputn(row.c_str(), row.size()); } string objIdStr = Int64ToStr(objId); objIdStr += "\n"; this->nodeIdsFileGzip->sputn(objIdStr.c_str(), objIdStr.size()); return false; } bool CsvStore::StoreWay(int64_t objId, const class MetaData &metaData, const TagMap &tags, const std::vector<int64_t> &refs) { string tagsJson; EncodeTags(tags, tagsJson); StrReplaceAll(tagsJson, "\"", "\"\""); string refsJson; EncodeInt64Vec(refs, refsJson); StrReplaceAll(refsJson, "\"", "\"\""); string usernameStr = metaData.username; if(metaData.username.size() > 0) { StrReplaceAll(usernameStr, "\"", "\"\""); usernameStr = "\""+usernameStr+"\""; } else usernameStr = "NULL"; string uidStr; if(metaData.uid!=0) uidStr = Int64ToStr(metaData.uid); else uidStr = "NULL"; string changesetStr = Int64ToStr(metaData.changeset); if(metaData.changeset==0) changesetStr="NULL"; string timestampStr = Int64ToStr(metaData.timestamp); if(metaData.timestamp==0) timestampStr="NULL"; string visibleStr = metaData.visible ? "true" : "false"; std::string changesetIndex="NULL"; stringstream ss; if(metaData.current and metaData.visible) { ss << objId <<","<< changesetStr <<","<< changesetIndex <<","<< usernameStr <<","<< uidStr <<","<< \ timestampStr <<","<< metaData.version <<",\"" << tagsJson << "\",\""<<refsJson<<"\",NULL\n"; string row(ss.str()); this->livewayFileGzip->sputn(row.c_str(), row.size()); } else { ss << objId <<","<< changesetStr <<","<< changesetIndex <<","<< usernameStr <<","<< uidStr <<","<< visibleStr <<","<<\ timestampStr <<","<< metaData.version <<",\"" << tagsJson << "\",\""<<refsJson<<"\",NULL\n"; string row(ss.str()); this->oldwayFileGzip->sputn(row.c_str(), row.size()); } string objIdStr = Int64ToStr(objId); objIdStr += "\n"; this->wayIdsFileGzip->sputn(objIdStr.c_str(), objIdStr.size()); for(size_t i=0; i<refs.size(); i++) { stringstream ss2; ss2 << objId <<","<< metaData.version <<","<< i <<","<< refs[i] << "\n"; string memStr(ss2.str()); this->wayMembersFileGzip->sputn(memStr.c_str(), memStr.size()); } return false; } bool CsvStore::StoreRelation(int64_t objId, const class MetaData &metaData, const TagMap &tags, const std::vector<std::string> &refTypeStrs, const std::vector<int64_t> &refIds, const std::vector<std::string> &refRoles) { string tagsJson; EncodeTags(tags, tagsJson); StrReplaceAll(tagsJson, "\"", "\"\""); string refsJson; EncodeRelationMems(refTypeStrs, refIds, refsJson); StrReplaceAll(refsJson, "\"", "\"\""); string refRolesJson; EncodeStringVec(refRoles, refRolesJson); StrReplaceAll(refRolesJson, "\"", "\"\""); string usernameStr = metaData.username; if(metaData.username.size() > 0) { StrReplaceAll(usernameStr, "\"", "\"\""); usernameStr = "\""+usernameStr+"\""; } else usernameStr = "NULL"; string uidStr; if(metaData.uid!=0) uidStr = Int64ToStr(metaData.uid); else uidStr = "NULL"; string changesetStr = Int64ToStr(metaData.changeset); if(metaData.changeset==0) changesetStr="NULL"; string timestampStr = Int64ToStr(metaData.timestamp); if(metaData.timestamp==0) timestampStr="NULL"; string visibleStr = metaData.visible ? "true" : "false"; std::string changesetIndex="NULL"; stringstream ss; if(metaData.current and metaData.visible) { ss << objId <<","<< changesetStr <<","<< changesetIndex <<","<< usernameStr <<","<< uidStr <<","<< \ timestampStr <<","<< metaData.version <<",\"" << tagsJson << "\",\""<<refsJson<<"\",\""<<refRolesJson<<"\",NULL\n"; string row(ss.str()); this->liverelationFileGzip->sputn(row.c_str(), row.size()); } else { ss << objId <<","<< changesetStr <<","<< changesetIndex <<","<< usernameStr <<","<< uidStr <<","<< visibleStr <<","<<\ timestampStr <<","<< metaData.version <<",\"" << tagsJson << "\",\""<<refsJson<<"\",\""<<refRolesJson<<"\",NULL\n"; string row(ss.str()); this->oldrelationFileGzip->sputn(row.c_str(), row.size()); } string objIdStr = Int64ToStr(objId); objIdStr += "\n"; this->relationIdsFileGzip->sputn(objIdStr.c_str(), objIdStr.size()); for(size_t i=0; i<refIds.size(); i++) { const std::string &refTypeStr = refTypeStrs[i]; stringstream ss2; ss2 << objId <<","<< metaData.version <<","<< i <<","<< refIds[i] << "\n"; string memStr(ss2.str()); if(refTypeStr == "node") { this->relationMemNodesFileGzip->sputn(memStr.c_str(), memStr.size()); } else if(refTypeStr == "way") { this->relationMemWaysFileGzip->sputn(memStr.c_str(), memStr.size()); } else if(refTypeStr == "relation") { this->relationMemRelsFileGzip->sputn(memStr.c_str(), memStr.size()); } } return false; } int main(int argc, char **argv) { cout << "Reading settings from config.cfg" << endl; std::map<string, string> config; ReadSettingsFile("config.cfg", config); cout << "Writing output to " << config["csv_absolute_path"] << endl; shared_ptr<class IDataStreamHandler> csvStore(new class CsvStore(config["csv_absolute_path"])); LoadOsmFromFile(config["dump_path"], csvStore); csvStore.reset(); cout << "All done!" << endl; }
36.030812
146
0.676359
[ "vector" ]
565049f64dbe754723d4119823c0c85090d0a10e
656
hpp
C++
ietf/ydk/models/ietf/ietf_inet_types.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
ietf/ydk/models/ietf/ietf_inet_types.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
ietf/ydk/models/ietf/ietf_inet_types.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _IETF_INET_TYPES_ #define _IETF_INET_TYPES_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace ietf { namespace ietf_inet_types { class IpVersion : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf ipv4; static const ydk::Enum::YLeaf ipv6; static int get_enum_value(const std::string & name) { if (name == "unknown") return 0; if (name == "ipv4") return 1; if (name == "ipv6") return 2; return -1; } }; } } #endif /* _IETF_INET_TYPES_ */
19.294118
61
0.609756
[ "vector" ]
5658ebc1d60f53632ec73fdfca9833c524c1eef9
4,422
cpp
C++
test/asmjit_test_unit.cpp
clayne/asmjit
a4cb51b532af0f8137c4182914244c3b05d7745f
[ "Zlib" ]
2,354
2016-07-13T16:08:25.000Z
2022-03-31T13:28:02.000Z
test/asmjit_test_unit.cpp
clayne/asmjit
a4cb51b532af0f8137c4182914244c3b05d7745f
[ "Zlib" ]
223
2016-07-14T17:32:11.000Z
2022-03-31T23:02:01.000Z
test/asmjit_test_unit.cpp
clayne/asmjit
a4cb51b532af0f8137c4182914244c3b05d7745f
[ "Zlib" ]
386
2016-07-23T09:02:14.000Z
2022-03-09T14:04:43.000Z
// This file is part of AsmJit project <https://asmjit.com> // // See asmjit.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #include <asmjit/core.h> #if !defined(ASMJIT_NO_X86) #include <asmjit/x86.h> #endif #include "asmjitutils.h" #include "broken.h" using namespace asmjit; static void dumpCpu(void) noexcept { const CpuInfo& cpu = CpuInfo::host(); // CPU Information // --------------- INFO("CPU Info:"); INFO(" Vendor : %s", cpu.vendor()); INFO(" Brand : %s", cpu.brand()); INFO(" Model ID : %u", cpu.modelId()); INFO(" Brand ID : %u", cpu.brandId()); INFO(" Family ID : %u", cpu.familyId()); INFO(" Stepping : %u", cpu.stepping()); INFO(" Processor Type : %u", cpu.processorType()); INFO(" Max logical Processors : %u", cpu.maxLogicalProcessors()); INFO(" Cache-Line Size : %u", cpu.cacheLineSize()); INFO(" HW-Thread Count : %u", cpu.hwThreadCount()); INFO(""); // CPU Features // ------------ #ifndef ASMJIT_NO_LOGGING INFO("CPU Features:"); CpuFeatures::Iterator it(cpu.features().iterator()); while (it.hasNext()) { uint32_t featureId = uint32_t(it.next()); StringTmp<64> featureString; Formatter::formatFeature(featureString, cpu.arch(), featureId); INFO(" %s\n", featureString.data()); }; INFO(""); #endif // !ASMJIT_NO_LOGGING } #define DUMP_TYPE(...) \ INFO(" %-26s: %u", #__VA_ARGS__, uint32_t(sizeof(__VA_ARGS__))) static void dumpSizeOf(void) noexcept { INFO("Size of C++ types:"); DUMP_TYPE(int8_t); DUMP_TYPE(int16_t); DUMP_TYPE(int32_t); DUMP_TYPE(int64_t); DUMP_TYPE(int); DUMP_TYPE(long); DUMP_TYPE(size_t); DUMP_TYPE(intptr_t); DUMP_TYPE(float); DUMP_TYPE(double); DUMP_TYPE(void*); INFO(""); INFO("Size of base classes:"); DUMP_TYPE(BaseAssembler); DUMP_TYPE(BaseEmitter); DUMP_TYPE(CodeBuffer); DUMP_TYPE(CodeHolder); DUMP_TYPE(ConstPool); DUMP_TYPE(LabelEntry); DUMP_TYPE(RelocEntry); DUMP_TYPE(Section); DUMP_TYPE(String); DUMP_TYPE(Target); DUMP_TYPE(Zone); DUMP_TYPE(ZoneAllocator); DUMP_TYPE(ZoneBitVector); DUMP_TYPE(ZoneHashNode); DUMP_TYPE(ZoneHash<ZoneHashNode>); DUMP_TYPE(ZoneList<int>); DUMP_TYPE(ZoneVector<int>); INFO(""); INFO("Size of operand classes:"); DUMP_TYPE(Operand); DUMP_TYPE(BaseReg); DUMP_TYPE(BaseMem); DUMP_TYPE(Imm); DUMP_TYPE(Label); INFO(""); INFO("Size of function classes:"); DUMP_TYPE(CallConv); DUMP_TYPE(FuncFrame); DUMP_TYPE(FuncValue); DUMP_TYPE(FuncDetail); DUMP_TYPE(FuncSignature); DUMP_TYPE(FuncArgsAssignment); INFO(""); #if !defined(ASMJIT_NO_BUILDER) INFO("Size of builder classes:"); DUMP_TYPE(BaseBuilder); DUMP_TYPE(BaseNode); DUMP_TYPE(InstNode); DUMP_TYPE(InstExNode); DUMP_TYPE(AlignNode); DUMP_TYPE(LabelNode); DUMP_TYPE(EmbedDataNode); DUMP_TYPE(EmbedLabelNode); DUMP_TYPE(ConstPoolNode); DUMP_TYPE(CommentNode); DUMP_TYPE(SentinelNode); INFO(""); #endif #if !defined(ASMJIT_NO_COMPILER) INFO("Size of compiler classes:"); DUMP_TYPE(BaseCompiler); DUMP_TYPE(FuncNode); DUMP_TYPE(FuncRetNode); DUMP_TYPE(InvokeNode); INFO(""); #endif #if !defined(ASMJIT_NO_X86) INFO("Size of x86-specific classes:"); DUMP_TYPE(x86::Assembler); #if !defined(ASMJIT_NO_BUILDER) DUMP_TYPE(x86::Builder); #endif #if !defined(ASMJIT_NO_COMPILER) DUMP_TYPE(x86::Compiler); #endif DUMP_TYPE(x86::InstDB::InstInfo); DUMP_TYPE(x86::InstDB::CommonInfo); DUMP_TYPE(x86::InstDB::OpSignature); DUMP_TYPE(x86::InstDB::InstSignature); INFO(""); #endif } #undef DUMP_TYPE static void onBeforeRun(void) noexcept { dumpCpu(); dumpSizeOf(); } int main(int argc, const char* argv[]) { #if defined(ASMJIT_BUILD_DEBUG) const char buildType[] = "Debug"; #else const char buildType[] = "Release"; #endif INFO("AsmJit Unit-Test v%u.%u.%u [Arch=%s] [Mode=%s]\n\n", unsigned((ASMJIT_LIBRARY_VERSION >> 16) ), unsigned((ASMJIT_LIBRARY_VERSION >> 8) & 0xFF), unsigned((ASMJIT_LIBRARY_VERSION ) & 0xFF), asmjitArchAsString(Arch::kHost), buildType ); return BrokenAPI::run(argc, argv, onBeforeRun); }
25.560694
69
0.64066
[ "model" ]
56619bc1b1f40b8f419d8fab1284d6495f9b6bdf
5,124
cpp
C++
examples/ini.cpp
r35382/bnflite
aac103f99d418c29d37140e19ba46070dd75c89a
[ "MIT" ]
70
2017-02-26T10:47:32.000Z
2022-03-28T17:38:02.000Z
examples/ini.cpp
r35382/bnflite
aac103f99d418c29d37140e19ba46070dd75c89a
[ "MIT" ]
3
2018-03-18T17:26:52.000Z
2021-12-06T10:41:44.000Z
examples/ini.cpp
r35382/bnflite
aac103f99d418c29d37140e19ba46070dd75c89a
[ "MIT" ]
5
2017-02-27T10:40:48.000Z
2021-11-22T14:17:15.000Z
/*************************************************************************\ * Parser of configuration ini-files (based on BNFlite) * * Copyright (c) 2017 by Alexander A. Semjonov. ALL RIGHTS RESERVED. * * * * This code 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. * * * * 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/>. * \*************************************************************************/ #pragma warning(disable: 4786) #include <vector> #include <iostream> #include "bnflite.h" using namespace bnf; using namespace std; /* somple ini file configuration example: [section_1] var1=value1 var2=value2 [section_2] var1=value1 var2=value2 */ const char* ini = // this sring represents some ini configuration file "; last modified 1 April 2001 by John Doe\n" " [ owner ]\n" "name=John Doe\n\n" "organization=Acme Widgets Inc.\n" "\n" "[database]\n \n" "; use IP address in case network name resolution is not working\n" "server=192.0.2.62 \n" "port= 143\n" "file=\"payroll.dat\"\n"; struct Section { string name; vector< pair< string, string> > value; Section(const char* name, size_t len) :name(name, len) {} }; vector <struct Section> Ini; // ini-file configuration container // example for custom interface instead of "typedef Interface<int> Gen;" class Gen :public Interface<> { public: Gen(const Gen& ifc, const char* text, size_t length, const char* name) :Interface<>(ifc, text, length, name){} Gen(const char* text, size_t length, const char* name) :Interface<>(text, length, name){} Gen(const Gen& front, const Gen& back) :Interface<>(front, back) {} Gen() :Interface<>() {}; }; static bool printMsg(const char* lexem, size_t len) { // debug function printf("Debug: %.*s;\n", len, lexem); return true; } Gen DoSection(vector<Gen>& res) { // save new section, it is 2nd lexem in section Rule in main Ini.push_back(Section(res[1].text, res[1].length)); return Gen(res.front(), res.back()); } Gen DoValue(vector<Gen>& res) { // save new entry: 4th lexem - name and 7th lexem is property value int i = res.size(); if (i > 2 ) Ini.back().value.push_back(make_pair( string(res[0].text, res[0].length), string(res[2].text, res[2].length))); return Gen(res.front(), res.back()); } static void Bind(Rule& section, Rule& entry) { Bind(section, DoSection); Bind(entry, DoValue); } // example of custom pre-parser static const char* ini_zero_parse(const char* ptr) { // skip ini file comments if (*ptr ==';' || *ptr =='#') while (*ptr != 0) if( *ptr++ == '\n') break; return ptr; } int main() { Token space(" \t"); // space and tab are grammar part in ini files Token delimiter(" \t\n\r"); // consider new lines as grammar part too Token name("_.,:(){}-#@&*|"); // start declare with special symbols name.Add('0', '9'); // appended numeric part name.Add('a', 'z'); // appended alphabetic lowercase part name.Add('A', 'Z'); // appended alphabetic capital part Token value(1,255); value.Remove("\n"); Lexem Name = 1*name; Lexem Value = *value; Lexem Equal = *space + "=" + *space; Lexem Left = *space + "[" + *space; // bracket Lexem Right = *space + "]" + *space; Lexem Delimiter = *delimiter; Rule Item = Name + Equal + Value + "\n"; Rule Section = Left + Name + Right + "\n"; Rule Inidata = Delimiter + *(Section + Delimiter + *(Item + Delimiter)) ; Bind(Section, Item); Gen gen; // this is Interface object int tst = Analyze(Inidata, ini, gen, ini_zero_parse); if (tst > 0) cout << "Section read:" << Ini.size(); else cout << "Parsing errors detected, status = " << hex << tst << endl << "stopped at: " << (gen.data + gen.length) << endl; for (vector<struct Section>::iterator j = Ini.begin(); j != Ini.end(); ++j) { cout << endl << "Section " << j->name << " has " << (*j).value.size() << " values: "; for (vector<pair<string, string> >::iterator i = j->value.begin(); i != j->value.end(); ++i) { cout << i->first << "=" << i->second <<"; "; } } return 0; }
32.636943
102
0.559719
[ "object", "vector" ]
566a6ee73716b3b24018cc73f0dba166baba1352
771
cpp
C++
problems/programmers/42842/junow.cpp
Lee-Park-Bae-Project/Algorithm
f7cc13a6319a73c3fbe771a92a70599c416844e1
[ "MIT" ]
null
null
null
problems/programmers/42842/junow.cpp
Lee-Park-Bae-Project/Algorithm
f7cc13a6319a73c3fbe771a92a70599c416844e1
[ "MIT" ]
19
2020-06-15T12:53:58.000Z
2020-08-10T04:26:45.000Z
problems/programmers/42842/junow.cpp
Lee-Park-Bae-Project/Algorithm
f7cc13a6319a73c3fbe771a92a70599c416844e1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define endl "\n" using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pair<int, int>> vpii; const int dy[4] = {-1, 0, 1, 0}; const int dx[4] = {0, 1, 0, -1}; vector<int> solution(int brown, int yellow) { vector<int> answer; for (int h = 3; h < (brown + yellow) / 2; h++) { if ((brown + yellow) % h != 0) continue; int w = (brown + yellow) / h; if ((w - 2) * (h - 2) == yellow) { answer.push_back(w); answer.push_back(h); return answer; } } return answer; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); auto answer = solution(10, 2); for (auto& _answer : answer) { cout << _answer << " "; } return 0; }
19.769231
50
0.573281
[ "vector" ]
566b067cb81314b5a4d8e51f67deff5830c4f14d
1,644
hpp
C++
include/solvers/gauss_jordan.hpp
shikharvashistha/hpr-blas
73f109d45701fc3816af0a1ecd42f11d494a6f97
[ "MIT" ]
10
2019-02-13T10:53:51.000Z
2021-11-21T20:30:58.000Z
include/solvers/gauss_jordan.hpp
jamesquinlan/hpr-blas
2975b4378b36a0bdc55d0dbd4f979163f7009678
[ "MIT" ]
3
2020-07-20T16:45:52.000Z
2020-10-17T11:19:32.000Z
include/solvers/gauss_jordan.hpp
jamesquinlan/hpr-blas
2975b4378b36a0bdc55d0dbd4f979163f7009678
[ "MIT" ]
6
2020-03-12T21:20:54.000Z
2021-06-01T05:35:35.000Z
#pragma once // gauss_jordan.hpp: Gauss-Jordan matrix inversion // // Copyright (C) 2017-2019 Stillwater Supercomputing, Inc. // // This file is part of the HPR-BLAS project, which is released under an MIT Open Source license. #include <boost/numeric/mtl/mtl.hpp> namespace sw { namespace hprblas { template<typename Matrix> Matrix GaussJordanInversion(const Matrix& A) { using Scalar = typename mtl::Collection<Matrix>::value_type; size_t m = A.num_rows(); size_t n = A.num_cols(); Matrix a(n, m), inv(m, n); a = A; // you need a deep copy inv = Scalar(1); // Performing elementary operations for (unsigned i = 0; i < m; ++i) { if (a[i][i] == 0) { unsigned c = 1; while (a[i + c][i] == 0 && (i + c) < n) ++c; if ((i + c) == n) break; for (unsigned j = i, k = 0; k < n; ++k) { std::swap(a[j][k], a[j + c][k]); std::cerr << "TBD" << std::endl; // need to create a permutation matrix } } // transform to diagonal matrix for (unsigned j = 0; j < m; j++) { if (i != j) { Scalar scale = a[j][i] / a[i][i]; for (unsigned k = 0; k < n; ++k) { a[j][k] = a[j][k] - a[i][k] * scale; inv[j][k] = inv[j][k] - inv[i][k] * scale; } } //std::cout << i << "," << j << std::endl; //sw::hprblas::printMatrix(std::cout, "a", a); //sw::hprblas::printMatrix(std::cout, "inv", inv); } } // transform to identity matrix for (unsigned i = 0; i < m; ++i) { Scalar normalize = a[i][i]; a[i][i] = Scalar(1); for (unsigned j = 0; j < n; ++j) { inv[i][j] /= normalize; } } //printMatrix(std::cout, "conversion", a); return inv; } } // namespace hprblas } // namespace sw
26.516129
97
0.563869
[ "transform" ]
5672541a372c25073b3b34f348ff0841e9ba47a4
319
cpp
C++
1036A.cpp
shaonsani/Codefoce_solving
80b821267f35bc62cd8016a378e7facc890d6ad0
[ "MIT" ]
null
null
null
1036A.cpp
shaonsani/Codefoce_solving
80b821267f35bc62cd8016a378e7facc890d6ad0
[ "MIT" ]
null
null
null
1036A.cpp
shaonsani/Codefoce_solving
80b821267f35bc62cd8016a378e7facc890d6ad0
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef set<char> setchar; typedef set<int> sett; typedef long long ll; #define vec(a) a.begin(),a.end() #define pb push_back int main() { ll n,k,a; cin>>n>>k; a=k/n; if(k%n) {a++;} cout<<a<<endl; return 0; }
12.76
33
0.576803
[ "vector" ]
56742f999bbc95d915770e2a892133245cc38ce6
9,895
hxx
C++
Validator/GenICam/library/CPP/include/xsde/cxx/parser/expat/document.hxx
genicam/GenICamXmlValidator
f3d0873dc2f39e09e98933aee927274a087a2a90
[ "Apache-2.0" ]
null
null
null
Validator/GenICam/library/CPP/include/xsde/cxx/parser/expat/document.hxx
genicam/GenICamXmlValidator
f3d0873dc2f39e09e98933aee927274a087a2a90
[ "Apache-2.0" ]
2
2020-10-30T16:10:09.000Z
2020-11-09T01:55:49.000Z
Validator/GenICam/library/CPP/include/xsde/cxx/parser/expat/document.hxx
genicam/GenICamXmlValidator
f3d0873dc2f39e09e98933aee927274a087a2a90
[ "Apache-2.0" ]
null
null
null
// file : xsde/cxx/parser/expat/document.hxx // author : Boris Kolpackov <boris@codesynthesis.com> // copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC // license : GNU GPL v2 + exceptions; see accompanying LICENSE file #ifndef XSDE_CXX_PARSER_EXPAT_DOCUMENT_HXX #define XSDE_CXX_PARSER_EXPAT_DOCUMENT_HXX #include <xsde/cxx/config.hxx> #include <stddef.h> // size_t #ifdef XSDE_STL # include <string> #endif #ifdef XSDE_IOSTREAM # include <iosfwd> #endif #include <xsde/c/expat/expat.h> // We only support UTF-8 expat for now. // #ifdef XML_UNICODE #error UTF-16 expat (XML_UNICODE defined) is not supported #endif #include <xsde/cxx/string.hxx> #ifdef XSDE_STL # include <xsde/cxx/string-sequence-stl.hxx> #else # include <xsde/cxx/string-sequence.hxx> #endif #include <xsde/cxx/parser/context.hxx> #include <xsde/cxx/parser/elements.hxx> #ifndef XSDE_EXCEPTIONS # include <xsde/cxx/parser/error.hxx> #endif namespace xsde { namespace cxx { namespace parser { namespace expat { // Simple auto pointer for Expat's XML_Parser object. // struct parser_auto_ptr { ~parser_auto_ptr (); explicit parser_auto_ptr (XML_Parser = 0); parser_auto_ptr& operator= (XML_Parser); public: operator XML_Parser () { return parser_; } private: parser_auto_ptr (const parser_auto_ptr&); parser_auto_ptr& operator= (const parser_auto_ptr&); private: XML_Parser parser_; }; // // class document_pimpl { public: virtual ~document_pimpl (); #ifdef XSDE_POLYMORPHIC document_pimpl (parser_base&, const char* root_element_name, bool polymorphic = false); document_pimpl (parser_base&, const char* root_element_namespace, const char* root_element_name, bool polymorphic = false); #ifdef XSDE_STL document_pimpl (parser_base&, const std::string& root_element_name, bool polymorphic = false); document_pimpl (parser_base&, const std::string& root_element_namespace, const std::string& root_element_name, bool polymorphic = false); #endif // XSDE_STL protected: document_pimpl (); // Non-polymorphic parsing. document_pimpl (const char* root_element_name); document_pimpl (const char* root_element_namespace, const char* root_element_name); #ifdef XSDE_STL document_pimpl (const std::string& root_element_name); document_pimpl (const std::string& root_element_namespace, const std::string& root_element_name); #endif #else // XSDE_POLYMORPHIC document_pimpl (parser_base&, const char* root_element_name); document_pimpl (parser_base&, const char* root_element_namespace, const char* root_element_name); #ifdef XSDE_STL document_pimpl (parser_base&, const std::string& root_element_name); document_pimpl (parser_base&, const std::string& root_element_namespace, const std::string& root_element_name); #endif protected: document_pimpl (); #endif // XSDE_POLYMORPHIC // This function is called to obtain the root element type parser. // If the returned pointed is 0 then the whole document content // is ignored. // // The type argument contains the type name and namespace if // xsi:type attribute or an element that substitutes the root // was specified and 0 otherwise. The type argument is in the // form "<name> <namespace>" with the space and namespace part // absent if the type does not have a namespace. // // #ifdef XSDE_POLYMORPHIC virtual parser_base* start_root_element (const ro_string& ns, const ro_string& name, const char* type); #else virtual parser_base* start_root_element (const ro_string& ns, const ro_string& name); #endif // This function is called to indicate the completion of document // parsing. The parser argument contains the pointer returned by // start_root_element. // virtual void end_root_element (const ro_string& ns, const ro_string& name, parser_base* parser); public: // If you override start_root_element() then you will most // likely also want to override reset() in order to reset // root element parser(s). // virtual void reset (); #ifdef XSDE_IOSTREAM public: // Parse a local file. The file is accessed with std::ifstream // in binary mode. The std::ios_base::failure exception is used // to report io errors (badbit and failbit) if XSDE_EXCEPTIONS // is defined. Otherwise error codes are used. // void parse (const char* file); #ifdef XSDE_STL void parse (const std::string& file); #endif // Parse std::istream. std::ios_base::failure exception is used // to report io errors (badbit and failbit) if XSDE_EXCEPTIONS // is defined. Otherwise error codes are used. // void parse (std::istream&); #endif public: // Parse a chunk of input. You can call this function multiple // times with the last call having the last argument true. // void parse (const void* data, size_t size, bool last); public: // Low-level Expat-specific parsing API. A typical use case // would look like this (pseudo-code): // // XML_Parser xml_parser (XML_ParserCreateNS (0, ' ')); // // xxx_pimpl root; // document_pimpl doc (root, "root"); // // root.pre (); // doc.parse_begin (xml_parser); // // while (more_stuff_to_parse) // { // // Call XML_Parse or XML_ParseBuffer: // // // if (XML_Parse (...) != XML_STATUS_ERROR) // break; // } // // doc.parse_end (); // result_type result (root.post_xxx ()); // // Notes: // // 1. If your XML instances use XML namespaces, XML_ParserCreateNS // functions should be used to create the XML parser. Space // (XML_Char (' ')) should be used as a separator (the second // argument to XML_ParserCreateNS). // // 2. If XML_Parse or XML_ParseBuffer fail, call parse_end to // determine the error which is indicated either via exception // or set as an error code. // void parse_begin (XML_Parser); void parse_end (); #ifndef XSDE_EXCEPTIONS public: const error& _error () const; #endif protected: void set (); void clear (); protected: static void XMLCALL start_element (void*, const XML_Char*, const XML_Char**); static void XMLCALL end_element (void*, const XML_Char*); static void XMLCALL characters (void*, const XML_Char*, int); #ifdef XSDE_POLYMORPHIC static void XMLCALL start_namespace_decl (void*, const XML_Char*, const XML_Char*); static void XMLCALL end_namespace_decl (void*, const XML_Char*); #endif protected: void start_element_ (const XML_Char* ns_name, const XML_Char** atts); void end_element_ (const XML_Char* ns_name); void characters_ (const XML_Char* s, size_t n); #ifdef XSDE_POLYMORPHIC void start_namespace_decl_ (const XML_Char* prefix, const XML_Char* ns); void end_namespace_decl_ (const XML_Char* prefix); #endif protected: bool first_; XML_Parser xml_parser_; parser_auto_ptr auto_xml_parser_; context context_; parser_base* parser_; string root_name_; string root_ns_; #ifdef XSDE_POLYMORPHIC bool polymorphic_; string_sequence prefixes_; string_sequence prefix_namespaces_; #endif #ifndef XSDE_EXCEPTIONS error error_; #endif // Support for ISO-8859-1 conversion. // #ifdef XSDE_ENCODING_ISO8859_1 protected: const char* conv_data (const XML_Char* utf_s, size_t iso_n, string& var); const char* conv_data (const XML_Char* utf_s, size_t utf_n, size_t iso_n, string& var); const char* conv_name (const XML_Char* utf_s, size_t iso_n, string& var); xml_error xml_error_; char data_buf_[256]; char name_buf_[128]; #endif private: void init_root_name (const char* ns, const char* name); }; } } } } #include <xsde/cxx/parser/expat/document.ixx> #endif // XSDE_CXX_PARSER_EXPAT_DOCUMENT_HXX
27.562674
77
0.562304
[ "object" ]
56745f0bc184bbf759faa2f0fa90a964871bad27
1,819
cpp
C++
strategies/gallery.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
strategies/gallery.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
strategies/gallery.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
/* GALLERY : 감시 카메라 설치 Difficulty : 중 Input : 3 6 5 0 1 1 2 1 3 2 5 0 4 4 2 0 1 2 3 1000 1 0 1 Output : 3 2 999 */ #include <iostream> #include <vector> #define MAX_G 1001 #define UNWATCHED 0 #define WATCHED 1 #define INSTALLED 2 std::vector<int> adjacents[MAX_G]; std::vector<bool> visited; int installedCamera = 0; void clear() { for (int i = 0; i < MAX_G; i++) { adjacents[i].clear(); } visited = std::vector<bool>(MAX_G, false); installedCamera = 0; } int dfs(int here) { int children[3] = {0, 0, 0}; visited[here] = true; for (int i = 0; i < adjacents[here].size(); i++) { int there = adjacents[here][i]; if (!(visited[there])) { children[dfs(there)]++; } } if (children[UNWATCHED] > 0) { installedCamera++; return INSTALLED; } if (children[INSTALLED] > 0) { return WATCHED; } return UNWATCHED; } int installCamera(int g) { for (int u = 0; u < g; u++) { if (!(visited[u]) && (dfs(u) == UNWATCHED)) { installedCamera++; } } return installedCamera; } int main(int argc, char const *argv[]) { int C; std::cin >> C; for (int c = 0; c < C; c++) { clear(); int g; int h; std::cin >> g; std::cin >> h; for (int i = 0; i < h; i++) { int g1; int g2; std::cin >> g1; std::cin >> g2; adjacents[g1].push_back(g2); adjacents[g2].push_back(g1); } std::cout << installCamera(g) << std::endl; } return 0; }
15.033058
52
0.4442
[ "vector" ]
56746c35a6f458192f38149536731541937755fd
498
cpp
C++
android-31/java/nio/charset/CoderMalfunctionError.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/nio/charset/CoderMalfunctionError.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/nio/charset/CoderMalfunctionError.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../lang/Exception.hpp" #include "./CoderMalfunctionError.hpp" namespace java::nio::charset { // Fields // QJniObject forward CoderMalfunctionError::CoderMalfunctionError(QJniObject obj) : java::lang::Error(obj) {} // Constructors CoderMalfunctionError::CoderMalfunctionError(java::lang::Exception arg0) : java::lang::Error( "java.nio.charset.CoderMalfunctionError", "(Ljava/lang/Exception;)V", arg0.object() ) {} // Methods } // namespace java::nio::charset
22.636364
89
0.708835
[ "object" ]
567d87092183806ef35ad20944546c2325dbf57e
7,057
cpp
C++
src/utils/warp_options.cpp
blairdgeo/node-gdal
a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6
[ "Apache-2.0" ]
1
2015-07-04T20:09:20.000Z
2015-07-04T20:09:20.000Z
src/utils/warp_options.cpp
blairdgeo/node-gdal
a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6
[ "Apache-2.0" ]
null
null
null
src/utils/warp_options.cpp
blairdgeo/node-gdal
a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6
[ "Apache-2.0" ]
null
null
null
#include "warp_options.hpp" #include "../gdal_dataset.hpp" #include "../gdal_geometry.hpp" #include "../gdal_common.hpp" #include <stdio.h> namespace node_gdal { WarpOptions::WarpOptions() : options(NULL), additional_options(), src_bands("src band ids"), dst_bands("dst band ids"), src_nodata(NULL), dst_nodata(NULL) { options = GDALCreateWarpOptions(); } WarpOptions::~WarpOptions() { // Dont use: GDALDestroyWarpOptions( options ); - it assumes ownership of everything if(options) delete options; if(src_nodata) delete src_nodata; if(dst_nodata) delete dst_nodata; } int WarpOptions::parseResamplingAlg(Handle<Value> value){ if(value->IsUndefined() || value->IsNull()){ options->eResampleAlg = GRA_NearestNeighbour; return 0; } if(!value->IsString()){ NanThrowTypeError("resampling property must be a string"); return 1; } std::string name = *NanUtf8String(value); if(name == "NearestNeighbor") { options->eResampleAlg = GRA_NearestNeighbour; return 0; } if(name == "NearestNeighbour") { options->eResampleAlg = GRA_NearestNeighbour; return 0; } if(name == "Bilinear") { options->eResampleAlg = GRA_Bilinear; return 0; } if(name == "Cubic") { options->eResampleAlg = GRA_Cubic; return 0; } if(name == "CubicSpline") { options->eResampleAlg = GRA_CubicSpline; return 0; } if(name == "Lanczos") { options->eResampleAlg = GRA_Lanczos; return 0; } if(name == "Average") { options->eResampleAlg = GRA_Average; return 0; } if(name == "Mode") { options->eResampleAlg = GRA_Mode; return 0; } NanThrowError("Invalid resampling algorithm"); return 1; } /* * { * options : string[] | object * memoryLimit : int * resampleAlg : string * src: Dataset * dst: Dataset * srcBands: int | int[] * dstBands: int | int[] * nBands: int * srcAlphaBand: int * dstAlphaBand: int * srcNoData: double * dstNoData: double * cutline: geometry * blend: double * } */ int WarpOptions::parse(Handle<Value> value) { NanScope(); if(!value->IsObject() || value->IsNull()) NanThrowTypeError("Warp options must be an object"); Handle<Object> obj = value.As<Object>(); Handle<Value> prop; if(obj->HasOwnProperty(NanNew("options")) && additional_options.parse(obj->Get(NanNew("options")))){ return 1; // error parsing string list } if(obj->HasOwnProperty(NanNew("memoryLimit"))){ prop = obj->Get(NanNew("memoryLimit")); if(prop->IsNumber()){ options->dfWarpMemoryLimit = prop->Int32Value(); } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("memoryLimit property must be an integer"); return 1; } } if(obj->HasOwnProperty(NanNew("resampling"))){ prop = obj->Get(NanNew("resampling")); if(parseResamplingAlg(prop)){ return 1; //error parsing resampling algorithm } } if(obj->HasOwnProperty(NanNew("src"))){ prop = obj->Get(NanNew("src")); if(prop->IsObject() && !prop->IsNull() && NanHasInstance(Dataset::constructor, prop)){ Dataset *ds = ObjectWrap::Unwrap<Dataset>(prop.As<Object>()); options->hSrcDS = ds->getDataset(); if(!options->hSrcDS){ #if GDAL_VERSION_MAJOR < 2 if(ds->getDatasource()) { NanThrowError("src dataset must be a raster dataset"); return 1; } #endif NanThrowError("src dataset already closed"); return 1; } } else { NanThrowTypeError("src property must be a Dataset object"); return 1; } } else { NanThrowError("Warp options must include a source dataset"); return 1; } if(obj->HasOwnProperty(NanNew("dst"))){ prop = obj->Get(NanNew("dst")); if(prop->IsObject() && !prop->IsNull() && NanHasInstance(Dataset::constructor, prop)){ Dataset *ds = ObjectWrap::Unwrap<Dataset>(prop.As<Object>()); options->hDstDS = ds->getDataset(); if(!options->hDstDS){ #if GDAL_VERSION_MAJOR < 2 if(ds->getDatasource()) { NanThrowError("dst dataset must be a raster dataset"); return 1; } #endif NanThrowError("dst dataset already closed"); return 1; } } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("dst property must be a Dataset object"); return 1; } } if(obj->HasOwnProperty(NanNew("srcBands"))){ prop = obj->Get(NanNew("srcBands")); if(src_bands.parse(prop)){ return 1; //error parsing number list } options->panSrcBands = src_bands.get(); options->nBandCount = src_bands.length(); } if(obj->HasOwnProperty(NanNew("dstBands"))){ prop = obj->Get(NanNew("dstBands")); if(dst_bands.parse(prop)){ return 1; //error parsing number list } options->panDstBands = dst_bands.get(); if (!options->panSrcBands) { NanThrowError("srcBands must be provided if dstBands option is used"); return 1; } if(dst_bands.length() != options->nBandCount){ NanThrowError("Number of dst bands must equal number of src bands"); return 1; } } if (options->panSrcBands && !options->panDstBands) { NanThrowError("dstBands must be provided if srcBands option is used"); return 1; } if(obj->HasOwnProperty(NanNew("srcNodata"))){ prop = obj->Get(NanNew("srcNodata")); if(prop->IsNumber()){ src_nodata = new double(prop->NumberValue()); options->padfSrcNoDataReal = src_nodata; } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("srcNodata property must be a number"); return 1; } } if(obj->HasOwnProperty(NanNew("dstNodata"))){ prop = obj->Get(NanNew("dstNodata")); if(prop->IsNumber()){ dst_nodata = new double(prop->NumberValue()); options->padfDstNoDataReal = dst_nodata; } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("dstNodata property must be a number"); return 1; } } if(obj->HasOwnProperty(NanNew("srcAlphaBand"))){ prop = obj->Get(NanNew("srcAlphaBand")); if(prop->IsNumber()){ options->nSrcAlphaBand = prop->Int32Value(); } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("srcAlphaBand property must be an integer"); return 1; } } if(obj->HasOwnProperty(NanNew("dstAlphaBand"))){ prop = obj->Get(NanNew("dstAlphaBand")); if(prop->IsNumber()){ options->nDstAlphaBand = prop->Int32Value(); } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("dstAlphaBand property must be an integer"); return 1; } } if(obj->HasOwnProperty(NanNew("blend"))){ prop = obj->Get(NanNew("blend")); if(prop->IsNumber()){ options->dfCutlineBlendDist = prop->NumberValue(); } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("cutline blend distance must be a number"); return 1; } } if(obj->HasOwnProperty(NanNew("cutline"))){ prop = obj->Get(NanNew("cutline")); if(prop->IsObject() && !prop->IsNull() && NanHasInstance(Geometry::constructor, prop)){ options->hCutline = ObjectWrap::Unwrap<Geometry>(prop.As<Object>())->get(); } else if (!prop->IsUndefined() && !prop->IsNull()) { NanThrowTypeError("cutline property must be a Geometry object"); return 1; } } return 0; } } //node_gdal namespace
31.932127
101
0.665013
[ "geometry", "object" ]
5685d9ae4c874170051509089fec49e127053d01
3,799
cpp
C++
apps/tests/bezier_merging/_potrace_params.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
27
2020-08-17T17:25:59.000Z
2022-03-01T05:49:12.000Z
apps/tests/bezier_merging/_potrace_params.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
4
2020-08-26T13:54:59.000Z
2020-09-21T07:19:22.000Z
apps/tests/bezier_merging/_potrace_params.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
5
2020-08-26T23:26:48.000Z
2021-01-04T09:06:07.000Z
#include <iostream> // #include <polyvec/api.hpp> #include <polyvec/curve-tracer/bezier_merging.hpp> #include <polyvec/core/log.hpp> #include <polyvec/misc.hpp> #include <polyvec/utils/num.hpp> #include <polyvec/io/vtk_curve_writer.hpp> #include <polyvec/geometry/winding_number.hpp> // #include <Eigen/Core> #include <Eigen/Geometry> NAMESPACE_BEGIN() ::polyvec::BezierCurve build_bezier(const Eigen::Matrix<double, 2, 4> ctrl) { ::polyvec::BezierCurve bz; bz.set_control_points(ctrl); return bz; }; NAMESPACE_END() NAMESPACE_BEGIN(polyvectest) NAMESPACE_BEGIN(BezierMerging) int potrace_params(int, char**) { // Creat the points and then test the mapping Eigen::Matrix<double, 2, 3> points0; Eigen::Matrix<double, 2, 4> yy; Eigen::Matrix2d A; Eigen::Vector2d b; Eigen::Matrix2d Amanu; Eigen::Vector2d bmanu; polyvec::VtkCurveWriter writer; points0.col(0) << 2, 10; points0.col(1) << 5, 7; points0.col(2) << 4, 12; // // First Just Create a bezier and draw it // const double alpha_manu = 0.8; const double beta_manu = 0.3; yy.col(0) = points0.col(0); yy.col(1) = ::polyvec::Num::lerp<Eigen::Vector2d>(points0.col(0), points0.col(1), alpha_manu); yy.col(2) = ::polyvec::Num::lerp<Eigen::Vector2d>(points0.col(2), points0.col(1), beta_manu); yy.col(3) = points0.col(2); writer.add_polyline(points0); writer.add_point(yy.col(0)); writer.add_point(yy.col(1)); writer.add_point(yy.col(2)); writer.add_point(yy.col(3)); writer.add_polyline(build_bezier(yy).get_tesselation2()); writer.dump("test_dump/potrace_params_00.vtk"); writer.clear(); // // Now create the potrace parameterization // ::polyfit::BezierMerging::PointParameters point_params{yy}; assert_break(point_params.is_potracable()); { double alpha, beta; Eigen::Vector2d oo; bool is; point_params.is_potracable(is, oo, alpha, beta); assert_break(is == true); assert_break(std::abs(alpha - alpha_manu) < 1e-8); assert_break(std::abs(beta - beta_manu) < 1e-8); assert_break((oo - points0.col(1)).norm() < 1e-8); } ::polyfit::BezierMerging::PotraceParameters potrace_params = point_params.as_potrace_params(); writer.add_polyline( build_bezier(potrace_params.get_yy().control_points).get_tesselation2()); writer.dump("test_dump/potrace_params_01.vtk"); writer.clear(); // // Now draw the closest equiparam bezier // writer.add_polyline( build_bezier(potrace_params.equiparamed().get_yy().control_points) .get_tesselation2()); writer.dump("test_dump/potrace_params_02.vtk"); writer.clear(); // // Now check that the area works // Eigen::Matrix2Xd tess; tess = build_bezier(yy).get_tesselation2(); double area_tess; { bool is_ccw; polyvec::WindingNumber::compute_orientation(tess, is_ccw, area_tess); } double area_analytic = potrace_params.get_areay(); double area_eqp_analytic = potrace_params.equiparamed().get_areay(); printf("Testing area \n"); printf("areas: tess: %.6f, ana: %.6f, anaeq: %.6f \n", area_tess, area_analytic, area_eqp_analytic); // // Now check that the tangent things works // printf("Testing inverse tangent solver \n"); { ::polyvec::BezierCurve bzcurve = build_bezier(yy); for (int i = 1; i < 99 ; ++i) { double t_solved; bool success; const double t = 1. / 99 * i; const Eigen::Vector2d tan = bzcurve.dposdt(t).normalized(); potrace_params.t_for_tangent(tan, t_solved, success); assert_break( success ); assert_break( std::abs(t-t_solved) < 1e-10 ); } } return EXIT_FAILURE; } NAMESPACE_END(BezierMerging) NAMESPACE_END(polyvectest)
28.140741
80
0.669387
[ "geometry" ]
5685e795efe94b322001b492fe52cc06a463f6cb
12,701
hpp
C++
sample-servers/sample-server/src/main/headers/nativefx_server.hpp
suyashjoshi/NativeFX
f1736d60830503d61a5d30587defb9cd805dc0d1
[ "Apache-2.0" ]
135
2019-06-16T10:23:49.000Z
2022-03-19T13:20:24.000Z
sample-servers/sample-server/src/main/headers/nativefx_server.hpp
suyashjoshi/NativeFX
f1736d60830503d61a5d30587defb9cd805dc0d1
[ "Apache-2.0" ]
23
2019-06-27T07:21:11.000Z
2021-06-09T08:41:09.000Z
sample-servers/sample-server/src/main/headers/nativefx_server.hpp
suyashjoshi/NativeFX
f1736d60830503d61a5d30587defb9cd805dc0d1
[ "Apache-2.0" ]
14
2019-06-25T12:35:06.000Z
2021-10-19T19:00:49.000Z
// #pragma once // /* // * Copyright 2019-2019 Michael Hoffer <info@michaelhoffer.de>. All rights reserved. // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // * // * If you use this software for scientific research then please cite the following publication(s): // * // * M. Hoffer, C. Poliwoda, & G. Wittum. (2013). Visual reflection library: // * a framework for declarative GUI programming on the Java platform. // * Computing and Visualization in Science, 2013, 16(4), // * 181–192. http://doi.org/10.1007/s00791-014-0230-y // */ // // ---------------------------------------- VERSION ---------------------------------------- // /// major version number // #define NATIVEFX_VERSION_MAJOR 0 // /// minor version number // #define NATIVEFX_VERSION_MINOR 0 // /// patch number // #define NATIVEFX_VERSION_PATCH 1 // /// complete version number // #define NATIVEFX_VERSION_CODE (NATIVEFX_VERSION_MAJOR * 10000 + NATIVEFX_VERSION_MINOR * 100 + NATIVEFX_VERSION_PATCH) // /// version number as string // #define NATIVEFX_VERSION_STRING "0.0.1" // // ---------------------------------------- INCLUDES ---------------------------------------- // #include <iostream> // #include <chrono> // #include <thread> // // force boost to be included as header only, also on windows // #define BOOST_ALL_NO_LIB 1 // #include <boost/thread/xtime.hpp> // #define _USE_MATH_DEFINES // #include <cmath> // // in case M_PI hasn't been defined we do it manually // // see https://github.com/miho/NativeFX/issues/12 // #ifndef M_PI // #define M_PI 3.14159265358979323846 // #endif // M_PI // #include "args/args.hxx" // #include "nativefx/shared_memory.h" // // ---------------------------------------- NATIVEFX CODE ---------------------------------------- // namespace nativefx { // namespace ipc = boost::interprocess; // ipc::shared_memory_object shm_buffer; // ipc::mapped_region buffer_region; // ipc::message_queue* evt_mq; // // deprecated // uchar* create_shared_buffer(std::string buffer_name, int w, int h) { // // create the shared memory buffer object. // shm_buffer = ipc::shared_memory_object ( // ipc::create_only, // buffer_name.c_str(), // ipc::read_write // ); // // set the size of the shared image buffer (w*h*#channels*sizeof(uchar)) // shm_buffer.truncate( w*h // TODO properly resize shared memory // */*#channels*/4 // */*channel size*/sizeof(uchar) // ); // // map the shared memory buffer object in this process // buffer_region = ipc::mapped_region( // shm_buffer, // ipc::read_write // ); // // get the address of the shared image buffer // void * buffer_addr = buffer_region.get_address(); // // cast shared memory pointer to correct uchar type // uchar* buffer_data = (uchar*) buffer_addr; // return buffer_data; // } // typedef std::function<void (std::string const &name, uchar* buffer_data, int W, int H)> redraw_callback; // typedef std::function<void (std::string const &name, event* evt)> event_callback; // /** // * Test function to verify buffer data functionality. // */ // void set_rgba(uchar* buffer_data, int buffer_w, int buffer_h, int x, int y, uchar r, uchar g, uchar b, uchar a) { // buffer_data[y*buffer_w*4+x*4+0] = b; // B // buffer_data[y*buffer_w*4+x*4+1] = g; // G // buffer_data[y*buffer_w*4+x*4+2] = r; // R // buffer_data[y*buffer_w*4+x*4+3] = a; // A // } // /** // * Deletes pre-existing shared memory objects. // * // * @param name name of the shared memory object to delete // * @return status of this operation // */ // int delete_shared_mem(std::string const &name) { // std::string info_name = name + IPC_INFO_NAME; // std::string buffer_name = name + IPC_BUFF_NAME; // std::string evt_mq_name = name + IPC_EVT_MQ_NAME; // ipc::shared_memory_object::remove(info_name.c_str()); // ipc::shared_memory_object::remove(buffer_name.c_str()); // ipc::message_queue::remove(evt_mq_name.c_str()); // std::cout << "> deleted shared-mem" <<std::endl; // std::cout << " -> name: " << name<<std::endl; // return SUCCESS; // } // /** // * Starts a NativeFX server. // * // * @param name name of the shared memory object to delete // * @param redraw should contain the draw commands (is called repetitively) // * @param events should contain the event handling (is called repetitively whenever events are to be processed) // * @return status of this operation // */ // int start_server(std::string const &name, redraw_callback redraw, event_callback events) // { // std::string info_name = name + IPC_INFO_NAME; // std::string buffer_name = name + IPC_BUFF_NAME; // std::string evt_mq_name = name + IPC_EVT_MQ_NAME; // std::cout << "> creating shared-mem" <<std::endl; // std::cout << " -> name: " << name<<std::endl; // ipc::shared_memory_object shm_info; // try { // // create the shared memory info object. // shm_info = ipc::shared_memory_object( // ipc::create_only, // info_name.c_str(), // ipc::read_write // ); // evt_mq = create_evt_mq(evt_mq_name); // } catch(ipc::interprocess_exception const & ex) { // // remove shared memory objects // ipc::shared_memory_object::remove(info_name.c_str()); // ipc::shared_memory_object::remove(buffer_name.c_str()); // ipc::message_queue::remove(evt_mq_name.c_str()); // std::cout << "> deleted pre-existing shared-mem" <<std::endl; // std::cout << " -> name: " << name<<std::endl; // // create the shared memory info object. // shm_info = ipc::shared_memory_object( // ipc::create_only, // info_name.c_str(), // ipc::read_write // ); // evt_mq = create_evt_mq(evt_mq_name); // std::cout << "> created shared-mem" << std::endl; // std::cout << " -> name: " << name << std::endl; // } // // set the shm size // shm_info.truncate(sizeof(struct shared_memory_info)); // // map the shared memory info object in this process // ipc::mapped_region info_region(shm_info, ipc::read_write); // // get the adress of the info object // void* info_addr = info_region.get_address(); // // construct the shared structure in memory // shared_memory_info* info_data = new (info_addr) shared_memory_info; // // init c-strings of info_data struct // strcpy(info_data->client_to_server_msg, ""); // strcpy(info_data->client_to_server_res, ""); // strcpy(info_data->server_to_client_msg, ""); // strcpy(info_data->server_to_client_res, ""); // int W = info_data->w; // int H = info_data->h; // uchar* buffer_data = create_shared_buffer(buffer_name, W, H); // double full = W*H; // std::size_t MAX_SIZE = max_event_message_size(); // void* evt_mq_msg_buff = malloc(MAX_SIZE); // int counter = 0; // while(true) { // // timed locking of resources // boost::system_time const timeout= // boost::get_system_time()+ boost::posix_time::milliseconds(LOCK_TIMEOUT); // bool locking_success = info_data->mutex.timed_lock(timeout); // if(!locking_success) { // std::cerr << "[" + info_name + "] " << "ERROR: cannot connect to '" << info_name << "':" << std::endl; // std::cerr << " -> But we are unable to lock the resources." << std::endl; // std::cerr << " -> Client not running?." << std::endl; // return ERROR | CONNECTION_ERROR; // } // bool is_dirty = info_data->dirty; // // if still is dirty it means that the client hasn't drawn the previous // // frame. in this case we just wait with updating the buffer until the // // client draws the content. // if(is_dirty) { // info_data->mutex.unlock(); // // continue; we still might want to process events // } else { // redraw(name, buffer_data, W, H); // info_data->dirty = true; // int new_W = info_data->w; // int new_H = info_data->h; // if(new_W!=W || new_H != H) { // // trigger buffer resize // W = new_W; // H = new_H; // std::cout << "[" + info_name + "]" << "> resize to W: " << W << ", H: " << H << std::endl; // ipc::shared_memory_object::remove(buffer_name.c_str()); // buffer_data = create_shared_buffer(buffer_name, W, H); // info_data->buffer_ready = true; // } // info_data->mutex.unlock(); // } // // process events // ipc::message_queue::size_type recvd_size; // unsigned int priority; // while(evt_mq->get_num_msg() > 0) { // // timed locking of resources // boost::system_time const timeout= // boost::get_system_time() + boost::posix_time::milliseconds(LOCK_TIMEOUT); // bool result = evt_mq->timed_receive(evt_mq_msg_buff, MAX_SIZE, recvd_size, priority, timeout); // if(!result) { // std::cerr << "[" + info_name + "] ERROR: can't read messages, message queue not accessible." << std::endl; // } // event* evt = static_cast<event*>(evt_mq_msg_buff); // events(name, evt); // } // end while has event messages // } // end while true // // remove shared memory objects // ipc::shared_memory_object::remove(info_name.c_str()); // ipc::shared_memory_object::remove(buffer_name.c_str()); // ipc::message_queue::remove(evt_mq_name.c_str()); // free(evt_mq_msg_buff); // return SUCCESS; // } // /** // * Starts a NativeFX server. It parses the specified CLI arguments and performs the requested commands. // * // * @param name name of the shared memory object to delete // * @param argc number of CLI arguments // * @param argv CLI arguments // * @param redraw should contain the draw commands (is called repetitively) // * @param events should contain the event handling (is called repetitively whenever events are to be processed) // * @return status of this operation // */ // int start_server(int argc, char *argv[], redraw_callback redraw, event_callback events) // { // args::ArgumentParser parser("This is a NativeFX server program.", "---"); // args::HelpFlag helpArg(parser, "help", "Display this help menu", {'h', "help"}); // args::ValueFlag<std::string> nameArg(parser, "name", "Defines the name of the shared memory objects to be created by this program", {'n', "name"}); // args::Flag deleteSharedMem(parser, "delete", "Indicates that existing shared memory with the specified name should be deleted", {'d', "delete"}); // try // { // parser.ParseCLI(argc, argv); // } // catch (const args::Completion& e) // { // std::cout << e.what(); // return NFX_SUCCESS; // } // catch (const args::Help&) // { // std::cerr << parser; // return NFX_ERROR | NFX_ARGS_ERROR; // } // catch (const args::ParseError& e) // { // std::cerr << e.what() << std::endl; // std::cerr << parser; // return NFX_ERROR | NFX_ARGS_ERROR; // } // std::string name = args::get(nameArg); // if(name.size() == 0) { // std::cerr << std::endl << std::endl << "ERROR: 'name' must be specified to create or delete shared memory!" << std::endl << std::endl; // std::cerr << parser; // return NFX_ERROR | NFX_ARGS_ERROR; // } // if(deleteSharedMem) { // // remove shared memory objects // return delete_shared_mem(name); // } // return start_server(name, redraw, events); // } // } // end namespace nativefx
35.37883
154
0.584206
[ "object" ]
5688727889cbdb3ce520ec8055262f2d156a109e
1,156
cpp
C++
distributed-implementation/legacy-first-attempt/NimGameState.cpp
AleksanderGondek/GUT_Manycore_Architectures_MCTS
43607dff9cee76f9a686c56e481ce1a70ad831b7
[ "Apache-2.0" ]
2
2016-12-29T22:58:49.000Z
2018-09-17T17:15:06.000Z
distributed-implementation/legacy-first-attempt/NimGameState.cpp
AleksanderGondek/GUT_Manycore_Architectures_MCTS
43607dff9cee76f9a686c56e481ce1a70ad831b7
[ "Apache-2.0" ]
null
null
null
distributed-implementation/legacy-first-attempt/NimGameState.cpp
AleksanderGondek/GUT_Manycore_Architectures_MCTS
43607dff9cee76f9a686c56e481ce1a70ad831b7
[ "Apache-2.0" ]
null
null
null
// // Created by agondek on 12/6/15. // #include <sstream> #include <vector> #include "NimGameState.h" NimGameState::NimGameState(int lastActivePlayer, int chips) { this->lastActivePlayer = lastActivePlayer; this->chips = chips; } NimGameState NimGameState::clone(void) { NimGameState deepClone(this->lastActivePlayer, this->chips); return deepClone; } void NimGameState::performAction(int action) { this->chips -= action; this->lastActivePlayer = 3 - this->lastActivePlayer; } std::vector<int> NimGameState::getAvailableActions(void) { std::vector<int> actions; if(this->chips > 0) { for(int i=1; i<std::min(4,(this->chips+1)); i++) //TODO: Why plus 1 { actions.push_back(i); } } return actions; } std::string NimGameState::representation(void) { std::stringstream buffer; buffer << "Last active player: " << this->lastActivePlayer << "; Chips: " << this->chips << std::endl; return buffer.str(); } int NimGameState::getValue(int playerId) { if(this->lastActivePlayer == playerId) { return 1; } else { return 0; } }
19.931034
106
0.631488
[ "vector" ]
5688aff062fe8ca5066a29838f941219e90ea916
1,120
hpp
C++
code/include/texturing/TexturedPlaneRenderable.hpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
4
2016-06-24T09:22:18.000Z
2019-06-13T13:50:53.000Z
code/include/texturing/TexturedPlaneRenderable.hpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
null
null
null
code/include/texturing/TexturedPlaneRenderable.hpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
2
2016-06-10T12:46:17.000Z
2018-10-14T06:37:21.000Z
#ifndef TEXTURED_PLANE_RENDERABLE_HPP #define TEXTURED_PLANE_RENDERABLE_HPP #include "./../HierarchicalRenderable.hpp" #include "./../lighting/Material.hpp" #include <vector> #include <glm/glm.hpp> class TexturedPlaneRenderable : public HierarchicalRenderable { public : ~TexturedPlaneRenderable(); TexturedPlaneRenderable(ShaderProgramPtr shaderProgram, const std::string& filename); void setMaterial(const MaterialPtr& material); private: void do_draw(); void do_animate( float time ); void do_keyPressedEvent( sf::Event& e ); void updateTextureOption(); std::vector< glm::vec3 > m_positions; std::vector< glm::vec4 > m_colors; std::vector< glm::vec3 > m_normals; std::vector< glm::vec2 > m_texCoords; std::vector< glm::vec2 > m_origTexCoords; unsigned int m_pBuffer; unsigned int m_cBuffer; unsigned int m_nBuffer; unsigned int m_tBuffer; unsigned int m_texId; unsigned int m_wrapOption; unsigned int m_filterOption; MaterialPtr m_material; }; typedef std::shared_ptr<TexturedPlaneRenderable> TexturedPlaneRenderablePtr; #endif
26.046512
89
0.735714
[ "vector" ]
56897012ed61c278253775e33e9b84821f3ececd
1,865
cpp
C++
cpp/src/solutions/median_of_two_sorted_arrays.cpp
LazyWolfLin/leetcode
731516713755c839b0507f00198862375754a8c8
[ "Apache-2.0" ]
null
null
null
cpp/src/solutions/median_of_two_sorted_arrays.cpp
LazyWolfLin/leetcode
731516713755c839b0507f00198862375754a8c8
[ "Apache-2.0" ]
null
null
null
cpp/src/solutions/median_of_two_sorted_arrays.cpp
LazyWolfLin/leetcode
731516713755c839b0507f00198862375754a8c8
[ "Apache-2.0" ]
null
null
null
// LeetCode 4. Median of Two Sorted Arrays in C++ #include "common.h" class Solution { public: double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) { if (nums1.size() > nums2.size()) { swap(nums1, nums2); } int m = nums1.size(), n = nums2.size(); int l = 0, r = m + 1, half = (m + n + 1) / 2; int i, j; while (l <= r) { i = (l + r) / 2, j = half - i; if (i > 0 && nums1[i - 1] > nums2[j]) { r = i; } else if (i < m && nums1[i] < nums2[j - 1]) { l = i; } else break; } int ans = 0; if (i == 0) { ans = nums2[j - 1]; } else if (j == 0) { ans = nums1[i - 1]; } else { ans = max(nums1[i - 1], nums2[j - 1]); } if ((m + n) % 2 == 0) { if (i == m) { ans += nums2[j]; } else if (j == n) { ans += nums1[i]; } else { ans += min(nums1[i], nums2[j]); } } else { ans += ans; } return ans / 2.0f; } }; TEST(findMedianSortedArrays, example1) { vector<int> nums1 = {1, 3}, nums2 = {2}; double ans = 2.0f; EXPECT_EQ(Solution().findMedianSortedArrays(nums1, nums2), ans); } TEST(findMedianSortedArrays, example2) { vector<int> nums1 = {1, 2}, nums2 = {3, 4}; double ans = 2.5f; EXPECT_EQ(Solution().findMedianSortedArrays(nums1, nums2), ans); } TEST(findMedianSortedArrays, example3) { vector<int> nums1 = {0, 0}, nums2 = {0, 0}; double ans = 0.0f; EXPECT_EQ(Solution().findMedianSortedArrays(nums1, nums2), ans); } TEST(findMedianSortedArrays, example4) { vector<int> nums1, nums2 = {1}; double ans = 1.0f; EXPECT_EQ(Solution().findMedianSortedArrays(nums1, nums2), ans); } TEST(findMedianSortedArrays, example5) { vector<int> nums1 = {2}, nums2; double ans = 2.0f; EXPECT_EQ(Solution().findMedianSortedArrays(nums1, nums2), ans); }
25.202703
73
0.542091
[ "vector" ]
568aec472f2c5e23eba588c0438cde10d3a06b2f
5,081
cpp
C++
rw_rh_engine_lib/render_client/im3d_state_recorder.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
232
2016-08-29T00:33:32.000Z
2022-03-29T22:39:51.000Z
rw_rh_engine_lib/render_client/im3d_state_recorder.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
10
2021-01-02T12:40:49.000Z
2021-08-31T06:31:04.000Z
rw_rh_engine_lib/render_client/im3d_state_recorder.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
40
2017-12-18T06:14:39.000Z
2022-01-29T16:35:23.000Z
// // Created by peter on 17.02.2021. // #include "im3d_state_recorder.h" #include "data_desc/immediate_mode/im_state.h" #include <ipc/MemoryReader.h> #include <ipc/MemoryWriter.h> namespace rh::rw::engine { constexpr auto Im3DVertexCountLimit = 100000; constexpr auto Im3DIndexCountLimit = 100000; Im3DStateRecorder::Im3DStateRecorder( ImmediateState &im_state ) noexcept : ImState( im_state ) { VertexBuffer.resize( Im3DVertexCountLimit ); IndexBuffer.resize( Im3DIndexCountLimit ); DrawCalls.resize( 4000 ); } Im3DStateRecorder::~Im3DStateRecorder() noexcept = default; void Im3DStateRecorder::Transform( RwIm3DVertex *vertices, uint32_t count, RwMatrix *ltm, [[maybe_unused]] uint32_t flags ) { StashedVertices = vertices; StashedVerticesCount = count; if ( ltm ) { StashedWorldTransform = DirectX::XMFLOAT4X3{ ltm->right.x, ltm->up.x, ltm->at.x, ltm->pos.x, ltm->right.y, ltm->up.y, ltm->at.y, ltm->pos.y, ltm->right.z, ltm->up.z, ltm->at.z, ltm->pos.z, }; } else { DirectX::XMStoreFloat4x3( &StashedWorldTransform, DirectX::XMMatrixTranspose( DirectX::XMMatrixIdentity() ) ); } } void Im3DStateRecorder::RenderPrimitive( RwPrimitiveType prim_type ) { auto &result_dc = DrawCalls[DrawCallCount]; result_dc.IndexBufferOffset = IndexCount; result_dc.VertexBufferOffset = VertexCount; assert( StashedVertices ); CopyMemory( ( VertexBuffer.data() + VertexCount ), StashedVertices, StashedVerticesCount * sizeof( RwIm3DVertex ) ); VertexCount += StashedVerticesCount; result_dc.IndexCount = 0; result_dc.VertexCount = StashedVerticesCount; result_dc.RasterId = ImState.Raster; result_dc.WorldTransform = StashedWorldTransform; result_dc.State = { ImState.ColorBlendSrc, ImState.ColorBlendDst, ImState.ColorBlendOp, ImState.BlendEnable, ImState.ZTestEnable, ImState.ZWriteEnable, ImState.StencilEnable, static_cast<uint8_t>( prim_type ) }; DrawCallCount++; } void Im3DStateRecorder::RenderIndexedPrimitive( RwPrimitiveType prim_type, uint16_t *indices, int32_t num_indices ) { auto &result_dc = DrawCalls[DrawCallCount]; result_dc.IndexBufferOffset = IndexCount; result_dc.VertexBufferOffset = VertexCount; assert( indices ); assert( StashedVertices ); CopyMemory( ( IndexBuffer.data() + IndexCount ), indices, num_indices * sizeof( uint16_t ) ); CopyMemory( ( VertexBuffer.data() + VertexCount ), StashedVertices, StashedVerticesCount * sizeof( RwIm3DVertex ) ); VertexCount += StashedVerticesCount; IndexCount += num_indices; result_dc.IndexCount = num_indices; result_dc.VertexCount = StashedVerticesCount; result_dc.RasterId = ImState.Raster; result_dc.WorldTransform = StashedWorldTransform; result_dc.State = { ImState.ColorBlendSrc, ImState.ColorBlendDst, ImState.ColorBlendOp, ImState.BlendEnable, ImState.ZTestEnable, ImState.ZWriteEnable, ImState.StencilEnable, static_cast<uint8_t>( prim_type ) }; DrawCallCount++; } uint64_t Im3DStateRecorder::Serialize( MemoryWriter &writer ) { // serialize index buffer uint64_t index_count = IndexCount; writer.Write( &index_count ); if ( IndexCount > 0 ) writer.Write( IndexBuffer.data(), IndexCount ); // serialize vertex buffer uint64_t vertex_count = VertexCount; writer.Write( &vertex_count ); if ( VertexCount <= 0 ) return writer.Pos(); writer.Write( VertexBuffer.data(), VertexCount ); // serialize drawcalls uint64_t dc_count = DrawCallCount; writer.Write( &dc_count ); if ( DrawCallCount <= 0 ) return writer.Pos(); writer.Write( DrawCalls.data(), DrawCallCount ); return writer.Pos(); } Im3DRenderState Im3DRenderState::Deserialize( MemoryReader &reader ) { Im3DRenderState result{}; auto idx_count = *reader.Read<uint64_t>(); if ( idx_count > 0 ) { result.IndexBuffer = { reader.Read<uint16_t>( idx_count ), static_cast<size_t>( idx_count ) }; } auto vtx_count = *reader.Read<uint64_t>(); if ( vtx_count <= 0 ) return result; result.VertexBuffer = { reader.Read<RwIm3DVertex>( vtx_count ), static_cast<size_t>( vtx_count ) }; auto dc_count = *reader.Read<uint64_t>(); if ( dc_count <= 0 ) return result; result.DrawCalls = { reader.Read<Im3DDrawCall>( dc_count ), static_cast<size_t>( dc_count ) }; return result; } void Im3DStateRecorder::Flush() { DrawCallCount = 0; VertexCount = 0; IndexCount = 0; } } // namespace rh::rw::engine
31.559006
77
0.637867
[ "transform" ]
568b7445091cffe0f771f31421e00d036c57d1cd
20,206
cpp
C++
util/processImage.cpp
csgcmai/lqp_face
db4ec672b352044692f8d1bcbfa181b35567b95c
[ "BSD-3-Clause" ]
1
2020-04-06T16:31:56.000Z
2020-04-06T16:31:56.000Z
util/processImage.cpp
csgcmai/lqp_face
db4ec672b352044692f8d1bcbfa181b35567b95c
[ "BSD-3-Clause" ]
null
null
null
util/processImage.cpp
csgcmai/lqp_face
db4ec672b352044692f8d1bcbfa181b35567b95c
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2013, Sibt ul Hussain <sibt.ul.hussain at gmail dot com> All rights reserved. Released under BSD License ------------------------- For license terms please see license.lic */ #include "processImage.h" void ProcessImage::ProcessSaveRes(Image &image, vector<REAL>&r, vector<REAL>& g, vector<REAL>& b, const string&ofile) {// Work on each color channel RGB if (gamma == 1 && !dog) ReadImage(image, r, g, b); if (gamma != 1)// Perform the gamma normalization of the image... // image magick gamma is x=y^(1/gamma); so sending // 1/gamma leads to x=y^gamma; // to have tip style normalization... { image.gamma(1 / gamma); if (!dog) ReadImage(image, r, g, b); } if (dog) { // Now using ImageMagick Implementation for padding UINT k2size = ceil(k2 * 3); Image image2 = image; // 3 to include 3 sigma bell image.blur(ceil(k1 * 3), k1);// applies separable filters... image2.blur(k2size, k2); SubtractImage(image, image2, r, g, b); } WriteImageFile(ofile + "_dog", r, g, b, image.rows(), image.columns()); if (constr || coneq) { REAL imgstat[6]; ExtractChannelStats(r, g, b, imgstat); if (constr) DoContrastStretching(r, g, b, imgstat); if (coneq) DoContrastEqualization(r, g, b, imgstat); } } /*Returns same pixel values for red, green & blue channels if a single channel information is demanded. * Thus same computational methods (atleast for Avg, L1 & L1Sqrt Norms)can be used for the computation of features*/ void ProcessImage::Process(Image &image, vector<REAL>&r, vector<REAL>& g, vector<REAL>& b) { switch (channel) { case WandellOCS: case SandeOCS: ProcessOCS(image, r, g, b); break; case HSL: ProcessHSL(image, r, g, b); break; case RGB: ProcessRGB(image, r, g, b); break; case Gray: ProcessGray(image, r); copy(r.begin(), r.end(), g.begin()); copy(r.begin(), r.end(), b.begin()); break; case Red: case Green: case Blue: case ABSGradientMag: Process(image, r); copy(r.begin(), r.end(), g.begin()); copy(r.begin(), r.end(), b.begin()); break; } } void ProcessImage::ProcessRGB(Image &image, vector<REAL>&r, vector<REAL>& g, vector<REAL>& b) {// Work on each color channel RGB if (gamma == 1 && !dog) { ReadImage(image, r, g, b); } if (gamma != 1)// Perform the gamma normalization of the image... // image magick gamma is x=y^(1/gamma); so sending // 1/gamma leads to x=y^gamma; // to have tip style normalization... { image.gamma(1 / gamma); if (!dog) ReadImage(image, r, g, b); } if (dog) { // Now using ImageMagick Implementation for padding UINT k2size = ceil(k2 * 3); Image image2 = image; // 3 to include 3 sigma bell image.blur(ceil(k1 * 3), k1);// applies separable filters... image2.blur(k2size, k2); SubtractImage(image, image2, r, g, b); } if (constr || coneq) { REAL imgstat[6]; ExtractChannelStats(r, g, b, imgstat); if (constr) DoContrastStretching(r, g, b, imgstat); if (coneq) DoContrastEqualization(r, g, b, imgstat); } } void ProcessImage::ProcessOCS(Image &image, vector<REAL>&rpixval, vector<REAL>& gpixval, vector<REAL>& bpixval) {// Work on each color channel HSL // Currently only reading the OCS 1 & OCS 2 channels REAL wtm[3][3] = { { 0.2661, 0.6019, 0.0006 }, { -0.1250, 0.0377, -0.1332 }, { -0.0803, -0.3315, 0.4490 } }, stm[3][3] = { { 0.7071, -0.7071, 0 }, { 0.4082, 0.4082, -0.8165 }, { 0.5774, 0.5774, 0.5774 } }; REAL (*tm)[3]; if (channel == WandellOCS) tm = wtm; else tm = stm; UINT n = image.columns(), m = image.rows(); const PixelPacket *pix1 = image.getConstPixels(0, 0, n, m); PixelPacket tpix; UINT count = 0, tvar; REAL factor = 1.0 / MaxRGB; for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j, ++count) { tpix = pix1[tvar + j];//0.2814 0.6938 0.0638 rpixval[count] = (tpix.red * tm[0][0] + tpix.green * tm[0][1] + tpix.blue * tm[0][2]) * factor; gpixval[count] = (tpix.red * tm[1][0] + tpix.green * tm[1][1] + tpix.blue * tm[1][2]) * factor; bpixval[count] = (tpix.red * tm[2][0] + tpix.green * tm[2][1] + tpix.blue * tm[2][2]) * factor; } } } // for specific Channel.. void ProcessImage::Process(Image &image, vector<REAL>&des1) { if (gamma == 1 && !dog) ReadImage(image, des1); if (gamma != 1)// Perform the gamma normalization of the image... { image.gamma(1 / gamma); if (!dog) { ReadImage(image, des1); } } if (dog) { // Now using ImageMagick Implementation for padding UINT k2size = ceil(k2 * 3); Image image2 = image; // 2 to include 2 sigma bell image.blur(ceil(k1 * 3), k1);// applies separable filters... image2.blur(k2size, k2); SubtractImage(image, image2, des1); } if (constr || coneq) { REAL imgstat[2]; ExtractChannelStats(des1, imgstat); if (constr) DoContrastStretching(des1, imgstat); if (coneq) DoContrastEqualization(des1, imgstat); } } void ProcessImage::ProcessHSL(Image &image, vector<REAL>&h, vector<REAL>& s, vector<REAL>& l) {// Work on each color channel RGB if (gamma == 1 && !dog) ReadHSLImage(image, h, s, l); if (gamma != 1)// Perform the gamma normalization of the image... // image magick gamma is x=y^1/gamma; so sending // 1/gamma leads to x=y^gamma; // to have tip(Bill) style normalization... { image.gamma(1 / gamma); if (!dog) ReadHSLImage(image, h, s, l); } if (dog) { // Now using ImageMagick Implementation for padding UINT k2size = ceil(k2 * 3); Image image2 = image; // 2 to include 2 sigma bell image.blur(ceil(k1 * 3), k1);// applies separable filters... image2.blur(k2size, k2); SubtractImageHSL(image, image2, h, s, l); } if (constr || coneq) { REAL imgstat[6]; ExtractChannelStats(h, s, l, imgstat); if (constr) DoContrastStretching(h, s, l, imgstat); if (coneq) DoContrastEqualization(h, s, l, imgstat); } } void ProcessImage::ProcessGray(Image &image, vector<REAL>&des1) { REAL imgstat[2]; if (gamma == 1 && !dog) ReadImage(image, des1); if (gamma != 1)// Perform the gamma normalization of the image... { image.gamma(1 / gamma); if (!dog) { ReadImage(image, des1); } } if (dog) { // Now using ImageMagick Implementation for padding UINT k2size = ceil(k2 * 3); Image image2 = image; // 2 to include 2 sigma bell image.blur(ceil(k1 * 3), k1);// applies separable filters... image2.blur(k2size, k2); SubtractImage(image, image2, des1); } if (constr || coneq) { REAL imgstat[2]; ExtractChannelStats(des1, imgstat); if (constr) DoContrastStretching(des1, imgstat); if (coneq) DoContrastEqualization(des1, imgstat); } } void ProcessImage::Normalize(vector<REAL>& ivector, REAL factor) { /*Multiply the Given input Image with the factor value*/ for (vector<REAL>::iterator iter = ivector.begin(); iter != ivector.end(); ++iter) *iter *= factor; } void ProcessImage::Normalize(vector<REAL>& rch, vector<REAL>& gch, vector<REAL>& bch, REAL factor) { vector<REAL>::iterator riter = rch.begin(), giter = gch.begin(), biter = bch.begin(); for (; riter != rch.end(); ++riter, ++giter, ++biter) { *riter *= factor; *giter *= factor; *biter *= factor; } } void ProcessImage::ReadImage(const Image& image, vector<REAL>&r, vector<REAL>&g, vector<REAL>&b) { UINT m = image.rows(), n = image.columns(); const PixelPacket *pix1 = image.getConstPixels(0, 0, n, m); PixelPacket tpix; UINT count = 0, tvar; REAL factor = 1.0 / MaxRGB; for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j, ++count) { tpix = pix1[tvar + j]; r[count] = tpix.red * factor; g[count] = tpix.green * factor; b[count] = tpix.blue * factor; } } } /*void ProcessImage::ReadGrayImage(const Image& image, vector<REAL>&pixval) { UINT m = image.rows(), n = image.columns(); ColorGray mycolor; UINT count = 0; for (UINT i = 0; i < m; ++i) { for (UINT j = 0; j < n; ++j) { ColorGray mycolor = image.pixelColor(j, i); pixval[count++] = mycolor.shade(); } } }*/ void ProcessImage::ReadHSLImage(const Image &image, vector<REAL>&h, vector<REAL>&s, vector<REAL>&l) { int count = 0; for (unsigned int row = 0; row < image.rows(); row++) { for (unsigned int col = 0; col < image.columns(); col++, ++count) { Magick::Color pixCol = image.pixelColor(col, row); Magick::ColorHSL hslPixCol = Magick::ColorHSL(pixCol); // white: 0.0h 0.0s 1.0l, black: 0.0h 0.0s 0.0h h[count] = hslPixCol.hue(); s[count] = hslPixCol.saturation(); l[count] = hslPixCol.luminosity(); } } } void ProcessImage::ReadImage(Image& image, vector<REAL>&pixval) { UINT m = image.rows(), n = image.columns(); if (channel == Gray) { image.type(GrayscaleType); ColorGray mycolor; UINT count = 0; for (UINT i = 0; i < m; ++i) { for (UINT j = 0; j < n; ++j) { ColorGray mycolor = image.pixelColor(j, i); pixval[count++] = mycolor.shade(); } } } // look into folder ~/ocs/ // sRGB2XYZ ==> Standard RGB values to XYZ color Space, then we convert from the XYZ to opponent Color Space // Where O1== luminance component... // O2 is the red-green channel // O3 is the blue-yellow channel.... else if (channel == O1 || channel == O2 || channel == O3) { // Older Transformation matrix... // REAL tm[3][3]={{0.2814, 0.6938, 0.0638}, // {-0.0971 0.1458 -0.0250}, // {-0.0930 -0.2529 0.4665}}; // // RGB2OCS rgb 2 opponent Color Space... REAL tm[3][3] = { { 0.2661, 0.6019, 0.0006 }, { -0.1250, 0.0377, -0.1332 }, { -0.0803, -0.3315, 0.4490 } }; const PixelPacket *pix1 = image.getConstPixels(0, 0, n, m); PixelPacket tpix; UINT count = 0, tvar; REAL factor = 1.0 / MaxRGB; UINT row = channel == O1 ? 0 : channel == O2 ? 1 : 2; for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) { tpix = pix1[tvar + j];//0.2814 0.6938 0.0638 pixval[count++] = (tpix.red * tm[row][0] + tpix.green * tm[row][1] + tpix.blue * tm[row][2]) * factor; } } } else if (channel == ABSGradientMag) { UINT width = image.columns(), height = image.rows(); const PixelPacket *pix = image.getConstPixels(0, 0, width, height); REAL factor = 255.0 / (pow(2.0, 16.0) - 1);// scaling factor to have real values[0,1] UINT count = 0; for (int ty = 1; ty < height - 1; ty++) { for (int tx = 1; tx < width - 1; tx++) { //abs(g)=abs(gx)+abs(gy) // first color channel double dy = (pix[tx + (ty + 1) * width].red - pix[tx + (ty - 1) * width].red) * factor, dy2 = (pix[tx + (ty + 1) * width].green - pix[tx + (ty - 1) * width].green) * factor, dy3 = (pix[tx + (ty + 1) * width].blue - pix[tx + (ty - 1) * width].blue) * factor, dx = (pix[(tx + 1) + ty * width].red - pix[(tx - 1) + ty * width].red) * factor, dx2 = (pix[(tx + 1) + ty * width].green - pix[(tx - 1) + ty * width].green) * factor, dx3 = (pix[(tx + 1) + ty * width].blue - pix[(tx - 1) + ty * width].blue) * factor, v = ABS(dx) + ABS(dy), v2 = ABS(dx2) + ABS(dy2), v3 = ABS( dx3) + ABS(dy3); // pick channel with strongest ABSOLUTE gradient if (v2 > v) { v = v2; } if (v3 > v) { v = v3; } pixval[count++] = v; } } } else { const PixelPacket *pix1 = image.getConstPixels(0, 0, n, m); UINT count = 0, tvar; REAL factor = 1.0 / MaxRGB; if (channel == Red) { for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) pixval[count++] = pix1[tvar + j].red * factor; } } else if (channel == Blue) { for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) pixval[count++] = pix1[tvar + j].blue * factor; } } else { for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) pixval[count++] = pix1[tvar + j].green * factor; } } } } void ProcessImage::SubtractImage(const Image& image1, const Image& image2, vector<REAL>&r, vector<REAL>&g, vector<REAL>&b) { UINT m = image1.rows(), n = image1.columns(); if (m != image2.rows() && n != image2.columns()) { cout << " Subtract Image: Image Dimensions doesn't match " << endl; return; } ColorRGB mycolor1, mycolor2; const PixelPacket *pix1 = image1.getConstPixels(0, 0, n, m), *pix2 = image2.getConstPixels(0, 0, n, m); PixelPacket tpix1, tpix2; UINT count = 0, tvar; for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j, ++count) { tpix1 = pix1[tvar + j]; tpix2 = pix2[tvar + j]; r[count] = ((REAL) (tpix1.red - tpix2.red)) / MaxRGB; g[count] = ((REAL) (tpix1.green - tpix2.green)) / MaxRGB; b[count] = ((REAL) (tpix1.blue - tpix2.blue)) / MaxRGB; } } } void ProcessImage::SubtractImageHSL(const Image& image1, const Image& image2, vector<REAL>&h, vector<REAL>&s, vector<REAL>&l) { int count = 0; Magick::ColorHSL hslPixCol1, hslPixCol2; for (unsigned int row = 0; row < image1.rows(); row++) { for (unsigned int col = 0; col < image1.columns(); col++, ++count) { hslPixCol1 = Magick::ColorHSL(image1.pixelColor(col, row)); hslPixCol2 = Magick::ColorHSL(image2.pixelColor(col, row)); // white: 0.0h 0.0s 1.0l, black: 0.0h 0.0s 0.0h h[count] = hslPixCol1.hue() - hslPixCol2.hue(); s[count] = hslPixCol1.saturation() - hslPixCol2.saturation(); l[count] = hslPixCol1.luminosity() - hslPixCol2.luminosity(); } } } void ProcessImage::ExtractChannelStats(vector<REAL>&gray, REAL imgstat[]) { imgstat[0] = -30000; imgstat[1] = +30000; for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) { if (*giter > imgstat[0]) imgstat[0] = *giter; if (*giter < imgstat[1]) imgstat[1] = *giter; } } void ProcessImage::ExtractChannelStats(vector<REAL>&r, vector<REAL>&g, vector<REAL>&b, REAL imgstat[]) { imgstat[0] = imgstat[2] = imgstat[4] = -30000; imgstat[1] = imgstat[3] = imgstat[5] = +30000; for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { if (*riter > imgstat[0]) imgstat[0] = *riter; if (*riter < imgstat[1]) imgstat[1] = *riter; //green if (*giter > imgstat[2]) imgstat[2] = *giter; if (*giter < imgstat[3]) imgstat[3] = *giter; //blue if (*biter > imgstat[4]) imgstat[4] = *biter; if (*biter < imgstat[5]) imgstat[5] = *biter; } } void ProcessImage::SubtractImage(const Image& image1, const Image& image2, vector<REAL>&pixval) { UINT m = image1.rows(), n = image1.columns(); if (m != image2.rows() && n != image2.columns()) { cout << " Subtract Image: Image Dimensions doesn't match " << endl; return; } if (channel == Gray) { ColorGray mycolor1, mycolor2; const PixelPacket *pix1 = image1.getConstPixels(0, 0, n, m), *pix2 = image2.getConstPixels(0, 0, n, m); UINT count = 0; for (UINT i = 0; i < m; ++i) { for (UINT j = 0; j < n; ++j) { mycolor1 = *(pix1 + i * n + j); mycolor2 = *(pix2 + i * n + j); pixval[count++] = mycolor1.shade() - mycolor2.shade(); } } } else { ColorRGB mycolor1, mycolor2; const PixelPacket *pix1 = image1.getConstPixels(0, 0, n, m), *pix2 = image2.getConstPixels(0, 0, n, m); UINT count = 0, tvar; if (channel == Red) { for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) pixval[count++] = pix1[tvar + j].red - pix2[tvar + j].red; } } else if (channel == Green) { for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) pixval[count++] = pix1[tvar + j].green - pix2[tvar + j].green; } } else { for (UINT i = 0; i < m; ++i) { tvar = i * n; for (UINT j = 0; j < n; ++j) pixval[count++] = pix1[tvar + j].blue - pix2[tvar + j].blue; } } } } void ProcessImage::DoContrastStretching(vector<REAL>&gray, REAL imgstat[]) { REAL mult = ((maxr - minr) / (imgstat[0] - imgstat[1])); for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) *giter = (*giter - imgstat[1]) * mult + minr; } void ProcessImage::DoContrastStretching(vector<REAL>&r, vector<REAL>&g, vector<REAL>&b, REAL imgstat[]) { // TODO: Should Use the histogram base statistics... if (uchstat) // Use Channel Based Statistics for contrast Stretching { for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { *riter = (*riter - imgstat[1]) * ((maxr - minr) / (imgstat[0] - imgstat[1])) + minr; *giter = (*giter - imgstat[3]) * ((maxr - minr) / (imgstat[2] - imgstat[3])) + minr; *biter = (*biter - imgstat[5]) * ((maxr - minr) / (imgstat[4] - imgstat[5])) + minr; } } else // Use Image base Statistic { REAL maxi, mini; maxi = *max_element(imgstat, imgstat + 6); mini = *min_element(imgstat, imgstat + 6); REAL mult = ((maxr - minr) / (maxi - mini)); for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { *riter = (*riter - mini) * mult + minr; *giter = (*giter - mini) * mult + minr; *biter = (*biter - mini) * mult + minr; } } } void ProcessImage::DoContrastEqualization(vector<REAL>&gray, REAL imgstat[]) { REAL mag = 0; for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) { mag += pow(ABS(*giter), alpha); } UINT len = gray.size(); mag /= len; for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) { *giter /= mag; } mag = 0; for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) { mag += pow(MIN(tou, ABS(*giter)), alpha); } mag /= len; mag = pow(mag, 1 / alpha); for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) { *giter /= mag; } // Tanh transformation...% Optional... for (vector<REAL>::iterator giter = gray.begin(); giter != gray.end(); ++giter) { *giter = tou * tanh(*giter / tou); } } // Bill's Method for Contrast Stretching See TIP paper void ProcessImage::DoContrastEqualization(vector<REAL>&r, vector<REAL>&g, vector<REAL>&b, REAL imgstat[]) { REAL mar = 0, mag = 0, mab = 0; for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { mar += pow(ABS(*riter), alpha); mag += pow(ABS(*giter), alpha); mab += pow(ABS(*biter), alpha); } UINT len = r.size(); mar /= len; mag /= len; mab /= len; for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { *riter /= mar; *giter /= mag; *biter /= mar; } mar = mag = mab = 0; for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { mar += pow(MIN(tou, ABS(*riter)), alpha); mag += pow(MIN(tou, ABS(*giter)), alpha); mab += pow(MIN(tou, ABS(*biter)), alpha); } mar /= len; mag /= len; mab /= len; mar = pow(mar, 1 / alpha); mag = pow(mag, 1 / alpha); mab = pow(mab, 1 / alpha); for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { *riter /= mar; *giter /= mag; *biter /= mar; } // Tanh transformation... for (vector<REAL>::iterator riter = r.begin(), giter = g.begin(), biter = b.begin(); riter != r.end(); ++riter, ++giter, ++biter) { *riter = tou * tanh(*riter / tou); *giter = tou * tanh(*giter / tou); *biter = tou * tanh(*biter / tou); } } /*void ProcessImage::Gaussian(vector<REAL>& input,vector<REAL>&ker, UINT imwidth,UINT imheight, ,vector<REAL>&output)// already padded image as input.. { UINT fsize = ker.size()/2; REAL sum =0; REAL *fil; // apply in the X-direction for(UINT i=0; i < imheight-2*fsize;++i) for(UINT j=0;j < imwidth-2*fsize;++j) { sum=0; fil = &input[i*imwidth+j]; for(UINT k=0; k < ker.size();++k) sum+= ker[k] * fil[k]; output[i*(imwidth-2*fsize)+j]=sum; } //apply in the Y-direction for(UINT i=0; i < imheight-2*fsize;++i) for(UINT j=0;j < imwidth-2*fsize;++j) { sum=0; fil = &input[i*imwidth+j]; for(UINT k=0; k < ker.size();++k) sum+ = ker[k] * fil[k]; output[i*(imwidth-2*fsize)+j]=sum; } } */
30.339339
116
0.595962
[ "vector" ]
568e54d01b5cafc82d81e94f5f442ff8ce27e499
7,209
cpp
C++
C++Server/GS_Manager/src/GsDatabase.cpp
IncompleteWorlds/01_gs4cubesat
4386a3a8b984e96cab364bab83fc2fb49aa5cc3d
[ "RSA-MD" ]
null
null
null
C++Server/GS_Manager/src/GsDatabase.cpp
IncompleteWorlds/01_gs4cubesat
4386a3a8b984e96cab364bab83fc2fb49aa5cc3d
[ "RSA-MD" ]
null
null
null
C++Server/GS_Manager/src/GsDatabase.cpp
IncompleteWorlds/01_gs4cubesat
4386a3a8b984e96cab364bab83fc2fb49aa5cc3d
[ "RSA-MD" ]
null
null
null
/** * CubeGS * An online Ground Segment for Cubesats and Small Sats * (c) 2016 Incomplete Worlds * */ #include <iostream> #include <string> #include "Constants.h" #include "GSException.h" #include "ConfigurationManager.h" #include "SQLiteCpp/Statement.h" #include "GsDatabase.h" using namespace std; GsDatabase::GsDatabase() : db{} { } GsDatabase::~GsDatabase() { } void GsDatabase::open() { auto dbName = ConfigurationManager::getInstance().getValue(ConfigurationManager::KEY_GS_MANAGER_DATABASE); cout << "INFO: Opening GS Manager database: " << dbName << endl; shared_ptr<SQLite::Database> tmpDB{ new SQLite::Database(dbName, SQLite::OPEN_READWRITE) }; db = std::move(tmpDB); // TODO: Check if tables exist, if not, create them // if (db->tableExists(GS_MANAGER_DB_NAME) == false) // { // // Create the table // } // string tmpCreateStatement = "CREATE TABLE t_ground_stations (" \ // " 'identifier' TEXT," \ // " 'name' TEXT NOT NULL," \ // " 'description' TEXT," \ // " 'code' TEXT NOT NULL," \ // " 'owner' TEXT," \ // " PRIMARY KEY(identifier)" \ // ")"; /* * CREATE TABLE `t_ground_station` ( `identifier` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT NOT NULL, `description` TEXT, `code` TEXT NOT NULL, `owner` TEXT, `latitude` DOUBLE NOT NULL, `longitude` DOUBLE NOT NULL, `altitude` DOUBLE NOT NULL, `connectionType` INTEGER, `url` TEXT, `port` INTEGER, `comPort` TEXT, `speed` INTEGER, `parity` BOOLEAN, `controlBits` INTEGER ); */ // SQLite::Statement query(this->db, tmpCreateStatement); // SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'; //create table if not exists TableName (col1 typ1, ..., colN typN) // drop table if exists TableName } /** * @brief GsDatabase::create * It will return the identifier of the created G/S * @param inNewGS * @return */ string GsDatabase::create(const IW::GroundStation& inNewGS) { string output{""}; SQLite::Statement query(*this->db, "INSERT INTO t_ground_station" \ "('name', 'description', 'code', 'owner', 'latitude', " \ "'longitude', 'altitude', 'connectionType', 'url', 'port'," \ "'comPort', 'speed', 'parity', 'controlBits')" \ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); // Bind the first parameter // Identifier it is auto generated query.bind(1, inNewGS.name); query.bind(2, inNewGS.description); query.bind(3, inNewGS.code); query.bind(4, inNewGS.owner); query.bind(5, inNewGS.latitude); query.bind(6, inNewGS.longitude); query.bind(7, inNewGS.altitude); query.bind(8, static_cast<int>(inNewGS.connectionType)); query.bind(9, inNewGS.url); query.bind(10, inNewGS.port); query.bind(11, inNewGS.comPort); query.bind(12, inNewGS.speed); query.bind(13, inNewGS.parity); query.bind(14, inNewGS.controlBits); if (query.exec() == 1) { long long int lastId = db->getLastInsertRowid(); try { output = to_string(lastId); } catch(...) { // Do nothing } } else { string tmpMessage = "Unable to create new ground station"; cout << "ERROR: " << tmpMessage << endl; cout << "SQL ERROR: " << query.getErrorMsg() << endl; throw GSException(tmpMessage); } return output; } void GsDatabase::remove(const int64_t &inGsId) { SQLite::Statement query(*this->db, "DELETE FROM t_ground_station WHERE identifier = ?"); // Bind the first parameter query.bind(1, std::to_string(inGsId)); // We only retrieve the first value if (query.exec() == 0) { string tmpMessage = "Ground station not found. Id: " + inGsId; cout << "ERROR: " << tmpMessage << endl; cout << "SQL ERROR: " << query.getErrorMsg() << endl; throw GSException(tmpMessage); } } void GsDatabase::update(const IW::GroundStation &inStation) { remove(inStation.identifier); create(inStation); } IW::GroundStation GsDatabase::getById(const string &inGsId) { IW::GroundStation output; if (inGsId.empty() == false) { SQLite::Statement query(*this->db, "SELECT * FROM t_ground_station WHERE identifier = ?"); // Bind the first parameter query.bind(1, inGsId); // We only retrieve the first value if (query.executeStep() == true) { output = extractData(query); } else { string tmpMessage = "Ground station not found. Id: " + inGsId; cout << "ERROR: " << tmpMessage << endl; cout << "SQL ERROR: " << query.getErrorMsg() << endl; throw GSException(tmpMessage); } } return output; } IW::GroundStation GsDatabase::getByCode(const string &inGsCode) { IW::GroundStation output; if (inGsCode.empty() == false) { SQLite::Statement query(*this->db, "SELECT * FROM t_ground_station WHERE code = ?"); // Bind the first parameter query.bind(1, inGsCode); // We only retrieve the first value if (query.executeStep() == true) { output = extractData(query); } else { string tmpMessage = "Ground station not found. Code: " + inGsCode; cout << "ERROR: " << tmpMessage << endl; cout << "SQL ERROR: " << query.getErrorMsg() << endl; throw GSException(tmpMessage); } } return output; } vector<IW::GroundStation> GsDatabase::getAll() { vector<IW::GroundStation> output; SQLite::Statement query(*this->db, "SELECT * FROM t_ground_station"); // We only retrieve the first value while (query.executeStep() == true) { IW::GroundStation tmpStation = extractData(query); output.push_back(tmpStation); } return output; } IW::GroundStation GsDatabase::extractData(SQLite::Statement &inQuery) { IW::GroundStation output; output.identifier = inQuery.getColumn(0).getInt(); output.name = inQuery.getColumn(1).getString(); output.description = inQuery.getColumn(2).getString(); output.code = inQuery.getColumn(3).getString(); output.owner = inQuery.getColumn(4).getString(); // Position output.latitude = inQuery.getColumn(5).getDouble(); output.longitude = inQuery.getColumn(6).getDouble(); output.altitude = inQuery.getColumn(7).getDouble(); // Connection details output.connectionType = static_cast<IW::ConnectionTypeEnum>(inQuery.getColumn(8).getInt()); // TCP connection parameters output.url = inQuery.getColumn(9).getString(); output.port = inQuery.getColumn(10).getInt(); // Serial connection parameters output.comPort = inQuery.getColumn(11).getString(); output.speed = inQuery.getColumn(12).getInt(); output.parity = inQuery.getColumn(13).getInt(); output.controlBits = inQuery.getColumn(14).getInt(); return output; }
26.601476
110
0.604522
[ "vector" ]
569b075023c58766ad166f67bad23116d15079f4
3,733
cpp
C++
src/regalloc.cpp
MathCarnelutt/t1-compilers
8c80894d9de396195a0508de5982bc9b3d839ca0
[ "MIT" ]
null
null
null
src/regalloc.cpp
MathCarnelutt/t1-compilers
8c80894d9de396195a0508de5982bc9b3d839ca0
[ "MIT" ]
null
null
null
src/regalloc.cpp
MathCarnelutt/t1-compilers
8c80894d9de396195a0508de5982bc9b3d839ca0
[ "MIT" ]
null
null
null
#include "regalloc.hpp" #include <iostream> #include <fstream> #include <list> #include <string> Regalloc::Regalloc() {} Regalloc::~Regalloc() { delete graph; } void Regalloc::build() { // Getting graph name std::string line; std::getline(std::cin, line); std::size_t startPos = 6; std::size_t endPos = line.find(':'); int graphId = std::stoi(std::string(line, startPos, endPos - startPos)); graph = new Reg::Graph(graphId); // Getting K std::getline(std::cin, line); startPos = 2; K = std::stoi(std::string(line, startPos, line.size() - startPos)); // Getting all the edges while (std::getline(std::cin, line)) { endPos = line.find_first_of(" "); startPos = 0; int vId = std::stoi(std::string(line, startPos, endPos - startPos)); bool v1Phys = vId < K; graph->addVertex(vId, v1Phys); startPos = endPos + 5; endPos = line.find_first_of(" ", startPos); while ((endPos = line.find_first_of(" ", startPos)) != std::string::npos) { int v2Id = std::stoi(std::string(line, startPos, endPos - startPos)); bool v2Phys = v2Id < K; graph->addVertex(v2Id, v2Phys); graph->addEdge(vId, v2Id); startPos = endPos + 1; } int v2Id = std::stoi(std::string(line, startPos, line.length() - startPos)); bool v2Phys = v2Id < K; graph->addVertex(v2Id, v2Phys); graph->addEdge(vId, v2Id); } // Printing Graph info std::cout << "Graph " << graph->getId() << " -> Physical Registers: " << K << std::endl << "----------------------------------------" << std::endl; } // For testing purposes void Regalloc::exportToDot(const std::string filepath) { std::ofstream file; file.open(filepath); if (file.is_open()) { graph->exportToDot(file); } file.close(); } int Regalloc::getK() { return K; } int Regalloc::getGraphNumber() { return graph->getId(); } void Regalloc::simplify(int k) { while (!graph->isEmpty()) { Reg::Vertex *v = graph->getVertexToBeRemoved(k); graph->removeVertex(v->getId()); currStack.push_back(v); bool potentialSpill = v->getDegree() >= k; std::cout << "Push: " << v->getId() << ((potentialSpill) ? " *" : "") << std::endl; } } bool Regalloc::assign(int k) { bool colors[K]; while (!currStack.empty()) { for (int i = 0; i < k; i++) colors[i] = true; Reg::Vertex *vertex = currStack.back(); currStack.pop_back(); graph->readdVertex(vertex); std::vector<Reg::Edge *> adjacentEdges = graph->getEdges(vertex->getId()); // Check the available colors for (auto edge : adjacentEdges) { auto v2 = graph->getVertexById(edge->getV2()); if (v2 == nullptr) continue; int color = v2->getColor(); if (color >= 0) { colors[color] = false; } } // Tries to use the first available color int i; for (i = 0; i < k; i++) { if (colors[i]) { vertex->paint(i); std::cout << "Pop: " << vertex->getId() << " -> " << i << std::endl; break; } } // If no colors are available, SPILL if (i == k) { std::cout << "Pop: " << vertex->getId() << " -> NO COLOR AVAILABLE" << std::endl; return false; } } return true; } void Regalloc::rebuild() { while (!currStack.empty()) { Reg::Vertex *vertex = currStack.back(); currStack.pop_back(); graph->readdVertex(vertex); } }
25.222973
93
0.524243
[ "vector" ]
569e06c7f737c1beb1214eb62da0405886fe4d13
2,394
cpp
C++
tests/utests/proposal/proposal_operations_tests.cpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
tests/utests/proposal/proposal_operations_tests.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
tests/utests/proposal/proposal_operations_tests.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#include <boost/test/unit_test.hpp> #include <fc/io/json.hpp> #include <scorum/protocol/operations.hpp> #include <detail.hpp> using detail::to_hex; namespace proposal_operations_tests { using namespace scorum::protocol; BOOST_AUTO_TEST_SUITE(proposal_create_operation_tests) BOOST_AUTO_TEST_CASE(serialize_proposal_create_operation_to_json) { registration_committee_add_member_operation add_member_op; add_member_op.account_name = "alice"; proposal_create_operation op; op.operation = add_member_op; BOOST_CHECK_EQUAL( R"({"creator":"","lifetime_sec":0,"operation":["registration_committee_add_member",{"account_name":"alice"}]})", fc::json::to_string(op)); } BOOST_AUTO_TEST_CASE(deserialize_proposal_create_operation_from_json) { fc::variant v = fc::json::from_string( R"({"creator":"","lifetime_sec":0,"operation":["registration_committee_add_member",{"account_name":"alice"}]})"); proposal_create_operation op; fc::from_variant(v, op); registration_committee_add_member_operation& add_member_op = op.operation.get<registration_committee_add_member_operation>(); BOOST_CHECK_EQUAL("alice", add_member_op.account_name); } BOOST_AUTO_TEST_CASE(serialize_proposal_create_operation_to_hex) { registration_committee_add_member_operation add_member_op; add_member_op.account_name = "alice"; proposal_create_operation proposal_create_op; proposal_create_op.operation = add_member_op; scorum::protocol::operation op = proposal_create_op; BOOST_CHECK_EQUAL("1d00000000000005616c696365", to_hex(op)); } BOOST_AUTO_TEST_CASE(deserialize_proposal_create_operation_from_hex) { const std::string hex_str = "1d00000000000005616c696365"; std::vector<char> buffer; buffer.resize(hex_str.size() / 2); BOOST_REQUIRE_EQUAL(hex_str.size(), buffer.size() * 2); fc::from_hex(hex_str, buffer.data(), buffer.size()); operation op; fc::raw::unpack<scorum::protocol::operation>(buffer, op); proposal_create_operation& proposal_create_op = op.get<proposal_create_operation>(); registration_committee_add_member_operation& add_member_op = proposal_create_op.operation.get<registration_committee_add_member_operation>(); BOOST_CHECK_EQUAL("alice", add_member_op.account_name); } BOOST_AUTO_TEST_SUITE_END() } // namespace proposal_operations_tests
28.843373
121
0.76817
[ "vector" ]
56a25f3d29e1172bcd0fd26f110a650c7b8cfa64
4,369
hpp
C++
src/LowLevel/LowLevelDefinitions.hpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
41
2018-01-23T09:27:32.000Z
2021-02-15T15:49:07.000Z
src/LowLevel/LowLevelDefinitions.hpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
20
2018-01-25T04:25:48.000Z
2019-03-09T02:49:41.000Z
src/LowLevel/LowLevelDefinitions.hpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
5
2018-04-10T12:19:13.000Z
2020-02-17T03:30:50.000Z
#pragma once #include <CQLDriver/Common/Utility/EnumUtils.hpp> #include <ostream> namespace cql { // For more information, check the cql protocol definition on: // https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec /** * Message direction, either request or response * The value of this enum can use to calculate the <version> in frame header, * for example: header.version = static_cast<std::size_t>(direction) | DefaultVerion; */ enum class MessageDirection { Request = 0, Response = 0x80, Mask_ = 0x80 }; template <> struct EnumDescriptions<MessageDirection> { static const std::vector<std::pair<MessageDirection, const char*>>& get(); }; /** * Message type, each type is either request type or response type * The value of this enum is the <opcode> in frame header. * Check native_protocol_v4.spec section 2.4. */ enum class MessageType { Error = 0, Startup = 1, Ready = 2, Authenticate = 3, Options = 5, Supported = 6, Query = 7, Result = 8, Prepare = 9, Execute = 0xa, Register = 0xb, Event = 0xc, Batch = 0xd, AuthChallenge = 0xe, AuthResponse = 0xf, AuthSuccess = 0x10, Max_ = 0x11 // only for array definition }; template <> struct EnumDescriptions<MessageType> { static const std::vector<std::pair<MessageType, const char*>>& get(); }; /** * Flags in message header * The value of this enum is the <flags> in frame header. * Check native_protocol_v4.spec section 2.2. */ enum class MessageHeaderFlags { None = 0, Compression = 1, Tracing = 2, CustomPayload = 4, Warning = 8 }; template <> struct EnumDescriptions<MessageHeaderFlags> { static const std::vector<std::pair<MessageHeaderFlags, const char*>>& get(); }; /** * Flags in query parameters. * The value of this enum is the <flags> in query parameters. * Check native_protocol_v4.spec section 4.1.4. */ enum class QueryParametersFlags { None = 0, WithValues = 1, SkipMetadata = 2, WithPageSize = 4, WithPagingState = 8, WithSerialConsistency = 16, WithDefaultTimestamp = 32, WithNamesForValue = 64 }; template <> struct EnumDescriptions<QueryParametersFlags> { static const std::vector<std::pair<QueryParametersFlags, const char*>>& get(); }; /** * Flags in batch parameters. * The value of this enum is the <flags> in batch parameters. * Check native_protocol_v4.spec section 4.1.7. */ enum class BatchParametersFlags { None = 0, WithSerialConsistency = 16, WithDefaultTimestamp = 32 }; template <> struct EnumDescriptions<BatchParametersFlags> { static const std::vector<std::pair<BatchParametersFlags, const char*>>& get(); }; /** * Indicating whether the following query is a prepared one or not * The value of this enum is the <kind> in batch query. * Check native_protocol_v4.spec section 4.1.7. */ enum class BatchQueryKind { Query = 0, PreparedQueryId = 1 }; template <> struct EnumDescriptions<BatchQueryKind> { static const std::vector<std::pair<BatchQueryKind, const char*>>& get(); }; /** * The kind of the query result. * The value of this enum is the <kind> in result message. * Check native_protocol_v4.spec section 4.2.5. */ enum class ResultKind { Unknown = 0x0000, Void = 0x0001, Rows = 0x0002, SetKeySpace = 0x0003, Prepared = 0x0004, SchemaChange = 0x0005 }; template <> struct EnumDescriptions<ResultKind> { static const std::vector<std::pair<ResultKind, const char*>>& get(); }; /** * Flags in metadata of rows result. * The value of this enum is the <flags> in metadata of rows result. * Check native_protocol_v4.spec section 4.2.5.2. */ enum class ResultRowsMetadataFlags { None = 0, GlobalTableSpec = 1, HasMorePages = 2, NoMetadata = 4 }; template <> struct EnumDescriptions<ResultRowsMetadataFlags> { static const std::vector<std::pair<ResultRowsMetadataFlags, const char*>>& get(); }; /** * Flags in metadata of prepared result. * The value of this enum is the <flags> in metadata of prepared result. * Check native_protocol_v4.spec section 4.2.5.4. */ enum class ResultPreparedMetadataFlags { None = 0, GlobalTableSpec = 1 }; template <> struct EnumDescriptions<ResultPreparedMetadataFlags> { static const std::vector<std::pair<ResultPreparedMetadataFlags, const char*>>& get(); }; }
24.683616
87
0.695125
[ "vector" ]
56a27e63b5b89fc99969095ed48513a21741bdc8
11,901
cpp
C++
Engine2D/GameEngine.cpp
MarkusPfundstein/OpenGL-2D-RPG-Engine-iPhone
b9643e6a6243952f8e17f216a860e58b197e2247
[ "Unlicense" ]
2
2015-11-05T21:25:18.000Z
2016-02-15T08:55:44.000Z
Engine2D/GameEngine.cpp
MarkusPfundstein/OpenGL-2D-RPG-Engine-iPhone
b9643e6a6243952f8e17f216a860e58b197e2247
[ "Unlicense" ]
null
null
null
Engine2D/GameEngine.cpp
MarkusPfundstein/OpenGL-2D-RPG-Engine-iPhone
b9643e6a6243952f8e17f216a860e58b197e2247
[ "Unlicense" ]
null
null
null
// // GameEngine.cpp // OpenGL // // Created by Markus Pfundstein on 9/10/11. // Copyright 2011 The Saints. All rights reserved. // #include <iostream> using namespace std; #include "GameEngine.h" #include "Constants.h" #include "Script.h" #include "NPC.h" #include "Object.h" #include "Characters.h" GameEngine::GameEngine() { } GameEngine::~GameEngine() { delete this->gui; delete this->camera; delete this->script; delete this->font_silon; delete this->player; delete this->current_map; delete this->battleEngine; delete this->inventory; } bool GameEngine::initGameEngine() { //printf("Initialize Game Engine\n" this->script = NULL; this->player = NULL; this->gui = NULL; this->font_silon = NULL; this->inventory = NULL; this->isPaused = false; this->goOnWithScript = false; this->currentGameState = WORLD_MAP; // initialize cam this->camera = new Camera(); Texture2D *texFontSilom = new Texture2D((char*)"font_silom.png"); this->font_silon = new Font(*texFontSilom, (char*)"Font Silom"); delete texFontSilom, texFontSilom = NULL; Texture2D *tileset_gui; tileset_gui = new Texture2D((char*)"mainGUI.png"); this->gui = new Gui(*tileset_gui); delete tileset_gui, tileset_gui = NULL; // initialize player object which will walk around on the worldmap this->player = new Player(); this->player->pointToEngine(*this); // initialize script engine this->script = new Script(); this->script->loadDialog(*this->font_silon, *this->player, *this); // initialize items this->inventory = new Inventory(); this->inventory->load(*this->script); // initialize battleEngine this->battleEngine = new BattleEngine(*this->font_silon, *this, *this->inventory); /* ========================================== */ // for BATTLE TEST purposes // 4 characters Texture2D *tempSet = new Texture2D((char*)"female1bat.png"); Texture2D *weaponSet = new Texture2D((char*)"melee2.png"); this->player->setNCharsInGroup(3); charactersForBattle = new Characters[this->player->getNCharsInGroup()]; char charName[40]; memset(charName, 0, 40); for (int i = 0; i < this->player->getNCharsInGroup(); i++) { sprintf(charName, "Character:%d", i); charactersForBattle[i].create(*tempSet, 4, 2, charName); charactersForBattle[i].createWeapon(*weaponSet, 4, 1); this->player->setCharacter(charactersForBattle[i], i); Characters *c = &this->player->getCharacterAtPosition(i); c->setLevel(10); c->setMaxHitpoints(300); c->setHitpoints(100); c->setMaxManapoints(100); c->setManapoints(30); c->setActionPoints(10); c->setLimitPoints(0); c->setMaxLimitpoints(0); c->setIsAlive(true); c->setAttackStrength(20); c->setDefense(10); c=NULL; } delete tempSet, tempSet = NULL; delete weaponSet, weaponSet = NULL; // ITEMS for (int i = 0; i < this->inventory->getItemsUsed(); i++) { // we create a couple items of each and set them to collected so that the player can use them this->inventory->getItemsAtPosition(i).setNumberCollected(3); } // END OF BATTLE TEST PURPOSES /* ========================================== */ // load first world this->current_map = NULL; if (!this->loadNewMap((char*)"forest1.txt")) { return false; } return true; } void GameEngine::update_objects() { // is paused means that no the script doesnt get updated ... the graphics and objects are still getting updated... if (this->isPaused) updateWaiting(); if (this->currentGameState == WORLD_MAP || this->currentGameState == DIALOG) { if (this->newMapLoaded) { if (!this->current_map->getIsActive()) { //printf("map is not active, load new one\n"); this->newMapLoaded = false; this->loadNewMap(this->current_map->getNewWorld()); } if (this->goOnWithScript && !this->isPaused) { // read next line of the script with entry point 0 int goOn = this->script->getDialog().readNextLine(0); this->updateDialog(goOn); } this->player->update_position(*this->current_map); this->camera->update(*this->player, *this->current_map); // check for encounter if (this->current_map->updateWorld(*this->player) == CALLBACK_BATTLE && this->currentGameState != DIALOG) { int whichBattle =2;//= rand()%this->current_map->getNumberDifferentBattles(); this->battleEngine->initializeBattle(*this->player, this->current_map->getBattleListItem(whichBattle)); this->currentGameState = BATTLE; } } } else if (this->currentGameState == BATTLE) { int result = this->battleEngine->update(); if (result!=1) { this->battleEngine->clearMemory(); if (result == -1) { this->currentGameState = WORLD_MAP; } else { this->currentGameState = WORLD_MAP; } } } } void GameEngine::draw_scene(int fps) { if (this->newMapLoaded) { if (this->currentGameState != BATTLE) { // adjust matrix to draw the drawing scene this->adjust_scene(); this->current_map->draw(this->camera->getRect()); if (this->currentGameState == DIALOG) { if (!this->isPaused) this->script->getDialog().show(*this->player); } } else // we are in battle Mode { this->battleEngine->draw(); } // to enable gui drawing setMatrixToGUIMode(); // if we have a battle we draw the battle if (SHOW_PLAYER_POS && this->currentGameState != BATTLE) { this->font_silon->draw_string(0, 0, 1.0, 10, 0.8f, 0, 0.2f, 0.8f, "Player X:%1.f, Y:%1.f", this->player->getRect().pos.x/TILE_SIZE, (this->player->getRect().pos.y/TILE_SIZE)+1); } if (SHOW_FPS) { this->font_silon->draw_string(0.0, 300.0, 1.0, 10, 0.8f, 0.2f, 0.5f, 1.0f, "FPS: %d", fps); } if (!this->isPaused) this->gui->draw(this->currentGameState); } } void GameEngine::handle_input(const Point2D &at_position) { if (!this->isPaused) { if (this->currentGameState == WORLD_MAP) { this->gui->handle_player_movement(at_position, *this->player); ACTION_CODES actionCode = (ACTION_CODES)this->gui->handle_player_action(at_position, *this->current_map); this->startDialog(actionCode, NULL); } else if (this->currentGameState == DIALOG) { int goOn = this->script->getDialog().handleInput(at_position, *this->camera); this->updateDialog(goOn); } else if (this->currentGameState == BATTLE) { this->battleEngine->handleInput(at_position); } } } void GameEngine::startDialog(ACTION_CODES actionCode, const char* optionalString) { if (actionCode == ACTION_NPC) { // open dialog according to NPC name if (this->script->getDialog().startDialog(this->gui->getInteractedNPC()->getName(), ".dlg")) { this->currentGameState = DIALOG; this->gui->getInteractedNPC()->setLocked(true); this->script->getDialog().pointToNPC(*this->gui->getInteractedNPC()); int goOn = this->script->getDialog().readNextLine(0); this->updateDialog(goOn); } } else if (actionCode == ACTION_OBJECT) { // if the object has a dialog script if (this->script->getDialog().startDialog(this->gui->getInteractedObject()->getName(), ".dlg")) { this->currentGameState = DIALOG; this->script->getDialog().pointToObject(*this->gui->getInteractedObject()); int goOn = this->script->getDialog().readNextLine(0); this->updateDialog(goOn); } } else if (actionCode == ACTION_EVENTTILE) { // if there is a event tile we open the event script if (this->script->getDialog().startDialog(optionalString, NULL)) { this->currentGameState = DIALOG; int goOn = this->script->getDialog().readNextLine(0); if (goOn != 0) this->player->setMoving(false); this->updateDialog(goOn); } } } void GameEngine::updateDialog(int goOn) { if (goOn == -1) { // do nothing, this happens when the player clicks outside an input rect } else if (goOn == 1) this->goOnWithScript = false; else if (goOn == 2) { // after wait time script will go on automatically this->goOnWithScript = true; } else if (goOn == 0) { if (this->gui->getInteractedNPC() != NULL) // we call this function only if we have a npc, objects cant be locked this->gui->getInteractedNPC()->setLocked(false); this->script->getDialog().clearDialog(); this->currentGameState = WORLD_MAP; this->goOnWithScript = false; this->player->setChecksForCollison(true); } } void GameEngine::input_stop() { this->player->setMoving(false); } bool GameEngine::loadNewMap(const char* filename) { char fileToLoad[40]; memset(fileToLoad, 0, 40); strcpy(fileToLoad, filename); Point2D playerStart; if (this->current_map != NULL) { playerStart = this->current_map->getNewDestination(); delete this->current_map; this->current_map = NULL; } else { playerStart.x = NEW_GAME_START_X; playerStart.y = NEW_GAME_START_Y; } //printf("GameEngine: loadNewMap!!!\n"); // load new map this->current_map = new WorldMap(); if (!this->current_map->initWorld(fileToLoad, *this->script)) { //printf("ERROR: Initializing world\n"); return false; } this->script->getDialog().setWorldUsed(*this->current_map); // set player graphic this->player->setOnTile(playerStart); this->current_map->createDisplayList(*this->player); this->newMapLoaded = true; return true; } void GameEngine::adjust_scene() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); //rotated due to landscape mode glOrthof(this->camera->getRect().pos.y, this->camera->getRect().pos.y+this->camera->getRect().height, (this->camera->getRect().pos.x+this->camera->getRect().width), this->camera->getRect().pos.x, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(90.0f, 0, 0, 1); glTranslatef(0.0f, -SCREEN_HEIGHT_IPHONE, 0.0f); } void GameEngine::setPaused(bool val) { //printf("Game Engine state to wait: %d with Duration: %d\n", val, this->pauseDuration); this->pauseTimer = 0; this->isPaused = val; } void GameEngine::setPauseDuration(int val) { this->pauseDuration = val; } void GameEngine::updateWaiting() { if (this->pauseTimer < this->pauseDuration) { this->pauseTimer++; } else { this->pauseTimer = 0; this->isPaused = false; } } bool GameEngine::getIfPaused() const { return this->isPaused; }
29.026829
213
0.574658
[ "object" ]
56b1817e1df52f35d5822470edaead5e5bc27691
725
hpp
C++
graph/dijkstra.hpp
dutinmeow/library
3501f36656795f432ac816941ec7e9548dc3d6ef
[ "MIT" ]
7
2022-01-23T07:58:19.000Z
2022-02-25T04:11:12.000Z
graph/dijkstra.hpp
dutinmeow/library
3501f36656795f432ac816941ec7e9548dc3d6ef
[ "MIT" ]
null
null
null
graph/dijkstra.hpp
dutinmeow/library
3501f36656795f432ac816941ec7e9548dc3d6ef
[ "MIT" ]
null
null
null
#include "utility/chmin.hpp" #pragma region dijkstra #ifndef DIJKSTRA_HPP #define DIJKSTRA_HPP namespace graph { template<typename T> pair<vector<long long>, vector<int>> dijkstra(const vector<vector<pair<int, T>>> &G, int s) { int n = G.size(); priority_queue<pair<T, int>, vector<pair<T, int>>, greater<pair<T, int>>> pq; vector<T> dis(n, numeric_limits<T>::max()); vector<int> par(n, -1); pq.emplace(0, s); dis[s] = 0; par[s] = s; while (!pq.empty()) { auto [d, u] = pq.top(); pq.pop(); if (d != dis[u]) continue; for (auto [v, w] : G[u]) if (chmin(dis[v], d + w)) { par[v] = u; pq.emplace(dis[v], v); } } return {dis, par}; } } #endif #pragma endregion dijkstra
20.714286
94
0.587586
[ "vector" ]
56b419aa3c216cf4e276c695b4b301f15d1d7a97
32,156
cc
C++
arcane/src/arcane/tests/ModuleSimpleHydroSimd.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/tests/ModuleSimpleHydroSimd.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/tests/ModuleSimpleHydroSimd.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* ModuleSimpleHydroSimd.cc (C) 2000-2020 */ /* */ /* Module Hydrodynamique simple avec vectorisation. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #ifdef ARCANE_CHECK #define ARCANE_TRACE_ENUMERATOR #endif #include "arcane/utils/List.h" #include "arcane/utils/ArcaneGlobal.h" #include "arcane/utils/PlatformUtils.h" #include "arcane/utils/StringBuilder.h" #include "arcane/utils/ITraceMng.h" #include "arcane/ITimeLoop.h" #include "arcane/ISubDomain.h" #include "arcane/IMesh.h" #include "arcane/IApplication.h" #include "arcane/EntryPoint.h" #include "arcane/MathUtils.h" #include "arcane/ITimeLoopMng.h" #include "arcane/VariableTypes.h" #include "arcane/ItemEnumerator.h" #include "arcane/IParallelMng.h" #include "arcane/ModuleFactory.h" #include "arcane/TimeLoopEntryPointInfo.h" #include "arcane/ItemPrinter.h" #include "arcane/Concurrency.h" #include "arcane/BasicService.h" #include "arcane/ServiceBuildInfo.h" #include "arcane/ServiceBuilder.h" #include "arcane/FactoryService.h" #include "arcane/IMainFactory.h" #include "arcane/tests/TypesSimpleHydro.h" #include "arcane/SimdMathUtils.h" #include "arcane/SimdItem.h" #include "arcane/VariableView.h" #ifdef __INTEL_COMPILER #define HYDRO_PRAGMA_IVDEP _Pragma("ivdep") #else #define HYDRO_PRAGMA_IVDEP #endif /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace SimpleHydro { using namespace Arcane; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Module hydrodynamique simplifié avec vectorisation et parallélisation * par les threads. * * Ce module implémente une hydrodynamique simple tri-dimensionnel, * parallèle, avec une pseudo-viscosité aux mailles en utilisant * les classes de vectorisation fournies par Arcane. */ class SimpleHydroSimdService : public BasicService , public ISimpleHydroService { public: //! Constructeur explicit SimpleHydroSimdService(const ServiceBuildInfo& sbi); ~SimpleHydroSimdService(); //!< Destructeur public: virtual VersionInfo versionInfo() const { return VersionInfo(1,0,1); } public: void hydroBuild(); void hydroStartInit(); void hydroInit(); void hydroContinueInit() {} void hydroExit(); void computeForces(); void computePressureForce(){} void computePseudoViscosity(){} void computeVelocity(); void computeViscosityWork(); void applyBoundaryCondition(); void moveNodes(); void computeGeometricValues(); void updateDensity(); void applyEquationOfState(); void computeDeltaT(); void setModule(SimpleHydro::SimpleHydroModuleBase* module) override { m_module = module; } private: void computeGeometricValues2(); void cellScalarPseudoViscosity(); inline void computeCQs(Real3 node_coord[8],Real3 face_coord[6],Cell cell); private: VariableCellInt64 m_cell_unique_id; //!< Unique ID associé à la maille VariableCellInt32 m_sub_domain_id; //!< Numéro du sous-domaine associé à la maille VariableCellReal m_density; //!< Densite par maille VariableCellReal m_pressure; //!< Pression par maille VariableCellReal m_cell_mass; //!< Masse par maille VariableCellReal m_internal_energy; //!< Energie interne des mailles VariableCellReal m_volume; //!< Volume des mailles VariableCellReal m_old_volume; //!< Volume d'une maille à l'itération précédente VariableNodeReal3 m_force; //!< Force aux noeuds VariableNodeReal3 m_velocity; //!< Vitesse aux noeuds VariableNodeReal m_node_mass; //! Masse nodale VariableCellReal m_cell_viscosity_force; //!< Contribution locale des forces de viscosité VariableCellReal m_viscosity_work; //!< Travail des forces de viscosité par maille VariableCellReal m_adiabatic_cst; //!< Constante adiabatique par maille VariableCellReal m_caracteristic_length; //!< Longueur caractéristique par maille VariableCellReal m_sound_speed; //!< Vitesse du son dans la maille VariableNodeReal3 m_node_coord; //!< Coordonnées des noeuds VariableCellArrayReal3 m_cell_cqs; //!< Résultantes aux sommets pour chaque maille VariableScalarReal m_density_ratio_maximum; //!< Accroissement maximum de la densité sur un pas de temps VariableScalarReal m_delta_t_n; //!< Delta t n entre t^{n-1/2} et t^{n+1/2} VariableScalarReal m_delta_t_f; //!< Delta t n+\demi entre t^{n} et t^{n+1} VariableScalarReal m_old_dt_f; //!< Delta t n-\demi entre t^{n-1} et t^{n} SimpleHydro::SimpleHydroModuleBase* m_module; private: void _computePressureAndCellPseudoViscosityForces(); void _specialInit(); public: void computeCQsSimd(SimdReal3 node_coord[8],SimdReal3 face_coord[6],SimdReal3 cqs[8]); }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ SimpleHydroSimdService:: SimpleHydroSimdService(const ServiceBuildInfo& sbi) : BasicService(sbi) , m_cell_unique_id (VariableBuildInfo(sbi.mesh(),"UniqueId")) , m_sub_domain_id (VariableBuildInfo(sbi.mesh(),"SubDomainId")) , m_density (VariableBuildInfo(sbi.mesh(),"Density")) , m_pressure(VariableBuildInfo(sbi.mesh(),"Pressure")) , m_cell_mass(VariableBuildInfo(sbi.mesh(),"CellMass")) , m_internal_energy(VariableBuildInfo(sbi.mesh(),"InternalEnergy")) , m_volume(VariableBuildInfo(sbi.mesh(),"CellVolume")) , m_old_volume(VariableBuildInfo(sbi.mesh(),"OldCellVolume")) , m_force(VariableBuildInfo(sbi.mesh(),"Force",IVariable::PNoNeedSync)) , m_velocity(VariableBuildInfo(sbi.mesh(),"Velocity")) , m_node_mass(VariableBuildInfo(sbi.mesh(),"NodeMass")) , m_cell_viscosity_force(VariableBuildInfo(sbi.mesh(),"CellViscosityForce")) , m_viscosity_work(VariableBuildInfo(sbi.mesh(),"ViscosityWork")) , m_adiabatic_cst(VariableBuildInfo(sbi.mesh(),"AdiabaticCst")) , m_caracteristic_length(VariableBuildInfo(sbi.mesh(),"CaracteristicLength")) , m_sound_speed(VariableBuildInfo(sbi.mesh(),"SoundSpeed")) , m_node_coord(VariableBuildInfo(sbi.mesh(),"NodeCoord")) , m_cell_cqs(VariableBuildInfo(sbi.mesh(),"CellCQS")) , m_density_ratio_maximum(VariableBuildInfo(sbi.mesh(),"DensityRatioMaximum")) , m_delta_t_n(VariableBuildInfo(sbi.mesh(),"CenteredDeltaT")) , m_delta_t_f(VariableBuildInfo(sbi.mesh(),"SplitDeltaT")) , m_old_dt_f(VariableBuildInfo(sbi.mesh(),"OldDTf")) , m_module(nullptr) { if (TaskFactory::isActive()){ info() << "USE CONCURRENCY!!!!!"; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ SimpleHydroSimdService:: ~SimpleHydroSimdService() { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SimpleHydroSimdService:: hydroBuild() { info() << "Using hydro with vectorisation name=" << SimdInfo::name() << " vector_size=" << SimdReal::Length << " index_size=" << SimdInfo::Int32IndexSize; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SimpleHydroSimdService:: hydroExit() { info() << "Hydro exit entry point"; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Initialisation du module hydro lors du démarrage du cas. */ void SimpleHydroSimdService:: hydroStartInit() { info() << "START_INIT sizeof(ItemLocalId)=" << sizeof(ItemLocalId); ENUMERATE_CELL(icell,allCells()){ m_sub_domain_id[icell]=subDomain()->subDomainId(); m_cell_unique_id[icell]=icell->uniqueId(); } // Dimensionne les variables tableaux m_cell_cqs.resize(8); //info() << "SimpleHydro SIMD initialisation vec_size=" << SimdReal::BLOCK_SIZE; // Vérifie que les valeurs initiales sont correctes { Integer nb_error = 0; auto in_pressure = viewIn(m_pressure); auto in_adiabatic_cst = viewIn(m_adiabatic_cst); VariableCellRealInView in_density = viewIn(m_density); ENUMERATE_CELL(icell,allCells()){ CellLocalId cid = *icell; Real pressure = in_pressure[cid]; Real adiabatic_cst = in_adiabatic_cst[cid]; Real density = in_density[cid]; if (math::isZero(pressure) || math::isZero(density) || math::isZero(adiabatic_cst)){ info() << "Null valeur for cell=" << ItemPrinter(*icell) << " density=" << density << " pressure=" << pressure << " adiabatic_cst=" << adiabatic_cst; ++nb_error; } } if (nb_error!=0) fatal() << "Some (" << nb_error << ") cells are not initialised"; } // Initialise le delta-t Real deltat_init = m_module->getDeltatInit(); m_delta_t_n = deltat_init; m_delta_t_f = deltat_init; // Initialise les données géométriques: volume, cqs, longueurs caractéristiques computeGeometricValues(); m_node_mass.fill(ARCANE_REAL(0.0)); m_velocity.fill(Real3::zero()); // Initialisation de la masses des mailles et des masses nodale ENUMERATE_CELL(icell,allCells()){ Cell cell = *icell; m_cell_mass[icell] = m_density[icell] * m_volume[icell]; Real contrib_node_mass = ARCANE_REAL(0.125) * m_cell_mass[cell]; for( NodeEnumerator i_node(cell.nodes()); i_node.hasNext(); ++i_node ){ m_node_mass[i_node] += contrib_node_mass; } } m_node_mass.synchronize(); // Initialise l'énergie et la vitesse du son auto in_pressure = viewIn(m_pressure); auto in_density = viewIn(m_density); auto in_adiabatic_cst = viewIn(m_adiabatic_cst); VariableCellRealOutView out_internal_energy = viewOut(m_internal_energy); auto out_sound_speed = viewOut(m_sound_speed); ENUMERATE_SIMD_CELL(icell,allCells()){ SimdCell vi = *icell; SimdReal pressure = in_pressure[vi]; SimdReal adiabatic_cst = in_adiabatic_cst[vi]; SimdReal density = in_density[vi]; out_internal_energy[vi] = pressure / ((adiabatic_cst-ARCANE_REAL(1.0)) * density); out_sound_speed[vi] = math::sqrt(adiabatic_cst*pressure/density); } info() << "END_START_INIT"; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcul des forces au temps courant \f$t^{n}\f$ */ void SimpleHydroSimdService:: computeForces() { // Remise à zéro du vecteur des forces. m_force.fill(Real3::null()); VariableNodeReal3OutView out_force = viewOut(m_force); VariableNodeReal3InView in_force = viewIn(m_force); // Calcul pour chaque noeud de chaque maille la contribution // des forces de pression et de la pseudo-viscosite si necessaire if (m_module->getViscosity()==TypesSimpleHydro::ViscosityCellScalar){ _computePressureAndCellPseudoViscosityForces(); } else{ ENUMERATE_CELL(icell,allCells()){ Cell cell = *icell; Real pressure = m_pressure[cell]; for( NodeEnumerator i_node(cell.nodes()); i_node.hasNext(); ++i_node ){ NodeLocalId nid = *i_node; out_force[nid] = in_force[nid] + pressure * m_cell_cqs[icell][i_node.index()]; } } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Pseudo viscosité scalaire aux mailles */ void SimpleHydroSimdService:: _computePressureAndCellPseudoViscosityForces() { Real linear_coef = m_module->getViscosityLinearCoef(); Real quadratic_coef = m_module->getViscosityQuadraticCoef(); auto in_pressure = viewIn(m_pressure); auto in_density = viewIn(m_density); auto out_cell_viscosity_force = viewOut(m_cell_viscosity_force); // Boucle sur les mailles du maillage ENUMERATE_CELL(icell,allCells().view()){ Cell cell = *icell; CellLocalId cid(cell); const Real rho = in_density[cell]; const Real pressure = in_pressure[icell]; // Calcul de la divergence de la vitesse Real delta_speed = 0.; for( NodeEnumerator i_node(cell.nodes()); i_node.hasNext(); ++i_node ) delta_speed += math::scaMul(m_velocity[i_node],m_cell_cqs[icell][i_node.index()]); delta_speed /= m_volume[icell]; // Capture uniquement les chocs bool shock = (math::min(ARCANE_REAL(0.0),delta_speed)<ARCANE_REAL(0.0)); if (shock){ Real sound_speed = m_sound_speed[icell]; Real dx = m_caracteristic_length[icell]; Real quadratic_viscosity = rho * dx * dx * delta_speed * delta_speed; Real linear_viscosity = -rho*sound_speed* dx * delta_speed; Real scalar_viscosity = linear_coef * linear_viscosity + quadratic_coef * quadratic_viscosity; out_cell_viscosity_force[cid] = scalar_viscosity; for( NodeEnumerator i_node(cell.nodes()); i_node.hasNext(); ++i_node ) m_force[i_node] += (pressure + scalar_viscosity)*m_cell_cqs[icell][i_node.index()]; } else{ out_cell_viscosity_force[cid] = ARCANE_REAL(0.0); for( NodeEnumerator i_node(cell.nodes()); i_node.hasNext(); ++i_node ) m_force[i_node] += pressure * m_cell_cqs[icell][i_node.index()]; } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcul de l'impulsion (phase2). */ void SimpleHydroSimdService:: computeVelocity() { m_force.synchronize(); auto in_old_velocity = viewIn(m_velocity); auto in_node_mass = viewIn(m_node_mass); auto in_force = viewIn(m_force); auto out_velocity = viewOut(m_velocity); // Calcule l'impulsion aux noeuds ENUMERATE_SIMD_NODE(i_node,allNodes()){ SimdNode node = *i_node; SimdReal node_mass = in_node_mass[node]; SimdReal3 old_velocity = in_old_velocity[node]; SimdReal3 new_velocity = old_velocity + (m_delta_t_n() / node_mass) * in_force[i_node]; out_velocity[node] = new_velocity; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcul de l'impulsion (phase3). */ void SimpleHydroSimdService:: computeViscosityWork() { arcaneParallelForeach(allCells(),[this](CellVectorView cells){ auto in_cell_viscosity_force = viewIn(m_cell_viscosity_force); auto out_viscosity_work = viewOut(m_viscosity_work); // Calcul du travail des forces de viscosité dans une maille ENUMERATE_CELL(icell,cells){ Cell cell = *icell; CellLocalId cid(cell); Real work = 0.; Real scalar_viscosity = in_cell_viscosity_force[cid]; if (!math::isZero(scalar_viscosity)) for( NodeEnumerator i_node(cell.nodes()); i_node.hasNext(); ++i_node ) work += math::scaMul(scalar_viscosity*m_cell_cqs[icell][i_node.index()],m_velocity[i_node]); out_viscosity_work[cid] = work; } } ); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Prise en compte des conditions aux limites. */ void SimpleHydroSimdService:: applyBoundaryCondition() { for( auto bc : m_module->getBoundaryConditions() ){ FaceGroup face_group = bc->getSurface(); NodeGroup node_group = face_group.nodeGroup(); Real value = bc->getValue(); TypesSimpleHydro::eBoundaryCondition type = bc->getType(); // boucle sur les faces de la surface ENUMERATE_FACE(j,face_group){ Face face = *j; Integer nb_node = face.nbNode(); // boucle sur les noeuds de la face for( Integer k=0; k<nb_node; ++k ){ Node node = face.node(k); switch(type) { case TypesSimpleHydro::VelocityX: m_velocity[node].x = value; break; case TypesSimpleHydro::VelocityY: m_velocity[node].y = value; break; case TypesSimpleHydro::VelocityZ: m_velocity[node].z = value; break; case TypesSimpleHydro::Unknown: break; } } } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* * \brief Déplace les noeuds. */ void SimpleHydroSimdService:: moveNodes() { Real deltat_f = m_delta_t_f(); ENUMERATE_NODE(i_node,allNodes()){ m_node_coord[i_node] += deltat_f * m_velocity[i_node]; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Mise à jour des densités et calcul de l'accroissements max * de la densité sur l'ensemble du maillage. */ void SimpleHydroSimdService:: updateDensity() { Real density_ratio_maximum = ARCANE_REAL(0.0); HYDRO_PRAGMA_IVDEP ENUMERATE_CELL(icell,allCells()){ Real old_density = m_density[icell]; Real new_density = m_cell_mass[icell] / m_volume[icell]; m_density[icell] = new_density; Real density_ratio = (new_density - old_density) / new_density; if (density_ratio_maximum<density_ratio) density_ratio_maximum = density_ratio; } m_density_ratio_maximum = density_ratio_maximum; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Applique l'équation d'état et calcul l'énergie interne et la * pression. */ void SimpleHydroSimdService:: applyEquationOfState() { const Real deltatf = m_delta_t_f(); const bool add_viscosity_force = (m_module->getViscosity()!=TypesSimpleHydro::ViscosityNo); auto in_adiabatic_cst = viewIn(m_adiabatic_cst); auto in_volume = viewIn(m_volume); auto in_density = viewIn(m_density); auto in_old_volume = viewIn(m_old_volume); auto in_internal_energy = viewIn(m_internal_energy); auto in_cell_mass = viewIn(m_cell_mass); auto in_viscosity_work = viewIn(m_viscosity_work); auto out_internal_energy = viewOut(m_internal_energy); auto out_sound_speed = viewOut(m_sound_speed); auto out_pressure = viewOut(m_pressure); // Calcul de l'énergie interne arcaneParallelForeach(allCells(),[&](CellVectorView cells){ ENUMERATE_SIMD_CELL(icell,cells){ SimdCell vi = *icell; SimdReal adiabatic_cst = in_adiabatic_cst[vi]; SimdReal volume_ratio = in_volume[vi] / in_old_volume[vi]; SimdReal x = ARCANE_REAL(0.5)*(adiabatic_cst-ARCANE_REAL(1.0)); SimdReal numer_accrois_nrj = ARCANE_REAL(1.0) + x*(ARCANE_REAL(1.0)-volume_ratio); SimdReal denom_accrois_nrj = ARCANE_REAL(1.0) + x*(ARCANE_REAL(1.0)-(ARCANE_REAL(1.0)/volume_ratio)); SimdReal internal_energy = in_internal_energy[vi]; internal_energy = internal_energy * (numer_accrois_nrj/denom_accrois_nrj); // Prise en compte du travail des forces de viscosité if (add_viscosity_force) internal_energy = internal_energy - deltatf*in_viscosity_work[vi] / (in_cell_mass[vi]*denom_accrois_nrj); out_internal_energy[vi] = internal_energy; SimdReal density = in_density[vi]; SimdReal pressure = (adiabatic_cst-ARCANE_REAL(1.0)) * density * internal_energy; SimdReal sound_speed = math::sqrt(adiabatic_cst*pressure/density); out_pressure[vi] = pressure; out_sound_speed[vi] = sound_speed; } } ); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcul des nouveaux pas de temps. */ void SimpleHydroSimdService:: computeDeltaT() { const Real old_dt = m_global_deltat(); // Calcul du pas de temps pour le respect du critère de CFL Real minimum_aux = FloatInfo<Real>::maxValue(); Real new_dt = FloatInfo<Real>::maxValue(); HYDRO_PRAGMA_IVDEP ENUMERATE_CELL(icell,ownCells()){ Real cell_dx = m_caracteristic_length[icell]; Real sound_speed = m_sound_speed[icell]; Real dx_sound = cell_dx / sound_speed; minimum_aux = math::min(minimum_aux,dx_sound); } new_dt = m_module->getCfl()*minimum_aux; // Pas de variations trop brutales à la hausse comme à la baisse Real max_dt = (ARCANE_REAL(1.0)+m_module->getVariationSup())*old_dt; Real min_dt = (ARCANE_REAL(1.0)-m_module->getVariationInf())*old_dt; new_dt = math::min(new_dt,max_dt); new_dt = math::max(new_dt,min_dt); // control de l'accroissement relatif de la densité Real dgr = m_module->getDensityGlobalRatio(); if (m_density_ratio_maximum()>dgr) new_dt = math::min(old_dt*dgr/m_density_ratio_maximum(),new_dt); IParallelMng* pm = mesh()->parallelMng(); new_dt = pm->reduce(Parallel::ReduceMin,new_dt); // Respect des valeurs min et max imposées par le fichier de données .plt new_dt = math::min(new_dt,m_module->getDeltatMax()); new_dt = math::max(new_dt,m_module->getDeltatMin()); // Le dernier calcul se fait exactement au temps stopTime() { Real stop_time = m_module->getFinalTime(); bool not_yet_finish = ( m_global_time() < stop_time); bool too_much = ( (m_global_time()+new_dt) > stop_time); if ( not_yet_finish && too_much ){ new_dt = stop_time - m_global_time(); subDomain()->timeLoopMng()->stopComputeLoop(true); } } // Mise à jour des variables m_old_dt_f.assign(old_dt); m_delta_t_n.assign(ARCANE_REAL(0.5)*(old_dt+new_dt)); m_delta_t_f.assign(new_dt); m_global_deltat.assign(new_dt); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcul des résultantes aux noeuds d'une maille hexaédrique. * * La méthode utilisée est celle du découpage en quatre triangles. */ inline void SimpleHydroSimdService:: computeCQsSimd(SimdReal3 node_coord[8],SimdReal3 face_coord[6],SimdReal3 cqs[8]) { const SimdReal3 c0 = face_coord[0]; const SimdReal3 c1 = face_coord[1]; const SimdReal3 c2 = face_coord[2]; const SimdReal3 c3 = face_coord[3]; const SimdReal3 c4 = face_coord[4]; const SimdReal3 c5 = face_coord[5]; const Real demi = ARCANE_REAL(0.5); const Real five = ARCANE_REAL(5.0); // Calcul des normales face 1 : const SimdReal3 n1a04 = demi * math::cross(node_coord[0] - c0 , node_coord[3] - c0); const SimdReal3 n1a03 = demi * math::cross(node_coord[3] - c0 , node_coord[2] - c0); const SimdReal3 n1a02 = demi * math::cross(node_coord[2] - c0 , node_coord[1] - c0); const SimdReal3 n1a01 = demi * math::cross(node_coord[1] - c0 , node_coord[0] - c0); // Calcul des normales face 2 : const SimdReal3 n2a05 = demi * math::cross(node_coord[0] - c1 , node_coord[4] - c1); const SimdReal3 n2a12 = demi * math::cross(node_coord[4] - c1 , node_coord[7] - c1); const SimdReal3 n2a08 = demi * math::cross(node_coord[7] - c1 , node_coord[3] - c1); const SimdReal3 n2a04 = demi * math::cross(node_coord[3] - c1 , node_coord[0] - c1); // Calcul des normales face 3 : const SimdReal3 n3a01 = demi * math::cross(node_coord[0] - c2 , node_coord[1] - c2); const SimdReal3 n3a06 = demi * math::cross(node_coord[1] - c2 , node_coord[5] - c2); const SimdReal3 n3a09 = demi * math::cross(node_coord[5] - c2 , node_coord[4] - c2); const SimdReal3 n3a05 = demi * math::cross(node_coord[4] - c2 , node_coord[0] - c2); // Calcul des normales face 4 : const SimdReal3 n4a09 = demi * math::cross(node_coord[4] - c3 , node_coord[5] - c3); const SimdReal3 n4a10 = demi * math::cross(node_coord[5] - c3 , node_coord[6] - c3); const SimdReal3 n4a11 = demi * math::cross(node_coord[6] - c3 , node_coord[7] - c3); const SimdReal3 n4a12 = demi * math::cross(node_coord[7] - c3 , node_coord[4] - c3); // Calcul des normales face 5 : const SimdReal3 n5a02 = demi * math::cross(node_coord[1] - c4 , node_coord[2] - c4); const SimdReal3 n5a07 = demi * math::cross(node_coord[2] - c4 , node_coord[6] - c4); const SimdReal3 n5a10 = demi * math::cross(node_coord[6] - c4 , node_coord[5] - c4); const SimdReal3 n5a06 = demi * math::cross(node_coord[5] - c4 , node_coord[1] - c4); // Calcul des normales face 6 : const SimdReal3 n6a03 = demi * math::cross(node_coord[2] - c5 , node_coord[3] - c5); const SimdReal3 n6a08 = demi * math::cross(node_coord[3] - c5 , node_coord[7] - c5); const SimdReal3 n6a11 = demi * math::cross(node_coord[7] - c5 , node_coord[6] - c5); const SimdReal3 n6a07 = demi * math::cross(node_coord[6] - c5 , node_coord[2] - c5); const Real real_1div12 = ARCANE_REAL(1.0) / ARCANE_REAL(12.0); cqs[0] = (five*(n1a01 + n1a04 + n2a04 + n2a05 + n3a05 + n3a01) + (n1a02 + n1a03 + n2a08 + n2a12 + n3a06 + n3a09))*real_1div12; cqs[1] = (five*(n1a01 + n1a02 + n3a01 + n3a06 + n5a06 + n5a02) + (n1a04 + n1a03 + n3a09 + n3a05 + n5a10 + n5a07))*real_1div12; cqs[2] = (five*(n1a02 + n1a03 + n5a07 + n5a02 + n6a07 + n6a03) + (n1a01 + n1a04 + n5a06 + n5a10 + n6a11 + n6a08))*real_1div12; cqs[3] = (five*(n1a03 + n1a04 + n2a08 + n2a04 + n6a08 + n6a03) + (n1a01 + n1a02 + n2a05 + n2a12 + n6a07 + n6a11))*real_1div12; cqs[4] = (five*(n2a05 + n2a12 + n3a05 + n3a09 + n4a09 + n4a12) + (n2a08 + n2a04 + n3a01 + n3a06 + n4a10 + n4a11))*real_1div12; cqs[5] = (five*(n3a06 + n3a09 + n4a09 + n4a10 + n5a10 + n5a06) + (n3a01 + n3a05 + n4a12 + n4a11 + n5a07 + n5a02))*real_1div12; cqs[6] = (five*(n4a11 + n4a10 + n5a10 + n5a07 + n6a07 + n6a11) + (n4a12 + n4a09 + n5a06 + n5a02 + n6a03 + n6a08))*real_1div12; cqs[7] = (five*(n2a08 + n2a12 + n4a12 + n4a11 + n6a11 + n6a08) + (n2a04 + n2a05 + n4a09 + n4a10 + n6a07 + n6a03))*real_1div12; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcul du volume des mailles, des longueurs caractéristiques * et des résultantes aux sommets. */ void SimpleHydroSimdService:: computeGeometricValues() { auto out_caracteristic_length = viewOut(m_caracteristic_length); arcaneParallelForeach(allCells(),[&](CellVectorView cells){ // Copie locale des coordonnées des sommets d'une maille SimdReal3 coord[8]; // Coordonnées des centres des faces SimdReal3 face_coord[6]; SimdReal3 cqs[8]; int nb_done = 0; //std::cerr << "SIZE=" << cells.size() << '\n'; ENUMERATE_SIMD_CELL(ivecitem,cells){ ++nb_done; SimdCell vitem = *ivecitem; for( CellEnumerator iscell(ivecitem.enumerator()); iscell.hasNext(); ++iscell ){ Cell cell(*iscell); Integer si(iscell.index()); // Recopie les coordonnées locales (pour le cache) for( NodeEnumerator i_node(cell.nodes()); i_node.index()<8; ++i_node ){ coord[i_node.index()].set(si,m_node_coord[i_node]); //info() << "COORD lid=" << cell.localId() << " i=" << i << " index=" << i_node.index() << " v=" << coord[i_node.index()][i]; } } // Calcul les coordonnées des centres des faces face_coord[0] = ARCANE_REAL(0.25) * ( coord[0] + coord[3] + coord[2] + coord[1] ); face_coord[1] = ARCANE_REAL(0.25) * ( coord[0] + coord[4] + coord[7] + coord[3] ); face_coord[2] = ARCANE_REAL(0.25) * ( coord[0] + coord[1] + coord[5] + coord[4] ); face_coord[3] = ARCANE_REAL(0.25) * ( coord[4] + coord[5] + coord[6] + coord[7] ); face_coord[4] = ARCANE_REAL(0.25) * ( coord[1] + coord[2] + coord[6] + coord[5] ); face_coord[5] = ARCANE_REAL(0.25) * ( coord[2] + coord[3] + coord[7] + coord[6] ); // Calcule la longueur caractéristique de la maille. SimdReal3 median1 = face_coord[0]-face_coord[3]; SimdReal3 median2 = face_coord[2]-face_coord[5]; SimdReal3 median3 = face_coord[1]-face_coord[4]; SimdReal d1 = math::normL2(median1); SimdReal d2 = math::normL2(median2); SimdReal d3 = math::normL2(median3); SimdReal dx_numerator = d1*d2*d3; SimdReal dx_denominator = d1*d2 + d1*d3 + d2*d3; out_caracteristic_length[vitem] = dx_numerator / dx_denominator; //for( Integer i=0; i<NV; ++i ){ //Cell cell(vitem.item(i)); // Calcule les résultantes aux sommets computeCQsSimd(coord,face_coord,cqs); //} // Calcul des résultantes aux sommets : for( CellEnumerator si(ivecitem.enumerator()); si.hasNext(); ++si ){ Cell cell(*si); Integer sidx(si.index()); ArrayView<Real3> cqsv = m_cell_cqs[cell]; for( Integer i_node=0; i_node<8; ++i_node ) cqsv[i_node] = cqs[i_node][sidx]; } /*for( Integer i=0; i<NV; ++i ){ Cell cell(vitem.item(i)); for( Integer z=0; z<8; ++z ){ info() << "CQS lid=" << cell.localId() << " i=" << i << " z=" << z << " v=" << m_cell_cqs[cell][z]; } }*/ // Calcule le volume de la maille for( CellEnumerator si(ivecitem.enumerator()); si.hasNext(); ++si ){ Cell cell(*si); Integer sidx(si.index()); Real volume = 0.; for( Integer i_node=0; i_node<8; ++i_node ) volume += math::dot(coord[i_node][sidx],cqs[i_node][sidx]); volume /= ARCANE_REAL(3.0); m_old_volume[cell] = m_volume[cell]; m_volume[cell] = volume; } /*SimdReal volume(0.0); for( Integer i_node=0; i_node<8; ++i_node ) volume = volume + math::dot(coord[i_node],cqs[i_node]); volume = volume / ARCANE_REAL(3.0); for( Integer i=0; i<NV; ++i ){ Cell cell(vitem.item(i)); m_old_volume[cell] = m_volume[cell]; m_volume[cell] = volume[i]; }*/ } } ); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SimpleHydroSimdService:: hydroInit() { if (m_module->getBackwardIteration()!=0){ subDomain()->timeLoopMng()->setBackwardSavePeriod(10); } info() << "INIT: DTmin=" << m_module->getDeltatMin() << " DTmax="<< m_module->getDeltatMax() << " DT="<< m_global_deltat(); if (m_global_deltat() > m_module->getDeltatMax()) ARCANE_FATAL("DeltaT > DTMax"); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_REGISTER_SERVICE(SimpleHydroSimdService, ServiceProperty("StdHydroSimdService",ST_CaseOption), ARCANE_SERVICE_INTERFACE(SimpleHydro::ISimpleHydroService)); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace SimpleHydro /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
38.51018
137
0.59712
[ "mesh" ]
56b51619ec9621096fa94370ac8c595451f75b6e
1,754
cpp
C++
CombBLAS/ReleaseTests/FindSparse.cpp
shoaibkamil/OLD-kdt-specializer
85074ec1990df980d25096ea8c55dd81350e531e
[ "BSD-3-Clause" ]
1
2021-11-15T02:11:33.000Z
2021-11-15T02:11:33.000Z
CombBLAS/ReleaseTests/FindSparse.cpp
shoaibkamil/OLD-kdt-specializer
85074ec1990df980d25096ea8c55dd81350e531e
[ "BSD-3-Clause" ]
null
null
null
CombBLAS/ReleaseTests/FindSparse.cpp
shoaibkamil/OLD-kdt-specializer
85074ec1990df980d25096ea8c55dd81350e531e
[ "BSD-3-Clause" ]
null
null
null
#include <mpi.h> #include <sys/time.h> #include <iostream> #include <functional> #include <algorithm> #include <vector> #include <sstream> #include "../SpTuples.h" #include "../SpDCCols.h" #include "../SpParMat.h" #include "../FullyDistVec.h" using namespace std; int main(int argc, char* argv[]) { MPI::Init(argc, argv); int nprocs = MPI::COMM_WORLD.Get_size(); int myrank = MPI::COMM_WORLD.Get_rank(); if(argc < 3) { if(myrank == 0) { cout << "Usage: ./FindSparse <BASEADDRESS> <Matrix>" << endl; cout << "Input files should be under <BASEADDRESS> in appropriate format" << endl; } MPI::Finalize(); return -1; } { string directory(argv[1]); string matrixname(argv[2]); matrixname = directory+"/"+matrixname; ifstream inputmatrix(matrixname.c_str()); if(myrank == 0) { if(inputmatrix.fail()) { cout << "One of the input files do not exist, aborting" << endl; MPI::COMM_WORLD.Abort(NOFILE); return -1; } } MPI::COMM_WORLD.Barrier(); typedef SpParMat <int, double, SpDCCols<int,double> > PARDBMAT; PARDBMAT A; // declare objects FullyDistVec<int,int> crow, ccol; FullyDistVec<int,double> cval; A.ReadDistribute(inputmatrix, 0); A.Find(crow, ccol, cval); PARDBMAT B(A.getnrow(), A.getncol(), crow, ccol, cval); // Sparse() if (A == B) { SpParHelper::Print("Find and Sparse working correctly\n"); } else { SpParHelper::Print("ERROR in Find(), go fix it!\n"); SpParHelper::Print("Rows array: \n"); crow.DebugPrint(); SpParHelper::Print("Columns array: \n"); ccol.DebugPrint(); SpParHelper::Print("Values array: \n"); cval.DebugPrint(); } inputmatrix.clear(); inputmatrix.close(); } MPI::Finalize(); return 0; }
20.635294
85
0.63683
[ "vector" ]
56b55549fefbc563b6f49ed10f61ef2dac2c9937
226
cpp
C++
Header.cpp
tingli-shen/Jumping-Array-Puzzle
f04c67d7ecd656d5ecee8cc344ea073dcec2318e
[ "MIT" ]
null
null
null
Header.cpp
tingli-shen/Jumping-Array-Puzzle
f04c67d7ecd656d5ecee8cc344ea073dcec2318e
[ "MIT" ]
null
null
null
Header.cpp
tingli-shen/Jumping-Array-Puzzle
f04c67d7ecd656d5ecee8cc344ea073dcec2318e
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include <vector> #include <string> #include "Header.h" using namespace std; int tree::zeroSite() { for (int i = 0; i < num.length(); i++) if (num[i] == '0') return i; }
17.384615
40
0.584071
[ "vector" ]
56b574571471c6b95087b94bee674ed8d3be4026
4,394
cpp
C++
Project/Riaju1/Plugins/SpriteStudio5/Source/SpriteStudio5/Private/Player/SsPlayerCellmap.cpp
SpriteStudio/RiaJuSniper_UnrealEngine4Project
5b7ffb0e4161eaa9249c164c0dfeb16b636ff6ae
[ "MIT" ]
3
2018-04-16T23:58:23.000Z
2020-10-24T04:42:43.000Z
Project/Riaju1/Plugins/SpriteStudio5/Source/SpriteStudio5/Private/Player/SsPlayerCellmap.cpp
SpriteStudio/RiaJuSniper_UnrealEngine4Project
5b7ffb0e4161eaa9249c164c0dfeb16b636ff6ae
[ "MIT" ]
null
null
null
Project/Riaju1/Plugins/SpriteStudio5/Source/SpriteStudio5/Private/Player/SsPlayerCellmap.cpp
SpriteStudio/RiaJuSniper_UnrealEngine4Project
5b7ffb0e4161eaa9249c164c0dfeb16b636ff6ae
[ "MIT" ]
6
2018-04-12T20:27:12.000Z
2021-03-07T19:54:49.000Z
#include "SpriteStudio5PrivatePCH.h" #include "SsPlayerCellmap.h" #include "SsProject.h" #include "SsAnimePack.h" #include "SsCellMap.h" #include "SsPlayerAnimedecode.h" #include "SsPlayerMatrix.h" FSsCelMapLinker::FSsCelMapLinker() : CellMap(0) , Tex(0) { } FSsCelMapLinker::FSsCelMapLinker(FSsCellMap* cellmap, FName filePath) { CellMap = cellmap; size_t num = CellMap->Cells.Num(); for ( size_t i = 0 ; i < num ; i++ ) { if(!CellDic.Contains(CellMap->Cells[i].CellName)) { CellDic.Add(CellMap->Cells[i].CellName); } CellDic[CellMap->Cells[i].CellName] = &(CellMap->Cells[i]); } Tex = cellmap->Texture; if(NULL == Tex->Resource) { Tex->UpdateResource(); } } FSsCelMapLinker::~FSsCelMapLinker() { CellDic.Empty(); } void FSsCellMapList::Clear() { CellMapDic.Empty(); CellMapList.Empty(); } void FSsCellMapList::SetCellMapPath(const FName& filepath) { CellMapPath = filepath; } void FSsCellMapList::Set(USsProject* proj , FSsAnimePack* animepack) { Clear(); SetCellMapPath( FName(*(proj->GetImageBasepath())) ); for(int32 i = 0 ; i < animepack->CellmapNames.Num() ; i++) { int32 CellmapIndex = proj->FindCellMapIndex(animepack->CellmapNames[i]); if(0 <= CellmapIndex) { Add(&proj->CellmapList[CellmapIndex]); } else { UE_LOG(LogTemp, Warning, TEXT(" Not found cellmap = %s"), *(animepack->CellmapNames[i].ToString())); } } for(int32 i = 0; i < animepack->Model.PartList.Num(); ++i) { if(SsPartType::Effect == animepack->Model.PartList[i].Type) { int32 EffectIndex = proj->FindEffectIndex(animepack->Model.PartList[i].RefEffectName); if(0 <= EffectIndex) { for(int32 j = 0; j < proj->EffectList[EffectIndex].EffectData.NodeList.Num(); ++j) { int32 CellmapIndex = proj->FindCellMapIndex(proj->EffectList[EffectIndex].EffectData.NodeList[j].Behavior.CellMapName); if(0 <= CellmapIndex) { Add(&(proj->CellmapList[CellmapIndex])); } } } } } } void FSsCellMapList::Add(FSsCellMap* cellmap) { FName CellMapNameEx = FName( *(cellmap->CellMapName.ToString() + TEXT(".ssce")) ); if(!CellMapDic.Contains(CellMapNameEx)) { FSsCelMapLinker* linker = new FSsCelMapLinker(cellmap , this->CellMapPath); CellMapDic.Add(CellMapNameEx); CellMapDic[ CellMapNameEx ] = linker ; CellMapList.Add( linker ); } } FSsCelMapLinker* FSsCellMapList::GetCellMapLink( const FName& name ) { FSsCelMapLinker* l = CellMapDic[name]; if ( l != 0 ) return l; return 0; } void GetCellValue(FSsCelMapLinker* l, FName& cellName, FSsCellValue& v) { v.Cell = l->FindCell( cellName ); v.FilterMode = l->CellMap->FilterMode; v.WrapMode = l->CellMap->WrapMode; if ( l->Tex ) { v.Texture = l->Tex; } else { v.Texture = 0; } CalcUvs( &v ); } void GetCellValue(FSsCellMapList* cellList, FName& cellMapName, FName& cellName, FSsCellValue& v) { FSsCelMapLinker* l = cellList->GetCellMapLink( cellMapName ); GetCellValue( l , cellName , v ); } void GetCellValue(FSsCellMapList* cellList, int32 cellMapid, FName& cellName, FSsCellValue& v) { FSsCelMapLinker* l = cellList->GetCellMapLink( cellMapid ); GetCellValue( l , cellName , v ); } void CalcUvs( FSsCellValue* cellv ) { //SsCellMap* map = cellv->cellmapl->cellMap; FSsCell* cell = cellv->Cell; // if ( cell == 0 || map == 0) if ( cell == 0 ) { cellv->Uvs[0].X = cellv->Uvs[0].Y = 0; cellv->Uvs[1].X = cellv->Uvs[1].Y = 0; cellv->Uvs[2].X = cellv->Uvs[2].Y = 0; cellv->Uvs[3].X = cellv->Uvs[3].Y = 0; return; } FVector2D wh; wh.X = (float)cellv->Texture->Resource->GetSizeX(); wh.Y = (float)cellv->Texture->Resource->GetSizeY(); // FVector2D wh = map->pixelSize; // 右上に向かって+になる float left = cell->Pos.X / wh.X; float right = (cell->Pos.X + cell->Size.X) / wh.X; // LB->RB->LT->RT 順 // 頂点をZ順にしている都合上UV値は上下逆転させている float top = cell->Pos.Y / wh.Y; float bottom = ( cell->Pos.Y + cell->Size.Y) / wh.Y; if (cell->Rotated) { // 反時計回りに90度回転されているため起こして描画されるようにしてやる。 // 13 // 02 cellv->Uvs[0].X = cellv->Uvs[1].X = left; cellv->Uvs[2].X = cellv->Uvs[3].X = right; cellv->Uvs[1].Y = cellv->Uvs[3].Y = top; cellv->Uvs[0].Y = cellv->Uvs[2].Y = bottom; } else { // そのまま。頂点の順番は下記の通り // 01 // 23 cellv->Uvs[0].X = cellv->Uvs[2].X = left; cellv->Uvs[1].X = cellv->Uvs[3].X = right; cellv->Uvs[0].Y = cellv->Uvs[1].Y = top; cellv->Uvs[2].Y = cellv->Uvs[3].Y = bottom; } }
22.191919
124
0.653391
[ "model" ]
56b702e480acb6fd8a5a254a4943758276bd8638
646
cpp
C++
Bridges.cpp
dineshkwal/DS-and-algo-codes
c1466279d57af4476fcc082d787d0efbf0ef4a1a
[ "MIT" ]
null
null
null
Bridges.cpp
dineshkwal/DS-and-algo-codes
c1466279d57af4476fcc082d787d0efbf0ef4a1a
[ "MIT" ]
null
null
null
Bridges.cpp
dineshkwal/DS-and-algo-codes
c1466279d57af4476fcc082d787d0efbf0ef4a1a
[ "MIT" ]
null
null
null
const int kLimit = 100001; unordered_set<int> bridges; vector<int> id(kLimit); vector<int> lowlink(kLimit); vector<bool> visited(kLimit, false); int counter = 0; void dfs(const vector<vector<pair<int, int>>>& graph, int u, int parent = -1) { visited[u] = true; id[u] = counter++; lowlink[u] = id[u]; for (const auto& edge : graph[u]) { const auto v = edge.first; const auto z = edge.second; if (!visited[v]) { dfs(graph, v, u); lowlink[u] = min(lowlink[u], lowlink[v]); if (id[u] < lowlink[v]) { bridges.emplace(z); } } else if (v != parent) { lowlink[u] = min(lowlink[u], id[v]); } } }
18.457143
77
0.585139
[ "vector" ]
56beb1cc18c767ab18a7d96fb094536111199f35
24,288
cpp
C++
src/ui/common/ui_params.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
6
2020-03-29T09:37:01.000Z
2022-01-20T08:56:31.000Z
src/ui/common/ui_params.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
1
2021-03-05T08:00:50.000Z
2021-03-05T08:00:50.000Z
src/ui/common/ui_params.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
11
2019-05-13T00:04:38.000Z
2022-01-20T08:56:38.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file ui_params.cpp * \author Collin Johnson * * Definition of functions to turn the contents of a utils::ConfigFile into * the appropriate UI params structs. */ #include <ui/common/ui_params.h> #include <utils/config_file.h> #include <utils/config_file_utils.h> #include <iostream> namespace vulcan { namespace ui { // Constants defining the parameter strings in the configuration file const std::string LPM_DISPLAY_HEADING ("LocalMetricDisplayParameters"); const std::string FRONT_LASER_COLOR_KEY ("front_laser_color"); const std::string BACK_LASER_COLOR_KEY ("back_laser_color"); const std::string WARNING_LASER_COLOR_KEY ("warning_laser_color"); const std::string CRITICAL_LASER_COLOR_KEY ("critical_laser_color"); const std::string INTENSITY_LASER_COLOR_KEY ("intensity_laser_color"); const std::string EXTRACTED_LINES_COLOR_KEY ("extracted_lines_color"); const std::string OCCUPIED_COLOR_KEY ("occupied_cell_color"); const std::string DYNAMIC_COLOR_KEY ("dynamic_cell_color"); const std::string LIMITED_VIS_COLOR_KEY ("limited_visibility_cell_color"); const std::string HAZARD_COLOR_KEY ("hazard_cell_color"); const std::string QUASI_STATIC_COLOR_KEY ("quasi_static_cell_color"); const std::string ROBOT_COLOR_KEY ("robot_color"); const std::string TRACE_COLOR_KEY ("robot_trace_color"); const std::string ODOM_TRACE_COLOR_KEY ("odometry_trace_color"); const std::string PARTICLES_COLOR_KEY ("particles_color"); const std::string CIRCLE_COLOR_KEY ("target_circle_color"); const std::string ARROW_COLOR_KEY ("target_arrow_color"); const std::string METRIC_PATH_COLOR_KEY ("metric_path_color"); const std::string TRACE_LENGTH_KEY ("max_trace_length"); const std::string LOCAL_METRIC_MESSAGE_KEY ("local_metric_hssh_message_output_channel"); const std::string METRIC_PATH_KEY ("metric_waypoint_path_channel"); const std::string REACHED_CIRCLE_COLOR_KEY ("reached_target_circle_color"); const std::string REACHED_ARROW_COLOR_KEY ("reached_target_arrow_color"); const std::string ACQUIRING_TARGET_COLOR_KEY("acquiring_target_color"); const std::string ACTIVE_TARGET_COLOR_KEY ("active_target_color"); const std::string INACTIVE_TARGET_COLOR_KEY ("inactive_target_color"); const std::string LOCAL_TOPO_DISPLAY_HEADING("LocalTopoDisplayParameters"); const std::string FRONTIER_CELL_COLOR_KEY ("frontier_color"); const std::string GATEWAY_CELL_COLOR_KEY ("gateway_color"); const std::string JUNCTION_COLOR_KEY ("junction_color"); const std::string DEAD_END_COLOR_KEY ("dead_end_color"); const std::string SKELETON_CELL_COLOR_KEY ("skeleton_cell_color"); const std::string REDUCED_CELL_COLOR_KEY ("reduced_cell_color"); const std::string SOURCE_CELL_COLOR_KEY ("source_color"); const std::string EXPLORED_COLOR_KEY ("explored_color"); const std::string UNKNOWN_AREA_COLOR_KEY ("unknown_area_color"); const std::string LOCAL_PATH_COLOR_KEY ("local_path_color"); const std::string LOCAL_DECISION_COLOR_KEY ("local_decision_color"); const std::string LOCAL_DEST_COLOR_KEY ("local_destination_color"); const std::string LOCAL_PATH_DEST_COLOR_KEY ("local_path_dest_color"); const std::string LOCAL_PATH_DECI_COLOR_KEY ("local_path_decision_color"); const std::string LOCAL_DEST_DECI_COLOR_KEY ("local_dest_decision_color"); const std::string GATEWAY_END_COLOR_KEY ("gateway_endpoint_color"); const std::string LOCAL_PATH_START_COLOR_KEY("local_path_start_color"); const std::string LOCAL_PATH_END_COLOR_KEY ("local_path_end_color"); const std::string ISOVIST_RAY_COLOR_KEY ("isovist_ray_color"); const std::string ISOVIST_FIELD_COLORS_KEY ("isovist_field_colors"); const std::string GLOBAL_TOPO_DISPLAY_HEADING("GlobalTopoDisplayParameters"); const std::string GLOBAL_PLACE_COLOR_KEY ("place_color"); const std::string GLOBAL_PATH_COLOR_KEY ("path_color"); const std::string GLOBAL_FRONTIER_COLOR_KEY ("frontier_color"); const std::string GLOBAL_LOCATION_COLOR_KEY ("global_location_color"); const std::string HYP_TREE_NODE_COLOR_KEY ("hypothesis_tree_node_color"); const std::string HYP_TREE_EDGE_COLOR_KEY ("hypothesis_tree_edge_color"); const std::string HYP_TREE_BEST_COLOR_KEY ("hypothesis_tree_best_node_color"); const std::string HYP_TREE_HOVER_COLOR_KEY ("hypothesis_tree_hover_node_color"); const std::string HYP_TREE_SEL_A_COLOR_KEY ("hypothesis_tree_selected_node_a_color"); const std::string HYP_TREE_SEL_B_COLOR_KEY ("hypothesis_tree_selected_node_b_color"); const std::string HYP_TREE_SEL_C_COLOR_KEY ("hypothesis_tree_selected_node_c_color"); const std::string CORRECT_MAP_CHANNEL_KEY ("correct_global_topo_map_output_channel"); const std::string METRIC_PLANNER_DISPLAY_HEADING("MetricPlannerDisplayParameters"); const std::string TRAJECTORY_COLOR_RED_KEY ("trajectory_color_red"); const std::string TRAJECTORY_COLOR_BLUE_KEY ("trajectory_color_blue"); const std::string TRAJECTORY_COLOR_GREEN_KEY ("trajectory_color_green"); const std::string ROBOT_COLOR_RED_KEY ("robot_color_red"); const std::string ROBOT_COLOR_BLUE_KEY ("robot_color_blue"); const std::string ROBOT_COLOR_GREEN_KEY ("robot_color_green"); const std::string ROBOT_COLOR_GREY_KEY ("robot_color_grey"); const std::string ROBOT_COLOR_LIGHT_BLUE_KEY ("robot_color_light_blue"); const std::string ROBOT_COLOR_VIOLET_KEY ("robot_color_violet"); const std::string FLOW_TAIL_COLOR_KEY ("flow_tail_color"); const std::string FLOW_HEAD_COLOR_KEY ("flow_head_color"); const std::string RRT_NODE_COLOR_KEY ("node_color"); const std::string RRT_EDGE_COLOR_KEY ("edge_color"); const std::string RRT_START_COLOR_KEY ("start_color"); const std::string RRT_TARGET_COLOR_KEY ("target_color"); const std::string RRT_GOAL_REGION_COLOR_KEY ("goal_region_color"); const std::string RRT_GOAL_PATH_COLOR_KEY ("goal_path_color"); const std::string ROBOT_MODEL_CONFIG_FILE_KEY ("robot_model_config_file"); const std::string METRIC_PLANNER_CONFIG_FILE_KEY("metric_planner_config_file"); const std::string RELOCALIZATION_DISPLAY_HEADING("RelocalizationDisplayParameters"); const std::string REQUEST_OUTPUT_CHANNEL_KEY ("relocalization_request_output_channel"); const std::string SCRIPTING_DISPLAY_HEADING("ScriptingDisplayParameters"); const std::string SCRIPT_HOVER_COLOR_KEY ("hover_color"); const std::string SCRIPT_SELECT_COLOR_KEY ("selected_color"); const std::string SCRIPT_FINAL_COLOR_KEY ("finalized_color"); const std::string DECISION_PLANNER_DISPLAY_HEADING("DecisionPlannerDisplayParameters"); const std::string SEQUENCE_OUTPUT_CHANNEL_KEY ("target_sequence_output_channel"); const std::string ENTRY_FRAGMENT_COLOR_KEY ("place_entry_fragment_color"); const std::string EXIT_FRAGMENT_COLOR_KEY ("place_exit_fragment_color"); const std::string PATH_EXIT_COLOR_KEY ("path_exit_point_color"); const std::string GOAL_PLANNER_DISPLAY_HEADING("GoalPlannerDisplayParameters"); // Using GLOBAL_LOCATION_COLOR_KEY const std::string GLOBAL_TARGET_COLOR_KEY ("global_target_color"); const std::string PLACE_VERTEX_COLOR_KEY ("place_vertex_color"); const std::string SEGMENT_VERTEX_COLOR_KEY ("path_segment_vertex_color"); const std::string GRAPH_EDGE_COLOR_KEY ("graph_edge_color"); const std::string GRAPH_PATH_COLOR_KEY ("graph_path_color"); const std::string ROUTE_ELEMENT_COLOR_KEY ("route_element_color"); const std::string VISITED_ELEMENT_COLOR_KEY ("visited_element_color"); const std::string ACTIVE_ELEMENT_COLOR_KEY ("active_element_color"); const std::string REMAINING_ELEMENT_COLOR_KEY ("remaining_element_color"); const std::string ROUTE_COMMAND_OUTPUT_CHANNEL_KEY ("route_command_output_channel"); const std::string GOAL_TARGET_OUTPUT_CHANNEL_KEY ("goal_target_output_channel"); const std::string GLOBAL_LOCATION_OUTPUT_CHANNEL_KEY("set_global_location_output_channel"); const std::string VISION_DISPLAY_HEADING("VisionDisplayParameters"); const std::string GROUND_PLANE_COLOR_KEY("ground_plane_boundary_color"); const std::string MAIN_FRAME_HEADING("MainFrameParameters"); const std::string FPS_KEY ("frames_per_second"); // Helpers for loading the parameters of the various structs lpm_display_params_t load_lpm_display_params (const utils::ConfigFile& config); local_topo_display_params_t load_local_topo_display_params (const utils::ConfigFile& config); global_topo_display_params_t load_global_topo_display_params (const utils::ConfigFile& config); relocalization_display_params_t load_relocalization_display_params (const utils::ConfigFile& config); scripting_display_params_t load_scripting_display_params (const utils::ConfigFile& config); metric_planner_display_params_t load_metric_planner_display_params (const utils::ConfigFile& config); decision_planner_display_params_t load_decision_planner_display_params(const utils::ConfigFile& config); goal_planner_display_params_t load_goal_planner_display_params (const utils::ConfigFile& config); vision_display_params_t load_vision_display_params (const utils::ConfigFile& config); main_frame_params_t load_main_frame_params (const utils::ConfigFile& config); ui_params_t load_ui_params(const utils::ConfigFile& config) { ui_params_t params; params.lpmParams = load_lpm_display_params(config); params.localTopoParams = load_local_topo_display_params(config); params.globalTopoParams = load_global_topo_display_params(config); params.relocalizationParams = load_relocalization_display_params(config); params.scriptingParams = load_scripting_display_params(config); params.metricPlannerDisplayParams = load_metric_planner_display_params(config); params.decisionPlannerParams = load_decision_planner_display_params(config); params.goalPlannerParams = load_goal_planner_display_params(config); params.visionParams = load_vision_display_params(config); params.mainFrameParams = load_main_frame_params(config); return params; } lpm_display_params_t load_lpm_display_params(const utils::ConfigFile& config) { lpm_display_params_t params; params.frontLaserColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, FRONT_LASER_COLOR_KEY)); params.backLaserColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, BACK_LASER_COLOR_KEY)); params.warningLaserColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, WARNING_LASER_COLOR_KEY)); params.criticalLaserColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, CRITICAL_LASER_COLOR_KEY)); params.intensityLaserColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, INTENSITY_LASER_COLOR_KEY)); params.extractedLinesColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, EXTRACTED_LINES_COLOR_KEY)); params.occupiedColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, OCCUPIED_COLOR_KEY)); params.dynamicColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, DYNAMIC_COLOR_KEY)); params.limitedVisibilityColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, LIMITED_VIS_COLOR_KEY)); params.hazardColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, HAZARD_COLOR_KEY)); params.quasiStaticColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, QUASI_STATIC_COLOR_KEY)); params.robotColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, ROBOT_COLOR_KEY)); params.traceColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, TRACE_COLOR_KEY)); params.odometryTraceColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, ODOM_TRACE_COLOR_KEY)); params.particlesColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, PARTICLES_COLOR_KEY)); params.targetCircleColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, CIRCLE_COLOR_KEY)); params.targetArrowColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, ARROW_COLOR_KEY)); params.metricPathColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, METRIC_PATH_COLOR_KEY)); params.reachedTargetCircleColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, REACHED_CIRCLE_COLOR_KEY)); params.reachedTargetArrowColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, REACHED_ARROW_COLOR_KEY)); params.acquiringTrackingColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, ACQUIRING_TARGET_COLOR_KEY)); params.activeTrackingColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, ACTIVE_TARGET_COLOR_KEY)); params.inactiveTrackingColor = GLColor(config.getValueAsString(LPM_DISPLAY_HEADING, INACTIVE_TARGET_COLOR_KEY)); params.maxTraceLength = config.getValueAsUInt16(LPM_DISPLAY_HEADING, TRACE_LENGTH_KEY); params.messageChannel = config.getValueAsString(LPM_DISPLAY_HEADING, LOCAL_METRIC_MESSAGE_KEY); params.metricPathChannel = config.getValueAsString(LPM_DISPLAY_HEADING, METRIC_PATH_KEY); return params; } local_topo_display_params_t load_local_topo_display_params(const utils::ConfigFile& config) { local_topo_display_params_t params; params.frontierColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, FRONTIER_CELL_COLOR_KEY)); params.gatewayColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, GATEWAY_CELL_COLOR_KEY)); params.junctionColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, JUNCTION_COLOR_KEY)); params.deadEndColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, DEAD_END_COLOR_KEY)); params.skeletonCellColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, SKELETON_CELL_COLOR_KEY)); params.reducedCellColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, REDUCED_CELL_COLOR_KEY)); params.sourceColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, SOURCE_CELL_COLOR_KEY)); params.unknownColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, UNKNOWN_AREA_COLOR_KEY)); params.pathColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_PATH_COLOR_KEY)); params.decisionColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_DECISION_COLOR_KEY)); params.destinationColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_DEST_COLOR_KEY)); params.pathDecisionColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_PATH_DECI_COLOR_KEY)); params.pathDestColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_PATH_DEST_COLOR_KEY)); params.destDecisionColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_DEST_DECI_COLOR_KEY)); params.exploredColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, EXPLORED_COLOR_KEY)); params.gatewayEndpointColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, GATEWAY_END_COLOR_KEY)); params.pathStartColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_PATH_START_COLOR_KEY)); params.pathEndColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, LOCAL_PATH_END_COLOR_KEY)); params.isovistRayColor = GLColor(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, ISOVIST_RAY_COLOR_KEY)); std::vector<std::string> fieldColors = utils::split_into_strings(config.getValueAsString(LOCAL_TOPO_DISPLAY_HEADING, ISOVIST_FIELD_COLORS_KEY), ';'); for(auto& color : fieldColors) { params.isovistFieldColors.push_back(GLColor(color)); } return params; } global_topo_display_params_t load_global_topo_display_params(const utils::ConfigFile& config) { global_topo_display_params_t params; params.pathColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, GLOBAL_PATH_COLOR_KEY)); params.placeColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, GLOBAL_PLACE_COLOR_KEY)); params.locationColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, GLOBAL_LOCATION_COLOR_KEY)); params.frontierColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, GLOBAL_FRONTIER_COLOR_KEY)); params.nodeColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_NODE_COLOR_KEY)); params.edgeColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_EDGE_COLOR_KEY)); params.bestNodeColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_BEST_COLOR_KEY)); params.hoverNodeColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_HOVER_COLOR_KEY)); params.selectedMapAColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_SEL_A_COLOR_KEY)); params.selectedMapBColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_SEL_B_COLOR_KEY)); params.selectedMapCColor = GLColor(config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, HYP_TREE_SEL_C_COLOR_KEY)); params.correctMapOutputChannel = config.getValueAsString(GLOBAL_TOPO_DISPLAY_HEADING, CORRECT_MAP_CHANNEL_KEY); return params; } relocalization_display_params_t load_relocalization_display_params(const utils::ConfigFile& config) { relocalization_display_params_t params; params.requestChannel = config.getValueAsString(RELOCALIZATION_DISPLAY_HEADING, REQUEST_OUTPUT_CHANNEL_KEY); return params; } scripting_display_params_t load_scripting_display_params(const utils::ConfigFile& config) { scripting_display_params_t params; params.hoverColor = GLColor(config.getValueAsString(SCRIPTING_DISPLAY_HEADING, SCRIPT_HOVER_COLOR_KEY)); params.selectedColor = GLColor(config.getValueAsString(SCRIPTING_DISPLAY_HEADING, SCRIPT_SELECT_COLOR_KEY)); params.finalizedColor = GLColor(config.getValueAsString(SCRIPTING_DISPLAY_HEADING, SCRIPT_FINAL_COLOR_KEY)); return params; } metric_planner_display_params_t load_metric_planner_display_params(const utils::ConfigFile& config) { metric_planner_display_params_t params; params.trajectoryColorRed = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, TRAJECTORY_COLOR_RED_KEY)); params.trajectoryColorBlue = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, TRAJECTORY_COLOR_BLUE_KEY)); params.trajectoryColorGreen = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, TRAJECTORY_COLOR_GREEN_KEY)); params.robotColorRed = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_COLOR_RED_KEY)); params.robotColorBlue = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_COLOR_BLUE_KEY)); params.robotColorGreen = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_COLOR_GREEN_KEY)); params.robotColorGrey = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_COLOR_GREY_KEY)); params.robotColorLightBlue = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_COLOR_LIGHT_BLUE_KEY)); params.robotColorViolet = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_COLOR_VIOLET_KEY)); params.flowTailColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, FLOW_TAIL_COLOR_KEY)); params.flowHeadColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, FLOW_HEAD_COLOR_KEY)); params.nodeColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, RRT_NODE_COLOR_KEY)); params.edgeColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, RRT_EDGE_COLOR_KEY)); params.startColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, RRT_START_COLOR_KEY)); params.targetColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, RRT_TARGET_COLOR_KEY)); params.goalRegionColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, RRT_GOAL_REGION_COLOR_KEY)); params.goalPathColor = GLColor(config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, RRT_GOAL_PATH_COLOR_KEY)); params.collisionModelConfig = config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, ROBOT_MODEL_CONFIG_FILE_KEY); params.mpepcConfig = config.getValueAsString(METRIC_PLANNER_DISPLAY_HEADING, METRIC_PLANNER_CONFIG_FILE_KEY); return params; } decision_planner_display_params_t load_decision_planner_display_params(const utils::ConfigFile& config) { decision_planner_display_params_t params; params.targetSequenceChannel = config.getValueAsString(DECISION_PLANNER_DISPLAY_HEADING, SEQUENCE_OUTPUT_CHANNEL_KEY); params.placeEntryFragmentColor = GLColor(config.getValueAsString(DECISION_PLANNER_DISPLAY_HEADING, ENTRY_FRAGMENT_COLOR_KEY)); params.placeExitFragmentColor = GLColor(config.getValueAsString(DECISION_PLANNER_DISPLAY_HEADING, EXIT_FRAGMENT_COLOR_KEY)); params.pathExitPointColor = GLColor(config.getValueAsString(DECISION_PLANNER_DISPLAY_HEADING, PATH_EXIT_COLOR_KEY)); return params; } goal_planner_display_params_t load_goal_planner_display_params(const utils::ConfigFile& config) { goal_planner_display_params_t params; params.globalLocationColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, GLOBAL_LOCATION_COLOR_KEY)); params.globalTargetColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, GLOBAL_TARGET_COLOR_KEY)); params.placeVertexColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, PLACE_VERTEX_COLOR_KEY)); params.pathSegmentVertexColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, SEGMENT_VERTEX_COLOR_KEY)); params.edgeColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, GRAPH_EDGE_COLOR_KEY)); params.graphPathColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, GRAPH_PATH_COLOR_KEY)); params.routeElementColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, ROUTE_ELEMENT_COLOR_KEY)); params.visitedElementColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, VISITED_ELEMENT_COLOR_KEY)); params.activeElementColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, ACTIVE_ELEMENT_COLOR_KEY)); params.remainingElementColor = GLColor(config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, REMAINING_ELEMENT_COLOR_KEY)); params.routeCommandOutputChannel = config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, ROUTE_COMMAND_OUTPUT_CHANNEL_KEY); params.goalTargetOutputChannel = config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, GOAL_TARGET_OUTPUT_CHANNEL_KEY); params.setGlobalLocationOutputChannel = config.getValueAsString(GOAL_PLANNER_DISPLAY_HEADING, GLOBAL_LOCATION_OUTPUT_CHANNEL_KEY); return params; } vision_display_params_t load_vision_display_params(const utils::ConfigFile& config) { vision_display_params_t params; params.groundPlaneColor = GLColor(config.getValueAsString(VISION_DISPLAY_HEADING, GROUND_PLANE_COLOR_KEY)); return params; } main_frame_params_t load_main_frame_params(const utils::ConfigFile& config) { main_frame_params_t params; params.framesPerSecond = config.getValueAsUInt8(MAIN_FRAME_HEADING, FPS_KEY); return params; } } // namespace ui } // namespace vulcan
61.178841
153
0.805048
[ "vector" ]
56c3148afdd91ee3358177ee1dc86ffe3bca4570
3,945
cpp
C++
src/PlaneCut.cpp
chenming-wu/robust-plane-cut
9577b2d547764501dd9a071e79aa0b2afe2ff958
[ "FSFAP" ]
null
null
null
src/PlaneCut.cpp
chenming-wu/robust-plane-cut
9577b2d547764501dd9a071e79aa0b2afe2ff958
[ "FSFAP" ]
null
null
null
src/PlaneCut.cpp
chenming-wu/robust-plane-cut
9577b2d547764501dd9a071e79aa0b2afe2ff958
[ "FSFAP" ]
null
null
null
#include "PlaneCut.h" #include <CGAL/Polygon_mesh_processing/repair.h> constexpr double eps = 1e-8; constexpr double eps10 = 10 * eps; inline bool negative(Vector3& p, double C, Point3& a) { Vector3 probe(a.x(), a.y(), a.z()); return probe * p + C > eps; } inline bool positive(Vector3& p, double C, Point3& a) { Vector3 probe(a.x(), a.y(), a.z()); return probe * p + C < -eps; } bool PlaneCutter::cut(Polyhedron& poly_left, Polyhedron& poly_right, const Plane& pl) { int IntrCnt = 0; std::vector<Edge_iterator> Edges; std::vector<Halfedge_handle> ModifiedEdges; //Side to be modified Edges.reserve(poly_left.size_of_halfedges() / 2); // clear degenerate edges for (auto& e : edges(poly_left)) { if (CGAL::Polygon_mesh_processing::is_degenerate_edge(e, poly_left)) { poly_left.join_vertex(e.halfedge()); } } for (Polyhedron::Edge_iterator it = poly_left.edges_begin(); it != poly_left.edges_end(); ++it) { Edges.push_back(it); } Vector3 cut(pl.a(), pl.b(), pl.c()); double C = pl.d(); cut = cut / CGAL::sqrt(cut.squared_length()); C = C / CGAL::sqrt(cut.squared_length()); double d0, d1; for (std::vector<Polyhedron::Edge_iterator>::iterator it = Edges.begin(); it != Edges.end(); ++it) { Halfedge_handle h = *it; Vector3 p1(h->prev()->vertex()->point().x(), h->prev()->vertex()->point().y(), h->prev()->vertex()->point().z()); Vector3 p2(h->vertex()->point().x(), h->vertex()->point().y(), h->vertex()->point().z()); d0 = cut * p1 + C; d1 = cut * p2 + C; Vector3 Q; if ((d0 >= 0 && d1 < 0) || (d0 < 0 && d1 >= 0)) { Q = p1 + ((d0 / (d0 - d1)) * (p2 - p1)); Point3 newPnt(Q.x(), Q.y(), Q.z()); if (std::abs(d0) < eps10) { h->prev()->vertex()->point() = newPnt; } else if (std::abs(d1) < eps10) { h->vertex()->point() = newPnt; } else { IntrCnt++; Halfedge_handle t = poly_left.split_edge(h); t->vertex()->point() = newPnt; ModifiedEdges.push_back(t); } } } std::cout << "Modified edges = " << ModifiedEdges.size() << std::endl; for (std::vector<Halfedge_handle>::iterator it = ModifiedEdges.begin(); it != ModifiedEdges.end(); it++) { Halfedge_handle h = *it; Halfedge_handle g = h->opposite()->prev(); Facet_handle f_h = h->facet(); Facet_handle g_h = g->facet(); Halfedge_handle tmp_he; if (f_h != nullptr && !f_h->is_triangle()) { if (f_h->is_quad()) { tmp_he = poly_left.split_facet(h, h->next()->next()); } else { tmp_he = poly_left.split_facet(h, h->next()->next()); poly_left.split_facet(h, h->next()->next()); } } if (g_h != nullptr && !g_h->is_triangle()) { if (g_h->is_quad()) { tmp_he = poly_left.split_facet(g, g->next()->next()); } else { tmp_he = poly_left.split_facet(g, g->next()->next()); poly_left.split_facet(g, g->next()->next()); } } } poly_right = poly_left; for (Facet_iterator it = poly_left.facets_begin(), nd = poly_left.facets_end(); it != nd;) { Facet_iterator itNext = it; ++itNext; Halfedge_handle h = it->halfedge(); if (h == NULL) { it = itNext; continue; } Halfedge_handle e = h; do { if (positive(cut, C, h->vertex()->point())) { poly_left.erase_facet(e); break; } h = h->next(); } while (h != e); it = itNext; } for (Facet_iterator it = poly_right.facets_begin(), nd = poly_right.facets_end(); it != nd;) { Facet_iterator itNext = it; ++itNext; Halfedge_handle h = it->halfedge(); if (h == NULL) { it = itNext; continue; } Halfedge_handle e = h; do { if (negative(cut, C, h->vertex()->point())) { poly_right.erase_facet(e); break; } h = h->next(); } while (h != e); it = itNext; } return true; } std::pair<Polyhedron, Polyhedron> PlaneCutter::cut(const Polyhedron& poly, const Plane& pl) { Polyhedron o1; Polyhedron o2; o1 = poly; cut(o1, o2, pl); return std::make_pair(o1, o2); }
22.803468
115
0.591888
[ "vector" ]
56c34808cd967345d515af52322c96f6d66e7f4a
3,372
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/audiofx/CAudioEffectDescriptor.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/audiofx/CAudioEffectDescriptor.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/audiofx/CAudioEffectDescriptor.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/media/audiofx/CAudioEffectDescriptor.h" using Elastos::Utility::IUUIDHelper; using Elastos::Utility::CUUIDHelper; namespace Elastos { namespace Droid { namespace Media { namespace Audiofx { CAudioEffectDescriptor::CAudioEffectDescriptor() : mConnectMode(String(NULL)) , mName(String(NULL)) , mImplementor(String(NULL)) {} CAR_INTERFACE_IMPL(CAudioEffectDescriptor, Object, IAudioEffectDescriptor) CAR_OBJECT_IMPL(CAudioEffectDescriptor) ECode CAudioEffectDescriptor::constructor( /* [in] */ const String& type, /* [in] */ const String& uuid, /* [in] */ const String& connectMode, /* [in] */ const String& name, /* [in] */ const String& implementor) { mConnectMode = connectMode; mName = name; mImplementor = implementor; AutoPtr<IUUIDHelper> helper; CUUIDHelper::AcquireSingleton((IUUIDHelper**)&helper); helper->FromString(type,(IUUID**)&mType); helper->FromString(uuid,(IUUID**)&mUuid); return NOERROR; } ECode CAudioEffectDescriptor::GetType( /* [out] */ IUUID** type) { VALIDATE_NOT_NULL(type); *type = mType; REFCOUNT_ADD(*type); return NOERROR; } ECode CAudioEffectDescriptor::SetType( /* [in] */ IUUID* type) { VALIDATE_NOT_NULL(type); mType = type; return NOERROR; } ECode CAudioEffectDescriptor::GetUuid( /* [out] */ IUUID** uuid) { VALIDATE_NOT_NULL(uuid); *uuid = mUuid; REFCOUNT_ADD(*uuid); return NOERROR; } ECode CAudioEffectDescriptor::SetUuid( /* [in] */ IUUID* uuid) { VALIDATE_NOT_NULL(uuid); mUuid = uuid; return NOERROR; } ECode CAudioEffectDescriptor::GetConnectMode( /* [out] */ String* connectMode) { VALIDATE_NOT_NULL(connectMode); *connectMode = mConnectMode; return NOERROR; } ECode CAudioEffectDescriptor::SetConnectMode( /* [in] */ const String& connectMode) { mConnectMode = connectMode; return NOERROR; } ECode CAudioEffectDescriptor::GetName( /* [out] */ String* name) { VALIDATE_NOT_NULL(name); *name = mName; return NOERROR; } ECode CAudioEffectDescriptor::SetName( /* [in] */ const String& name) { mName = name; return NOERROR; } ECode CAudioEffectDescriptor::GetImplementor( /* [out] */ String* implementor) { VALIDATE_NOT_NULL(implementor); *implementor = mImplementor; return NOERROR; } ECode CAudioEffectDescriptor::SetImplementor( /* [in] */ const String& implementor) { mImplementor = implementor; return NOERROR; } } // namespace Audiofx } // namespace Media } // namepsace Droid } // namespace Elastos
24.434783
75
0.662218
[ "object" ]
56c42b5bc24c01d931f5dccd1d4c900ab9b85a21
3,264
cpp
C++
modules/wechat_qrcode/src/zxing/qrcode/decoder/datamask.cpp
donglinb/opencv_contrib
eaa4f33ddd68a04c8f01035baeac8b2b906bc45b
[ "Apache-2.0" ]
7
2021-02-08T15:49:28.000Z
2022-03-26T01:34:14.000Z
modules/wechat_qrcode/src/zxing/qrcode/decoder/datamask.cpp
donglinb/opencv_contrib
eaa4f33ddd68a04c8f01035baeac8b2b906bc45b
[ "Apache-2.0" ]
1
2019-08-02T10:28:05.000Z
2019-08-02T10:28:05.000Z
modules/wechat_qrcode/src/zxing/qrcode/decoder/datamask.cpp
donglinb/opencv_contrib
eaa4f33ddd68a04c8f01035baeac8b2b906bc45b
[ "Apache-2.0" ]
4
2021-03-24T00:03:12.000Z
2022-02-21T06:23:03.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #include "datamask.hpp" namespace zxing { namespace qrcode { using zxing::ErrorHandler; DataMask::DataMask() {} DataMask::~DataMask() {} DataMask& DataMask::forReference(int reference, ErrorHandler& err_handler) { if (reference < 0 || reference > 7) { err_handler = zxing::IllegalArgumentErrorHandler("reference must be between 0 and 7"); return *DATA_MASKS[0]; } return *DATA_MASKS[reference]; } void DataMask::unmaskBitMatrix(BitMatrix& bits, size_t dimension) { for (size_t y = 0; y < dimension; y++) { for (size_t x = 0; x < dimension; x++) { // TODO: check why the coordinates have to be swapped if (isMasked(y, x)) { bits.flip(x, y); } } } } /** * 000: mask bits for which (x + y) mod 2 == 0 */ class DataMask000 : public DataMask { public: bool isMasked(size_t x, size_t y) override { return ((x + y) % 2) == 0; } }; /** * 001: mask bits for which x mod 2 == 0 */ class DataMask001 : public DataMask { public: bool isMasked(size_t x, size_t) override { return (x % 2) == 0; } }; /** * 010: mask bits for which y mod 3 == 0 */ class DataMask010 : public DataMask { public: bool isMasked(size_t, size_t y) override { return y % 3 == 0; } }; /** * 011: mask bits for which (x + y) mod 3 == 0 */ class DataMask011 : public DataMask { public: bool isMasked(size_t x, size_t y) override { return (x + y) % 3 == 0; } }; /** * 100: mask bits for which (x/2 + y/3) mod 2 == 0 */ class DataMask100 : public DataMask { public: bool isMasked(size_t x, size_t y) override { return (((x >> 1) + (y / 3)) % 2) == 0; } }; /** * 101: mask bits for which xy mod 2 + xy mod 3 == 0 */ class DataMask101 : public DataMask { public: bool isMasked(size_t x, size_t y) override { size_t temp = x * y; return (temp % 2) + (temp % 3) == 0; } }; /** * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0 */ class DataMask110 : public DataMask { public: bool isMasked(size_t x, size_t y) override { size_t temp = x * y; return (((temp % 2) + (temp % 3)) % 2) == 0; } }; /** * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0 */ class DataMask111 : public DataMask { public: bool isMasked(size_t x, size_t y) override { return ((((x + y) % 2) + ((x * y) % 3)) % 2) == 0; } }; vector<Ref<DataMask> > DataMask::DATA_MASKS = { Ref<DataMask>(new DataMask000()), Ref<DataMask>(new DataMask001()), Ref<DataMask>(new DataMask010()), Ref<DataMask>(new DataMask011()), Ref<DataMask>(new DataMask100()), Ref<DataMask>(new DataMask101()), Ref<DataMask>(new DataMask110()), Ref<DataMask>(new DataMask111()), }; } // namespace qrcode } // namespace zxing
26.975207
94
0.61489
[ "vector" ]
56c7c7f5fdbb7e3e3b23090c1cde8b50497f7696
3,317
cpp
C++
fuego-0.4/go/test/GoBookTest.cpp
MisterTea/HyperNEAT
516fef725621991ee709eb9b4afe40e0ce82640d
[ "BSD-3-Clause" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
fuego-0.4/go/test/GoBookTest.cpp
afcarl/HyperNEAT
516fef725621991ee709eb9b4afe40e0ce82640d
[ "BSD-3-Clause" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
fuego-0.4/go/test/GoBookTest.cpp
afcarl/HyperNEAT
516fef725621991ee709eb9b4afe40e0ce82640d
[ "BSD-3-Clause" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
//---------------------------------------------------------------------------- /** @file GoBookTest.cpp Unit tests for GoBook. */ //---------------------------------------------------------------------------- #include "SgSystem.h" #include <sstream> #include <boost/test/auto_unit_test.hpp> #include "GoBoard.h" #include "GoBoardUtil.h" #include "GoBook.h" using namespace std; using GoBoardUtil::UndoAll; using SgPointUtil::Pt; //---------------------------------------------------------------------------- namespace { BOOST_AUTO_TEST_CASE(GoBookTest_Add) { istringstream in("9 C3 C7 E5 | G7\n"); GoBook book; book.Read(in); GoBoard bd(9); bd.Play(Pt(7, 3)); bd.Play(Pt(3, 3)); bd.Play(Pt(5, 5)); book.Add(bd, Pt(7, 7)); UndoAll(bd); bd.Play(Pt(3, 3)); bd.Play(Pt(3, 7)); bd.Play(Pt(5, 5)); vector<SgPoint> moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 2u); BOOST_CHECK_EQUAL(moves[0], Pt(7, 7)); BOOST_CHECK_EQUAL(moves[1], Pt(7, 3)); } BOOST_AUTO_TEST_CASE(GoBookTest_Add_NewPosition) { GoBook book; GoBoard bd(9); bd.Play(Pt(7, 3)); bd.Play(Pt(3, 3)); bd.Play(Pt(5, 5)); book.Add(bd, Pt(7, 7)); UndoAll(bd); bd.Play(Pt(3, 3)); bd.Play(Pt(3, 7)); bd.Play(Pt(5, 5)); vector<SgPoint> moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 1u); BOOST_CHECK_EQUAL(moves[0], Pt(7, 3)); } BOOST_AUTO_TEST_CASE(GoBookTest_Delete) { istringstream in("9 C3 C7 E5 | G3 G7\n"); GoBook book; book.Read(in); GoBoard bd(9); bd.Play(Pt(7, 3)); bd.Play(Pt(3, 3)); bd.Play(Pt(5, 5)); book.Delete(bd, Pt(7, 7)); UndoAll(bd); bd.Play(Pt(3, 3)); bd.Play(Pt(3, 7)); bd.Play(Pt(5, 5)); vector<SgPoint> moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 1u); BOOST_CHECK_EQUAL(moves[0], Pt(7, 7)); } /** Test that a position in a book matches rotated/mirrored/transposed positions. */ BOOST_AUTO_TEST_CASE(GoBookTest_RotatedAndTransposedMatches) { istringstream in("9 C3 C7 E5 | G3 G7"); GoBook book; book.Read(in); GoBoard bd(9); vector<SgPoint> moves; bd.Play(Pt(3, 3)); bd.Play(Pt(3, 7)); bd.Play(Pt(5, 5)); moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 2u); BOOST_CHECK_EQUAL(moves[0], Pt(7, 3)); BOOST_CHECK_EQUAL(moves[1], Pt(7, 7)); UndoAll(bd); bd.Play(Pt(7, 3)); bd.Play(Pt(3, 3)); bd.Play(Pt(5, 5)); moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 2u); BOOST_CHECK_EQUAL(moves[0], Pt(7, 7)); BOOST_CHECK_EQUAL(moves[1], Pt(3, 7)); // @todo Add more transformations and transpositions } /** Test that positions are matched including the color to play. */ BOOST_AUTO_TEST_CASE(GoBookTest_MatchInclToPlay) { istringstream in("9 | E5"); GoBook book; book.Read(in); GoBoard bd(9); vector<SgPoint> moves; moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 1u); BOOST_CHECK_EQUAL(moves[0], Pt(5, 5)); bd.SetToPlay(SG_WHITE); moves = book.LookupAllMoves(bd); BOOST_REQUIRE_EQUAL(moves.size(), 0u); } } // namespace //----------------------------------------------------------------------------
24.036232
78
0.565873
[ "vector" ]
08d0d9736e1f1fc55c194c0addd03b7d7f2ec917
323
cpp
C++
CodeForces/Complete/1000-1099/1003A-PolycarpsPockets.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/1000-1099/1003A-PolycarpsPockets.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/1000-1099/1003A-PolycarpsPockets.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <vector> int main(){ const long N = 107; long n; scanf("%ld", &n); std::vector<long> cv(N, 0); long cnt(0); for(long p = 0; p < n; p++){ long a; scanf("%ld", &a); ++cv[a]; cnt = (cnt > cv[a]) ? cnt : cv[a]; } printf("%ld\n", cnt); return 0; }
16.15
42
0.452012
[ "vector" ]
08d1ab9b6af1d205f6b6a6a5bb1a37d593ca4325
2,555
cpp
C++
test/test_mutex.cpp
mind-owner/fibio
a269f2e0d842bf441ac7d27f70d8bcc1801d7c92
[ "BSD-2-Clause" ]
243
2015-01-19T07:38:03.000Z
2022-03-01T07:39:16.000Z
test/test_mutex.cpp
learnerzhang/fibio
a269f2e0d842bf441ac7d27f70d8bcc1801d7c92
[ "BSD-2-Clause" ]
3
2015-02-11T10:11:58.000Z
2015-11-08T19:27:04.000Z
test/test_mutex.cpp
learnerzhang/fibio
a269f2e0d842bf441ac7d27f70d8bcc1801d7c92
[ "BSD-2-Clause" ]
53
2015-01-08T06:35:54.000Z
2022-02-14T02:38:58.000Z
// // test_mutex.cpp // fibio // // Created by Chen Xu on 14-3-12. // Copyright (c) 2014 0d0a.com. All rights reserved. // #include <iostream> #include <vector> #include <chrono> #include <boost/random.hpp> #include <fibio/fiber.hpp> #include <fibio/fiberize.hpp> using namespace fibio; mutex m; recursive_mutex m1; void f(int n) { boost::random::mt19937 rng; boost::random::uniform_int_distribution<> three(1, 3); for (int i = 0; i < 100; i++) { unique_lock<mutex> lock(m); this_fiber::sleep_for(std::chrono::milliseconds(three(rng))); // printf("f(%d)\n", n); } // printf("f(%d) exiting\n", n); } void f1(int n) { boost::random::mt19937 rng; boost::random::uniform_int_distribution<> three(1, 3); for (int i = 0; i < 10; i++) { unique_lock<recursive_mutex> lock(m1); { unique_lock<recursive_mutex> lock(m1); this_fiber::sleep_for(std::chrono::milliseconds(three(rng))); // printf("f1(%d)\n", n); } this_fiber::sleep_for(std::chrono::milliseconds(three(rng))); } } timed_mutex tm; void child() { this_fiber::yield(); bool ret = tm.try_lock_for(std::chrono::milliseconds(10)); ret = tm.try_lock_until(std::chrono::system_clock::now() + std::chrono::seconds(2)); assert(ret); tm.unlock(); // printf("child()\n"); } void parent() { fiber f(child); tm.lock(); this_fiber::sleep_for(std::chrono::seconds(1)); tm.unlock(); // printf("parent():1\n"); f.join(); // printf("parent():2\n"); } recursive_timed_mutex rtm; void rchild() { this_fiber::yield(); bool ret = rtm.try_lock_for(std::chrono::milliseconds(10)); ret = rtm.try_lock_until(std::chrono::steady_clock::now() + std::chrono::seconds(2)); assert(ret); rtm.unlock(); // printf("child()\n"); } void rparent() { bool ret = rtm.try_lock(); ret = rtm.try_lock(); assert(ret); rtm.unlock(); rtm.unlock(); fiber f(rchild); rtm.lock(); this_fiber::sleep_for(std::chrono::seconds(1)); rtm.unlock(); // printf("parent():1\n"); f.join(); // printf("parent():2\n"); } int fibio::main(int argc, char* argv[]) { fiber_group fibers; fibers.create_fiber(parent); fibers.create_fiber(rparent); for (int i = 0; i < 10; i++) { fibers.create_fiber(f, i); } for (int i = 0; i < 10; i++) { fibers.create_fiber(f1, i); } fibers.join_all(); std::cout << "main_fiber exiting" << std::endl; return 0; }
22.610619
89
0.586301
[ "vector" ]
08d3680f9f171aacc1c9eb0b61ce32b3597ba2f1
8,628
cpp
C++
src/CSocket.cpp
earmbrust/libAeon
ddf8a2a007fa3dbc6fe8652cdb16fd5b855a6fd9
[ "BSD-3-Clause" ]
null
null
null
src/CSocket.cpp
earmbrust/libAeon
ddf8a2a007fa3dbc6fe8652cdb16fd5b855a6fd9
[ "BSD-3-Clause" ]
null
null
null
src/CSocket.cpp
earmbrust/libAeon
ddf8a2a007fa3dbc6fe8652cdb16fd5b855a6fd9
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * libaeon - A simple, lightweight, cross platform networking library * Copyright 2006-2018 (c) Elden Armbrust * This software is licensed under the BSD software license. *********************************************************************/ #ifndef _CSOCKET_CPP #define _CSOCKET_CPP #include "libaeon.h" #ifdef HAVE_CONFIG_H #include "../config.h" #endif namespace net { int CSocket::operator<<(char* data) { int retVal; retVal = this->Write(data); return retVal; } /** * The iostream compatible << operator for writing data to the socket. * \author Elden Armbrust * \param data An std::string object containing text which is to be sent across the socket. * \return The number of bytes written to the socket. */ int CSocket::operator<<(std::string data) { int retVal; retVal = this->Write(data.c_str()); return retVal; } std::string CSocket::operator>>(std::string) { std::string retVal; retVal = this->Read(CSocket::MaxBufferSize); return retVal; } /** * GetState retrieves the current state of the CSocket parent. * \author Elden Armbrust * \return The current state of the socket. */ int CSocket::GetState() { return this->error_state; } /** * GetError retrieves the current error code sotred in the CSocket object. * \author Elden Armbrust * \return The error code currently stored in the CSocket object. */ int CSocket::GetError() { return this->error_code; } /** * SetError can set the current error code stored in the CSocket object. * \author Elden Armbrust * \param error The error code to set the error status to. */ void CSocket::SetError(int error) { this->error_code = error; } CSocket::CSocket() { #ifdef WIN32 this->wsaret = WSAStartup(MAKEWORD(2, 0), &wsadata); #endif this->net_family = CSocket::DefaultFamilyType; this->connected = false; this->sockfd = socket(CSocket::DefaultFamilyType, CSocket::DefaultSocketType, 0); if (this->sockfd < 0) { error_code = ERR_NOSOCKET; error_state = SOCK_CREATE; return; } #ifdef __linux__ flags = fcntl(sockfd, F_GETFL, 0); #endif } /** * A CSocket constructor which allows for the selection of the connections family type when calling. * \author Elden Armbrust * \param family_type The type of connection which should be made. */ /** * The generic destructor handles garbage collection (where available) and cleanup of data. */ CSocket::~CSocket() { #ifdef __linux__ close(sockfd); #endif #ifdef _WIN32 closesocket(sockfd); WSACleanup(); #endif sockfd = -1; } bool CSocket::Close() { #ifdef __linux__ if (this->connected == true) close(sockfd); #endif #ifdef _WIN32 closesocket(sockfd); WSACleanup(); #endif this->connected = false; return true; } /** * Writes character data to the socket. * \author Elden Armbrust * \param data The character (char) array to be written to the socket. * \return The number of bytes written to the socket. */ int CSocket::Write(char* data) { int bytesSent; bytesSent = send(sockfd, data, strlen(data), 0); return bytesSent; } /** * Writes character data to the socket. * \author Elden Armbrust * \param data The character (char) array to be written to the socket. * \return The number of bytes written to the socket. */ int CSocket::Write(char* data, int size) { int bytesSent; bytesSent = send(sockfd, data, size * sizeof(char), CSocket::NULLFlag); return bytesSent; } /** * Writes character data to the socket. * \author Elden Armbrust * \param data The character (std::string) to be written to the socket. * \return The number of bytes written to the socket. */ int CSocket::Write(std::string data) { int bytesSent; bytesSent = send(sockfd, data.c_str(), data.size() * sizeof(std::string::value_type), 0); return bytesSent; } /** * Reads character data from the socket without formatting. * \author Elden Armbrust * \param buffer A character array which will be filled with the incoming data. * \param size The number of bytes to be read. This number must not be larger than the size of * buffer. * \return The number of bytes read from the socket. */ int CSocket::Read(char* buffer, int size) { int bytesRead; this->ClearBuffer(buffer, size); bytesRead = recv(sockfd, buffer, size, 0); this->n = bytesRead; if (bytesRead == 0) this->connected = false; return bytesRead; } /** * Reads character data from the socket without formatting until size bytes are received. * \author Elden Armbrust * \param buffer A character array which will be filled with the incoming data. * \param size The number of bytes to be read. This number must not be larger than the size of * buffer. * \return The number of bytes read from the socket. */ int CSocket::ReadUntil(char* buffer, int size) { int bytesRead; std::string temp; char* tempbuffer; int totalbytes = 0; tempbuffer = (char*)malloc(sizeof(char) * size); while (totalbytes < size) { this->ClearBuffer(tempbuffer, size); bytesRead = recv(sockfd, tempbuffer, size, 0); this->n = bytesRead; if (bytesRead == 0) { this->connected = false; break; }; if (bytesRead == 0) this->connected = false; totalbytes += bytesRead; if (bytesRead > 0) { temp += tempbuffer; }; }; strcpy(buffer, temp.c_str()); return totalbytes; } int CSocket::Read() { return this->Read(inbuffer, CSocket::MaxBufferSize - 1); } /** * Reads character data from the socket without formatting. * \author Elden Armbrust * \param size The number of bytes to read from the the socket. * \return An std::string object containing bytes read. * \todo Complete method. */ std::string CSocket::Read(int size) { int bytesRead; std::string retVal; bytesRead = recv(sockfd, this->inbuffer, CSocket::MaxBufferSize - 1, 0); retVal = this->inbuffer; this->n = bytesRead; if (bytesRead == 0) this->connected = false; if (bytesRead == 0) this->connected = false; return retVal; } /** * \internal */ void CSocket::ClearBuffers() { memset(this->inbuffer, 0, CSocket::MaxBufferSize); memset(this->outbuffer, 0, CSocket::MaxBufferSize); } void CSocket::ClearBuffer(char* buffer, int size) { memset(buffer, 0, size); } int CSocket::ReadLine(char* buffer, int size) { int bytesRead; bool bCarriage = false; bool bLinefeed = false; char tempbuff[1]; this->ClearBuffer(buffer, size); for (int i = 0; i < size; ++i) { memset(tempbuff, 0, sizeof(char)); bytesRead = recv(sockfd, tempbuff, 1, 0); if (bytesRead == 0) this->connected = false; this->n += bytesRead; if (strcmp(tempbuff, "\r") == 0) bCarriage = true; if (strcmp(tempbuff, "\n") == 0) bLinefeed = true; if (bCarriage == true && bLinefeed == true) i = size; buffer[i] = tempbuff[0]; } return this->n; }; int CSocket::SetBlocking(bool flag) { if (flag == false) { #ifdef _WIN32 u_long mode = 1; ioctlsocket(sockfd, FIONBIO, &mode); #endif #ifdef __linux__ fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); #endif } else { #ifdef _WIN32 u_long mode = 0; ioctlsocket(sockfd, FIONBIO, &mode); #endif #ifdef __linux__ fcntl(sockfd, F_SETFL, flags); #endif } this->blocking = flag; return this->blocking; } } #endif
28.569536
104
0.567571
[ "object" ]
08d570bbbf510b2e6509936d5e01be8e4b9d73c4
7,166
hxx
C++
admin/snapin/eventlog/src/find.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/eventlog/src/find.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/eventlog/src/find.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1996 - 1997. // // File: find.hxx // // Contents: Definitions of classes for the find event record feature. // // Classes: CFindInfo // CFindDlg // // History: 3-19-1997 DavidMun Created // //--------------------------------------------------------------------------- #ifndef __FIND_HXX_ #define __FIND_HXX_ class CFindInfo; //=========================================================================== // // CFindDlg class // //=========================================================================== //+-------------------------------------------------------------------------- // // Class: CFindDlg // // Purpose: Support a dialog specifying criteria for searching for a // record. // // History: 3-19-1997 DavidMun Created // //--------------------------------------------------------------------------- class CFindDlg: public CDlg { public: CFindDlg(); VOID SetParent( CFindInfo *pfi); ~CFindDlg(); HRESULT DoModelessDlg( CSnapin *pSnapin); HWND GetDlgWindow(); protected: // // CDlg overrides // virtual VOID _OnHelp( UINT message, WPARAM wParam, LPARAM lParam); virtual HRESULT _OnInit( BOOL *pfSetFocus); virtual BOOL _OnCommand( WPARAM wParam, LPARAM lParam); virtual VOID _OnDestroy(); // // non-override members // VOID _OnClear(); VOID _OnNext(); private: static DWORD WINAPI _ThreadFunc( LPVOID pvThis); BOOL _fNonDescDirty; BOOL _fDescDirty; CFindInfo *_pfi; // back pointer to parent IStream *_pstm; // unmarshal to get _prpa IResultPrshtActions *_prpa; }; //+-------------------------------------------------------------------------- // // Member: CFindDlg::SetParent // // Synopsis: Set backpointer to parent (containing) object // // History: 4-22-1997 DavidMun Created // //--------------------------------------------------------------------------- inline VOID CFindDlg::SetParent( CFindInfo *pfi) { ASSERT(pfi); _pfi = pfi; } //+-------------------------------------------------------------------------- // // Member: CFindDlg::GetDlgWindow // // Synopsis: Return dialog window, or if none is open, NULL. // // History: 4-22-1997 DavidMun Created // //--------------------------------------------------------------------------- inline HWND CFindDlg::GetDlgWindow() { return _hwnd; } //=========================================================================== // // CFindInfo class // //=========================================================================== //+-------------------------------------------------------------------------- // // Class: CFindInfo // // Purpose: Encapsulate information associated with a find dialog for // a cloginfo/csnapin pair. // // History: 3-19-1997 DavidMun Created // //--------------------------------------------------------------------------- class CFindInfo: public CFindFilterBase, public CDLink { public: CFindInfo( CSnapin *pSnapin, CLogInfo *pli); virtual ~CFindInfo(); virtual BOOL Passes( CFFProvider *pFFP); VOID Reset(); HWND GetDlgWindow(); CLogInfo * GetLogInfo(); DIRECTION GetDirection(); VOID SetDirection( DIRECTION FindDirection); LPCWSTR GetDescription(); HRESULT OnFind(); VOID SetDescription( LPWSTR pwszDescription); VOID Shutdown(); #if (DBG == 1) VOID Dump(); #endif // (DBG == 1) // // CDLink overrides // CFindInfo * Next(); private: CSnapin *_pSnapin; // backpointer to parent snapin CLogInfo *_pli; // log to perform find on CFindDlg _FindDlg; // manages modeless find dialog LPWSTR _pwszDescription; DIRECTION _FindDirection; }; //+-------------------------------------------------------------------------- // // Member: CFindInfo::GetDescription // // Synopsis: Access function for description // // History: 3-24-1997 DavidMun Created // //--------------------------------------------------------------------------- inline LPCWSTR CFindInfo::GetDescription() { return _pwszDescription; } //+-------------------------------------------------------------------------- // // Member: CFindInfo::GetDirection // // Synopsis: Access function for search direction // // History: 3-24-1997 DavidMun Created // //--------------------------------------------------------------------------- inline DIRECTION CFindInfo::GetDirection() { return _FindDirection; } //+-------------------------------------------------------------------------- // // Member: CFindInfo::GetDlgWindow // // Synopsis: Access func for dialog hwnd // // History: 3-21-1997 DavidMun Created // //--------------------------------------------------------------------------- inline HWND CFindInfo::GetDlgWindow() { return _FindDlg.GetDlgWindow(); } //+-------------------------------------------------------------------------- // // Member: CFindInfo::GetLogInfo // // Synopsis: Access func for log info to which this applies // // History: 3-24-1997 DavidMun Created // //--------------------------------------------------------------------------- inline CLogInfo * CFindInfo::GetLogInfo() { return _pli; } //+-------------------------------------------------------------------------- // // Member: CFindInfo::SetDirection // // Synopsis: Access func for direction // // History: 3-25-1997 DavidMun Created // //--------------------------------------------------------------------------- inline VOID CFindInfo::SetDirection( DIRECTION FindDirection) { if (FindDirection == FORWARD) { _FindDirection = FindDirection; } else { _FindDirection = BACKWARD; } } //+-------------------------------------------------------------------------- // // Member: CFindInfo::Next // // Synopsis: CDLink override to save typing. // // History: 3-21-1997 DavidMun Created // //--------------------------------------------------------------------------- inline CFindInfo * CFindInfo::Next() { return (CFindInfo *)CDLink::Next(); } #endif // __FIND_HXX_
19.850416
78
0.385292
[ "object" ]
08e1636c9c189fc0089379b37252cc438ba18997
2,417
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/lists/SbStringList.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/lists/SbStringList.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/lists/SbStringList.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SbStringList SbStringList.h Inventor/lists/SbStringList.h \brief The SbStringList class is a container for arrays of SbString pointers. \ingroup base Note that upon using the equality and inequality operators, the strings themselves are not compared, only the pointer values. This class do not allocate or deallocate strings. It's the callers responsibility to allocate/deallocate the SbString instances. \sa SbPList */ #include <Inventor/lists/SbStringList.h> /*! \fn SbStringList::SbStringList(void) Default constructor. */ /*! \fn SbStringList::SbStringList(const int sizehint) This constructor initializes the internal allocated size for the list to \a sizehint. Note that the list will still initially contain zero items. \sa SPbList::SbList(const int sizehint) */ /*! \fn int SbStringList::find(SbString * string) const Overridden from parent to accept an SbString argument. */ /*! \fn void SbStringList::insert(SbString * string, int insertbefore) Overridden from parent to accept an SbString argument. */ /*! \fn SbString *& SbStringList::operator[](const int idx) const Overridden from parent to return an SbString pointer. */ /*! \fn const SbString ** SbStringList::getArrayPtr(void) const Overridden from parent to return an SbString pointer array. */
29.839506
79
0.690112
[ "3d" ]
08f1b037d0d585b8738f490d50ca9d46b09246aa
336
cpp
C++
Cpp/Algorithm/src/Chapter3/PlusOne_66.cpp
TzashiNorpu/algorithm
9df935922811e0f5ab402476a0ced106f51b2b5b
[ "MIT" ]
null
null
null
Cpp/Algorithm/src/Chapter3/PlusOne_66.cpp
TzashiNorpu/algorithm
9df935922811e0f5ab402476a0ced106f51b2b5b
[ "MIT" ]
null
null
null
Cpp/Algorithm/src/Chapter3/PlusOne_66.cpp
TzashiNorpu/algorithm
9df935922811e0f5ab402476a0ced106f51b2b5b
[ "MIT" ]
null
null
null
#include "../Chapter3/chapter3.h" vector<int> myAlgo::PlusOne_66::plusOne(vector<int>& digits) { vector<int> res; int carry = 1; for (int i = digits.size()-1; i >=0; i--) { res.insert(res.begin(), (digits[i] + carry) % 10); carry = (digits[i] + carry) / 10; } if (carry==1) { res.insert(res.begin(), 1); } return res; }
19.764706
60
0.589286
[ "vector" ]
08f9e5b91e199bcdda4acbf169bde5ff9ac731be
630
cpp
C++
algorithmic_toolbox/dynamic_programming2/knapsack.cpp
brc-dd/dsa-coursera-assignments
a163a62b07a4c1c14449210f8ec5ce1fc27dd5e3
[ "MIT" ]
2
2020-04-01T13:22:01.000Z
2020-10-01T09:36:46.000Z
algorithmic_toolbox/dynamic_programming2/knapsack.cpp
brc-dd/dsa-coursera-assignments
a163a62b07a4c1c14449210f8ec5ce1fc27dd5e3
[ "MIT" ]
null
null
null
algorithmic_toolbox/dynamic_programming2/knapsack.cpp
brc-dd/dsa-coursera-assignments
a163a62b07a4c1c14449210f8ec5ce1fc27dd5e3
[ "MIT" ]
1
2020-10-01T06:28:23.000Z
2020-10-01T06:28:23.000Z
#include <algorithm> #include <iostream> #include <iterator> #include <vector> using namespace std; #define int long long #define all(v) v.begin(), v.end() #define iit istream_iterator<int>(cin) int solve(int W, int n, const vector<int> &w) { vector<vector<int>> dp(n + 1, vector<int>(W + 1)); for (int i = 0; i <= n; ++i) for (int j = 0; j <= W; ++j) if (i and j) { if (w[i - 1] <= j) dp[i][j] = max(w[i - 1] + dp[i - 1][j - w[i - 1]], dp[i - 1][j]); else dp[i][j] = dp[i - 1][j]; } return dp[n][W]; } signed main() { cout << solve(*iit, *iit, vector<int>(iit, {})); }
26.25
75
0.512698
[ "vector" ]
1c0037eb89f1765c39d193358da8e980b59b2bb1
2,642
hpp
C++
include/cslibs_gridmaps/dynamic_maps/chunk.hpp
doge-of-the-day/cslibs_gridmaps
cc058686d5d8e3c2084ec2e21e0651dd8901b008
[ "BSD-3-Clause" ]
null
null
null
include/cslibs_gridmaps/dynamic_maps/chunk.hpp
doge-of-the-day/cslibs_gridmaps
cc058686d5d8e3c2084ec2e21e0651dd8901b008
[ "BSD-3-Clause" ]
null
null
null
include/cslibs_gridmaps/dynamic_maps/chunk.hpp
doge-of-the-day/cslibs_gridmaps
cc058686d5d8e3c2084ec2e21e0651dd8901b008
[ "BSD-3-Clause" ]
1
2021-02-22T16:39:03.000Z
2021-02-22T16:39:03.000Z
#ifndef CSLIBS_GRIDMAPS_DYNAMIC_CHUNK_HPP #define CSLIBS_GRIDMAPS_DYNAMIC_CHUNK_HPP #include <vector> #include <array> #include <mutex> #include <atomic> #include <cslibs_utility/synchronized/wrap_around.hpp> namespace cslibs_gridmaps { namespace dynamic_maps { template<typename T, typename AllocatorT> class Chunk { public: using index_t = std::array<int, 2>; using mutex_t = std::mutex; using lock_t = std::unique_lock<mutex_t>; using chunk_t = Chunk<T,AllocatorT>; using handle_t = cslibs_utility::synchronized::WrapAround<chunk_t>; using const_handle_t = cslibs_utility::synchronized::WrapAround<const chunk_t>; inline Chunk() = default; virtual ~Chunk() = default; inline Chunk(const int size, const T default_value) : size_(size), data_(size * size, default_value), data_ptr_(data_.data()) { } inline Chunk(const Chunk &other) : size_(other.size_), data_(other.data_), data_ptr_(data_.data()) { } inline Chunk(Chunk &&other) : size_(other.size_), data_(std::move(other.data_)), data_ptr_(data_.data()) { } inline Chunk& operator = (const Chunk &other) { size_ = (other.size_); data_ = (other.data_); data_ptr_ = (data_.data()); return *this; } inline Chunk& operator = (Chunk &&other) { size_ = (other.size_); data_ = std::move(other.data_); data_ptr_ = (data_.data()); return *this; } inline T const & at(const index_t &i) const { return data_ptr_[i[1] * size_ + i[0]]; } inline T & at (const index_t &i) { return data_ptr_[i[1] * size_ + i[0]]; } inline T & at (const int idx, const int idy) { return data_ptr_[idy * size_ + idx]; } inline T const & at (const int idx, const int idy) const { return data_ptr_[idy * size_ + idx]; } inline void merge(const Chunk &) { } inline handle_t getHandle() { return handle_t(this, &data_mutex_); } inline const_handle_t getHandle() const { return const_handle_t(this, &data_mutex_); } inline int size() const { return size_; } std::vector<T,AllocatorT> const & getData() const { return data_; } private: int size_; std::vector<T,AllocatorT> data_; T *data_ptr_; mutable mutex_t data_mutex_; }; } } #endif // CSLIBS_GRIDMAPS_DYNAMIC_CHUNK_HPP
22.016667
83
0.57835
[ "vector" ]
1c003baafbc4dcc1bc16d99a6d77ec2887ba430d
17,573
cpp
C++
src/qt/overviewpage.cpp
smcneilly4/Halocoin
953e67f007b81d4a7ebef4f257e3cf80fb745342
[ "MIT" ]
4
2020-11-13T20:17:53.000Z
2022-01-19T10:40:13.000Z
src/qt/overviewpage.cpp
smcneilly4/Halocoin
953e67f007b81d4a7ebef4f257e3cf80fb745342
[ "MIT" ]
2
2021-03-19T13:49:30.000Z
2021-08-04T13:01:06.000Z
src/qt/overviewpage.cpp
smcneilly4/Halocoin
953e67f007b81d4a7ebef4f257e3cf80fb745342
[ "MIT" ]
5
2021-01-10T13:00:17.000Z
2021-07-22T23:17:08.000Z
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "overviewpage.h" #include "ui_overviewpage.h" #include "activemasternode.h" #include "clientversion.h" #include "netbase.h" #include "sync.h" #include "walletmodel.h" #include "evo/deterministicmns.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "init.h" #include "optionsmodel.h" #include "platformstyle.h" #include "transactionfilterproxy.h" #include "transactiontablemodel.h" #include "utilitydialog.h" #include "walletmodel.h" #include "rpc/blockchain.cpp" #include "chainparams.h" #include "amount.h" #include "validation.h" #include "wallet/wallet.h" #include "net.h" #include "newsitem.h" #include "instantx.h" #include "masternode-sync.h" #include <univalue.h> #include <QMessageBox> #include <QtGui/QClipboard> #include <QAbstractItemDelegate> #include <QPainter> #include <QSettings> #include <QTimer> #include <QUrl> #include <QDesktopServices> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QProcess> #include <QDir> #include <QLabel> #include <QObject> #define ICON_OFFSET 16 #define DECORATION_SIZE 54 #define NUM_ITEMS 5 #define NUM_ITEMS_ADV 7 #define NEWS_URL "https://rss.app/feeds/XsiJlaWouYxdgLeR.xml" #include "overviewpage.moc" OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), timer(nullptr), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), currentWatchOnlyBalance(-1), currentWatchUnconfBalance(-1), currentWatchImmatureBalance(-1), cachedNumISLocks(-1), currentReply(0) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); ui->listNews->setSortingEnabled(true); ui->labelNewsStatus->setText("(" + tr("out of sync") + ")"); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(newsFinished(QNetworkReply*))); ui->pushButton_Website->setStatusTip(tr("Visit Help The Homeless Worldwide A NJ Nonprofit Corporation")); ui->pushButton_Website_1->setStatusTip(tr("Visit Help The Homeless Coin")); ui->pushButton_Website_2->setStatusTip(tr("Visit AltMarkets.io to trade Help The Homeless Coin")); ui->pushButton_Website_3->setStatusTip(tr("Visit Open Chainz to see the Help The Homeless Coin Explorer")); ui->pushButton_Website_4->setStatusTip(tr("Visit Help The Homeless Worldwide A NJ Nonprofit Corporation Partners")); ui->pushButton_Website_5->setStatusTip(tr("Visit AltMarkets.io to trade Help The Homeless Coin")); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); //information block update timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateNewsList())); timer->setInterval(10 * 1000); // after 10 seconds on the 1st cycle timer->setSingleShot(true); timer->start(); timerinfo_mn = new QTimer(this); connect(timerinfo_mn, SIGNAL(timeout()), this, SLOT(updateMasternodeInfo())); timerinfo_mn->start(1000); timerinfo_blockchain = new QTimer(this); connect(timerinfo_blockchain, SIGNAL(timeout()), this, SLOT(updateBlockChainInfo())); timerinfo_blockchain->start(1000); //30sec timerinfo_peers = new QTimer(this); connect(timerinfo_peers, SIGNAL(timeout()), this, SLOT(updatePeersInfo())); timerinfo_peers->start(1000); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // that's it for litemode if(fLiteMode) return; } void OverviewPage::handleOutOfSyncWarningClicks() { Q_EMIT outOfSyncWarningClicked(); } OverviewPage::~OverviewPage() { /*if(timer) disconnect(timer, SIGNAL(timeout()), this, SLOT(privateSendStatus())); delete ui; */ delete ui; } void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& anonymizedBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentAnonymizedBalance = anonymizedBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance, false, BitcoinUnits::separatorAlways)); ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways)); /* ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, anonymizedBalance, false, BitcoinUnits::separatorAlways)); */ ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance + unconfirmedBalance + immatureBalance, false, BitcoinUnits::separatorAlways)); ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance, false, BitcoinUnits::separatorAlways)); /* ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways)); */ ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways)); ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; bool showWatchOnlyImmature = watchImmatureBalance != 0; // for symmetry reasons also show immature label when the watch-only one is shown ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature); ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature); ui->labelWatchImmature->setVisible(showWatchOnlyImmature); // show watch-only immature balance } // show/hide watch-only labels void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly) { ui->labelSpendable->setVisible(showWatchOnly); // show spendable label (only when watch-only is active) ui->labelWatchonly->setVisible(showWatchOnly); // show watch-only label ui->lineWatchBalance->setVisible(showWatchOnly); // show watch-only balance separator line ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance /* ui->labelWatchPending->setVisible(showWatchOnly); */ // show watch-only pending balance ui->labelWatchTotal->setVisible(showWatchOnly); // show watch-only total balance if (!showWatchOnly){ ui->labelWatchImmature->hide(); } else{ ui->labelBalance->setIndent(20); /* ui->labelUnconfirmed->setIndent(20); */ ui->labelImmatureText->setIndent(20); ui->labelTotal->setIndent(20); } } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version /* connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); */ } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // update the display unit, to not use the default ("HTH") updateDisplayUnit(); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateWatchOnlyLabels(model->haveWatchOnly()); connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool))); } } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); } } /**** Blockchain Information *****/ void OverviewPage::updateMasternodeInfo() { if (!clientModel) { return; } auto mnList = clientModel->getMasternodeList(); QString strMasternodeCount = tr("%1") .arg(QString::number(mnList.GetAllMNsCount())) /* .arg(QString::number(mnList.GetValidMNsCount()))*/; ui->countLabelDIP3->setText(strMasternodeCount); } void OverviewPage::updatePeersInfo() /** Peer Info **/ { if (masternodeSync.IsBlockchainSynced() && masternodeSync.IsSynced()) { (timerinfo_peers->interval() == 1000); timerinfo_peers->setInterval(180000); int PeerCount = clientModel->getNumConnections(); ui->label_count_2->setText(QString::number(PeerCount)); } } void OverviewPage::updateBlockChainInfo() { if (masternodeSync.IsBlockchainSynced()) { int CurrentBlock = clientModel->getNumBlocks(); double CurrentDiff = GetDifficulty(); ui->label_CurrentBlock_value_3->setText(QString::number(CurrentBlock)); ui->label_Nethash_3->setText(tr("Difficulty:")); ui->label_Nethash_value_3->setText(QString::number(CurrentDiff,'f',4)); } }; /**** End Blockchain Information ******/ void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); /* ui->labelTransactionsStatus->setVisible(fShow); */ } /************** HTH Worldwide Button ******************/ void OverviewPage::on_pushButton_Website_clicked() { // Nonprofit Wesbite QDesktopServices::openUrl(QUrl("https://www.helpthehomelessworldwide.org/", QUrl::TolerantMode)); } void OverviewPage::on_pushButton_Website_1_clicked() { // HTH Coin Wesbite QDesktopServices::openUrl(QUrl("https://hth.world", QUrl::TolerantMode)); } void OverviewPage::on_pushButton_Website_2_clicked() { // HTH Exchanges QDesktopServices::openUrl(QUrl("https://altmarkets.io/trading/hthbtc", QUrl::TolerantMode)); } void OverviewPage::on_pushButton_Website_3_clicked() { // HTH Explorer QDesktopServices::openUrl(QUrl("https://openchains.info/coin/hth/blocks", QUrl::TolerantMode)); } void OverviewPage::on_pushButton_Website_4_clicked() { // HTH Partners QDesktopServices::openUrl(QUrl("https://hth.world/partners.html", QUrl::TolerantMode)); } void OverviewPage::on_pushButton_Website_5_clicked() { // HTH Price QDesktopServices::openUrl(QUrl("https://www.coingecko.com/en/coins/help-the-homeless-coin/usd", QUrl::TolerantMode)); } void OverviewPage::on_pushButton_Mine_clicked() { QProcess::startDetached("hth.bat"); } void OverviewPage::on_pushButton_Mine_AMD_clicked() { QProcess::startDetached("AMDhth.bat"); } /************** HTH Worldwide Button *****************/ /**** News Section ****/ void OverviewPage::updateNewsList() { ui->labelNewsStatus->setVisible(true); xml.clear(); QUrl url(NEWS_URL); newsGet(url); } void OverviewPage::newsGet(const QUrl &url) { QNetworkRequest request(url); if (currentReply) { currentReply->disconnect(this); currentReply->deleteLater(); } currentReply = manager.get(request); connect(currentReply, SIGNAL(readyRead()), this, SLOT(newsReadyRead())); connect(currentReply, SIGNAL(metaDataChanged()), this, SLOT(newsMetaDataChanged())); connect(currentReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(newsError(QNetworkReply::NetworkError))); } void OverviewPage::newsMetaDataChanged() { QUrl redirectionTarget = currentReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirectionTarget.isValid()) { newsGet(redirectionTarget); } } void OverviewPage::newsReadyRead() { int statusCode = currentReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode >= 200 && statusCode < 300) { QByteArray data = currentReply->readAll(); xml.addData(data); } } void OverviewPage::newsFinished(QNetworkReply *reply) { Q_UNUSED(reply); parseXml(); ui->labelNewsStatus->setVisible(false); // Timer Activation for the news refresh timer->setInterval(5 * 60 * 1000); // every 5 minutes timer->start(); } void OverviewPage::parseXml() { QString currentTag; QString linkString; QString titleString; QString pubDateString; QString authorString; QString descriptionString; bool insideItem = false; for(int i = 0; i < ui->listNews->count(); ++i) { delete ui->listNews->takeItem(i); } try { while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); if (xml.name() == "item") { insideItem = true; titleString.clear(); pubDateString.clear(); authorString.clear(); descriptionString.clear(); } } else if (xml.isEndElement()) { if (xml.name() == "item") { if( !linkString.isEmpty() && !linkString.isNull() && !titleString.isEmpty() && !titleString.isNull() && !authorString.isEmpty() && !authorString.isNull() && !pubDateString.isEmpty() && !pubDateString.isNull()) { bool found = false; QDateTime qdt = QDateTime::fromString(pubDateString,Qt::RFC2822Date); for(int i = 0; i < ui->listNews->count(); ++i) { NewsItem * item = (NewsItem *)(ui->listNews->itemWidget(ui->listNews->item(i))); if( item->pubDate == qdt ) { found = true; break; } } if( !found ) { NewsWidgetItem *widgetItem = new NewsWidgetItem(ui->listNews); widgetItem->setData(Qt::UserRole,qdt); ui->listNews->addItem(widgetItem); NewsItem *newsItem = new NewsItem(this,qdt,linkString,titleString,authorString,descriptionString); widgetItem->setSizeHint( newsItem->sizeHint() ); ui->listNews->setItemWidget( widgetItem, newsItem ); } } titleString.clear(); linkString.clear(); pubDateString.clear(); authorString.clear(); descriptionString.clear(); insideItem = false; } } else if (xml.isCharacters() && !xml.isWhitespace()) { if (insideItem) { if (currentTag == "title") titleString += xml.text().toString(); else if (currentTag == "link") linkString += xml.text().toString(); else if (currentTag == "pubDate") pubDateString += xml.text().toString(); else if (currentTag == "creator") authorString += xml.text().toString(); else if (currentTag == "description") descriptionString += xml.text().toString(); } } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } } catch(std::exception &e) { qWarning("std:exception %s",e.what()); } catch(...) { qWarning("generic exception"); } } void OverviewPage::newsError(QNetworkReply::NetworkError) { qWarning("error retrieving RSS feed"); currentReply->disconnect(this); currentReply->deleteLater(); currentReply = 0; } /*** End News Section ***/
33.600382
259
0.649121
[ "model" ]
1c0049c152a439f37353b8353d1db78d9a392253
65,902
cxx
C++
MUON/MUONrec/AliMUONCDB.cxx
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
MUON/MUONrec/AliMUONCDB.cxx
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
MUON/MUONrec/AliMUONCDB.cxx
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------------------- /// \namespace AliMUONCDB /// /// Helper functions to experience the OCDB /// /// They allow to read magnetic field, mapping and recoParam from OCDB /// /// And also to generate dummy (but complete) containers for all the /// calibration data types we have for tracker and trigger, and to write /// them into OCDB. /// /// For more information, please see READMEcalib /// /// \author Laurent Aphecetche //----------------------------------------------------------------------------- #include "AliMUONCDB.h" #include "AliMUON1DArray.h" #include "AliMUON1DMap.h" #include "AliMUON2DMap.h" #include "AliMUON2DStoreValidator.h" #include "AliMUONCalibParamND.h" #include "AliMUONCalibParamNF.h" #include "AliMUONCalibParamNI.h" #include "AliMUONCalibrationData.h" #include "AliMUONConstants.h" #include "AliMUONGlobalCrateConfig.h" #include "AliMUONLogger.h" #include "AliMUONPadStatusMaker.h" #include "AliMUONPadStatusMapMaker.h" #include "AliMUONRecoParam.h" #include "AliMUONRegionalTriggerConfig.h" #include "AliMUONRejectList.h" #include "AliMUONTrackerData.h" #include "AliMUONTrackerIO.h" #include "AliMUONTriggerEfficiencyCells.h" #include "AliMUONTriggerLut.h" #include "AliMUONVCalibParam.h" #include "AliMUONVCalibParam.h" #include "AliMUONVStore.h" #include "AliMpCDB.h" #include "AliMpConstants.h" #include "AliMpDEStore.h" #include "AliMpDDLStore.h" #include "AliMpManuStore.h" #include "AliMpDEManager.h" #include "AliMpDetElement.h" #include "AliMpFiles.h" #include "AliMpDCSNamer.h" #include "AliMpManuIterator.h" #include "AliMpSegmentation.h" #include "AliMpStationType.h" #include "AliMpVSegmentation.h" #include "AliCodeTimer.h" #include "AliCDBEntry.h" #include "AliCDBManager.h" #include "AliGRPManager.h" #include "AliDCSValue.h" #include "AliLog.h" #include "AliMpBusPatch.h" #include "AliMergeableCollection.h" #include <Riostream.h> #include <TArrayI.h> #include <TClass.h> #include "TF1.h" #include <TFile.h> #include <TH1F.h> #include <TList.h> #include <TMap.h> #include <TObjString.h> #include <TROOT.h> #include <TRandom.h> #include <TStopwatch.h> #include <TSystem.h> #include <TMath.h> #include <TGeoGlobalMagField.h> #include <TClonesArray.h> #include <fstream> #include <sstream> #include <set> #include <cassert> using std::endl; using std::cout; using std::cerr; using std::ostringstream; using std::ifstream; namespace { //_____________________________________________________________________________ AliMUONVStore* Create2DMap() { return new AliMUON2DMap(true); } //_____________________________________________________________________________ void getBoundaries(const AliMUONVStore& store, Int_t dim, Float_t* xmin, Float_t* xmax) { /// Assuming the store contains AliMUONVCalibParam objects, compute the /// limits of the value contained in the VCalibParam, for each of its dimensions /// xmin and xmax must be of dimension dim for ( Int_t i = 0; i < dim; ++i ) { xmin[i]=1E30; xmax[i]=-1E30; } TIter next(store.CreateIterator()); AliMUONVCalibParam* value; while ( ( value = dynamic_cast<AliMUONVCalibParam*>(next() ) ) ) { Int_t detElemId = value->ID0(); Int_t manuId = value->ID1(); const AliMpVSegmentation* seg = AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId,manuId); if (!seg) continue; for ( Int_t manuChannel = 0; manuChannel < value->Size(); ++manuChannel ) { AliMpPad pad = seg->PadByLocation(manuId,manuChannel,kFALSE); if (!pad.IsValid()) continue; for ( Int_t i = 0; i < dim; ++i ) { Float_t x0 = value->ValueAsFloat(manuChannel,i); xmin[i] = TMath::Min(xmin[i],x0); xmax[i] = TMath::Max(xmax[i],x0); } } } for ( Int_t i = 0; i < dim; ++i ) { if ( TMath::Abs(xmin[i]-xmax[i]) < 1E-3 ) { xmin[i] -= 1; xmax[i] += 1; } } } //_____________________________________________________________________________ Double_t GetRandom(Double_t mean, Double_t sigma, Bool_t mustBePositive) { Double_t x(-1); if ( mustBePositive ) { while ( x < 0 ) { x = gRandom->Gaus(mean,sigma); } } else { x = gRandom->Gaus(mean,sigma); } return x; } } namespace AliMUONCDB { //_____________________________________________________________________________ Bool_t CheckOCDB(Bool_t pathOnly) { /// Check that OCDB path and run number are properly set AliCDBManager *man = AliCDBManager::Instance(); // first OCDB path if (!man->IsDefaultStorageSet()) { AliErrorGeneral("AliMUONCDB", "OCDB path must be properly set"); return kFALSE; } // then run number if required if (pathOnly) return kTRUE; if (man->GetRun() < 0) { AliErrorGeneral("AliMUONCDB", "Run number must be properly set"); return kFALSE; } return kTRUE; } //______________________________________________________________________________ void CheckHV(Int_t runNumber, Int_t verbose) { /// Check the HV values in OCDB for a given run TList messages; messages.SetOwner(kTRUE); Bool_t patched(kTRUE); if (!AliCDBManager::Instance()->IsDefaultStorageSet()) { AliCDBManager::Instance()->SetDefaultStorage("raw://"); } AliCDBManager::Instance()->SetRun(runNumber); if (!CheckMapping()) { LoadMapping(); } AliMUONCalibrationData::CreateHV(runNumber, 0, patched, &messages); AliMUONCalibrationData cd(runNumber, true); AliMUONPadStatusMaker statusMaker(cd); AliMUONRecoParam *rp = LoadRecoParam(); if (!rp) { AliErrorGeneral("CheckHV", "Could not get RecoParam !!!"); return; } statusMaker.SetLimits(*rp); TIter next(&messages); TObjString *s; AliMpDCSNamer hvNamer("TRACKER"); AliMUONLogger log; Double_t meanHVValue(0.0); Double_t nofHVValues(0.0); while ((s = static_cast<TObjString *>(next()))) { TObjArray *a = s->String().Tokenize(":"); TString name(static_cast<TObjString *>(a->At(0))->String()); TObjArray *b = name.Tokenize(" "); name = static_cast<TObjString *>(b->At(0))->String(); delete a; delete b; if (name.Contains("sw") || name.Contains("SUMMARY")) { continue; } Int_t index = hvNamer.DCSIndexFromDCSAlias(name.Data()); Int_t detElemId = hvNamer.DetElemIdFromDCSAlias(name.Data()); AliMpDetElement *de = AliMpDDLStore::Instance()->GetDetElement(detElemId); if (!de) { AliErrorGeneral("CheckHV", Form("Could not get detElemId from dcsAlias %s", name.Data())); continue; } Int_t manuId; if (index >= 0) { const AliMpArrayI *array = de->ManusForHV(index); manuId = array->GetValue(0); } else { AliMpBusPatch *bp = AliMpDDLStore::Instance()->GetBusPatch(de->GetBusPatchId(0)); manuId = bp->GetManuId(0); } Int_t status = statusMaker.HVStatus(detElemId, manuId); log.Log(AliMUONPadStatusMaker::AsString(status).Data()); meanHVValue += MeanHVValueForDCSAlias((*cd.HV()), name.Data()); nofHVValues += 1.0; s->String() += Form(" (DE %4d) ", detElemId); s->String() += AliMUONPadStatusMaker::AsString(status).Data(); } TIter nextMessage(&messages); TObjString *msg; while ((msg = static_cast<TObjString *>(nextMessage()))) { if (verbose > 0 || msg->String().Contains("SUMMARY")) { AliInfoGeneral("CheckHV", Form("RUN %09d HVchannel %s", runNumber, msg->String().Data())); } } TString lmsg; Int_t occurance; TString totalLog; while (log.Next(lmsg, occurance)) { totalLog += Form("%s(%d)", lmsg.Data(), occurance); totalLog += " | "; } AliInfoGeneral("CheckHV", Form("RUN %09d %s", runNumber, totalLog.Data())); // one last loop to get the list of problematic HV channels nextMessage.Reset(); while ((msg = static_cast<TObjString *>(nextMessage()))) { if (msg->String().Contains("HV ")) { AliInfoGeneral("CheckHV", Form(" Problem at %s", msg->String().Data())); } } if (nofHVValues) { meanHVValue /= nofHVValues; AliInfoGeneral("CheckHV", Form("Mean HV for run %09d was %7.2f", runNumber, meanHVValue)); } AliCDBManager::Instance()->ClearCache(); } //______________________________________________________________________________ void CheckHV_ALIROOT_6402(const char *runlist, Bool_t verbose) { /// Check HV for some St1 channels (the ones that are remapped in /// AliMUONCalibrationData::PatchSt1DCSAliases /// (see JIRA bug ALIROOT-6402 for details) std::vector<int> runnumbers; ReadIntegers(runlist, runnumbers); std::vector<int> affectedRuns; for (unsigned int i = 0; i < runnumbers.size(); ++i) { int runNumber = runnumbers[i]; Bool_t affected = CheckHV_ALIROOT_6402(runNumber, verbose); std::cout << Form("RUN %09d is potentially affected by bug ALIROOT-6402 : %s", runNumber, affected ? "YES" : "NO") << std::endl; if (affected) { affectedRuns.push_back(runNumber); } } std::cout << Form("%4lu runs affected in the list of %4lu runs : ", affectedRuns.size(), runnumbers.size()); for (unsigned int i = 0; i < affectedRuns.size(); ++i) { std::cout << affectedRuns[i] << ","; } std::cout << std::endl; } //______________________________________________________________________________ Bool_t CheckHV_ALIROOT_6402(Int_t runNumber, Bool_t verbose) { /// Check HV for some St1 channels (the ones that are remapped in /// AliMUONCalibrationData::PatchSt1DCSAliases /// (see JIRA bug ALIROOT-6402 for details) /// Returns true if that run is (potentially) affected by the bug /// Potentially means that the run is affected if reconstructed with an /// AliRoot version before the bug fix... AliLog::GetRootLogger()->SetGlobalLogLevel(AliLog::kError); TList messages; messages.SetOwner(kTRUE); if (!AliCDBManager::Instance()->IsDefaultStorageSet()) { AliCDBManager::Instance()->SetDefaultStorage("raw://"); } AliCDBManager::Instance()->SetRun(runNumber); LoadMapping(); TMap *hvMap = dynamic_cast<TMap *>(AliMUONCalibrationData::CreateObject(runNumber, "MUON/Calib/HV")); PatchHV(*hvMap, &messages, kTRUE); if (verbose) { TIter next(&messages); TObjString *msg; while ((msg = static_cast<TObjString *>(next()))) { std::cout << Form("RUN %09d %s", runNumber, msg->String().Data()) << std::endl; } } TIter next(hvMap); TObjString *hvChannelName; Bool_t affected(kFALSE); while ((hvChannelName = static_cast<TObjString *>(next()))) { TString name(hvChannelName->String()); if (IsSt1DCSAliasRemapped(name)) { Float_t hvvalue = MeanHVValueForDCSAlias(*hvMap, name.Data()); if (hvvalue < 1590.0) { affected = kTRUE; if (verbose) { std::cout << Form("RUN %09d %40s HV VALUE %7.2f", runNumber, name.Data(), hvvalue) << std::endl; } } } } AliCDBManager::Instance()->ClearCache(); return affected; } //_____________________________________________________________________________ Bool_t CheckMapping(Bool_t segmentationOnly) { /// Check that the mapping has been loaded // first the segmentation if (!AliMpSegmentation::Instance(false)) { AliErrorGeneral("AliMUONCDB", "Mapping segmentation must be loaded first"); return kFALSE; } // then the others if required if (segmentationOnly) return kTRUE; if (!AliMpDDLStore::Instance(false) || !AliMpDEStore::Instance(false) || !AliMpManuStore::Instance(false)) { AliErrorGeneral("AliMUONCDB", "Full mapping must be loaded first"); return kFALSE; } return kTRUE; } //______________________________________________________________________________ Bool_t IsSt1DCSAliasRemapped(const TString &name) { Bool_t isit(kFALSE); if (name.Contains("Chamber00Left")) { if (name.Contains("Quad1Sect0")) isit = kTRUE; if (name.Contains("Quad1Sect1")) isit = kTRUE; if (name.Contains("Quad1Sect2")) isit = kTRUE; if (name.Contains("Quad2Sect2")) isit = kTRUE; if (name.Contains("Quad2Sect1")) isit = kTRUE; if (name.Contains("Quad2Sect0")) isit = kTRUE; } else if (name.Contains("Chamber01Left")) { if (name.Contains("Quad2Sect2")) isit = kTRUE; if (name.Contains("Quad2Sect0")) isit = kTRUE; } return isit; } //_____________________________________________________________________________ Bool_t LoadField() { /// Load magnetic field (existing field will be deleted). /// OCDB path and run number are supposed to be set. AliInfoGeneral("AliMUONCDB", "Loading field map from GRP..."); if (!CheckOCDB()) return kFALSE; AliGRPManager grpMan; // make sure the old field is deleted even if it is locked if (TGeoGlobalMagField::Instance()->IsLocked()) delete TGeoGlobalMagField::Instance(); if (!grpMan.ReadGRPEntry() || !grpMan.SetMagField()) { AliErrorGeneral("AliMUONCDB", "failed to load magnetic field from OCDB"); return kFALSE; } return kTRUE; } //_____________________________________________________________________________ Bool_t LoadMapping(Bool_t segmentationOnly) { /// Load mapping (existing mapping will be unloaded). /// OCDB path and run number are supposed to be set. AliInfoGeneral("AliMUONCDB", "Loading mapping from OCDB..."); if (!CheckOCDB()) return kFALSE; // in case it has already been set AliMpCDB::UnloadAll(); if (segmentationOnly) { if (!AliMpCDB::LoadMpSegmentation(kTRUE)) { AliErrorGeneral("AliMUONCDB", "failed to load segmentation from OCDB"); return kFALSE; } } else { if (!AliMpCDB::LoadAll(kTRUE)) { AliErrorGeneral("AliMUONCDB", "failed to load mapping from OCDB"); return kFALSE; } } return kTRUE; } //_____________________________________________________________________________ AliMUONRecoParam *LoadRecoParam() { /// Load and return reconstruction parameters. /// OCDB path is supposed to be set. AliInfoGeneral("AliMUONCDB", "Loading RecoParam from OCDB..."); if (!CheckOCDB()) return 0x0; AliMUONRecoParam *recoParam = 0x0; AliCDBEntry *entry = AliCDBManager::Instance()->Get("MUON/Calib/RecoParam"); if (entry) { // load recoParam according OCDB content (single or array) if (!(recoParam = dynamic_cast<AliMUONRecoParam *>(entry->GetObject()))) { TObjArray *recoParamArray = static_cast<TObjArray *>(entry->GetObject()); // recoParamArray->SetOwner(kTRUE); // FIXME: this should be done, but is causing a problem at the end of the reco... investigate why... for (Int_t i = 0; i < recoParamArray->GetEntriesFast(); i++) { recoParam = static_cast<AliMUONRecoParam *>(recoParamArray->UncheckedAt(i)); if (recoParam->IsDefault()) break; recoParam = 0x0; } } } if (!recoParam) AliErrorGeneral("AliMUONCDB", "failed to load RecoParam from OCDB"); return recoParam; } //_____________________________________________________________________________ TClonesArray *LoadAlignmentData() { /// Load and return the array of alignment objects. AliInfoGeneral("AliMUONCDB", "Loading Alignemnt from OCDB..."); if (!CheckOCDB()) return 0x0; TClonesArray *alignmentArray = 0x0; AliCDBEntry *entry = AliCDBManager::Instance()->Get("MUON/Align/Data"); if (entry) { // load alignement array alignmentArray = dynamic_cast<TClonesArray *>(entry->GetObject()); } if (!alignmentArray) { AliErrorGeneral("AliMUONCDB", "failed to load Alignemnt from OCDB"); } return alignmentArray; } //_____________________________________________________________________________ AliMUONVStore * Diff(AliMUONVStore &store1, AliMUONVStore &store2, const char *opt) { /// creates a store which contains store1-store2 /// if opt="abs" the difference is absolute one, /// if opt="rel" then what is stored is (store1-store2)/store1 /// if opt="percent" then what is stored is rel*100 /// /// WARNING Works only for stores which holds AliMUONVCalibParam objects TString sopt(opt); sopt.ToUpper(); if (!sopt.Contains("ABS") && !sopt.Contains("REL") && !sopt.Contains("PERCENT")) { AliErrorGeneral("AliMUONCDB", Form("opt %s not supported. Only ABS, REL, PERCENT are", opt)); return 0x0; } AliMUONVStore *d = static_cast<AliMUONVStore *>(store1.Clone()); TIter next(d->CreateIterator()); AliMUONVCalibParam *param; while ((param = dynamic_cast<AliMUONVCalibParam *>(next()))) { Int_t detElemId = param->ID0(); Int_t manuId = param->ID1(); AliMUONVCalibParam *param2 = dynamic_cast<AliMUONVCalibParam *>(store2.FindObject(detElemId, manuId)); //FIXME: this might happen. Handle it. if (!param2) { cerr << "param2 is null : FIXME : this might happen !" << endl; delete d; return 0; } for (Int_t i = 0; i < param->Size(); ++i) { for (Int_t j = 0; j < param->Dimension(); ++j) { Float_t value(0); if (sopt.Contains("ABS")) { value = param->ValueAsFloat(i, j) - param2->ValueAsFloat(i, j); } else if (sopt.Contains("REL") || sopt.Contains("PERCENT")) { if (param->ValueAsFloat(i, j)) { value = (param->ValueAsFloat(i, j) - param2->ValueAsFloat(i, j)) / param->ValueAsFloat(i, j); } else { continue; } if (sopt.Contains("PERCENT")) value *= 100.0; } param->SetValueAsFloat(i, j, value); } } } return d; } //_____________________________________________________________________________ TH1 ** Plot(const AliMUONVStore &store, const char *name, Int_t nbins) { /// Make histograms of each dimension of the AliMUONVCalibParam /// contained inside store. /// It produces histograms named name_0, name_1, etc... if (!CheckMapping(kTRUE)) return 0x0; TIter next(store.CreateIterator()); AliMUONVCalibParam *param; Int_t n(0); const Int_t kNStations = AliMpConstants::NofTrackingChambers() / 2; Int_t *nPerStation = new Int_t[kNStations]; TH1 **h(0x0); for (Int_t i = 0; i < kNStations; ++i) nPerStation[i] = 0; while ((param = static_cast<AliMUONVCalibParam *>(next()))) { if (!h) { Int_t dim = param->Dimension(); h = new TH1 *[dim]; Float_t *xmin = new Float_t[dim]; Float_t *xmax = new Float_t[dim]; getBoundaries(store, dim, xmin, xmax); for (Int_t i = 0; i < dim; ++i) { h[i] = new TH1F(Form("%s_%d", name, i), Form("%s_%d", name, i), nbins, xmin[i], xmax[i]); AliInfoGeneral("AliMUONCDB", Form("Created histogram %s", h[i]->GetName())); } delete[] xmin; delete[] xmax; } Int_t detElemId = param->ID0(); Int_t manuId = param->ID1(); Int_t station = AliMpDEManager::GetChamberId(detElemId) / 2; const AliMpVSegmentation *seg = AliMpSegmentation::Instance()->GetMpSegmentationByElectronics(detElemId, manuId); if (!seg) continue; for (Int_t manuChannel = 0; manuChannel < param->Size(); ++manuChannel) { AliMpPad pad = seg->PadByLocation(manuId, manuChannel, kFALSE); if (!pad.IsValid()) continue; ++n; ++nPerStation[station]; for (Int_t dim = 0; dim < param->Dimension(); ++dim) { h[dim]->Fill(param->ValueAsFloat(manuChannel, dim)); } } } for (Int_t i = 0; i < kNStations; ++i) { AliInfoGeneral("AliMUONCDB", Form("Station %d %d ", (i + 1), nPerStation[i])); } AliInfoGeneral("AliMUONCDB", Form("Number of channels = %d", n)); delete[] nPerStation; return h; } //_____________________________________________________________________________ Int_t MakeBusPatchEvolution(AliMergeableCollection &hc, int timeResolution) { /// Make a fake bus patch evolution mergeable collection, where /// the (mean) occupancy is the bus patch id if (!CheckMapping()) return 0; TDatime origin; double xmin = 0; double xmax = xmin + 3600; int nbins = TMath::Nint((xmax - xmin) / timeResolution); TIter next(AliMpDDLStore::Instance()->CreateBusPatchIterator()); AliMpBusPatch *bp; Int_t total(0); TF1 f1("f1", "pol0", xmin, xmax); while ((bp = static_cast<AliMpBusPatch *>(next()))) { ++total; TH1 *h = new TH1F(Form("BP%04d", bp->GetId()), Form("Number of hits in %d s bins", timeResolution), nbins, xmin, xmax); f1.SetParameter(0, bp->GetId()); h->FillRandom("f1", 10000); h->GetXaxis()->SetTimeDisplay(1); h->GetXaxis()->SetTimeFormat("%d/%m/%y %H:%M"); h->GetXaxis()->SetTimeOffset(origin.Convert()); hc.Adopt(Form("/BUSPATCH/HITS/%ds", timeResolution), h); } // number of events needed for normalization TH1 *h = new TH1F(Form("Nevents%ds", timeResolution), Form("Number of events %d s bins", timeResolution), nbins, xmin, xmax); f1.SetParameter(0, 4200); h->FillRandom("f1", 10000); h->GetXaxis()->SetTimeDisplay(1); h->GetXaxis()->SetTimeFormat("%d/%m/%y %H:%M"); h->GetXaxis()->SetTimeOffset(origin.Convert()); hc.Adopt("", h); return (total == 888); } //_____________________________________________________________________________ Int_t MakeHVStore(TMap &aliasMap, Bool_t defaultValues) { /// Create a HV store if (!CheckMapping()) return 0; AliMpDCSNamer hvNamer("TRACKER"); TObjArray *aliases = hvNamer.GenerateAliases(); Int_t nSwitch(0); Int_t nChannels(0); for (Int_t i = 0; i < aliases->GetEntries(); ++i) { TObjString *alias = static_cast<TObjString *>(aliases->At(i)); TString &aliasName = alias->String(); if (aliasName.Contains("sw")) { // HV Switch (St345 only) TObjArray *valueSet = new TObjArray; valueSet->SetOwner(kTRUE); Bool_t value = kTRUE; if (!defaultValues) { Float_t r = gRandom->Uniform(); if (r < 0.007) value = kFALSE; } for (UInt_t timeStamp = 0; timeStamp < 60 * 3; timeStamp += 60) { AliDCSValue *dcsValue = new AliDCSValue(value, timeStamp); valueSet->Add(dcsValue); } aliasMap.Add(new TObjString(*alias), valueSet); ++nSwitch; } else if (aliasName.Contains("Mon")) { TObjArray *valueSet = new TObjArray; valueSet->SetOwner(kTRUE); for (UInt_t timeStamp = 0; timeStamp < 60 * 15; timeStamp += 120) { Float_t value = 1500; if (!defaultValues) value = GetRandom(1750, 62.5, true); AliDCSValue *dcsValue = new AliDCSValue(value, timeStamp); valueSet->Add(dcsValue); } aliasMap.Add(new TObjString(*alias), valueSet); ++nChannels; } } delete aliases; AliInfoGeneral("AliMUONCDB", Form("%d HV channels and %d switches", nChannels, nSwitch)); return nChannels + nSwitch; } //_____________________________________________________________________________ Int_t MakeLVStore(TMap &aliasMap, Bool_t defaultValues, time_t refTime) { /// Create a MCH LV store if (!CheckMapping()) return 0; AliMpDCSNamer hvNamer("TRACKER"); TObjArray *aliases = hvNamer.GenerateAliases("Group"); Int_t npos(0), nneg(0), ndig(0); for (Int_t i = 0; i < aliases->GetEntries(); ++i) { TObjString *alias = static_cast<TObjString *>(aliases->At(i)); TString &aliasName = alias->String(); Float_t refValue = 0; if (aliasName.Contains("anp")) { refValue = 2.5; ++npos; } else if (aliasName.Contains("dig")) { refValue = 3.3; ++ndig; } else if (aliasName.Contains("ann")) { refValue = 2.5; // that's not a bug : even though we're describing // a negative value, the DCS data point is positive. ++nneg; } else { AliErrorGeneral("AliMUONCDB", "Should not be here ! CHECK ME !"); continue; } TObjArray *valueSet = new TObjArray; valueSet->SetOwner(kTRUE); Float_t value = refValue; for (UInt_t timeStamp = 0; timeStamp < 60 * 15; timeStamp += 120) { if (!defaultValues) value = GetRandom(refValue, 0.05, false); AliDCSValue *dcsValue = new AliDCSValue(value, refTime + timeStamp); valueSet->Add(dcsValue); } aliasMap.Add(new TObjString(*alias), valueSet); } Bool_t ok = (npos == nneg) && (npos == ndig) && (ndig == nneg); if (!ok) { AliErrorGeneral("AliMUONCDB", Form("Wrong number of LV channels : npos=%d nneg=%d ndig=%d", npos, nneg, ndig)); } else { AliInfoGeneral("AliMUONCDB", Form("%d LV groups - %d aliases", npos, aliasMap.GetEntries())); } delete aliases; return npos; } //_____________________________________________________________________________ void AddDCSValue(TMap &aliasMap, Int_t imeas, const char *smt, const char *sInOut, Int_t rpc, Float_t value) { TString sMeasure = (imeas == AliMpDCSNamer::kDCSHV) ? "HV.vEff" : "HV.actual.iMon"; TString alias = Form("MTR_%s_%s_RPC%i_%s", sInOut, smt, rpc, sMeasure.Data()); TObjArray *valueSet = new TObjArray; valueSet->SetOwner(kTRUE); for (UInt_t timeStamp = 0; timeStamp < 60 * 2; timeStamp += 60) { AliDCSValue *dcsValue = new AliDCSValue(value, timeStamp); valueSet->Add(dcsValue); } aliasMap.Add(new TObjString(alias), valueSet); } //_____________________________________________________________________________ Int_t MakeTriggerDCSStore(TMap &aliasMap) { /// Create a Trigger HV and Currents store // if (!CheckMapping()) return 0; Int_t nChannels[2] = {0, 0}; AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 1, 10400.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 2, 10351.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 3, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 4, 10450.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 5, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 6, 10100.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 7, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 8, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "INSIDE", 9, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 1, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 2, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 3, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 4, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 5, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 6, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 7, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 8, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT11", "OUTSIDE", 9, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 1, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 2, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 3, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 4, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 5, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 6, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 7, 10400.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 8, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "INSIDE", 9, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 1, 10400.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 2, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 3, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 4, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 5, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 6, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 7, 10100.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 8, 10400.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT12", "OUTSIDE", 9, 10400.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 1, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 2, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 3, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 4, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 5, 10100.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 6, 10100.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 7, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 8, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "INSIDE", 9, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 1, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 2, 10350.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 3, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 4, 10100.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 5, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 6, 10101.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 7, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 8, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT21", "OUTSIDE", 9, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 1, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 2, 10300.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 3, 9624.); // FEERIC AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 4, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 5, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 6, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 7, 10050.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 8, 10050.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "INSIDE", 9, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 1, 10225.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 2, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 3, 10150.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 4, 10100.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 5, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 6, 10200.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 7, 10250.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 8, 10225.); AddDCSValue(aliasMap, AliMpDCSNamer::kDCSHV, "MT22", "OUTSIDE", 9, 10250.); nChannels[0] = 72; TString chName[4] = {"MT11", "MT12", "MT21", "MT22"}; for (Int_t ich = 0; ich < 4; ich++) { for (Int_t iside = 0; iside < 2; iside++) { TString sInOut = (iside == 0) ? "INSIDE" : "OUTSIDE"; for (Int_t irpc = 1; irpc <= 9; irpc++) { AddDCSValue(aliasMap, AliMpDCSNamer::kDCSI, chName[ich].Data(), sInOut.Data(), irpc, 2.); ++nChannels[1]; } } } AliInfoGeneral("AliMUONCDB", Form("Trigger channels I -> %i HV -> %i", nChannels[0], nChannels[1])); return nChannels[0] + nChannels[1]; } //_____________________________________________________________________________ Int_t MakePedestalStore(AliMUONVStore &pedestalStore, Bool_t defaultValues) { /// Create a pedestal store. if defaultValues=true, ped.mean=ped.sigma=1, /// otherwise mean and sigma are from a gaussian (with parameters /// defined below by the kPedestal* constants) AliCodeTimerAutoGeneral("", 0); if (!CheckMapping()) return 0; Int_t nchannels(0); Int_t nmanus(0); const Int_t kChannels(AliMpConstants::ManuNofChannels()); // bending const Float_t kPedestalMeanMeanB(200.); const Float_t kPedestalMeanSigmaB(10.); const Float_t kPedestalSigmaMeanB(1.); const Float_t kPedestalSigmaSigmaB(0.2); // non bending const Float_t kPedestalMeanMeanNB(200.); const Float_t kPedestalMeanSigmaNB(10.); const Float_t kPedestalSigmaMeanNB(1.); const Float_t kPedestalSigmaSigmaNB(0.2); const Float_t kFractionOfDeadManu(0.); // within [0.,1.] Int_t detElemId; Int_t manuId; AliMpManuIterator it; while (it.Next(detElemId, manuId)) { // skip a given fraction of manus if (kFractionOfDeadManu > 0. && gRandom->Uniform() < kFractionOfDeadManu) continue; ++nmanus; AliMUONVCalibParam *ped = new AliMUONCalibParamNF(2, kChannels, detElemId, manuId, AliMUONVCalibParam::InvalidFloatValue()); AliMpDetElement *de = AliMpDDLStore::Instance()->GetDetElement(detElemId); for (Int_t manuChannel = 0; manuChannel < kChannels; ++manuChannel) { if (!de->IsConnectedChannel(manuId, manuChannel)) continue; ++nchannels; Float_t meanPedestal; Float_t sigmaPedestal; if (defaultValues) { meanPedestal = 0.0; sigmaPedestal = 1.0; } else { Bool_t positive(kTRUE); meanPedestal = 0.0; if (manuId & AliMpConstants::ManuMask(AliMp::kNonBendingPlane)) { // manu in non bending plane while (meanPedestal == 0.0) // avoid strict zero { meanPedestal = GetRandom(kPedestalMeanMeanNB, kPedestalMeanSigmaNB, positive); } sigmaPedestal = GetRandom(kPedestalSigmaMeanNB, kPedestalSigmaSigmaNB, positive); } else { // manu in bending plane while (meanPedestal == 0.0) // avoid strict zero { meanPedestal = GetRandom(kPedestalMeanMeanB, kPedestalMeanSigmaB, positive); } sigmaPedestal = GetRandom(kPedestalSigmaMeanB, kPedestalSigmaSigmaB, positive); } } ped->SetValueAsFloat(manuChannel, 0, meanPedestal); ped->SetValueAsFloat(manuChannel, 1, sigmaPedestal); } Bool_t ok = pedestalStore.Add(ped); if (!ok) { AliErrorGeneral("AliMUONCDB", Form("Could not set DetElemId=%d manuId=%d", detElemId, manuId)); } } AliInfoGeneral("AliMUONCDB", Form("%d Manus and %d channels.", nmanus, nchannels)); return nchannels; } //_____________________________________________________________________________ AliMUONRejectList * MakeRejectListStore(Bool_t defaultValues) { /// Create a reject list AliCodeTimerAutoGeneral("", 0); AliMUONRejectList *rl = new AliMUONRejectList; if (!defaultValues) { rl->SetDetectionElementProbability(510); rl->SetDetectionElementProbability(508); return rl; } return rl; } //_____________________________________________________________________________ Int_t MakeOccupancyMapStore(AliMUONVStore &occupancyMapStore, Bool_t defaultValues) { /// Create an occupancy map. AliCodeTimerAutoGeneral("", 0); if (!CheckMapping()) return 0; Int_t nmanus(0); Int_t detElemId; Int_t manuId; AliMpManuIterator it; Int_t nevents(1000); while (it.Next(detElemId, manuId)) { ++nmanus; AliMUONVCalibParam *occupancy = new AliMUONCalibParamND(5, 1, detElemId, manuId, 0); Double_t occ = 0.0; AliMpDetElement *de = AliMpDDLStore::Instance()->GetDetElement(detElemId); Int_t numberOfChannelsInManu = de->NofChannelsInManu(manuId); if (!defaultValues) occ = gRandom->Rndm(1); Double_t sumn = occ * nevents; occupancy->SetValueAsFloat(0, 0, sumn); occupancy->SetValueAsFloat(0, 1, sumn); occupancy->SetValueAsFloat(0, 2, sumn); occupancy->SetValueAsInt(0, 3, numberOfChannelsInManu); occupancy->SetValueAsInt(0, 4, nevents); Bool_t ok = occupancyMapStore.Add(occupancy); if (!ok) { AliErrorGeneral("AliMUONCDB", Form("Could not set DetElemId=%d manuId=%d", detElemId, manuId)); } } return nmanus; } //_____________________________________________________________________________ Int_t MakeLocalTriggerMaskStore(AliMUONVStore &localBoardMasks) { /// Generate local trigger masks store. All masks are set to FFFF AliCodeTimerAutoGeneral("", 0); Int_t ngenerated(0); // Generate fake mask values for all localboards and put that into // one single container (localBoardMasks) for (Int_t i = 1; i <= AliMpConstants::TotalNofLocalBoards(); ++i) { AliMUONVCalibParam *localBoard = new AliMUONCalibParamNI(1, 8, i, 0, 0); for (Int_t x = 0; x < 2; ++x) { for (Int_t y = 0; y < 4; ++y) { Int_t index = x * 4 + y; localBoard->SetValueAsInt(index, 0, 0xFFFF); ++ngenerated; } } localBoardMasks.Add(localBoard); } return ngenerated; } //_____________________________________________________________________________ Int_t MakeRegionalTriggerConfigStore(AliMUONRegionalTriggerConfig &rtm) { /// Make a regional trigger config store. Mask is set to FFFF for each local board (Ch.F.) AliCodeTimerAutoGeneral("", 0); if (!rtm.ReadData(AliMpFiles::LocalTriggerBoardMapping())) { AliErrorGeneral("AliMUONCDB", "Error when reading from mapping file"); return 0; } return rtm.GetNofTriggerCrates(); } //_____________________________________________________________________________ Int_t MakeGlobalTriggerConfigStore(AliMUONGlobalCrateConfig &gtm) { /// Make a global trigger config store. All masks (disable) set to 0x00 for each Darc board (Ch.F.) AliCodeTimerAutoGeneral("", 0); return gtm.ReadData(AliMpFiles::GlobalTriggerBoardMapping()); } //_____________________________________________________________________________ AliMUONTriggerLut * MakeTriggerLUT(const char *file) { /// Make a triggerlut object, from a file. AliCodeTimerAutoGeneral("", 0); AliMUONTriggerLut *lut = new AliMUONTriggerLut; lut->ReadFromFile(file); return lut; } //_____________________________________________________________________________ AliMUONTriggerEfficiencyCells * MakeTriggerEfficiency(const char *file) { /// Make a trigger efficiency object from a file. AliCodeTimerAutoGeneral("", 0); return new AliMUONTriggerEfficiencyCells(file); } //______________________________________________________________________________ void PatchHV(TMap &hvMap, TList *messages, Bool_t onlySt1remapped) { TIter next(&hvMap); TObjString *hvChannelName; while ((hvChannelName = static_cast<TObjString *>(next()))) { TString name(hvChannelName->String()); if (name.Contains("sw")) continue; // skip switches if (name.Contains("iMon")) continue; // skip HV currents if (onlySt1remapped) { if (!IsSt1DCSAliasRemapped(name)) { continue; } } TPair *hvPair = static_cast<TPair *>(hvMap.FindObject(name.Data())); TObjArray *values = static_cast<TObjArray *>(hvPair->Value()); if (!values) { AliErrorGeneral("PatchHV", Form("Could not get values for alias %s", name.Data())); } else { TString msg; Bool_t ok = AliMUONCalibrationData::PatchHVValues(*values, &msg, kFALSE); if (messages) { messages->Add(new TObjString(Form("%s %s", hvChannelName->String().Data(), msg.Data()))); } if (!ok) { AliErrorGeneral("PatchHV", Form("PatchHVValue was not successfull ! This is serious ! " "You'll have to check the logic for channel %s", hvChannelName->String().Data())); } } } } //_____________________________________________________________________________ void WriteToCDB(const char *calibpath, TObject *object, Int_t startRun, Int_t endRun, const char *filename) { /// Write a given object to OCDB TString comment(gSystem->ExpandPathName(filename)); WriteToCDB(object, calibpath, startRun, endRun, comment.Data()); } //_____________________________________________________________________________ void WriteToCDB(const char *calibpath, TObject *object, Int_t startRun, Int_t endRun, Bool_t defaultValues) { /// Write a given object to OCDB TString comment; if (defaultValues) comment += "Test with default values"; else comment += "Test with random values"; WriteToCDB(object, calibpath, startRun, endRun, comment.Data()); } //_____________________________________________________________________________ void WriteToCDB(TObject *object, const char *calibpath, Int_t startRun, Int_t endRun, const char *comment, const char *responsible) { /// Write a given object to OCDB if (!CheckOCDB(kTRUE)) return; AliCDBId id(calibpath, startRun, endRun); AliCDBMetaData md; md.SetAliRootVersion(gROOT->GetVersion()); md.SetComment(comment); md.SetResponsible(responsible); AliCDBManager::Instance()->Put(object, id, &md); } //_____________________________________________________________________________ void WriteLocalTriggerMasks(Int_t startRun, Int_t endRun) { /// Write local trigger masks to OCDB AliMUONVStore *ltm = new AliMUON1DArray(AliMpConstants::TotalNofLocalBoards() + 1); Int_t ngenerated = MakeLocalTriggerMaskStore(*ltm); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); if (ngenerated > 0) { WriteToCDB("MUON/Calib/LocalTriggerBoardMasks", ltm, startRun, endRun, true); } delete ltm; } //_____________________________________________________________________________ void WriteRegionalTriggerConfig(Int_t startRun, Int_t endRun) { /// Write regional trigger masks to OCDB AliMUONRegionalTriggerConfig *rtm = new AliMUONRegionalTriggerConfig(); Int_t ngenerated = MakeRegionalTriggerConfigStore(*rtm); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); if (ngenerated > 0) { WriteToCDB("MUON/Calib/RegionalTriggerConfig", rtm, startRun, endRun, true); } delete rtm; } //_____________________________________________________________________________ void WriteGlobalTriggerConfig(Int_t startRun, Int_t endRun) { /// Write global trigger masks to OCDB AliMUONGlobalCrateConfig *gtm = new AliMUONGlobalCrateConfig(); Int_t ngenerated = MakeGlobalTriggerConfigStore(*gtm); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); if (ngenerated > 0) { WriteToCDB("MUON/Calib/GlobalTriggerCrateConfig", gtm, startRun, endRun, true); } delete gtm; } //_____________________________________________________________________________ void WriteTriggerLut(Int_t startRun, Int_t endRun) { /// Write trigger LUT to OCDB AliMUONTriggerLut *lut = MakeTriggerLUT(); if (lut) { WriteToCDB("MUON/Calib/TriggerLut", lut, startRun, endRun, true); } delete lut; } //_____________________________________________________________________________ void WriteTriggerEfficiency(Int_t startRun, Int_t endRun) { /// Write trigger efficiency to OCDB AliMUONTriggerEfficiencyCells *eff = MakeTriggerEfficiency(); if (eff) { WriteToCDB("MUON/Calib/TriggerEfficiency", eff, startRun, endRun, true); } delete eff; } //_____________________________________________________________________________ void WriteHV(const char *inputFile, Int_t runNumber) { /// Read HV values from an external file containing a TMap of the DCS values /// store them into CDB located at cdbpath, with a validity period /// of exactly one run TFile *f = TFile::Open(gSystem->ExpandPathName(inputFile)); if (!f->IsOpen()) return; TMap *hvStore = static_cast<TMap *>(f->Get("map")); WriteToCDB("MUON/Calib/HV", hvStore, runNumber, runNumber, kFALSE); delete hvStore; } //_____________________________________________________________________________ void WriteHV(Bool_t defaultValues, Int_t startRun, Int_t endRun) { /// generate HV values (either cste = 1500 V) if defaultValues=true or random /// if defaultValues=false, see makeHVStore) and /// store them into CDB located at cdbpath, with a validity period /// ranging from startRun to endRun TMap *hvStore = new TMap; Int_t ngenerated = MakeHVStore(*hvStore, defaultValues); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); if (ngenerated > 0) { WriteToCDB("MUON/Calib/HV", hvStore, startRun, endRun, defaultValues); } delete hvStore; } //_____________________________________________________________________________ void WriteLV(Bool_t defaultValues, Int_t startRun, Int_t endRun, time_t refTime) { /// generate LV values (either cste = -2.5 / 3.3 / 2.5 V) if defaultValues=true /// or random if defaultValues=false, see makeLVStore) and /// store them into CDB located at cdbpath, with a validity period /// ranging from startRun to endRun TMap *lvStore = new TMap; Int_t ngenerated = MakeLVStore(*lvStore, defaultValues, refTime); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); if (ngenerated > 0) { WriteToCDB("MUON/Calib/LV", lvStore, startRun, endRun, defaultValues); } delete lvStore; } //_____________________________________________________________________________ void WriteTriggerDCS(Int_t startRun, Int_t endRun) { /// generate Trigger HV and current values (using nominal HV for avalanche mode) /// and store them into CDB located at cdbpath, with a validity period /// ranging from startRun to endRun TMap *triggerDCSStore = new TMap; Int_t ngenerated = MakeTriggerDCSStore(*triggerDCSStore); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); if (ngenerated > 0) { WriteToCDB("MUON/Calib/TriggerDCS", triggerDCSStore, startRun, endRun, true); } delete triggerDCSStore; } //_____________________________________________________________________________ void WritePedestals(Bool_t defaultValues, Int_t startRun, Int_t endRun) { /// generate pedestal values (either 0 if defaultValues=true or random /// if defaultValues=false, see makePedestalStore) and /// store them into CDB located at cdbpath, with a validity period /// ranging from startRun to endRun AliMUONVStore *pedestalStore = Create2DMap(); Int_t ngenerated = MakePedestalStore(*pedestalStore, defaultValues); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); WriteToCDB("MUON/Calib/Pedestals", pedestalStore, startRun, endRun, defaultValues); delete pedestalStore; } //_____________________________________________________________________________ void WriteOccupancyMap(Bool_t defaultValues, Int_t startRun, Int_t endRun) { /// generate occupancy map values (either empty one if defaultValues=true, or /// random one, see MakeOccupancyMapStore) and /// store them into CDB located at cdbpath, with a validity period /// ranging from startRun to endRun AliMUONVStore *occupancyMapStore = Create2DMap(); Int_t ngenerated = MakeOccupancyMapStore(*occupancyMapStore, defaultValues); AliInfoGeneral("AliMUONCDB", Form("Ngenerated = %d", ngenerated)); WriteToCDB("MUON/Calib/OccupancyMap", occupancyMapStore, startRun, endRun, defaultValues); delete occupancyMapStore; } //_____________________________________________________________________________ void WriteRejectList(Bool_t defaultValues, Int_t startRun, Int_t endRun) { /// generate reject list values (either empty one if defaultValues=true, or /// random one, see MakeRejectListStore) and /// store them into CDB located at cdbpath, with a validity period /// ranging from startRun to endRun AliMUONRejectList *rl = MakeRejectListStore(defaultValues); WriteToCDB("MUON/Calib/RejectList", rl, startRun, endRun, defaultValues); delete rl; } //_____________________________________________________________________________ void WriteMapping(Int_t startRun, Int_t endRun) { gSystem->Setenv("MINSTALL", gSystem->ExpandPathName("$ALICE_ROOT/MUON/mapping")); AliMpCDB::WriteMpData(startRun, endRun); AliMpCDB::WriteMpRunData(startRun, endRun); } //_____________________________________________________________________________ void WriteTrigger(Bool_t defaultValues, Int_t startRun, Int_t endRun) { /// Writes all Trigger related calibration to CDB WriteTriggerDCS(startRun, endRun); WriteLocalTriggerMasks(startRun, endRun); WriteRegionalTriggerConfig(startRun, endRun); WriteGlobalTriggerConfig(startRun, endRun); WriteTriggerLut(startRun, endRun); WriteTriggerEfficiency(startRun, endRun); } //_____________________________________________________________________________ void WriteConfig(Int_t startRun, Int_t endRun) { /// Write complete tracker configuration to OCDB ostringstream lines; TIter next(AliMpDDLStore::Instance()->CreateBusPatchIterator()); AliMpBusPatch *bp; while ((bp = static_cast<AliMpBusPatch *>(next()))) { for (Int_t imanu = 0; imanu < bp->GetNofManus(); ++imanu) { lines << bp->GetId() << " " << bp->GetManuId(imanu) << endl; } } AliMUON2DMap config(kTRUE); AliMUONTrackerIO::DecodeConfig(lines.str().c_str(), config); WriteToCDB("MUON/Calib/Config", &config, startRun, endRun, kTRUE); } //_____________________________________________________________________________ void WriteBPEVO(Int_t startRun, Int_t endRun) { /// Write a fake bus patch evolution to OCDB AliMergeableCollection bpevo("BPEVO"); if (MakeBusPatchEvolution(bpevo, 60)) { WriteToCDB("MUON/Calib/BPEVO", &bpevo, startRun, endRun, kTRUE); } } //_____________________________________________________________________________ void WriteTracker(Bool_t defaultValues, Int_t startRun, Int_t endRun) { /// Writes all Tracker related calibration to CDB WriteMapping(startRun, endRun); WriteHV(defaultValues, startRun, endRun); WriteLV(defaultValues, startRun, endRun); WritePedestals(defaultValues, startRun, endRun); WriteOccupancyMap(defaultValues, startRun, endRun); WriteRejectList(defaultValues, startRun, endRun); WriteConfig(startRun, endRun); WriteBPEVO(startRun, endRun); } //_____________________________________________________________________________ void ShowConfig(Bool_t withStatusMap) { /// Dumps the current tracker configuration, i.e. number and identity of missing buspatches /// If statusMap is true, will also take into account the status map to report the number /// of good channels if (!CheckOCDB()) return; LoadMapping(); if (!CheckMapping()) return; AliCDBEntry *e = AliCDBManager::Instance()->Get("MUON/Calib/Config"); if (!e) return; AliMUONVStore *config = static_cast<AliMUONVStore *>(e->GetObject()); AliMUONPadStatusMapMaker *statusMapMaker(0x0); AliMUONCalibrationData *cd(0x0); AliMUONPadStatusMaker *statusMaker(0x0); if (withStatusMap) { cd = new AliMUONCalibrationData(AliCDBManager::Instance()->GetRun()); statusMaker = new AliMUONPadStatusMaker(*cd); AliMUONRecoParam *recoParam = LoadRecoParam(); if (!recoParam) { AliErrorGeneral("ShowConfig", "Cannot get recoParams from OCDB !"); return; } statusMaker->SetLimits(*recoParam); UInt_t mask = recoParam->PadGoodnessMask(); delete recoParam; const Bool_t deferredInitialization = kFALSE; statusMapMaker = new AliMUONPadStatusMapMaker(*cd, mask, deferredInitialization); } TIter nextManu(config->CreateIterator()); AliMUONVCalibParam *param; AliMpExMap buspatches; while ((param = static_cast<AliMUONVCalibParam *>(nextManu()))) { Int_t detElemId = param->ID0(); Int_t manuId = param->ID1(); Int_t busPatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId, manuId); if (buspatches.GetValue(busPatchId) == 0x0) { buspatches.Add(busPatchId, new TObjString(Form("BP%04d", busPatchId))); } } TArrayI removed(buspatches.GetSize()); TIter next(AliMpDDLStore::Instance()->CreateBusPatchIterator()); AliMpBusPatch *bp; Int_t n(0); Int_t nok(0); Int_t nremoved(0); // accounting of bus patches first while ((bp = static_cast<AliMpBusPatch *>(next()))) { if (buspatches.GetValue(bp->GetId())) { ++nok; } else { removed.SetAt(bp->GetId(), nremoved++); } } // accounting of channels AliMpManuIterator it; Int_t totalNumberOfChannels(0); Int_t removedChannels(0); Int_t badChannels(0); Int_t badAndRemovedChannels(0); Int_t badOrRemovedChannels(0); Int_t detElemId, manuId; while (it.Next(detElemId, manuId)) { AliMpDetElement *de = AliMpDDLStore::Instance()->GetDetElement(detElemId); for (Int_t i = 0; i < AliMpConstants::ManuNofChannels(); ++i) { Int_t busPatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId, manuId); if (de->IsConnectedChannel(manuId, i)) { ++totalNumberOfChannels; Bool_t badBusPatch = (buspatches.GetValue(busPatchId) == 0x0); if (withStatusMap) { Bool_t badChannel = ( (statusMapMaker->StatusMap(detElemId, manuId, i) & AliMUONPadStatusMapMaker::SelfDeadMask()) != 0); if (badChannel) ++badChannels; if (badBusPatch && badChannel) ++badAndRemovedChannels; if (badBusPatch || badChannel) ++badOrRemovedChannels; } if (badBusPatch) ++removedChannels; } } } Int_t *indices = new Int_t[nremoved]; TMath::Sort(nremoved, removed.GetArray(), indices, kFALSE); for (Int_t i = 0; i < nremoved; ++i) { Int_t busPatchId = removed[indices[i]]; bp = AliMpDDLStore::Instance()->GetBusPatch(busPatchId); bp->Print(); } delete[] indices; cout << endl; cout << Form("Bus patches n=%3d nok=%3d nremoved=%3d", n, nok, nremoved) << endl; cout << Form("Channels n=%6d nremoved=%6d bad=%6d bad and removed=%6d bad or removed=%6d", totalNumberOfChannels, removedChannels, badChannels, badAndRemovedChannels, badOrRemovedChannels) << endl; if (totalNumberOfChannels > 0) { cout << Form("Percentage of readout channels %5.1f %%", removedChannels * 100.0 / totalNumberOfChannels) << endl; if (withStatusMap) { cout << Form("Percentage of non useable channels (bad or removed) %5.1f %%", badOrRemovedChannels * 100.0 / totalNumberOfChannels) << endl; } } delete statusMapMaker; delete cd; delete statusMaker; } //______________________________________________________________________________ void ReadIntegers(const char *filename, std::vector<int> &integers) { /// Read integers from filename, where integers are either /// separated by "," or by return carriage ifstream in(gSystem->ExpandPathName(filename)); int i; std::set<int> runset; char line[10000]; in.getline(line, 10000, '\n'); TString sline(line); if (sline.Contains(",")) { TObjArray *a = sline.Tokenize(","); TIter next(a); TObjString *s; while ((s = static_cast<TObjString *>(next()))) { runset.insert(s->String().Atoi()); } delete a; } else { runset.insert(sline.Atoi()); while (in >> i) { runset.insert(i); } } for (std::set<int>::const_iterator it = runset.begin(); it != runset.end(); ++it) { integers.push_back((*it)); } std::sort(integers.begin(), integers.end()); } namespace { void GetBusPatchIdAndNofChannels(std::vector<int> &busPatchIds, std::vector<int> &busPatchNofChannels) { busPatchIds.clear(); busPatchNofChannels.clear(); TIter nextBP(AliMpDDLStore::Instance()->CreateBusPatchIterator()); AliMpBusPatch *bp; while ((bp = static_cast<AliMpBusPatch *>(nextBP()))) { busPatchIds.push_back(bp->GetId()); } std::sort(busPatchIds.begin(),busPatchIds.end()); for ( int i = 0; i < busPatchIds.size(); ++i ) { int bpid = busPatchIds[i]; AliMpBusPatch* bp = AliMpDDLStore::Instance()->GetBusPatch(bpid); int bpnofchannels = 0; AliMpDetElement *de = AliMpDDLStore::Instance()->GetDetElement( AliMpDDLStore::Instance()->GetDEfromBus(bpid)); for (int i = 0; i < bp->GetNofManus(); ++i) { bpnofchannels += de->NofChannelsInManu(bp->GetManuId(i)); } busPatchNofChannels.push_back(bpnofchannels); } int totalNofChannels = 0; for ( int i = 0 ; i < busPatchIds.size(); ++i ) { totalNofChannels += busPatchNofChannels[i]; } assert(totalNofChannels==1064008); } std::set<int> GetConfig(int runNumber) { std::set<int> buspatches; AliCDBEntry *e = AliCDBManager::Instance()->Get("MUON/Calib/Config", runNumber); AliMUONVStore *config = static_cast<AliMUONVStore *>(e->GetObject()); TIter next(config->CreateIterator()); AliMUONVCalibParam* param; while ( ( param = static_cast<AliMUONVCalibParam*>(next()))) { buspatches.insert(AliMpDDLStore::Instance()->GetBusPatchId(param->ID0(),param->ID1())); } return buspatches; } } //______________________________________________________________________________ void ShowFaultyPedestalsBusPatches(const char *runlist, double fractionLimit, double meanLimit, double sigmaLimit, double outputFractionLimit, const char *outputBaseName, const char *ocdbPath) { /// Shows the list of bus patches where the fraction /// of pads with pedestal mean >= meanLimit || pedestal sigma >= sigmaLimit /// is greater than fractionLimit. /// /// Do this for each run in the runlist /// If a buspatch is bad for more than outputFractionLimit, printout its id AliLog::GetRootLogger()->SetGlobalLogLevel(AliLog::kError); AliCDBManager *man = AliCDBManager::Instance(); man->SetDefaultStorage(ocdbPath); std::vector<int> runnumbers; ReadIntegers(runlist, runnumbers); if (runnumbers.empty()) { std::cout << "empty runlist. Bailing out\n"; return; } man->SetRun(runnumbers[0]); AliMpCDB::LoadAll(); std::vector<int> busPatchIds; std::vector<int> busPatchNofChannels; GetBusPatchIdAndNofChannels(busPatchIds,busPatchNofChannels); std::vector<int> busPatchInConfig(busPatchIds.size()); std::vector<int> busPatchNotOK(busPatchIds.size()); for (int i = 0; i < runnumbers.size(); ++i ) { int runNumber = runnumbers[i]; man->SetRun(runNumber); std::set<int> buspatches = GetConfig(runNumber); AliCDBEntry *e = man->Get("MUON/Calib/Pedestals", runNumber); if (!e) { AliErrorGeneral("ShowFaultyPedestalsBusPatches", Form("Could not get Pedestals for run %09d", runNumber)); continue; } AliMUONVStore *pedmap = static_cast<AliMUONVStore *>(e->GetObject()); for ( int i = 0; i < busPatchIds.size(); ++i ) { Int_t detElemId = AliMpDDLStore::Instance()->GetDEfromBus(busPatchIds[i]); AliMpDetElement *de = AliMpDDLStore::Instance()->GetDetElement(detElemId); AliMpBusPatch* bp = AliMpDDLStore::Instance()->GetBusPatch(busPatchIds[i]); int nbad = 0; if (buspatches.find(busPatchIds[i]) != buspatches.end() ) { busPatchInConfig[i]++; } for (int m = 0; m < bp->GetNofManus(); ++m) { int manuId = bp->GetManuId(m); AliMUONVCalibParam *calibParam = static_cast<AliMUONVCalibParam *>(pedmap->FindObject(detElemId, manuId)); if (!calibParam) { continue; } int nofchannels = de->NofChannelsInManu(manuId); for (int c = 0; c < nofchannels; ++c) { float mean = calibParam->ValueAsFloat(c, 0); float sigma = calibParam->ValueAsFloat(c, 1); if (mean >= meanLimit || sigma >= sigmaLimit) { ++nbad; } } } if (nbad / busPatchNofChannels[i] > fractionLimit) { busPatchNotOK[i]++; } } } std::ofstream outfile(Form("%s.txt", outputBaseName)); for (int i = 0; i < busPatchIds.size(); ++i ) { if ( busPatchNotOK[i]) { float fraction = 1.0*busPatchNotOK[i]/busPatchInConfig[i]; if (fraction>outputFractionLimit) { outfile << Form("BP %04d is bad for %3d runs in %3d (%7.2f%%)\n", busPatchIds[i], busPatchNotOK[i], busPatchInConfig[i], fraction*100); } } } } //______________________________________________________________________________ void ShowFaultyBusPatches(const char* runlist, double occLimit, const char* outputBaseName, const char* ocdbPath) { /// Shows the list of bus patches above a given occupancy limit, /// for each run in the runlist AliLog::GetRootLogger()->SetGlobalLogLevel(AliLog::kError); // AliLog::SetPrintType(AliLog::kInfo,kFALSE); // AliLog::SetPrintType(AliLog::kWarning,kFALSE); // gErrorIgnoreLevel=kError; // to avoid all the TAlienFile::Open messages... AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(ocdbPath); Bool_t first(kTRUE); std::vector<int> runnumbers; ReadIntegers(runlist,runnumbers); AliMUON2DMap bpValues(kFALSE); std::ofstream outfile(Form("%s.txt",outputBaseName)); for ( unsigned int i = 0 ; i < runnumbers.size(); ++i ) { int runNumber = runnumbers[i]; man->SetRun(runNumber); if ( first ) { AliMpCDB::LoadAll(); first = kFALSE; } AliCDBEntry* e = man->Get("MUON/Calib/OccupancyMap",runNumber); if (!e) { AliErrorGeneral("ShowFaultyBusPatches", Form("Could not get OccupancyMap for run %09d",runNumber)); continue; } AliMUONVStore* occmap = static_cast<AliMUONVStore*>(e->GetObject()); AliMUONTrackerData td("occ","occ",*occmap); TIter nextBP(AliMpDDLStore::Instance()->CreateBusPatchIterator()); AliMpBusPatch* bp; std::set<int> buspatches; Double_t sumn = 1000.0; while ( ( bp = static_cast<AliMpBusPatch*>(nextBP()) ) ) { Double_t occ = td.BusPatch(bp->GetId(),2); if (occ>occLimit) { buspatches.insert(bp->GetId()); AliMUONVCalibParam* param = static_cast<AliMUONVCalibParam*>(bpValues.FindObject(bp->GetId())); if (!param) { param = new AliMUONCalibParamND(5, 1, bp->GetId(), 0); bpValues.Add(param); Int_t detElemId = AliMpDDLStore::Instance()->GetDEfromBus(bp->GetId()); AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); Int_t nchannels(0); for ( Int_t imanu = 0; imanu < bp->GetNofManus(); ++imanu ) { Int_t manuId = bp->GetManuId(imanu); nchannels += de->NofChannelsInManu(manuId); } param->SetValueAsDouble(0,2,sumn); param->SetValueAsDouble(0,3,nchannels); param->SetValueAsDouble(0,4,1); } Double_t sumw = sumn*(param->ValueAsDouble(0)/sumn+1.0/runnumbers.size()); Double_t sumw2 = 0.0; //(sumn-1)*ey*ey+sumw*sumw/sumn; param->SetValueAsDouble(0,0,sumw); param->SetValueAsDouble(0,1,sumw2); } } outfile << Form("RUN %09d",runNumber); for ( std::set<int>::const_iterator bit = buspatches.begin(); bit != buspatches.end(); ++bit ) { outfile << Form(" %4d",*bit); } outfile << endl; } outfile.close(); if ( bpValues.GetSize() == 0 ) { cout << Form("Great. No faulty bus patch (at the %g occupancy limit) found.",occLimit) << endl; gSystem->Exec(Form("rm %s.txt",outputBaseName)); } else { const char* name = "BPfailureRate"; AliMUONTrackerData* mpData = new AliMUONTrackerData(name,name,bpValues,2); mpData->SetDimensionName(0,name); TFile f(Form("%s.root",outputBaseName),"recreate"); mpData->Write(); f.Close(); cout << Form("Results are in %s.txt and %s.root",outputBaseName,outputBaseName) << endl; gSystem->Exec(Form("cat %s.txt",outputBaseName)); } } //______________________________________________________________________________ Double_t MeanHVValueForDCSAlias(TMap& hvMap, const char* hvChannel) { TPair* hvPair = static_cast<TPair*>(hvMap.FindObject(hvChannel)); if (!hvPair) { AliErrorGeneral("MeanHVValueForDCSAlias",Form("Did not find expected alias (%s)",hvChannel)); return 0.0; } else { TObjArray* values = static_cast<TObjArray*>(hvPair->Value()); if (!values) { AliErrorGeneral("MeanHVValueForDCSAlias",Form("Could not get values for alias %s",hvChannel)); return 0.0; } else { // find out min value, and makes a cut Float_t hv(0.0); Float_t n(0.0); TIter next(values); AliDCSValue* val; while ( ( val = static_cast<AliDCSValue*>(next()) ) ) { hv += val->GetFloat(); n += 1.0; } if (n>0.0) { hv /= n; return hv; } } return 0.0; } } }
30.694923
141
0.678143
[ "object", "vector", "3d" ]
1c0168ba6e8a672927a5e356b01d0e6026279251
716
hpp
C++
src/serial/contactpoint.hpp
divad-nhok/obsidian_fork
e5bee2b706f78249564f06c88a18be086b17c895
[ "MIT" ]
7
2015-01-04T13:50:24.000Z
2022-01-22T01:03:57.000Z
src/serial/contactpoint.hpp
divad-nhok/obsidian_fork
e5bee2b706f78249564f06c88a18be086b17c895
[ "MIT" ]
1
2018-08-16T00:46:58.000Z
2018-08-16T00:46:58.000Z
src/serial/contactpoint.hpp
divad-nhok/obsidian_fork
e5bee2b706f78249564f06c88a18be086b17c895
[ "MIT" ]
9
2016-08-31T05:42:00.000Z
2022-01-21T21:37:47.000Z
//! //! Contact Point Forward Model serialisation. //! //! \file serial/contactpoint.hpp //! \author Nahid Akbar //! \date May, 2014 //! \license Affero General Public License version 3 or later //! \copyright (c) 2014, NICTA //! #pragma once #include "datatype/datatypes.hpp" #include <string> namespace obsidian { namespace comms { std::string serialise(const ContactPointSpec& g); std::string serialise(const ContactPointParams& g); std::string serialise(const ContactPointResults& g); void unserialise(const std::string& s, ContactPointSpec& g); void unserialise(const std::string& s, ContactPointParams& g); void unserialise(const std::string& s, ContactPointResults& g); } }
23.866667
67
0.709497
[ "model" ]
1c0c965bd00ffba2b4bbdf635c957873f2e8b449
6,422
cpp
C++
src/ringmesh/geomodel/tools/geomodel_tools.cpp
ringmesh/RINGMesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
74
2017-10-26T15:40:23.000Z
2022-03-22T09:27:39.000Z
src/ringmesh/geomodel/tools/geomodel_tools.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
45
2017-10-26T15:54:01.000Z
2021-01-27T10:16:34.000Z
src/ringmesh/geomodel/tools/geomodel_tools.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
17
2018-03-27T11:31:24.000Z
2022-03-06T18:41:52.000Z
/* * Copyright (c) 2012-2018, Association Scientifique pour la Geologie et ses * Applications (ASGA). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ASGA nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ASGA BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://www.ring-team.org * * RING Project * Ecole Nationale Superieure de Geologie - GeoRessources * 2 Rue du Doyen Marcel Roubault - TSA 70605 * 54518 VANDOEUVRE-LES-NANCY * FRANCE */ #include <array> #include <iomanip> #include <iostream> #include <geogram/basic/command_line.h> #include <geogram/basic/progress.h> #include <ringmesh/basic/geometry.h> #include <ringmesh/geomodel/core/geomodel.h> #include <ringmesh/geomodel/core/geomodel_entity.h> #include <ringmesh/geomodel/core/geomodel_geological_entity.h> #include <ringmesh/geomodel/core/geomodel_mesh_entity.h> #include <ringmesh/geomodel/tools/geomodel_tools.h> #include <ringmesh/tetrahedralize/tetra_gen.h> /*! * @file Set of high level API functions */ namespace RINGMesh { template < index_t DIMENSION > void geomodel_tools_api copy_geomodel( const GeoModel< DIMENSION >& from, GeoModel< DIMENSION >& to ) { GeoModelBuilder< DIMENSION > to_builder( to ); to_builder.topology.copy_topology( from ); to_builder.geometry.copy_meshes( from ); to_builder.geology.copy_geology( from ); } template < index_t DIMENSION > void translate( GeoModel< DIMENSION >& geomodel, const vecn< DIMENSION >& translation_vector ) { GeoModelBuilder< DIMENSION > builder( geomodel ); for( auto v : range( geomodel.mesh.vertices.nb() ) ) { // Coordinates are not directly modified to // update the matching vertices in geomodel entities const auto& p = geomodel.mesh.vertices.vertex( v ); builder.geometry.set_mesh_entity_vertex( v, p + translation_vector ); } } void rotate( GeoModel3D& geomodel, const vec3& origin, const vec3& axis, double angle, bool degrees ) { if( length( axis ) < geomodel.epsilon() ) { Logger::err( "GeoModel", "Rotation around an epsilon length axis is impossible" ); return; } GEO::Matrix< 4, double > rot_mat{ rotation_matrix_about_arbitrary_axis( origin, axis, angle, degrees ) }; GeoModelBuilder3D builder( geomodel ); for( auto v : range( geomodel.mesh.vertices.nb() ) ) { const vec3& p = geomodel.mesh.vertices.vertex( v ); std::array< double, 4 > old{ { p[0], p[1], p[2], 1. } }; std::array< double, 4 > new_p{ { 0, 0, 0, 1. } }; GEO::mult( rot_mat, old.data(), new_p.data() ); ringmesh_assert( std::fabs( new_p[3] - 1. ) < global_epsilon ); builder.geometry.set_mesh_entity_vertex( v, vec3{ new_p.data() } ); } } void tetrahedralize( GeoModel3D& geomodel, index_t region_id, bool add_steiner_points ) { std::vector< std::vector< vec3 > > internal_vertices( geomodel.nb_regions() ); tetrahedralize( geomodel, region_id, add_steiner_points, internal_vertices ); } void tetrahedralize( GeoModel3D& geomodel, index_t region_id, bool add_steiner_points, const std::vector< std::vector< vec3 > >& internal_vertices ) { const std::string method{ GEO::CmdLine::get_arg( "algo:tet" ) }; if( region_id == NO_ID ) { Logger::out( "Info", "Using ", method ); GEO::ProgressTask progress( "Compute", geomodel.nb_regions() ); for( auto i : range( geomodel.nb_regions() ) ) { tetrahedralize( geomodel, i, add_steiner_points, internal_vertices ); progress.next(); } } else { std::unique_ptr< TetraGen > tetragen{ TetraGen::create( geomodel, region_id, method ) }; tetragen->set_boundaries( geomodel.region( region_id ), geomodel.wells() ); tetragen->set_internal_points( internal_vertices[region_id] ); bool status{ Logger::instance()->is_quiet() }; Logger::instance()->set_quiet( true ); tetragen->tetrahedralize( add_steiner_points ); Logger::instance()->set_quiet( status ); } // The GeoModelMesh should be updated, just erase everything // and it will be re-computed during its next access. geomodel.mesh.vertices.clear(); } template void geomodel_tools_api copy_geomodel( const GeoModel2D&, GeoModel2D& ); template void geomodel_tools_api translate( GeoModel2D&, const vec2& ); template void geomodel_tools_api copy_geomodel( const GeoModel3D&, GeoModel3D& ); template void geomodel_tools_api translate( GeoModel3D&, const vec3& ); } // namespace RINGMesh
39.158537
79
0.646528
[ "mesh", "geometry", "vector" ]
1c171bc435b3832c991d701d665474cab72ef2ac
9,657
cc
C++
app/GA/GAActionWalk.cc
hailongz/kk-game
56463c13347a5608e54ae0a069b0b9263f32d7c8
[ "MIT" ]
null
null
null
app/GA/GAActionWalk.cc
hailongz/kk-game
56463c13347a5608e54ae0a069b0b9263f32d7c8
[ "MIT" ]
null
null
null
app/GA/GAActionWalk.cc
hailongz/kk-game
56463c13347a5608e54ae0a069b0b9263f32d7c8
[ "MIT" ]
null
null
null
// // GAActionWalk.cpp // KKGame // // Created by zhanghailong on 2018/2/9. // Copyright © 2018年 kkmofang.cn. All rights reserved. // #include "kk-config.h" #include "GAActionWalk.h" #include "GABody.h" #include "GAShape.h" #include <chipmunk/chipmunk.h> namespace kk { namespace GA { IMP_SCRIPT_CLASS_BEGIN_NOALLOC(&Action::ScriptClass, ActionWalk, GAActionWalk) static kk::script::Property propertys[] = { {"target",(kk::script::Function) &ActionWalk::duk_target,(kk::script::Function) &ActionWalk::duk_setTarget}, }; kk::script::SetProperty(ctx, -1, propertys, sizeof(propertys) / sizeof(kk::script::Property)); IMP_SCRIPT_CLASS_END KK_IMP_ELEMENT_CREATE(ActionWalk) ActionWalk::ActionWalk(kk::Document * document,kk::CString name, kk::ElementKey elementId) :Action(document,name,elementId) ,x(0),y(0),speed(0),angle(0),_hasUpdate(false) ,_landing(true),_enabled(true),duration(0),_startTimeInterval(0) ,_navigateState(ActionWalkNavigateStateNone){ } void ActionWalk::exec(Context * context) { Action::exec(context); if(_navigateState == ActionWalkNavigateStateNavigating) { if(_navigateTimeIterval == 0) { _navigateTimeIterval = context->current(); } if(context->current() - _navigateTimeIterval > 300) { _navigateState = ActionWalkNavigateStateNone; Body * a = body(); if(a != nullptr && !_navigateVelocitys.empty()) { ::cpBody * cpBody = a->cpBody(); if(cpBody) { cpBodySetVelocity(cpBody, {0,0}); } } } else { return; } } Body * tBody = target.as<Body>(); if(tBody) { Point p = tBody->position(); if(p.x != this->x || p.y != this->y) { this->x = p.x; this->y = p.y; _hasUpdate = true; } if(_startTimeInterval == 0) { _startTimeInterval = context->current(); } if(!_landing && duration >0 && context->current() - _startTimeInterval >= duration) { Body * body = this->body(); if(body) { kk::Strong vv = new kk::ElementEvent(); kk::ElementEvent * e = vv.as<kk::ElementEvent>(); e->element = body; body->emit("done", e); } _landing = true; } } if(_hasUpdate) { Body * body = this->body(); if(body) { ::cpBody * cpBody = body->cpBody(); if(cpBody) { if(_enabled && speed > 0) { Point p = body->position(); cpVect v = cpvmult(cpvnormalize({this->x - p.x,this->y - p.y}), speed); cpBodySetVelocity(cpBody, v); } else { cpBodySetVelocity(cpBody, {0,0}); } _hasUpdate = false; } } } if(!_landing && speed > 0.0f && _enabled && tBody == nullptr) { Body * body = this->body(); if(body) { Point p = body->position(); Float v = cpvlength({this->x - p.x,this->y - p.y}); if(v > _distance || v < 5) { _landing = true; ::cpBody * cpBody = body->cpBody(); if(cpBody) { cpBodySetVelocity(cpBody, {0,0}); cpBodySetPosition(cpBody, {this->x,this->y}); } p.x = this->x; p.y = this->y; body->setPosition(p); kk::Strong vv = new kk::ElementEvent(); kk::ElementEvent * e = vv.as<kk::ElementEvent>(); e->element = body; body->emit("done", e); } else { _distance = v; } } } Body * body = this->body(); if(body) { _lastPosition = body->position(); } } void ActionWalk::changedKey(String& key) { Action::changedKey(key); if(key == "speed") { speed = floatValue(get(key.c_str())); } else if(key == "x") { this->x = floatValue(get(key.c_str())); } else if(key == "y") { this->y = floatValue(get(key.c_str())); } else if(key == "enabled") { _enabled = booleanValue(get(key.c_str())); } else if(key == "duration") { duration = floatValue(get(key.c_str())); _startTimeInterval = 0; } else if(key == "target") { kk::ElementKey elementId = int64Value(get(key.c_str())); kk::Document * doc = document(); if(doc) { kk::Strong e = doc->element(elementId); target = e.as<Body>(); } else { target = (kk::Object *) nullptr; } } _hasUpdate = true; _landing = false; _distance = MAXFLOAT; } duk_ret_t ActionWalk::duk_target(duk_context * ctx) { kk::script::PushObject(ctx, target.get()); return 1; } duk_ret_t ActionWalk::duk_setTarget(duk_context * ctx) { int top = duk_get_top(ctx); if(top >0 && duk_is_object(ctx, -top)) { kk::Object * v = kk::script::GetObject(ctx, -top); if(v != nullptr) { Body * body = dynamic_cast<kk::GA::Body *>(v); if(body != nullptr) { target = body; } else { target = (kk::Object *) nullptr; } } else { target = (kk::Object *) nullptr; } } return 0; } kk::Boolean ActionWalk::inCollisionShape(Shape * a, Shape * b,Point n) { kk::Boolean v = Action::inCollisionShape(a, b,n); if(a->body() == body()) { v = inCollisionShape(b,n) && v; } return v; } void ActionWalk::outCollisionShape(Shape * a, Shape * b,Point n) { Action::outCollisionShape(a, b, n); if(a->body() == body()) { outCollisionShape(b,n); } } kk::Boolean ActionWalk::inCollisionShape(Shape * shape,Point n) { Body * a = body(); Body * b = shape->body(); if(a && b) { cpVect p = cpvmult(cpv(-n.x,-n.y), 0.8f * speed); a->setPosition(_lastPosition); ::cpBody * cpBody = a->cpBody(); if(cpBody) { cpBodySetPosition(cpBody, {_lastPosition.x,_lastPosition.y}); cpBodySetVelocity(cpBody, {0,0}); cpBodyApplyImpulseAtLocalPoint(cpBody, p, {0,0}); p = cpvmult(cpvnormalize({this->x - _lastPosition.x,this->y - _lastPosition.y}), 0.8f * speed); cpBodyApplyImpulseAtLocalPoint(cpBody, p, {0,0}); } } _navigateState = ActionWalkNavigateStateNavigating; _navigateTimeIterval = 0; return true; } void ActionWalk::outCollisionShape(Shape * shape,Point n) { } } }
33.185567
120
0.364192
[ "object", "shape" ]
1c2b4378c53e2c1a7fb506edd72cce845486c068
2,018
cpp
C++
src/test.trap.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.trap.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.trap.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
/** * @file test.trap.cpp * @author Team Rogue++ * @date December 08, 2016 * * @brief Member definitions for the TrapTest class */ #include <exception> #include <iostream> #include <string> #include <vector> #include "include/armor.h" #include "include/level.h" #include "include/playerchar.h" #include "include/trap.h" #include "test.testable.h" /** * @brief Tests the Trap class. */ class TrapTest : public Testable { public: TrapTest(){} void test(){ comment("Commencing Trap tests..."); try { Trap trapCon = Trap(Coord(0,0), 0, false); assert(true, "Created Trap"); } catch (const std::exception& e) { assert(false, "Failure creating Trap"); } std::vector<Trap> traps; for (int i = 0 ; i < 6 ; ++i) { traps.push_back(Trap(Coord(0,0), i, true)); } PlayerChar* player = new PlayerChar(Coord(0,0), "Player Trap"); player->setDexterity(-5); Level* level = new Level(1, player); level->clear(); level->registerMob(player); Armor* armor = new Armor(Coord(0,0), Item::FLOOR, 1); armor->setEnchantment(1); player->equipArmor(armor); level = traps[0].activate(player, level); assert(level->getDepth() == 2, "Door Trap"); level->clear(); traps[1].activate(player, level); assert(armor->getEnchantment() == 0, "Rust Trap"); traps[2].activate(player, level); assert(player->hasCondition(PlayerChar::SLEEPING), "Sleep Trap"); player->clearConditions(); player->setCurrentHP(10); traps[3].activate(player, level); assert(player->hasCondition(PlayerChar::IMMOBILIZED), "Bear Trap"); player->clearConditions(); player->setCurrentHP(10); Coord position = player->getLocation(); traps[4].activate(player, level); assert(position != player->getLocation(), "Teleport Trap"); int playerHP = player->getHP(); traps[5].activate(player, level); int deltaHP = playerHP - player->getHP(); assert(deltaHP >= 1 && deltaHP <= 6, "Dart Trap"); comment("Finished Trap tests."); } };
24.313253
70
0.644202
[ "vector" ]
1c2d555d30849e81ceb1bc370c38a92a13d86d76
905
cpp
C++
uri-online-judge/1244/main.cpp
olegon/online-judges
4ec27c8940ae492ce71aec0cc9ed944b094bce55
[ "MIT" ]
12
2017-11-30T11:10:45.000Z
2022-01-26T23:49:19.000Z
uri-online-judge/1244/main.cpp
olegon/online-judges
4ec27c8940ae492ce71aec0cc9ed944b094bce55
[ "MIT" ]
null
null
null
uri-online-judge/1244/main.cpp
olegon/online-judges
4ec27c8940ae492ce71aec0cc9ed944b094bce55
[ "MIT" ]
4
2017-11-25T03:13:32.000Z
2019-08-16T08:08:10.000Z
/* Ordenação por Tamanho https://www.urionlinejudge.com.br/judge/pt/problems/view/1244 */ #include <iostream> #include <sstream> #include <vector> #include <algorithm> using namespace std; bool compare_by_size(string a, string b); int main (void) { int N; string LINE; cin >> N; cin.ignore(1); for (int i = 0; i < N; i++) { string word; vector<string> words; getline(cin, LINE); istringstream ss(LINE); while (getline(ss, word, ' ')) { words.push_back(word); } stable_sort(words.begin(), words.end(), compare_by_size); for (size_t i = 0; i < words.size(); i++) { if (i != 0) { cout << " "; } cout << words[i]; } cout << endl; } return 0; } bool compare_by_size(string a, string b) { return a.size() > b.size(); }
16.759259
65
0.520442
[ "vector" ]
1c2fab9ad2f96039d5cc67e2c55945130359974d
4,855
cpp
C++
mex/convn_cuda/tests/gtest_cudautils.cpp
dgoodwin208/ExSeqProcessing
cd7f8ff461af16aad22ac033d2cbd5f0aa935628
[ "MIT" ]
7
2020-06-03T21:12:35.000Z
2022-02-03T02:36:20.000Z
mex/convn_cuda/tests/gtest_cudautils.cpp
RuihanZhang2015/ExSeqProcessing
c9c3719b9e583def8a6401d16698363c6fe45574
[ "MIT" ]
2
2020-05-15T20:00:30.000Z
2020-05-15T20:01:00.000Z
mex/convn_cuda/tests/gtest_cudautils.cpp
RuihanZhang2015/ExSeqProcessing
c9c3719b9e583def8a6401d16698363c6fe45574
[ "MIT" ]
5
2020-06-01T18:50:18.000Z
2021-09-15T18:39:28.000Z
#include "gtest/gtest.h" #include "convn.h" #include "cudnnutils.h" #include <vector> #include <cstdint> #include <random> namespace { class ConvnTest : public ::testing::Test { protected: ConvnTest() { } virtual ~ConvnTest() { } }; //Generate uniform numbers [0,1) static void initImage(float* image, int imageSize) { static unsigned seed = 123456789; for (int index = 0; index < imageSize; index++) { seed = ( 1103515245 * seed + 12345 ) & 0xffffffff; image[index] = float(seed)*2.3283064e-10; //2^-32 } } static void generateStrides(const int* dimA, int* strideA, int nbDims, bool isNchw) { if (isNchw) { strideA[nbDims-1] = 1 ; for(int d = nbDims-2 ; d >= 0 ; d--) { strideA[d] = strideA[d+1] * dimA[d+1] ; } } else { strideA[1] = 1; strideA[nbDims-1] = strideA[1]*dimA[1]; for(int d = nbDims-2 ; d >= 2 ; d--) { strideA[d] = strideA[d+1] * dimA[d+1] ; } strideA[0] = strideA[2]*dimA[2]; } } TEST_F(ConvnTest, ConvnSampleTest) { // generate params int algo = 0; int benchmark = 0; int dimA[] = {1, 8, 32, 32}; int filterdimA[] = {8, 8, 3, 3}; int filtersize = filterdimA[0]*filterdimA[1]*filterdimA[2]*filterdimA[3]; int strideA[] = {8192, 1024, 32, 1}; int nbDims = 4; bool isNchw = true; generateStrides(dimA, strideA, nbDims, isNchw); int insize = strideA[0]*dimA[0]; int outdimA[] = {1, 8, 30, 30}; outdimA[0] = dimA[0]; int outstrideA[] = {7200, 900, 30, 1}; int outsize = outstrideA[0]*outdimA[0]; // Create a random filter and image float* hostI; float* hostF; float* hostO; hostI = (float*)calloc (insize, sizeof(hostI[0]) ); hostF = (float*)calloc (filtersize, sizeof(hostF[0]) ); hostO = (float*)calloc (outsize, sizeof(hostO[0]) ); // Create two random images initImage(hostI, insize); initImage(hostF, filtersize); cudnnutils::conv_handler(hostI, hostF, hostO, algo, dimA, filterdimA, benchmark); //TODO test the convolution output hostO } TEST_F(ConvnTest, ConvnBasicTest) { // process args const int batch_size = 1; const int channels = 3; const int height = 300; const int width = 300; const int image_bytes = batch_size * channels * height * width * sizeof(float); std::cout << "Creating image" << std::endl; float image[batch_size][channels][height][width]; for (int batch = 0; batch < batch_size; ++batch) { for (int channel = 0; channel < channels; ++channel) { for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { // image[batch][channel][row][col] = std::rand(); image[batch][channel][row][col] = 0.0f; } } } } std::cout << "Image created" << std::endl; const int kernel_channels = 3; const int kernel_height = 3; const int kernel_width = 3; float kernel[kernel_height][kernel_width][kernel_channels]; for (int channel = 0; channel < kernel_channels; ++channel) { for (int row = 0; row < kernel_height; ++row) { for (int col = 0; col < kernel_width; ++col) { // image[batch][channel][row][col] = std::rand(); kernel[channel][row][col] = 0.0f; } } } // toy kernel // clang-format off //float kernel[kernel_height][kernel_width] = { //{1, 1, 1}, //{1, -8, 1}, //{1, 1, 1} //}; // clang-format on std::cout << "Kernel Created" << std::endl; //// copy into higher dim, once for each channel, once for each output feature map (out_channel) //float h_kernel[batch_size][channels][kernel_height][kernel_width]; //for (int out_channel = 0; out_channel < out_channels; ++out_channel) { //for (int channel = 0; channel < channels; ++channel) { //for (int row = 0; row < kernel_height; ++row) { //for (int column = 0; column < kernel_width; ++column) { //h_kernel[out_channel][channel][row][column] = kernel[row][column]; //} //} //} //} float* h_output; h_output = cudautils::convn((float *) image, channels, height, width, (float *) kernel, kernel_channels, kernel_height, kernel_width); for (int batch = 0; batch < batch_size; ++batch) { for (int channel = 0; channel < channels; ++channel) { for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { // image[batch][channel][row][col] = std::rand(); ASSERT_EQ(image[batch][channel][row][col], 0.0f); } } } } } } // namespace
31.322581
138
0.552832
[ "vector" ]
1c359baffd7d7b2ace07d6992f17d385d5934ad8
406
cpp
C++
src/characters/shape.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
7
2016-12-19T21:13:41.000Z
2021-03-19T11:14:29.000Z
src/characters/shape.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
1
2017-06-17T12:14:08.000Z
2017-06-17T14:47:20.000Z
src/characters/shape.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
3
2017-11-07T12:22:10.000Z
2020-04-30T20:48:59.000Z
#include "shape.hpp" #include "../displayobject.hpp" #include "../util.hpp" #include <iostream> using namespace libapt; void Shape::Parse(uint8_t *& iter) { m_bounds = read<glm::vec4>(iter); m_geometryId = read<uint32_t>(iter); } void Shape::Update(const Transformation& t, std::shared_ptr<DisplayObject> dObj) { assert(m_geometry); if (t.visible) { m_geometry->Draw(t,m_owner); } else { } }
16.24
80
0.689655
[ "shape" ]
1c404c09f908e9fbabdba741029ff0c9bdada39a
820
hpp
C++
ROBOT-GRASP/include/MyDraw.hpp
IDLER1229/ROBOT-GRASP
f83590c0552da3058d98b18e6174235b5eb10939
[ "MIT" ]
null
null
null
ROBOT-GRASP/include/MyDraw.hpp
IDLER1229/ROBOT-GRASP
f83590c0552da3058d98b18e6174235b5eb10939
[ "MIT" ]
null
null
null
ROBOT-GRASP/include/MyDraw.hpp
IDLER1229/ROBOT-GRASP
f83590c0552da3058d98b18e6174235b5eb10939
[ "MIT" ]
null
null
null
/************************************************************************/ /* namespace cv */ /************************************************************************/ #include "Opencv.hpp" class Draw { public: virtual void drawRotateRect(Mat& src, RotatedRect& rr) = 0; virtual void drawConvexHull(Mat& src, PointSet& hull, Scalar color) = 0; virtual void drawBlack(SegmentSet& blackRegions, Mat& disp, Vec3b& color) = 0; virtual void draw(SegmentSet& segment, Mat& disp, vector<Vec3b>& colors) = 0; virtual void drawBoundBox(SegmentSet& segment, vector<double>& distance, Mat& color, Mat& depth, string categoryName) = 0; virtual void drawRegions(SegmentSet& segment, Mat& color, Mat& depth, Mat& disp) = 0; virtual void drawSobel(Mat& depth) = 0; };
41
123
0.543902
[ "vector" ]
1c4d676cfc1140765859d7ac71bc4e379bff91cb
12,719
cpp
C++
src/ecckd/solve_adept.cpp
ecmwf-ifs/ecckd
6115f9b8e29a55cb0f48916857bdc77fec41badd
[ "Apache-2.0" ]
null
null
null
src/ecckd/solve_adept.cpp
ecmwf-ifs/ecckd
6115f9b8e29a55cb0f48916857bdc77fec41badd
[ "Apache-2.0" ]
null
null
null
src/ecckd/solve_adept.cpp
ecmwf-ifs/ecckd
6115f9b8e29a55cb0f48916857bdc77fec41badd
[ "Apache-2.0" ]
null
null
null
// solve_adept.cpp - Optimize look-up table using Adept library // // Copyright (C) 2020- ECMWF. // // This software is licensed under the terms of the Apache Licence Version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Author: Robin Hogan // Email: r.j.hogan@ecmwf.int #include "solve_adept.h" #include "calc_cost_function_lw.h" #include "calc_cost_function_sw.h" #include "Error.h" #include "Timer.h" static const Real MIN_X = -1.0e20; void calc_total_optical_depth(CkdModel<true>& ckd_model, const LblFluxes& lbl1, aArray3D& optical_depth, bool first_call) { int nprof = lbl1.pressure_hl_.dimension(0); int nlev = lbl1.pressure_hl_.dimension(1)-1; optical_depth.resize(nprof,nlev,ckd_model.ng()); optical_depth = 0.0; // Rayleigh scattering if (ckd_model.is_sw()) { optical_depth += ckd_model.calc_rayleigh_optical_depth(lbl1.pressure_hl_); } Matrix temperature_fl, p_x_t; p_x_t = lbl1.temperature_hl_ * lbl1.pressure_hl_; temperature_fl = (p_x_t(__,range(0,end-1)) + p_x_t(__,range(1,end))) / (lbl1.pressure_hl_(__,range(0,end-1)) + lbl1.pressure_hl_(__,range(1,end))); for (int igas = 0; igas < ckd_model.molecules.size(); ++igas) { if (lbl1.gas_mapping(igas) >= 0) { if (first_call) { LOG << " Computing CKD optical depth of \"" << ckd_model.molecules[igas] << "\"\n"; } optical_depth += ckd_model.calc_optical_depth(ckd_model.molecules[igas], lbl1.pressure_hl_, temperature_fl, lbl1.vmr_fl_(__,lbl1.gas_mapping(igas),__)); } else { if (ckd_model.single_gas(igas).conc_dependence == NONE) { if (first_call) { LOG << " Computing CKD optical depth of background gases in \"" << ckd_model.molecules[igas] << "\"\n"; } optical_depth += ckd_model.calc_optical_depth(ckd_model.molecules[igas], lbl1.pressure_hl_, temperature_fl); } else { if (first_call) { LOG << " Skipping \"" << ckd_model.molecules[igas] << "\": not present in LBL file\n"; } } } } } Real calc_cost_function_and_gradient(CkdModel<true>& ckd_model, std::vector<LblFluxes>& lbl, Vector gradient, Real flux_weight, Real flux_profile_weight, Real broadband_weight, Real spectral_boundary_weight, Real negative_od_penalty, Array3D* relative_ckd_flux_dn, Array3D* relative_ckd_flux_up) { static bool first_call = true; // data.timer.start(data.rt_id); if (first_call) { LOG << " First calculation of cost function and gradient\n"; } ADEPT_ACTIVE_STACK->new_recording(); aReal cost = 0.0; Vector cost_fn_per_band(maxval(lbl[0].iband_per_g)+1); cost_fn_per_band = 0.0; // Loop over training scenes for (int ilbl = 0; ilbl < lbl.size(); ++ilbl) { if (first_call) { LOG << " LBL training scene " << ilbl << "\n"; } LblFluxes& lbl1 = lbl[ilbl]; int nprof = lbl1.pressure_hl_.dimension(0); int nlev = lbl1.pressure_hl_.dimension(1)-1; aArray3D optical_depth; calc_total_optical_depth(ckd_model, lbl1, optical_depth, first_call); int nnegative = count(optical_depth < 0.0); if (nnegative > 0) { aArray3D penalty(optical_depth.dimensions()); penalty.where(optical_depth < 0.0) = either_or(optical_depth*optical_depth, 0.0); aReal new_cost = negative_od_penalty * sum(penalty); cost += new_cost; optical_depth.where(optical_depth < 0.0) = 0.0; LOG << " Fixing negative optical depth at " << nnegative << " points: added " << new_cost << " to cost function\n"; } // If the pointers relative_ckd_flux_[dn|up] are not NULL, then // they point to 3D arrays of fluxes to be subtracted from the CKD // calculations. But since each profile is analyzed in turn, we // need to obtain a pointer to the relevant profile, or NULL. Matrix* rel_ckd_flux_dn = 0; Matrix* rel_ckd_flux_up = 0; Matrix rel_ckd_flux_dn_ref, rel_ckd_flux_up_ref; if (relative_ckd_flux_dn) { rel_ckd_flux_dn = &rel_ckd_flux_dn_ref; rel_ckd_flux_up = &rel_ckd_flux_up_ref; } // Loop over profiles in one scene for (int iprof = 0; iprof < nprof; ++iprof) { Vector layer_weight = sqrt(lbl1.pressure_hl_(iprof,range(1,end)))-sqrt(lbl1.pressure_hl_(iprof,range(0,end-1))); layer_weight /= sum(layer_weight); // Make a soft link to a slice of the relative-to fluxes if (relative_ckd_flux_dn) { rel_ckd_flux_dn_ref >>= (*relative_ckd_flux_dn)[iprof]; rel_ckd_flux_up_ref >>= (*relative_ckd_flux_up)[iprof]; } if (!lbl1.is_sw()) { Vector spectral_flux_dn_surf, spectral_flux_up_toa; if (!lbl1.spectral_flux_dn_surf_.empty()) { spectral_flux_dn_surf >>= lbl1.spectral_flux_dn_surf_(iprof,__); spectral_flux_up_toa >>= lbl1.spectral_flux_up_toa_(iprof,__); } cost += calc_cost_function_ckd_lw(lbl1.pressure_hl_(iprof,__), lbl1.planck_hl_(iprof,__,__), lbl1.surf_emissivity_(iprof,__), lbl1.surf_planck_(iprof,__), optical_depth(iprof,__,__), lbl1.spectral_flux_dn_(iprof,__,__), lbl1.spectral_flux_up_(iprof,__,__), lbl1.spectral_heating_rate_(iprof,__,__), spectral_flux_dn_surf, spectral_flux_up_toa, flux_weight, flux_profile_weight, broadband_weight, spectral_boundary_weight, layer_weight, rel_ckd_flux_dn, rel_ckd_flux_up, lbl1.iband_per_g); } else { // LOG << " " << iprof; //Real tsi_scaling = sum(lbl1.spectral_flux_dn_(iprof,0,__)) // / (lbl1.mu0_(iprof) * sum(ckd_model.solar_irradiance())); Real tsi_scaling = lbl1.tsi_ / sum(ckd_model.solar_irradiance()); Vector spectral_flux_dn_surf, spectral_flux_up_toa; if (!lbl1.spectral_flux_dn_surf_.empty()) { spectral_flux_dn_surf >>= lbl1.spectral_flux_dn_surf_(iprof,__); spectral_flux_up_toa >>= lbl1.spectral_flux_up_toa_(iprof,__); } cost += calc_cost_function_ckd_sw(lbl1.mu0_(iprof), lbl1.pressure_hl_(iprof,__), tsi_scaling * ckd_model.solar_irradiance(), lbl1.effective_spectral_albedo_, optical_depth(iprof,__,__), lbl1.spectral_flux_dn_(iprof,__,__), lbl1.spectral_flux_up_(iprof,__,__), lbl1.spectral_heating_rate_(iprof,__,__), spectral_flux_dn_surf, spectral_flux_up_toa, flux_weight, flux_profile_weight, broadband_weight, spectral_boundary_weight, layer_weight, rel_ckd_flux_dn, rel_ckd_flux_up, lbl1.iband_per_g, cost_fn_per_band); } } } // data.timer.start(data.autodiff_id); cost.set_gradient(1.0); ADEPT_ACTIVE_STACK->reverse(); ckd_model.x.get_gradient(gradient); first_call = false; // LOG << cost << " " << maxval(fabs(gradient)) << "\n"; // LOG << " Cost per band = " << cost_fn_per_band << "\n"; // data.timer.start(data.minimizer_id); return value(cost); } struct MyData { MyData() { minimizer_id = timer.new_activity("minimizer"); background_id = timer.new_activity("a-priori"); rt_id = timer.new_activity("radiative transfer"); // autodiff_id = timer.new_activity("automatic differentiation"); } CkdModel<true>* ckd_model; std::vector<LblFluxes>* lbl; Real flux_weight, flux_profile_weight, broadband_weight, prior_error; Real spectral_boundary_weight, negative_od_penalty; Array3D* relative_ckd_flux_dn; Array3D* relative_ckd_flux_up; Timer timer; int minimizer_id, background_id, rt_id, autodiff_id; }; class CkdOptimizable : public adept::Optimizable { public: virtual Real calc_cost_function(const Vector& x) { Vector gradient(x.size()); return calc_cost_function_gradient(x, gradient); } virtual Real calc_cost_function_gradient(const Vector& xdata, Vector gradient) { aVector& x = data.ckd_model->x; for (int ix = 0; ix < x.size(); ix++) { if (xdata[ix] > MIN_X) { x(ix) = exp(xdata[ix]); } else { x(ix) = 0.0; } } data.timer.start(data.rt_id); Real J = calc_cost_function_and_gradient(*(data.ckd_model), *(data.lbl), gradient, data.flux_weight, data.flux_profile_weight, data.broadband_weight, data.spectral_boundary_weight, data.negative_od_penalty, data.relative_ckd_flux_dn, data.relative_ckd_flux_up); data.timer.start(data.background_id); // Prior contribution //#define OLD_PRIOR 1 #ifdef OLD_PRIOR Vector gradient_prior = (1.0/(data.prior_error*data.prior_error)) * (xdata-data.ckd_model->x_prior); Real J_prior = 0.5*sum((xdata-data.ckd_model->x_prior) * gradient_prior); #else Vector gradient_prior(data.ckd_model->nx()); Real J_prior = data.ckd_model->calc_background_cost_function(xdata-data.ckd_model->x_prior, gradient_prior); #endif for (int ix = 0; ix < data.ckd_model->nx(); ix++) { if (xdata[ix] > MIN_X) { gradient[ix] = gradient(ix) * value(x(ix)) + gradient_prior(ix); } else { gradient[ix] = 0.0; } } // Sometimes tiny gradients can cause problems in the minimization // - set to zero gradient.where(fabs(gradient) < 1.0e-80) = 0.0; J += J_prior; /// std::cout << J << " " << J_prior << " infinity norm " << maxval(fabs(gradient)) << " " << maxval(fabs(gradient_prior)) << std::endl; data.timer.start(data.minimizer_id); return J; } virtual void report_progress(int niter, const Vector& x, Real cost, Real gnorm) { LOG << "Iteration " << niter << ": cost function = " << cost << ", gradient norm = " << gnorm << "\n"; } virtual bool provides_derivative(int order) { return (order>=0 && order <= 1); } MyData data; }; adept::MinimizerStatus solve_adept(CkdModel<true>& ckd_model, std::vector<LblFluxes>& lbl, Real flux_weight, Real flux_profile_weight, Real broadband_weight, Real spectral_boundary_weight, Real prior_error, int max_iterations, Real convergence_criterion, Real negative_od_penalty, bool is_bounded, Array3D* relative_ckd_flux_dn, Array3D* relative_ckd_flux_up) { int status=0; CkdOptimizable ckd_optimizable; adept::Minimizer minimizer(MINIMIZER_ALGORITHM_LIMITED_MEMORY_BFGS); minimizer.set_max_iterations(max_iterations); minimizer.set_max_step_size(2.0); minimizer.set_converged_gradient_norm(convergence_criterion); // State vector holds the logarithm of the molar absorption coefficients Vector x(ckd_model.nx()); // Values of zero are held at zero x = MIN_X; x.where(ckd_model.x > 0.0) = log(ckd_model.x.inactive_link()); ckd_model.x_prior = x; Vector x_min, x_max; if (is_bounded) { adept::minimizer_initialize_bounds(ckd_model.nx(), x_min, x_max); x_min.where(ckd_model.x_min > 0.0) = log(ckd_model.x_min.inactive_link()); x_max.where(ckd_model.x_max > 0.0) = log(ckd_model.x_max.inactive_link()); // For g points where the minimum absorption is zero, we set it to // a more realistic value, which is twice as far on the negative // side (in log space) as x_max is from x x_min.where(ckd_model.x_min == 0 && ckd_model.x > 0.0 && ckd_model.x_max > 0.0) = 3.0*x - 2.0*x_max; } MyData& data = ckd_optimizable.data; data.ckd_model = &ckd_model; data.lbl = &lbl; data.flux_weight=flux_weight; data.flux_profile_weight=flux_profile_weight; data.broadband_weight=broadband_weight; data.spectral_boundary_weight = spectral_boundary_weight; data.prior_error = prior_error; data.relative_ckd_flux_dn = relative_ckd_flux_dn; data.relative_ckd_flux_up = relative_ckd_flux_up; data.negative_od_penalty = negative_od_penalty; LOG << "Optimizing coefficients with Adept LBFGS algorithm: max iterations = " << max_iterations << ", convergence criterion = " << convergence_criterion << "\n"; LOG << " CKD model interpolation is "; if (ckd_model.logarithmic_interpolation) { LOG << "LOGARITHMIC\n"; } else { LOG << "LINEAR\n"; } data.timer.start(data.minimizer_id); // Call Adept minimizer if (is_bounded) { LOG << " Minimization is bounded\n"; LOG << " number bounded below: " << count(ckd_model.x_min>0) << ", above: " << count(ckd_model.x_max>0) << ", out of non-zero elements: " << count(ckd_model.x > 0) << "\n"; return minimizer.minimize(ckd_optimizable, x, x_min, x_max); } else { LOG << " Minimization is unbounded\n"; return minimizer.minimize(ckd_optimizable, x); } }
34.008021
141
0.680085
[ "vector", "model", "3d" ]
1c50d098fe2b97acbbf6d6248b5c0637901bfd90
1,412
cpp
C++
codechef/starters18/c.cpp
punnapavankumar9/coding-platforms
264803330f5b3857160ec809c0d79cba1aa479a3
[ "MIT" ]
null
null
null
codechef/starters18/c.cpp
punnapavankumar9/coding-platforms
264803330f5b3857160ec809c0d79cba1aa479a3
[ "MIT" ]
null
null
null
codechef/starters18/c.cpp
punnapavankumar9/coding-platforms
264803330f5b3857160ec809c0d79cba1aa479a3
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> #define endl "\n" typedef long long ll; typedef unsigned long long ull; const int mod = 1e9 + 7; using namespace std; vector<int> pol; bool isPol(string s){ int n = s.size(); for(int i = 0; i < n/2; i++){ if(s[i] != s[n-i-1]) return false; } return true; } void pre(){ string s; for(int i = 1; i <= 1000; i++){ s = ""; int temp = i; while(temp){ if(temp & 1) s += '1'; else s+= '0'; temp >>= 1; } if(isPol(s)){ pol.push_back(i); } } } int main(){ cin.tie(0)->sync_with_stdio(false);cout.tie(0); pre(); int t; cin >> t; while(t--){ int n; cin >> n; vector<int> arr; int pr = pol.size()-1; while(n){ int l = 0; int r = pr; int res = 0; while(l <= r){ int mid = (l + r)/2; if(pol[mid] <= n){ res = mid; l = mid + 1; }else{ r = mid -1; } } n -= pol[res]; pr = res; arr.push_back(pol[res]); } cout << arr.size() << "\n"; for(int num : arr){ cout << num << " "; } cout << " \n"; } return 0; }
20.463768
51
0.365439
[ "vector" ]
1c53c314d479081d567fc3e309fb5e18e16fe139
8,791
cpp
C++
code/AzureDeviceManagementCommon/BaseHandler.cpp
imingc/azure-client-tools
1a5d4846956c2c7aae5ed4ebf4020b6e2d5142c4
[ "MIT" ]
null
null
null
code/AzureDeviceManagementCommon/BaseHandler.cpp
imingc/azure-client-tools
1a5d4846956c2c7aae5ed4ebf4020b6e2d5142c4
[ "MIT" ]
null
null
null
code/AzureDeviceManagementCommon/BaseHandler.cpp
imingc/azure-client-tools
1a5d4846956c2c7aae5ed4ebf4020b6e2d5142c4
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "stdafx.h" #include "BaseHandler.h" #include "..\AzureDeviceManagementCommon\DMConstants.h" #include "..\AzureDeviceManagementCommon\Plugins\PluginConstants.h" using namespace Microsoft::Azure::DeviceManagement::Utils; using namespace std; namespace Microsoft { namespace Azure { namespace DeviceManagement { namespace Common { BaseHandler::BaseHandler( const std::string& id, const ReportedSchema& reportedSchema) : _id(id), _isConfigured(false), _reportedSchema(reportedSchema), _iPluginHost(nullptr), _handlerConfig(Json::Value()) { _metaData = make_shared<MetaData>(); _metaData->SetDeploymentId(JsonDeploymentIdUnspecified); SetDeploymentStatus(DeploymentStatus::eNotStarted); } bool BaseHandler::IsRefreshing( const Json::Value& desiredConfig) const { if (desiredConfig.isNull()) { throw DMException(ErrorInvalidJsonFormat); } if (desiredConfig.isString()) { return desiredConfig.asString() == JsonRefreshing; } return false; } std::string BaseHandler::GetHandlerType() const { return JsonHandlerTypeRaw; } string BaseHandler::GetId() const { return _id; } bool BaseHandler::IsConfigured() const { return _isConfigured; } void BaseHandler::FinalizeAndReport( Json::Value& reportedObject, std::shared_ptr<ReportedErrorList> errorList) { DeploymentStatus deploymentStatus = errorList->Count() == 0 ? DeploymentStatus::eSucceeded : DeploymentStatus::eFailed; _metaData->SetDeploymentStatus(deploymentStatus); reportedObject[JsonMeta] = _metaData->ToJsonObject(); reportedObject[JsonErrorList] = errorList->ToJsonObject(); _iPluginHost->Report(GetId().c_str(), deploymentStatus, reportedObject); } void BaseHandler::SignalRefreshing() { _iPluginHost->Report(GetId().c_str(), DeploymentStatus::ePending, Json::Value(JsonRefreshing)); } void BaseHandler::SetConfig( const Json::Value& handlerConfig) { _handlerConfig = handlerConfig; } Json::Value BaseHandler::GetConfig() const { return _handlerConfig; } void BaseHandler::Stop() { // default implementation. } DeploymentStatus BaseHandler::GetDeploymentStatus() const { return _metaData->GetDeploymentStatus(); } void BaseHandler::SetDeploymentStatus( DeploymentStatus deploymentStatus) { _metaData->SetDeploymentStatus(deploymentStatus); Json::Value root(Json::objectValue); root[JsonMeta] = _metaData->ToJsonObject(JsonDeploymentStatus); _deploymentStatusJson = root; } Json::Value BaseHandler::GetDeploymentStatusJson() const { return _deploymentStatusJson; } ReportedSchema BaseHandler::GetReportedSchema() const { return _reportedSchema; } OperationModel BaseHandler::TryGetOptionalSinglePropertyOpParameter( const Json::Value& groupRoot, const std::string& subGroupdId) { TRACELINEP(LoggingLevel::Verbose, "properties to search = ", groupRoot.toStyledString().c_str()); TRACELINEP(LoggingLevel::Verbose, "property to find = ", subGroupdId.c_str()); OperationModel operationDataModel; if (groupRoot.isNull()) { return operationDataModel; } if (groupRoot.isString()) { string s = groupRoot.asString(); if (s == JsonRefreshing) { return operationDataModel; } throw DMException(ErrorInvalidJsonFormat); } if (!groupRoot.isObject()) { throw DMException(ErrorInvalidJsonFormat); } Json::Value value = groupRoot[subGroupdId]; if (!value.isNull()) { operationDataModel.present = true; operationDataModel.value = value; return operationDataModel; } return operationDataModel; } OperationModelT<int> BaseHandler::TryGetOptionalSinglePropertyOpIntParameter( const Json::Value& groupRoot, const std::string& operationId) { OperationModelT<int> typedModel; OperationModel model = TryGetOptionalSinglePropertyOpParameter(groupRoot, operationId); typedModel.present = model.present; if (model.present) { if (!model.value.isInt()) { throw DMException(ErrorInvalidJsonFormat); } typedModel.value = model.value.asInt(); } return typedModel; } OperationModelT<bool> BaseHandler::TryGetOptionalSinglePropertyOpBoolParameter( const Json::Value& groupRoot, const std::string& operationId) { OperationModelT<bool> typedModel; OperationModel model = TryGetOptionalSinglePropertyOpParameter(groupRoot, operationId); typedModel.present = model.present; if (model.present) { if (!model.value.isBool()) { throw DMException(ErrorInvalidJsonFormat); } typedModel.value = model.value.asBool(); } return typedModel; } OperationModelT<std::string> BaseHandler::TryGetOptionalSinglePropertyOpStringParameter( const Json::Value& groupRoot, const std::string& operationId) { OperationModelT<std::string> typedModel; OperationModel model = TryGetOptionalSinglePropertyOpParameter(groupRoot, operationId); typedModel.present = model.present; if (model.present) { if (!model.value.isString()) { throw DMException(ErrorInvalidJsonFormat); } typedModel.value = model.value.asString(); } return typedModel; } string BaseHandler::GetSinglePropertyOpStringParameter( const Json::Value& groupRoot, const string& operationId) { OperationModelT<string> model = TryGetOptionalSinglePropertyOpStringParameter(groupRoot, operationId); if (!model.present) { throw DMException(ErrorInvalidJsonFormat); } return model.value; } bool BaseHandler::RunOperation( const string& subGroupId, shared_ptr<ReportedErrorList> errorList, const function<void()>& Action) { TRACELINE(LoggingLevel::Verbose, __FUNCTION__); TRACELINEP(LoggingLevel::Verbose, "Sub-Group: ", subGroupId.c_str()); bool result = false; std::shared_ptr<ReportedError> reportedError; try { Action(); result = true; } catch (const DMException& e) { TRACELINE(LoggingLevel::Error, e.DisplayMessage().c_str()); reportedError = make_shared<ReportedError>(); reportedError->SetContext(subGroupId); reportedError->SetSubsystem(e.SubSystem()); reportedError->SetCode(e.Code()); reportedError->SetMessage(e.Message()); } catch (const exception& e) { string message; message += "Generic standard exception occured: "; message += e.what(); TRACELINE(LoggingLevel::Error, message.c_str()); reportedError = make_shared<ReportedError>(); reportedError->SetContext(subGroupId); reportedError->SetSubsystem(JsonErrorSubsystemUnknown); reportedError->SetCode(JsonErrorGenericCode); reportedError->SetMessage(e.what()); } catch (...) { const char* displayMessage = "Generic exception occured."; TRACELINE(LoggingLevel::Error, displayMessage); reportedError = make_shared<ReportedError>(); reportedError->SetContext(subGroupId); reportedError->SetSubsystem(JsonErrorSubsystemUnknown); reportedError->SetCode(JsonErrorGenericCode); reportedError->SetMessage(displayMessage); } if (!result) { errorList->AddError(subGroupId, reportedError); } return result; } void BaseHandler::SetMdmServer( std::shared_ptr<IMdmServer> iMdmServer) { _mdmProxy.SetMdmServer(iMdmServer); } void BaseHandler::SetHandlerHost( std::shared_ptr<IRawHandlerHost> iPluginHost) { _iPluginHost = iPluginHost; } }}}}
28.635179
127
0.621431
[ "model" ]
1c55f0adad2d4c87dc158a5c0f31e0de66e6289a
665
cpp
C++
src/RESTAPI/RESTAPI_iptocountry_handler.cpp
fbourqueMeta/wlan-cloud-ucentralgw
adacc8b3fefa82f2bf6df6f1c8d70e5520a0d8a0
[ "BSD-3-Clause" ]
null
null
null
src/RESTAPI/RESTAPI_iptocountry_handler.cpp
fbourqueMeta/wlan-cloud-ucentralgw
adacc8b3fefa82f2bf6df6f1c8d70e5520a0d8a0
[ "BSD-3-Clause" ]
null
null
null
src/RESTAPI/RESTAPI_iptocountry_handler.cpp
fbourqueMeta/wlan-cloud-ucentralgw
adacc8b3fefa82f2bf6df6f1c8d70e5520a0d8a0
[ "BSD-3-Clause" ]
null
null
null
// // Created by stephane bourque on 2022-02-05. // #include "RESTAPI_iptocountry_handler.h" #include "FindCountry.h" namespace OpenWifi { void RESTAPI_iptocountry_handler::DoGet() { auto IPList = GetParameter("iplist",""); if(IPList.empty()) { return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); } auto IPAddresses = Poco::StringTokenizer(IPList,","); Poco::JSON::Object Answer; Answer.set("enabled", FindCountryFromIP()->Enabled()); Poco::JSON::Array Countries; for(const auto &i:IPAddresses) { Countries.add(FindCountryFromIP()->Get(i)); } Answer.set("countryCodes", Countries); return ReturnObject(Answer); } }
21.451613
66
0.706767
[ "object" ]
1c5c63fafba5f5cb6b10580096bc94dc11700e5a
1,847
hpp
C++
libcaf_core/caf/detail/message_builder_element.hpp
Hamdor/actor-framework
ce63edffa2b7acb698cfaea571142029d38e9ef0
[ "BSD-3-Clause" ]
2,517
2015-01-04T22:19:43.000Z
2022-03-31T12:20:48.000Z
libcaf_core/caf/detail/message_builder_element.hpp
Hamdor/actor-framework
ce63edffa2b7acb698cfaea571142029d38e9ef0
[ "BSD-3-Clause" ]
894
2015-01-07T14:21:21.000Z
2022-03-30T06:37:18.000Z
libcaf_core/caf/detail/message_builder_element.hpp
Hamdor/actor-framework
ce63edffa2b7acb698cfaea571142029d38e9ef0
[ "BSD-3-Clause" ]
570
2015-01-21T18:59:33.000Z
2022-03-31T19:00:02.000Z
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <memory> #include <new> #include "caf/byte.hpp" #include "caf/detail/core_export.hpp" #include "caf/detail/padded_size.hpp" namespace caf::detail { /// Wraps a value for either copying or moving it into a pre-allocated storage /// later. class CAF_CORE_EXPORT message_builder_element { public: virtual ~message_builder_element(); /// Uses placement new to create a copy of the wrapped value at given memory /// region. /// @returns the past-the-end pointer of the object, i.e., the first byte for /// the *next* object. virtual byte* copy_init(byte* storage) const = 0; /// Uses placement new to move the wrapped value to given memory region. /// @returns the past-the-end pointer of the object, i.e., the first byte for /// the *next* object. virtual byte* move_init(byte* storage) = 0; }; template <class T> class message_builder_element_impl : public message_builder_element { public: message_builder_element_impl(T value) : value_(std::move(value)) { // nop } byte* copy_init(byte* storage) const override { new (storage) T(value_); return storage + padded_size_v<T>; } byte* move_init(byte* storage) override { new (storage) T(std::move(value_)); return storage + padded_size_v<T>; } private: T value_; }; using message_builder_element_ptr = std::unique_ptr<message_builder_element>; template <class T> auto make_message_builder_element(T&& x) { using impl = message_builder_element_impl<std::decay_t<T>>; return message_builder_element_ptr{new impl(std::forward<T>(x))}; } } // namespace caf::detail
28.859375
79
0.71738
[ "object" ]
1c5fe3b65f3ec73311272b91be810d1c5fabc71c
11,494
cpp
C++
sample_projects/LEQuad/main_chibios_sparky.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
12
2016-07-12T10:26:47.000Z
2021-12-14T10:03:11.000Z
sample_projects/LEQuad/main_chibios_sparky.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
183
2015-01-22T12:35:18.000Z
2017-06-09T10:11:26.000Z
sample_projects/LEQuad/main_chibios_sparky.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
25
2015-02-03T15:15:48.000Z
2021-12-14T08:55:04.000Z
/* ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "boards/sparky_chibi/sparky_chibi.hpp" #include "drones/lequad.hpp" #include "hal/common/time_keeper.hpp" #include "hal/dummy/serial_dummy.hpp" #include "hal/dummy/i2c_dummy.hpp" #include "hal/dummy/file_dummy.hpp" #include "hal/dummy/adc_dummy.hpp" #include "hal/dummy/pwm_dummy.hpp" #include "simulation/dynamic_model_quad_diag.hpp" #include "simulation/simulation.hpp" #include "drivers/spektrum_satellite.hpp" #include "drivers/lsm330dlc.hpp" #include "drivers/hmc5883l.hpp" #include "drivers/gps_ublox.hpp" #include "drivers/sonar_i2cxl.hpp" #include "drivers/px4flow_i2c.hpp" extern "C" { #include "libs/ChibiOS/os/hal/include/hal_usb.h" } #define MAVLINK_SYS_ID 2 int main(void) { bool init_success = true; // ------------------------------------------------------------------------- // Create board // ------------------------------------------------------------------------- Sparky_chibi::conf_t board_config = Sparky_chibi::default_config(); // LEDs on STM32F4DISCOVERY // board_config.gpio_led_err = // { // .port = GPIOD, // .pin = GPIOD_PIN12_LED4 // }; // board_config.gpio_led_stat = // { // .port = GPIOD, // .pin = GPIOD_PIN13_LED3 // }; Sparky_chibi board(board_config); // Board initialisation init_success &= board.init(); // ------------------------------------------------------------------------- // Create devices that are not implemented in board yet // ------------------------------------------------------------------------- // Dummy peripherals Serial_dummy serial_dummy; I2c_dummy i2c_dummy; File_dummy file_dummy; Gpio_dummy gpio_dummy; Spektrum_satellite satellite_dummy(serial_dummy, gpio_dummy, gpio_dummy); Led_gpio led_dummy(gpio_dummy); PX4Flow_i2c flow_dummy(i2c_dummy); // ------------------------------------------------------------------------- // Create simulation // ------------------------------------------------------------------------- // Simulated servos Pwm_dummy pwm[8]; Servo sim_servo_0(pwm[0], servo_default_config_esc()); Servo sim_servo_1(pwm[1], servo_default_config_esc()); Servo sim_servo_2(pwm[2], servo_default_config_esc()); Servo sim_servo_3(pwm[3], servo_default_config_esc()); Servo sim_servo_4(pwm[4], servo_default_config_esc()); Servo sim_servo_5(pwm[5], servo_default_config_esc()); Servo sim_servo_6(pwm[6], servo_default_config_esc()); Servo sim_servo_7(pwm[7], servo_default_config_esc()); // Simulated dynamic model Dynamic_model_quad_diag sim_model(sim_servo_0, sim_servo_1, sim_servo_2, sim_servo_3); Simulation sim(sim_model); // Simulated battery Adc_dummy sim_adc_battery(11.1f); Battery sim_battery(sim_adc_battery); // Simulated IMU Imu sim_imu( sim.accelerometer(), sim.gyroscope(), sim.magnetometer() ); // ------------------------------------------------------------------------- // Create MAV // ------------------------------------------------------------------------- // Create MAV using real sensors // LEQuad::conf_t mav_config = LEQuad::default_config(MAVLINK_SYS_ID); // LEQuad mav = LEQuad( sim_imu, // sim.barometer(), // sim.gps(), // sim.sonar(), // flow_dummy, // board.serial_, // mavlink serial // satellite_dummy, // board.state_display_, // file_dummy, // sim_battery, // sim_servo_0, // sim_servo_1, // sim_servo_2, // sim_servo_3 , // sim_servo_4, // sim_servo_5, // sim_servo_6, // sim_servo_7 , // file_dummy, // file_dummy, // mav_config ); // Init mav // mav.init(); // ------------------------------------------------------------------------- // Main loop // ------------------------------------------------------------------------- // mav.loop(); State_display& disp = board.state_display_; // I2c_chibios& i2c = board.i2c1_; /** * Prepares the barometer */ static uint8_t txbuf[10] = "Hello!\r\n"; // const uint8_t ms5611_addr = 0x77; // const uint8_t COMMAND_RESET = 0x1E; ///< Reset sensor // const uint8_t COMMAND_GET_CALIBRATION = 0xA2; ///< Get 16bytes factory configuration from PROM /* * Initializes a serial-over-USB CDC driver. */ // sduObjectInit(&SDU1); // sduStart(&SDU1, &serusbcfg); /* * Activates the USB driver and then the USB bus pull-up on D+. * Note, a delay is inserted in order to not have to disconnect the cable * after a reset. */ // usbDisconnectBus(serusbcfg.usbp); // time_keeper_delay_ms(1500); // usbStart(serusbcfg.usbp, &usbcfg); // usbConnectBus(serusbcfg.usbp); // usbDisconnectBus(&USBD1); // time_keeper_delay_ms(1500); // usbStart(&USBD1, &usbcfg); // usbConnectBus(&USBD1); time_keeper_delay_ms(1500); // static SerialConfig uartCfg = // { // 9600, // bit rate // }; // // palSetPadMode(GPIOB, 10, PAL_MODE_ALTERNATE(7)); // used function : USART3_TX // palSetPadMode(GPIOB, 11, PAL_MODE_ALTERNATE(7)); // used function : USART3_RX // sdStart(&SD3, &uartCfg); // starts the serial driver with uartCfg as a config // char data[] = "Hello World ! \n \r"; // char data2[] = "ByeBye World ! \n \r"; /* * Activates the UART driver 2, PA2(TX) and PA3(RX) are routed to USART2. */ // uartStart(&UARTD2, &uart_cfg_1); // palSetPadMode(GPIOA, 2, PAL_MODE_ALTERNATE(7)); // palSetPadMode(GPIOA, 3, PAL_MODE_ALTERNATE(7)); // // uartStopReceive(&UARTD2); // uartStopSend(&UARTD2); // // uartStartReceive(&UARTD2, 16, buffer); // -------------------------------------------------------------------------------------------- // Use serial from board // Serial_chibios& serial = board.serial_; // Create serial here Serial_chibios serial1({Serial_chibios::SERIAL_2, &UARTD1, 38400}); serial1.init(); Serial_chibios& serial = serial1; // -------------------------------------------------------------------------------------------- Spi_chibios spi({ &SPID3, { NULL, GPIOB, 12, SPI_CR1_BR_2 | SPI_CR1_BR_1, 0 } }); // spi.init(); while (true) { disp.update(); time_keeper_delay_ms(100); serial.write(txbuf, sizeof(txbuf)); serial.write(txbuf, sizeof(txbuf)); serial.write(txbuf, sizeof(txbuf)); serial.write(txbuf, sizeof(txbuf)); for (size_t i = 0; i < 10; i++) { Servo& servo = board.servo_[i]; servo.write(1.0f); } serial.write(txbuf, sizeof(txbuf)); serial.write(txbuf, sizeof(txbuf)); serial.write(txbuf, sizeof(txbuf)); serial.write(txbuf, sizeof(txbuf)); for (size_t i = 0; i < 10; i++) { Servo& servo = board.servo_[i]; servo.write(-1.0f); } // spi.transfer(txbuf, rxbuf, 10); // uartStopSend(&UARTD2); // uartStartSend(&UARTD2, sizeof(data2), data2); // for (size_t i = 0; i < 10; i++) // { // Servo& servo = board.servo_[i]; // servo.write(-1.0f); // } // chnWrite(&SD3, (uint8_t *) data, strlen(data)); // // sdAsynchronousWrite(&SD3, (uint8_t *) data, strlen(data)); // for (size_t i = 0; i < 10; i++) // { // Servo& servo = board.servo_[i]; // servo.write(1.0f); // } // chnWrite(&SD3, (uint8_t *) data2, strlen(data)); // // sdAsynchronousWrite(&SD3, (uint8_t *) data2, strlen(data)); // for (size_t i = 0; i < 10; i++) // { // Servo& servo = board.servo_[i]; // servo.write(-1.0f); // } // time_keeper_delay_ms(1); // while (true) { // msg_t msg = usbTransmit(&USBD1, USBD2_DATA_REQUEST_EP, // txbuf, sizeof (txbuf) - 1); // if (msg == MSG_RESET) // { // time_keeper_delay_ms(500); // } // pwm1.set_pulse_width_us(1000); // pwm1.set_period_us(20000); // servo.write(-1.0f); // for (size_t i = 0; i < 10; i++) // { // Servo& servo = board.servo_[i]; // servo.write(-1.0f); // } // time_keeper_delay_ms(20); // for (size_t i = 0; i < 10; i++) // { // Servo& servo = board.servo_[i]; // servo.write(0.0f); // } // time_keeper_delay_ms(20); // for (size_t i = 0; i < 10; i++) // { // Servo& servo = board.servo_[i]; // servo.write(1.0f); // } // } // chnWrite(&SDU1, (uint8_t *)"Hello World!\r\n", 14); // // Reset sensor // txbuf[0] = COMMAND_RESET; // i2c.write(txbuf, 1, ms5611_addr); // // // Let time to the sensor to initialize // time_keeper_delay_ms(20); // // // Read calibration data // for (size_t i = 0; i < 6; i++) // { // txbuf[0] = COMMAND_GET_CALIBRATION + i * 2; // i2c.transfer(txbuf, 1, rxbuf, 2, ms5611_addr); // } // while (true) // { // if (SDU1.config->usbp->state == USB_ACTIVE) // { // static uint8_t buf[] = "0123456789abcdef\n"; // // chnRead(&SDU1, buf, sizeof buf - 1); // chnWrite(&SDU1, buf, sizeof buf - 1); // } // } } return 0; }
33.028736
112
0.471376
[ "model" ]
1c608a5e8d9f82da3f7573db20c3ac9aaa7e938f
19,124
cpp
C++
main.cpp
avrcolak/hey-
efbcb92a1d76339024cb1567cd272dd6a6b45874
[ "Unlicense" ]
1
2020-09-07T04:39:39.000Z
2020-09-07T04:39:39.000Z
main.cpp
avrcolak/hey-
efbcb92a1d76339024cb1567cd272dd6a6b45874
[ "Unlicense" ]
null
null
null
main.cpp
avrcolak/hey-
efbcb92a1d76339024cb1567cd272dd6a6b45874
[ "Unlicense" ]
null
null
null
#include <ggponet.h> #include <imgui.h> #include <imgui_impl_opengl2.h> #include <imgui_impl_sdl.h> #include <SDL.h> #include <stdio.h> #include <string.h> #include <windows.h> #include <gl/GL.h> #include "connection_report.h" #include "game.h" #include "utils.h" #define MAX_GRAPH_SIZE 4096 #define MAX_FAIRNESS 20 enum ROLE_TYPE { ROLE_TYPE_Spectator, ROLE_TYPE_Player, }; typedef struct ClientInit { unsigned short local_port; int num_players; ROLE_TYPE type; union { struct { char host_ip[128]; unsigned short host_port; }; struct { GGPOPlayer players[GGPO_MAX_SPECTATORS + GGPO_MAX_PLAYERS]; int local_player; int num_spectators; }; }; } ClientInit; typedef struct FrameInfo { int number; int hash; } FrameInfo; typedef struct FrameReport { FrameInfo current; FrameInfo periodic; } FrameReport; typedef struct GgpoHandles { GGPOSession* session; GGPOPlayerHandle local_player; } GgpoHandles; typedef void (APIENTRY* PFNGLUSEPROGRAMPROC) (unsigned int); typedef struct SdlHandles { SDL_Window* window; SDL_GLContext gl_context; PFNGLUSEPROGRAMPROC glUseProgram; SDL_Renderer* renderer; } SdlHandles; typedef struct ClientState { bool quit; bool show_performance_monitor; } ClientState; static ConnectionReport connection_report; static GgpoHandles ggpo; // participants[i] corresponds with connection_report.participants[i] static GGPOPlayerHandle participants[MAX_PARTICIPANTS]; static FrameReport frame_report; static void set_connection_state(GGPOPlayerHandle handle, CONNECTION_STATE state) { for (int i = 0; i < connection_report.num_participants; i++) { if (participants[i] == handle) { connection_report.participants[i].connect_progress = 0; connection_report.participants[i].state = state; break; } } } static void update_connect_progress(GGPOPlayerHandle handle, int progress) { for (int i = 0; i < connection_report.num_participants; i++) { if (participants[i] == handle) { connection_report.participants[i].connect_progress = progress; break; } } } static bool __cdecl on_event(GGPOEvent *info) { switch (info->code) { case GGPO_EVENTCODE_CONNECTED_TO_PEER: set_connection_state( info->u.connected.player, CONNECTION_STATE_synchronizing); break; case GGPO_EVENTCODE_SYNCHRONIZING_WITH_PEER: update_connect_progress( info->u.synchronizing.player, info->u.synchronizing.count / info->u.synchronizing.total); break; case GGPO_EVENTCODE_SYNCHRONIZED_WITH_PEER: update_connect_progress(info->u.synchronized.player, 100); break; case GGPO_EVENTCODE_RUNNING: for (int i = 0; i < connection_report.num_participants; i++) { connection_report.participants[i].state = CONNECTION_STATE_running; } strcpy_s(connection_report.status, ""); break; case GGPO_EVENTCODE_CONNECTION_INTERRUPTED: for (int i = 0; i < connection_report.num_participants; i++) { if (participants[i] == info->u.connection_interrupted.player) { connection_report.participants[i].disconnect_start = SDL_GetTicks(); connection_report.participants[i].disconnect_timeout = info->u.connection_interrupted.disconnect_timeout; connection_report.participants[i].state = CONNECTION_STATE_disconnecting; break; } } break; case GGPO_EVENTCODE_CONNECTION_RESUMED: set_connection_state( info->u.connection_resumed.player, CONNECTION_STATE_running); break; case GGPO_EVENTCODE_DISCONNECTED_FROM_PEER: set_connection_state( info->u.disconnected.player, CONNECTION_STATE_disconnected); break; case GGPO_EVENTCODE_TIMESYNC: SDL_Delay(1000 * info->u.timesync.frames_ahead / 60); break; } return true; } static void setup_imgui_frame(SdlHandles handles) { ImGui_ImplOpenGL2_NewFrame(); ImGui_ImplSDL2_NewFrame(handles.window); ImGui::NewFrame(); } void draw_centered_text(SdlHandles handles, char const *str, int y) { int w, h; SDL_GetWindowSize(handles.window, &w, &h); ImGui::GetBackgroundDrawList()->AddText( ImVec2(w / 2 - ImGui::CalcTextSize(str).x / 2, (float)y), IM_COL32_WHITE, str); } void draw_checksum(SdlHandles handles, FrameInfo frame_info, int y) { char checksum[128]; sprintf_s( checksum, COUNT_OF(checksum), "Frame: %04d Checksum: %08x", frame_info.number, frame_info.hash); draw_centered_text(handles, checksum, y); } void draw_performance_monitor(ClientState *cs) { GGPOPlayerHandle remotes[MAX_PLAYERS]; int num_remotes = 0; for (int i = 0; i < connection_report.num_participants; i++) { if (connection_report.participants[i].type == PARTICIPANT_TYPE_remote) { remotes[num_remotes] = participants[i]; num_remotes++; } } static int graph_size = 0; static int first_graph_index = 0; GGPONetworkStats stats = { 0 }; int i; if (graph_size < MAX_GRAPH_SIZE) { i = graph_size; graph_size++; } else { i = first_graph_index; first_graph_index = (first_graph_index + 1) % MAX_GRAPH_SIZE; } static float ping_graph[MAX_PLAYERS][MAX_GRAPH_SIZE] = { 0 }; static float remote_fairness_graph[MAX_PLAYERS][MAX_GRAPH_SIZE] = { 0 }; static float fairness_graph[MAX_GRAPH_SIZE] = { 0 }; for (int j = 0; j < num_remotes; j++) { ggpo_get_network_stats(ggpo.session, remotes[j], &stats); ping_graph[j][i] = (float)stats.network.ping; // Frame Advantage remote_fairness_graph[j][i] = (float)stats.timesync.remote_frames_behind; if (stats.timesync.local_frames_behind < 0 && stats.timesync.remote_frames_behind < 0) { // Both think it's unfair (which, ironically, is fair). fairness_graph[i] = (float)abs( abs(stats.timesync.local_frames_behind) - abs(stats.timesync.remote_frames_behind)); } else if (stats.timesync.local_frames_behind > 0 && stats.timesync.remote_frames_behind > 0) { // Impossible! Unless the network has negative transmit time. fairness_graph[i] = 0; } else { // They disagree. fairness_graph[i] = (float) abs(stats.timesync.local_frames_behind) + abs(stats.timesync.remote_frames_behind); } } ImGui::Begin("Performance Monitor", &cs->show_performance_monitor); ImGui::Separator(); ImGui::Text("Network"); for (int j = 0; j < num_remotes; j++) { char remote_label[128]; sprintf_s(remote_label, COUNT_OF(remote_label), "Remote %d", j); ImGui::Text(remote_label); ImGui::PlotLines( "", ping_graph[j], MAX_GRAPH_SIZE, i + MAX_GRAPH_SIZE, NULL, 0, 500, ImVec2(512, 100)); } char latency_in_ms[128], latency_in_frames[128], kbps[128]; sprintf_s( latency_in_ms, COUNT_OF(latency_in_ms), "%d ms", stats.network.ping); sprintf_s( latency_in_frames, COUNT_OF(latency_in_frames), "%.1f frames", stats.network.ping ? stats.network.ping * 60.0 / 1000 : 0); sprintf_s(kbps, COUNT_OF(kbps), "%.2f kilobytes/sec", stats.network.kbps_sent / 8.0); ImGui::Columns(4, "", false); ImGui::Text("Latency:"); ImGui::NextColumn(); ImGui::Text(latency_in_ms); ImGui::NextColumn(); ImGui::Text("Data Rate:"); ImGui::NextColumn(); ImGui::Text(latency_in_frames); ImGui::NextColumn(); ImGui::Text("Latency:"); ImGui::NextColumn(); ImGui::Text(latency_in_frames); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Synchronization"); for (int j = 0; j < num_remotes; j++) { char remote_label[128]; sprintf_s(remote_label, COUNT_OF(remote_label), "Remote %d", j); ImGui::Text(remote_label); ImGui::PlotLines( "", remote_fairness_graph[j], MAX_GRAPH_SIZE, i + MAX_GRAPH_SIZE, NULL, -MAX_FAIRNESS, MAX_FAIRNESS, ImVec2(512, 120)); char remote_frames_behind[128]; sprintf_s( remote_frames_behind, COUNT_OF(remote_frames_behind), "%d frames behind", stats.timesync.remote_frames_behind); ImGui::Columns(4, "", false); ImGui::Text("Fairness:"); ImGui::NextColumn(); ImGui::Text(remote_frames_behind); ImGui::NextColumn(); ImGui::Columns(1); } ImGui::Text("Local"); ImGui::PlotLines( "", fairness_graph, MAX_GRAPH_SIZE, i + MAX_GRAPH_SIZE, NULL, -MAX_FAIRNESS, MAX_FAIRNESS, ImVec2(512, 120)); char local_frames_behind[128]; sprintf_s( local_frames_behind, COUNT_OF(local_frames_behind), "%d frames behind", stats.timesync.local_frames_behind); ImGui::Columns(4, "", false); ImGui::Text("Fairness:"); ImGui::NextColumn(); ImGui::Text(local_frames_behind); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); char pid[128]; sprintf_s(pid, COUNT_OF(pid), "Process ID: %lu", GetCurrentProcessId()); ImGui::Text(pid); ImGui::SameLine(ImGui::GetWindowWidth() - 48); if (ImGui::Button("Close")) { cs->show_performance_monitor = false; } ImGui::End(); } static void draw_gui(SdlHandles handles, ClientState *cs) { draw_checksum(handles, frame_report.periodic, 18); draw_checksum(handles, frame_report.current, 34); draw_centered_text(handles, connection_report.status, 448); if (cs->show_performance_monitor) { draw_performance_monitor(cs); } } static void show_disconnected_player(GGPOErrorCode result, int player) { char logbuf[128]; if (GGPO_SUCCEEDED(result)) { sprintf_s( logbuf, sizeof logbuf, "Disconnected player %d.\n", player); } else { sprintf_s( logbuf, sizeof logbuf, "Error while disconnecting player (err:%d).\n", result); } strcpy_s(connection_report.status, logbuf); } static void disconnect_player(int player) { if (player < connection_report.num_participants) { GGPOErrorCode result = ggpo_disconnect_player(ggpo.session, participants[player]); show_disconnected_player(result, player); } } static void client_process_event(SDL_Event e, SdlHandles sdl, ClientState *cs) { switch (e.type) { case SDL_QUIT: cs->quit = true; return; break; case SDL_KEYDOWN: if (e.key.keysym.sym == SDLK_p) { cs->show_performance_monitor = !cs->show_performance_monitor; } else if (e.key.keysym.sym == SDLK_ESCAPE) { cs->quit = true; return; } else if (e.key.keysym.sym >= SDLK_F1 && e.key.keysym.sym <= SDLK_F12) { disconnect_player( (int)(e.key.keysym.sym - SDLK_F1)); } break; case SDL_WINDOWEVENT: switch (e.window.event) { case SDL_WINDOWEVENT_EXPOSED: SDL_UpdateWindowSurface(sdl.window); break; case SDL_WINDOWEVENT_CLOSE: cs->quit = true; return; } break; } ImGui_ImplSDL2_ProcessEvent(&e); return; } static void update_frame_report() { frame_report.current.number = game_frame_number(); frame_report.current.hash = game_state_hash(); if ((frame_report.current.number % 90) == 0) { frame_report.periodic = frame_report.current; } } static bool __cdecl advance_frame(int flags) { (void)flags; int disconnect_flags = 0; LocalInput inputs[MAX_PLAYERS] = { 0 }; GGPOErrorCode result = ggpo_synchronize_input( ggpo.session, (void*)inputs, sizeof(LocalInput) * MAX_PLAYERS, &disconnect_flags); if (GGPO_SUCCEEDED(result)) { step_game(inputs, disconnect_flags); ggpo_advance_frame(ggpo.session); update_frame_report(); return true; } return false; } static void work(LocalInput *input) { capture_input_state(input); GGPOErrorCode result = ggpo_add_local_input( ggpo.session, ggpo.local_player, input, sizeof(LocalInput)); if (GGPO_SUCCEEDED(result)) { advance_frame(0); } } static void render(SdlHandles sdl) { SDL_RenderFlush(sdl.renderer); ImGui::Render(); sdl.glUseProgram(0); ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(sdl.window); } static void main_loop(SdlHandles sdl) { frame_report = { 0 }; int start, next, now; start = next = now = SDL_GetTicks(); ClientState client_state = { 0 }; LocalInput local_input = { 0 }; while (1) { setup_imgui_frame(sdl); SDL_Event e; while (SDL_PollEvent(&e) != 0) { client_process_event(e, sdl, &client_state); if (client_state.quit) { return; } buffer_event(&e, &local_input); } now = SDL_GetTicks(); ggpo_idle(ggpo.session, max(0, next - now - 1)); if (now >= next) { work(&local_input); local_input = { 0 }; next = now + (1000 / 60); } draw_game(sdl.renderer, &connection_report); draw_gui(sdl, &client_state); render(sdl); } } static SdlHandles setup_sdl() { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_Window* window = SDL_CreateWindow( GAME_NAME, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, gl_context); // SDL_Renderer will push but not pop its shader program, so we have // to do so before using rendering with Dear ImGui. PFNGLUSEPROGRAMPROC glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram"); if (SDL_GL_SetSwapInterval(-1) != 0) { SDL_GL_SetSwapInterval(1); } // To match chosen Dear ImGui implementation. SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl"); SDL_SetHint(SDL_HINT_RENDER_BATCHING, "1"); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); return { window, gl_context, glUseProgram, renderer }; } static void tear_down_sdl(SdlHandles sdl) { SDL_GL_DeleteContext(sdl.gl_context); SDL_DestroyWindow(sdl.window); SDL_DestroyRenderer(sdl.renderer); SDL_Quit(); } static void setup_imgui(SdlHandles sdl) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGui_ImplSDL2_InitForOpenGL(sdl.window, sdl.gl_context); ImGui_ImplOpenGL2_Init(); } static void tear_down_imgui() { ImGui_ImplOpenGL2_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); } static void show_syntax_error() { SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Syntax: hey.exe <local port> <num players> ('local' | <remote ip>:<remote port>)*\n", "Could not start", NULL); } static int parse_args(int argc, char* args[], ClientInit *init) { if (argc < 3) { show_syntax_error(); return 1; } int offset = 1; init->local_port = (unsigned short)atoi(args[offset]); offset++; init->num_players = atoi(args[offset]); offset++; if (init->num_players < 0 || argc < offset + init->num_players) { show_syntax_error(); return 1; } if (strcmp(args[offset], "spectate") == 0) { init->type = ROLE_TYPE_Spectator; int result = sscanf_s( args[offset + 1], "%[^:]:%hu", init->host_ip, (unsigned int)sizeof init->host_ip, &init->host_port); if (result != 2) { show_syntax_error(); return 1; } return 0; } init->type = ROLE_TYPE_Player; GGPOPlayer* players = init->players; int i; for (i = 0; i < init->num_players; i++) { const char* arg = args[offset]; offset++; players[i].size = sizeof(players[i]); players[i].player_num = i + 1; if (!strcmp(arg, "local")) { players[i].type = GGPO_PLAYERTYPE_LOCAL; init->local_player = i; continue; } players[i].type = GGPO_PLAYERTYPE_REMOTE; int result = sscanf_s( arg, "%[^:]:%hd", players[i].u.remote.ip_address, (unsigned int)sizeof players[i].u.remote.ip_address, &(players[i].u.remote.port)); if (result != 2) { show_syntax_error(); return 1; } } init->num_spectators = 0; while (offset < argc) { players[i].type = GGPO_PLAYERTYPE_SPECTATOR; int result = sscanf_s( args[offset], "%[^:]:%hd", players[i].u.remote.ip_address, (unsigned int)sizeof players[i].u.remote.ip_address, &players[i].u.remote.port); if (result != 2) { show_syntax_error(); return 1; } offset++; i++; init->num_spectators++; } return 0; } static void adjust_window(SdlHandles const sdl, ClientInit const init) { SDL_Point window_offsets[] = { { 64, 64 }, { 740, 64 }, { 64, 600 }, { 740, 600 }, }; if (init.local_player < COUNT_OF(window_offsets)) { SDL_SetWindowPosition( sdl.window, window_offsets[init.local_player].x, window_offsets[init.local_player].y); } } static bool __cdecl begin_game_callback(const char *game) { return begin_game(game); } static bool __cdecl load_game_state_callback(unsigned char *buffer, int len) { return load_game_state(buffer, len); } static bool __cdecl save_game_state_callback( unsigned char **buffer, int *len, int *checksum, int frame) { return save_game_state(buffer, len, checksum, frame); } static void __cdecl free_buffer_callback(void *buffer) { free_game_state(buffer); } static bool __cdecl log_game_state_callback( char *filename, unsigned char *buffer, int len) { return log_game_state(filename, buffer, len); } static void setup_ggpo(ClientInit init) { WSADATA wd = { 0 }; WSAStartup(MAKEWORD(2, 2), &wd); GgpoHandles handles; GGPOSessionCallbacks cb; cb.on_event = on_event; cb.advance_frame = advance_frame; cb.begin_game = begin_game_callback; cb.load_game_state = load_game_state_callback; cb.free_buffer = free_buffer_callback; cb.log_game_state = log_game_state_callback; cb.save_game_state = save_game_state_callback; connection_report.num_participants = init.num_players; if (init.type == ROLE_TYPE_Spectator) { ggpo_start_spectating( &handles.session, &cb, GAME_NAME, init.num_players, sizeof(LocalInput), init.local_port, init.host_ip, init.host_port); strcpy_s(connection_report.status, "Starting new spectator session."); ggpo = handles; return; } GGPOErrorCode result = ggpo_start_session( &handles.session, &cb, GAME_NAME, init.num_players, sizeof(LocalInput), init.local_port); ggpo_set_disconnect_timeout(handles.session, 3000); ggpo_set_disconnect_notify_start(handles.session, 1000); for (int i = 0; i < init.num_players + init.num_spectators; i++) { GGPOPlayerHandle handle; result = ggpo_add_player( handles.session, init.players + i, &handle); participants[i] = handle; // HACK: Slightly fragile cast. connection_report.participants[i].type = (PARTICIPANT_TYPE)init.players[i].type; if (init.players[i].type == GGPO_PLAYERTYPE_LOCAL) { handles.local_player = handle; connection_report.participants[i].connect_progress = 100; set_connection_state(handle, CONNECTION_STATE_connecting); ggpo_set_frame_delay(handles.session, handle, 2); } else { connection_report.participants[i].connect_progress = 0; } } strcpy_s(connection_report.status, "Connecting to peers."); ggpo = handles; } static void tear_down_ggpo() { if (ggpo.session) { ggpo_close_session(ggpo.session); ggpo.session = NULL; } WSACleanup(); } int main(int argc, char* args[]) { SdlHandles sdl = setup_sdl(); ClientInit init; int result = parse_args(argc, args, &init); if (result != 0) { return result; } adjust_window(sdl, init); setup_ggpo(init); setup_imgui(sdl); setup_game(sdl.window, init.num_players); main_loop(sdl); tear_down_game(); tear_down_imgui(); tear_down_ggpo(); tear_down_sdl(sdl); return 0; }
20.69697
88
0.714965
[ "render" ]
1c69901c635b6fe928c7855f6a071201c872c028
4,444
cpp
C++
sam-project/bakker-et-al-2012/SAM/SAM/tests/src/hacking_strategy_test.cpp
amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam
518ab1cebaa80c19a12e92db8ae87386512ae053
[ "MIT" ]
1
2022-03-25T20:21:41.000Z
2022-03-25T20:21:41.000Z
sam-project/bakker-et-al-2012/SAM/SAM/tests/src/hacking_strategy_test.cpp
amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam
518ab1cebaa80c19a12e92db8ae87386512ae053
[ "MIT" ]
null
null
null
sam-project/bakker-et-al-2012/SAM/SAM/tests/src/hacking_strategy_test.cpp
amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam
518ab1cebaa80c19a12e92db8ae87386512ae053
[ "MIT" ]
null
null
null
// // Created by Amir Masoud Abdol on 2019-05-03. // #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE HackingStrategy Tests #include <boost/test/unit_test.hpp> namespace tt = boost::test_tools; #include <armadillo> #include <iostream> #include <vector> #include <algorithm> #include "sam.h" #include "Experiment.h" #include "ExperimentSetup.h" #include "ResearchStrategy.h" #include "HackingStrategy.h" #include "test_fixtures.h" using namespace arma; using namespace sam; using namespace std; bool FLAGS::VERBOSE = false; bool FLAGS::PROGRESS = false; bool FLAGS::DEBUG = false; bool FLAGS::UPDATECONFIG = false; BOOST_FIXTURE_TEST_SUITE( optional_stopping, SampleResearch ); // BOOST_AUTO_TEST_CASE( constructors ) // { // OptionalStopping::Parameters hsp; // hsp.name = HackingMethod::OptionalStopping; // } BOOST_AUTO_TEST_CASE( testing_measurements_size ) { // Using PatientDecision Maker because he'd satisfy the hacking strategy initResearch(); de_s_conf["preference"] = "PreRegisteredOutcome"; auto patient_dec_maker = ResearchStrategy::build(de_s_conf); auto optional_stopping = OptionalStopping("dv", 3, 1, 1); experiment->generateData(); experiment->calculateStatistics(); for (int i = 0; i < setup.ng(); ++i) BOOST_TEST( experiment->measurements[i].size() == setup.nobs()[i]); optional_stopping.perform(experiment, patient_dec_maker.get()); for (int i = 0; i < setup.ng(); ++i) BOOST_TEST( experiment->measurements[i].size() != setup.nobs()[i]); } BOOST_AUTO_TEST_CASE ( testing_updated_statistics ) { } BOOST_AUTO_TEST_SUITE_END(); BOOST_FIXTURE_TEST_SUITE( outliers_removal, SampleResearch ); // BOOST_AUTO_TEST_CASE( constructors ) // { // HackingStrategyParameters hsp; // hsp.name = HackingMethod::OutliersRemoval; // // } BOOST_AUTO_TEST_CASE( testing_measurements_size ) { initResearch(); de_s_conf["preference"] = "PreRegisteredOutcome"; auto patient_dec_maker = ResearchStrategy::build(de_s_conf); auto outliers_removal = OutliersRemoval("dv", "max first", 3, 1, 1, 20, {1}); experiment->generateData(); experiment->calculateStatistics(); for (int i = 0; i < setup.ng(); ++i) BOOST_TEST( experiment->measurements[i].size() == setup.nobs()[i]); // Adding 3 very far values // RandomNumberGenerator rng; arma::Row<float> outliers(3); for (int i = 0; i < setup.ng(); ++i) { // adding three new outliers outliers.each_col([](arma::Col<float> &v){ v = Random::get<std::normal_distribution<float>>(2.0, 0.1); }); experiment->measurements[i].insert_cols(experiment->measurements[i].size(), outliers); } // Performing the hack outliers_removal.perform(experiment, patient_dec_maker.get()); // Expecting them to be removed! for (int i = 0; i < setup.ng(); ++i) BOOST_TEST( experiment->measurements[i].size() == setup.nobs()[i]); } BOOST_AUTO_TEST_SUITE_END(); BOOST_FIXTURE_TEST_SUITE( groups_pooling, SampleResearch ); // BOOST_AUTO_TEST_CASE( constructors ) // { // HackingStrategyParameters hsp; // hsp.name = HackingMethod::GroupPooling; // // } BOOST_AUTO_TEST_CASE( testing_measurements_size ) { // Using PatientDecision Maker because he'd satisfy the hacking strategy initResearch(); de_s_conf["preference"] = "PreRegisteredOutcome"; auto patient_dec_maker = ResearchStrategy::build(de_s_conf); auto groups_pooling = GroupPooling({2}); experiment->generateData(); experiment->calculateStatistics(); for (int i = 0; i < setup.ng(); ++i) BOOST_TEST( experiment->measurements[i].size() == setup.nobs()[i]); // Performing the hack groups_pooling.perform(experiment, patient_dec_maker.get()); int n_new_groups = 3; BOOST_TEST( experiment->measurements.size() == n_new_groups + setup.ng() ); for (int i = setup.ng(); i < n_new_groups + setup.ng(); ++i) BOOST_TEST( experiment->measurements[i].size() == 2 * nobs); } BOOST_AUTO_TEST_SUITE_END();
26.771084
98
0.631638
[ "vector" ]
1c7116965d6d3112e28078ccbc7358eb0e6f58ce
12,622
cpp
C++
clang/test/Refactor/Extract/extract-reference-of-captured-variable.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
793
2015-12-03T16:45:26.000Z
2022-02-12T20:14:20.000Z
clang/test/Refactor/Extract/extract-reference-of-captured-variable.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
clang/test/Refactor/Extract/extract-reference-of-captured-variable.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
void takesPtr(int *x) { } typedef struct { int width, height; } Rectangle; void takesStructPtr(Rectangle *sp) { } void variableTakesRef(int x, Rectangle r) { int &y = x; takesPtr(&y); // CHECK1: (int &x) {\nint &y = x;\n takesPtr(&y);\n} Rectangle p = r; Rectangle &rp = p; takesStructPtr(&rp); // CHECK1: (const Rectangle &r) {\nRectangle p = r;\n Rectangle &rp = p;\n takesStructPtr(&rp);\n} // CHECK1: (Rectangle &p) {\nRectangle &rp = p;\n takesStructPtr(&rp);\n} int &member = ((r).width); int z = member; // CHECK1: (Rectangle &r) {\nint &member = ((r).width);\n int z = member;\n} // Even though y takes a reference to x, we still want to pass it by value here. int a = x; // CHECK1: (int x) {\nint a = x;\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:11:3-12:15 -selected=%s:14:3-16:22 -selected=%s:15:3-16:22 -selected=%s:19:3-20:17 -selected=%s:24:3-24:12 %s | FileCheck --check-prefix=CHECK1 %s class PrivateInstanceVariables { int x; Rectangle r; void method() { int &y = x; // CHECK2: extracted(int &x) {\nint &y = x;\n} Rectangle &rr = r; // CHECK2: extracted(Rectangle &r) {\nRectangle &rr = r;\n} int &z = ((r).width); // CHECK2: extracted(Rectangle &r) {\nint &z = ((r).width);\n} } }; // RUN: clang-refactor-test perform -action extract -selected=%s:35:5-35:15 -selected=%s:37:5-37:22 -selected=%s:39:5-39:25 %s | FileCheck --check-prefix=CHECK2 %s #ifdef USECONST #define CONST const #else #define CONST #endif void takesRef(CONST int &x) { } void takesStructRef(CONST Rectangle &r) { } void takesValue(int x) { } struct ConsTakesRef { ConsTakesRef(CONST int &x) { } void takesRef(CONST int &x) const { } void takesValue(int x) const { } }; int operator << (CONST Rectangle &r, CONST int &x) { return 0; } void callTakesRef(int x, Rectangle r) { takesRef(x); // CHECK3: extracted(int &x) {\ntakesRef(x);\n} // CHECK4: extracted(int x) {\ntakesRef(x);\n} takesValue(x); // CHECK3: extracted(int x) {\ntakesValue(x);\n} // CHECK4: extracted(int x) {\ntakesValue(x);\n} auto k = ConsTakesRef(x); auto y = ConsTakesRef(x); // CHECK3: extracted(int &x) {\nauto k = ConsTakesRef(x);\n} // CHECK4: extracted(int x) {\nauto k = ConsTakesRef(x);\n} y.takesRef((x)); // CHECK3: extracted(int &x, const ConsTakesRef &y) {\ny.takesRef((x));\n} // CHECK4: extracted(int x, const ConsTakesRef &y) {\ny.takesRef((x));\n} y.takesValue(x); // CHECK3: extracted(int x, const ConsTakesRef &y) {\ny.takesValue(x);\n} // CHECK4: extracted(int x, const ConsTakesRef &y) {\ny.takesValue(x);\n} takesStructRef((r)); // CHECK3: extracted(Rectangle &r) {\ntakesStructRef((r));\n} // CHECK4: extracted(const Rectangle &r) {\ntakesStructRef((r));\n} takesRef((r).height); // CHECK3: extracted(Rectangle &r) {\ntakesRef((r).height);\n} // CHECK4: extracted(const Rectangle &r) {\ntakesRef((r).height);\n} y.takesRef(r.width); // CHECK3: extracted(Rectangle &r, const ConsTakesRef &y) {\ny.takesRef(r.width);\n} // CHECK4: extracted(const Rectangle &r, const ConsTakesRef &y) {\ny.takesRef(r.width);\n} takesValue(r.width); // CHECK3: extracted(const Rectangle &r) {\ntakesValue(r.width);\n} // CHECK4: extracted(const Rectangle &r) {\ntakesValue(r.width);\n} r << x; // CHECK3: extracted(Rectangle &r, int &x) {\nreturn r << x;\n} // CHECK4: extracted(const Rectangle &r, int x) {\nreturn r << x;\n} int &r1 = x; takesRef(x); // CHECK3: extracted(int &x) {\nint &r1 = x;\n takesRef(x);\n} // CHECK4: extracted(int &x) {\nint &r1 = x;\n takesRef(x);\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:68:3-68:14 -selected=%s:71:3-71:16 -selected=%s:74:3-74:27 -selected=%s:77:3-77:18 -selected=%s:80:3-80:18 -selected=%s:83:3-83:22 -selected=%s:86:3-86:23 -selected=%s:89:3-89:22 -selected=%s:92:3-92:22 -selected=%s:95:3-95:9 -selected=%s:99:3-100:14 %s | FileCheck --check-prefix=CHECK3 %s // RUN: clang-refactor-test perform -action extract -selected=%s:68:3-68:14 -selected=%s:71:3-71:16 -selected=%s:74:3-74:27 -selected=%s:77:3-77:18 -selected=%s:80:3-80:18 -selected=%s:83:3-83:22 -selected=%s:86:3-86:23 -selected=%s:89:3-89:22 -selected=%s:92:3-92:22 -selected=%s:95:3-95:9 -selected=%s:99:3-100:14 %s -DUSECONST | FileCheck --check-prefix=CHECK4 %s void takesConstRef(const int &x) { } void callTakeRefAndConstRef(int x) { takesRef(x); takesConstRef(x); // CHECK5: extracted(int &x) {\ntakesRef(x);\n takesConstRef(x);\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:111:3-112:19 %s | FileCheck --check-prefix=CHECK5 %s class PrivateInstanceVariablesCallRefs { int x; Rectangle r; void callsTakeRef() { takesRef(x); // CHECK6: extracted(int &x) {\ntakesRef(x);\n} // CHECK7: extracted(int x) {\ntakesRef(x);\n} takesStructRef(r); // CHECK6: extracted(Rectangle &r) {\ntakesStructRef(r);\n} // CHECK7: extracted(const Rectangle &r) {\ntakesStructRef(r);\n} takesRef(r.width); // CHECK6: extracted(Rectangle &r) {\ntakesRef(r.width);\n} // CHECK7: extracted(const Rectangle &r) {\ntakesRef(r.width);\n} } }; // RUN: clang-refactor-test perform -action extract -selected=%s:123:5-123:16 -selected=%s:126:5-126:22 -selected=%s:129:5-129:22 %s | FileCheck --check-prefix=CHECK6 %s // RUN: clang-refactor-test perform -action extract -selected=%s:123:5-123:16 -selected=%s:126:5-126:22 -selected=%s:129:5-129:22 %s -DUSECONST | FileCheck --check-prefix=CHECK7 %s void variableTakesConstRef(int x, Rectangle r) { const int &y = x; // CHECK8: extracted(int x) {\nconst int &y = x;\n} const Rectangle &p = r; // CHECK8: extracted(const Rectangle &r) {\nconst Rectangle &p = r;\n} const int &z = r.width; // CHECK8: extracted(const Rectangle &r) {\nconst int &z = r.width;\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:139:3-139:19 -selected=%s:141:3-141:25 -selected=%s:143:3-143:25 %s | FileCheck --check-prefix=CHECK8 %s class ClassWithMethod { public: int method() CONST { return 0; } int operator + (int x) CONST { return x; } }; void nonConstMethodCallImpliesNonConstReceiver(ClassWithMethod x) { x.method(); // CHECK10: extracted(ClassWithMethod &x) {\nreturn x.method();\n} // CHECK11: extracted(const ClassWithMethod &x) {\nreturn x.method();\n} x.operator +(2); // CHECK10: extracted(ClassWithMethod &x) {\nreturn x.operator +(2);\n} // CHECK11: extracted(const ClassWithMethod &x) {\nreturn x.operator +(2);\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:156:3-156:14 -selected=%s:159:3-159:18 %s | FileCheck --check-prefix=CHECK10 %s // RUN: clang-refactor-test perform -action extract -selected=%s:156:3-156:14 -selected=%s:159:3-159:18 %s -DUSECONST | FileCheck --check-prefix=CHECK11 %s void ignoreMethodCallsOnPointer(ClassWithMethod *x) { x->method(); // CHECK12: extracted(ClassWithMethod *x) {\nreturn x->method();\n} x->operator +(2); // CHECK12: extracted(ClassWithMethod *x) {\nreturn x->operator +(2);\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:168:3-168:13 -selected=%s:170:3-170:19 %s | FileCheck --check-prefix=CHECK12 %s void takesRValueRef(int &&x) { } void takesRValueStructRef(Rectangle &&r) { } void callTakesRValueRef(int x) { takesRValueRef(static_cast<int&&>(x)); // CHECK13: extracted(int &x) {\ntakesRValueRef(static_cast<int&&>(x));\n} Rectangle r; takesRValueStructRef((static_cast<Rectangle&&>(r))); // CHECK13: extracted(Rectangle &r) {\ntakesRValueStructRef((static_cast<Rectangle&&>(r)));\n} int &&y = static_cast<int&&>(r.height); // CHECK13: extracted(Rectangle &r) {\nint &&y = static_cast<int&&>(r.height);\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:180:3-180:20 -selected=%s:183:3-183:54 -selected=%s:185:3-185:41 %s | FileCheck --check-prefix=CHECK13 %s void referencesInConditionalOperator(int x, int y) { takesRef(x == 0 ? x : y); // CHECK14: (int &x, int &y) {\ntakesRef(x == 0 ? x : y);\n} // CHECK15: (int x, int y) {\ntakesRef(x == 0 ? x : y);\n} Rectangle a, b; takesStructRef(y == 0 ? (a) : b); // CHECK14: (Rectangle &a, Rectangle &b, int y) {\ntakesStructRef(y == 0 ? (a) : b);\n} // CHECK15: (const Rectangle &a, const Rectangle &b, int y) {\ntakesStructRef(y == 0 ? (a) : b);\n} takesRef(x == 0 ? (a).width : (y == 0 ? y : b.height)); // CHECK14: (Rectangle &a, Rectangle &b, int x, int &y) {\ntakesRef(x == 0 ? (a).width : (y == 0 ? y : b.height));\n} // CHECK15: (const Rectangle &a, const Rectangle &b, int x, int y) {\ntakesRef(x == 0 ? (a).width : (y == 0 ? y : b.height));\n} takesRef((x == 0 ? a : (b)).width); // CHECK14: (Rectangle &a, Rectangle &b, int x) {\ntakesRef((x == 0 ? a : (b)).width);\n} // CHECK15: (const Rectangle &a, const Rectangle &b, int x) {\ntakesRef((x == 0 ? a : (b)).width);\n} takesRef(x == 0 ? y : y); // CHECK14: (int x, int &y) {\ntakesRef(x == 0 ? y : y);\n} // CHECK15: (int x, int y) {\ntakesRef(x == 0 ? y : y);\n} ClassWithMethod caller1, caller2; (x == 0 ? caller1 : caller2).method(); // CHECK14: (ClassWithMethod &caller1, ClassWithMethod &caller2, int x) {\nreturn (x == 0 ? caller1 : caller2).method();\n} // CHECK15: (const ClassWithMethod &caller1, const ClassWithMethod &caller2, int x) {\nreturn (x == 0 ? caller1 : caller2).method();\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:192:3-192:27 -selected=%s:196:3-196:35 -selected=%s:199:3-199:57 -selected=%s:202:3-202:37 -selected=%s:205:3-205:27 -selected=%s:209:3-209:40 %s | FileCheck --check-prefix=CHECK14 %s // RUN: clang-refactor-test perform -action extract -selected=%s:192:3-192:27 -selected=%s:196:3-196:35 -selected=%s:199:3-199:57 -selected=%s:202:3-202:37 -selected=%s:205:3-205:27 -selected=%s:209:3-209:40 %s -DUSECONST | FileCheck --check-prefix=CHECK15 %s class PrivateInstanceVariablesConditionalOperatorRefs { int x; Rectangle r; void callsTakeRef(int y) { takesRef(y == 0 ? x : r.width); } }; // CHECK16: (Rectangle &r, int &x, int y) {\ntakesRef(y == 0 ? x : r.width);\n} // RUN: clang-refactor-test perform -action extract -selected=%s:222:5-222:35 %s | FileCheck --check-prefix=CHECK16 %s class ReferencesInCommaOperator { int x; void callsTakeRef(int y, Rectangle r) { takesRef((x, y)); // CHECK17: (int x, int &y) {\ntakesRef((x, y));\n} takesRef((y, x)); // CHECK17: (int &x, int y) {\ntakesRef((y, x));\n} takesStructRef((takesValue(x), r)); // CHECK17: (Rectangle &r, int x) {\ntakesStructRef((takesValue(x), r));\n} } }; // RUN: clang-refactor-test perform -action extract -selected=%s:232:5-232:21 -selected=%s:234:5-234:21 -selected=%s:236:5-236:39 %s | FileCheck --check-prefix=CHECK17 %s struct StaticMember { static int staticMember; }; void memberMustBeNonStaticField(StaticMember s) { takesRef(s.staticMember); // CHECK18: (const StaticMember &s) {\ntakesRef(s.staticMember);\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:248:3-248:27 %s | FileCheck --check-prefix=CHECK18 %s class ClassWithMethod2 { public: ClassWithMethod member; }; class ClassWithMethod; void nonConstMethodCallImpliesNonConstReceiver2(ClassWithMethod2 x) { x.member.method(); // CHECK19: (ClassWithMethod2 &x) {\nreturn x.member.method();\n} // CHECK20: (const ClassWithMethod2 &x) {\nreturn x.member.method();\n} } // RUN: clang-refactor-test perform -action extract -selected=%s:261:3-261:20 %s | FileCheck --check-prefix=CHECK19 %s // RUN: clang-refactor-test perform -action extract -selected=%s:261:3-261:20 %s -DUSECONST | FileCheck --check-prefix=CHECK20 %s class PrivateInstaceVariablesCallRefsBase { int x; }; class PrivateInstanceVariablesCallRefs2: public PrivateInstaceVariablesCallRefsBase { int y; Rectangle r; void callsTakeRef() { takesRef(this->x); takesRef((this)->y); takesRef(static_cast<PrivateInstaceVariablesCallRefsBase *>(this)->x); takesRef((0, ((const_cast<PrivateInstanceVariablesCallRefs2 *>(this)->r.width)))); } // CHECK21: (PrivateInstanceVariablesCallRefs2 &object) {\ntakesRef(object.x);\n} // CHECK21: (PrivateInstanceVariablesCallRefs2 &object) {\ntakesRef((object).y);\n} // CHECK21: (PrivateInstanceVariablesCallRefs2 &object) {\ntakesRef(static_cast<PrivateInstaceVariablesCallRefsBase *>(&object)->x);\n} // CHECK21: (PrivateInstanceVariablesCallRefs2 &object) {\ntakesRef((0, ((const_cast<PrivateInstanceVariablesCallRefs2 *>(&object)->r.width))));\n} }; // RUN: clang-refactor-test perform -action extract -selected=%s:277:5-277:22 -selected=%s:278:5-278:24 -selected=%s:279:5-279:74 -selected=%s:280:5-280:86 %s | FileCheck --check-prefix=CHECK21 %s
43.826389
366
0.671367
[ "object" ]
1c721d88f0252483f298c0e6f04b304517f18b23
7,793
cc
C++
ShuntingYard/shunting-yard.cc
stephenfire/Book-DISO-WebAssembly
35054b59caa4284680d7dd73bf2637de5631caa7
[ "MIT" ]
57
2018-02-14T02:12:00.000Z
2022-03-04T09:12:26.000Z
ShuntingYard/shunting-yard.cc
stephenfire/Book-DISO-WebAssembly
35054b59caa4284680d7dd73bf2637de5631caa7
[ "MIT" ]
15
2018-08-23T12:37:53.000Z
2021-05-09T10:22:27.000Z
ShuntingYard/shunting-yard.cc
stephenfire/Book-DISO-WebAssembly
35054b59caa4284680d7dd73bf2637de5631caa7
[ "MIT" ]
15
2019-01-27T09:35:19.000Z
2022-02-03T13:56:03.000Z
#include <functional> #include <iostream> #include <sstream> #include <string> #include <vector> #include <deque> #include <cstdio> #include <cmath> class Token { public: enum Type { Unknown = 0, Number, Operator, LeftParen, RightParen, }; Token(Type t, const std::string& s, int prec = -1, bool ra = false) : type { t }, str ( s ), precedence { prec }, rightAssociative { ra } {} Type type { Type::Unknown }; std::string str {}; int precedence { -1 }; bool rightAssociative { false }; }; std::ostream& operator<<(std::ostream& os, const Token& token) { os << token.str; return os; } // Debug output template<class T, class U> void debugReport(const Token& token, const T& queue, const U& stack, const std::string& comment = "") { // String builder; std::ostringstream ossQueue; for(const auto &t : queue) { ossQueue << " " << t; } std::ostringstream ossStack; for(const auto &t : stack) { ossStack << " " << t; } printf("|%-5s|%-32s|%10s| %s\n" , token.str.c_str() , ossQueue.str().c_str() , ossStack.str().c_str() , comment.c_str() ); } std::deque<Token> exprToTokens(const std::string& expr) { std::deque<Token> tokens; for(const auto* p = expr.c_str(); *p; ++p) { if(isdigit(*p)) { const auto* b = p; for(; isdigit(*p); ++p) { ; } const auto s = std::string(b, p); tokens.push_back(Token { Token::Type::Number, s }); --p; } else { Token::Type t = Token::Type::Unknown; int pr = -1; // precedence bool ra = false; // rightAssociative switch(*p) { default: break; case '(': t = Token::Type::LeftParen; break; case ')': t = Token::Type::RightParen; break; case '^': t = Token::Type::Operator; pr = 4; ra = true; break; case '*': t = Token::Type::Operator; pr = 3; break; case '/': t = Token::Type::Operator; pr = 3; break; case '+': t = Token::Type::Operator; pr = 2; break; case '-': t = Token::Type::Operator; pr = 2; break; } tokens.push_back(Token { t, std::string(1, *p), pr, ra }); } } return tokens; } std::deque<Token> shuntingYard(const std::deque<Token>& tokens) { std::deque<Token> queue; std::vector<Token> stack; // While there are tokens to be read: for(auto token : tokens) { // Read a token switch(token.type) { case Token::Type::Number: // If the token is a number, then add it to the output queue queue.push_back(token); break; case Token::Type::Operator: { // If the token is operator, o1, then: const auto o1 = token; // while there is an operator token, while(!stack.empty()) { // o2, at the top of stack, and const auto o2 = stack.back(); // either o1 is left-associative and its precedence is // *less than or equal* to that of o2, // or o1 if right associative, and has precedence // *less than* that of o2, if((! o1.rightAssociative && o1.precedence <= o2.precedence) || ( o1.rightAssociative && o1.precedence < o2.precedence) ) { // then pop o2 off the stack, stack.pop_back(); // onto the output queue; queue.push_back(o2); continue; } // @@ otherwise, exit. break; } // push o1 onto the stack. stack.push_back(o1); } break; case Token::Type::LeftParen: // If token is left parenthesis, then push it onto the stack stack.push_back(token); break; case Token::Type::RightParen: // If token is right parenthesis: { bool match = false; while(! stack.empty()) { // Until the token at the top of the stack // is a left parenthesis, const auto tos = stack.back(); if(tos.type != Token::Type::LeftParen) { // pop operators off the stack stack.pop_back(); // onto the output queue. queue.push_back(tos); } stack.pop_back(); match = true; break; } if(!match && stack.empty()) { printf("RightParen error (%s)\n", token.str.c_str()); exit(0); } } break; default: printf("error (%s)\n", token.str.c_str()); exit(0); break; } debugReport(token, queue, stack); } while(! stack.empty()) { if(stack.back().type == Token::Type::LeftParen) { printf("Mismatched parentheses error\n"); exit(0); } // Pop the operator onto the output queue. queue.push_back(std::move(stack.back())); stack.pop_back(); } debugReport(Token { Token::Type::Unknown, "End" }, queue, stack); return queue; } int main () { // Set testcase; const std::string expr = "20-30/3+4*2^3"; printf("Shunting-yard: \n"); printf("|%-5s|%-32s|%-10s|\n", "Token", "Queue", "Stack"); const auto tokens = exprToTokens(expr); auto queue = shuntingYard(tokens); std::vector<int> stack; printf("\nCalculation: \n"); printf("|%-5s|%-32s|%-10s|\n", "Token", "Queue", "Stack"); while(! queue.empty()) { std::string op; const auto token = queue.front(); queue.pop_front(); switch(token.type) { case Token::Type::Number: stack.push_back(std::stoi(token.str)); op = "Push " + token.str; break; case Token::Type::Operator: { const auto rhs = stack.back(); stack.pop_back(); const auto lhs = stack.back(); stack.pop_back(); switch(token.str[0]) { default: printf("Operator error [%s]\n", token.str.c_str()); exit(0); break; case '^': stack.push_back(static_cast<int>(pow(lhs, rhs))); break; case '*': stack.push_back(lhs * rhs); break; case '/': stack.push_back(lhs / rhs); break; case '+': stack.push_back(lhs + rhs); break; case '-': stack.push_back(lhs - rhs); break; } op = "Push " + std::to_string(lhs) + " " + token.str + " " + std::to_string(rhs); } break; default: printf("Token error\n"); exit(0); } debugReport(token, queue, stack, op); } printf("\n result = %d\n", stack.back()); return 0; }
29.187266
141
0.445528
[ "vector" ]
1c74e0fe304c47a3759625e1ce6a7866618d3a5e
7,520
cpp
C++
Sources/SolarTears/Rendering/Common/Scene/ModernRenderableScene.cpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
4
2021-06-30T16:00:20.000Z
2021-10-13T06:17:56.000Z
Sources/SolarTears/Rendering/Common/Scene/ModernRenderableScene.cpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
Sources/SolarTears/Rendering/Common/Scene/ModernRenderableScene.cpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
#include "ModernRenderableScene.hpp" #include "../RenderingUtils.hpp" #include "../../../Core/FrameCounter.hpp" ModernRenderableScene::ModernRenderableScene(uint64_t constantDataAlignment) { mSceneUploadDataBufferPointer = nullptr; mMaterialDataSize = 0; mStaticObjectDataSize = 0; mObjectChunkDataSize = (uint32_t)Utils::AlignMemory(sizeof(BaseRenderableScene::PerObjectData), constantDataAlignment); mFrameChunkDataSize = (uint32_t)Utils::AlignMemory(sizeof(BaseRenderableScene::PerFrameData), constantDataAlignment); mMaterialChunkDataSize = (uint32_t)Utils::AlignMemory(sizeof(RenderableSceneMaterial), constantDataAlignment); } ModernRenderableScene::~ModernRenderableScene() { } void ModernRenderableScene::UpdateFrameData(const FrameDataUpdateInfo& frameUpdate, uint64_t frameNumber) { uint32_t frameResourceIndex = frameNumber % Utils::InFlightFrameCount; DirectX::XMMATRIX projMatrix = DirectX::XMLoadFloat4x4(&frameUpdate.ProjMatrix); PerFrameData perFrameData = PackFrameData(frameUpdate.CameraLocation, projMatrix); uint64_t frameDataOffset = GetUploadFrameDataOffset(frameResourceIndex); memcpy((std::byte*)mSceneUploadDataBufferPointer + frameDataOffset, &perFrameData, sizeof(PerFrameData)); } void ModernRenderableScene::UpdateRigidSceneObjects(const std::span<ObjectDataUpdateInfo> rigidObjectUpdates, uint64_t frameNumber) { uint32_t prevFrameUpdateIndex = 0; uint32_t currFrameUpdateIndex = 0; uint32_t nextFrameUpdateIndex = 0; uint32_t objectUpdateIndex = 0; //Merge mPrevFrameMeshUpdates and rigidObjectUpdates into updates for the next frame and leftovers, keeping the result sorted while(mPrevFrameRigidMeshUpdates[prevFrameUpdateIndex].MeshHandleIndex != (uint32_t)(-1) || objectUpdateIndex < rigidObjectUpdates.size()) { assert(rigidObjectUpdates[objectUpdateIndex].ObjectId > GetStaticObjectCount()); uint32_t updatedObjectPrevFrameIndex = mPrevFrameRigidMeshUpdates[prevFrameUpdateIndex].MeshHandleIndex; uint32_t updatedObjectToMergeIndex = rigidObjectUpdates[objectUpdateIndex].ObjectId; if(updatedObjectPrevFrameIndex < updatedObjectToMergeIndex) { uint32_t prevDataIndex = mPrevFrameRigidMeshUpdates[objectUpdateIndex].ObjectDataIndex; //Schedule 1 update for the current frame mCurrFrameRigidMeshUpdateIndices[currFrameUpdateIndex] = updatedObjectPrevFrameIndex; mCurrFrameDataToUpdate[currFrameUpdateIndex] = mPrevFrameDataToUpdate[prevDataIndex]; //The remaining updates of the same object go to the next frame while(mPrevFrameRigidMeshUpdates[++prevFrameUpdateIndex].MeshHandleIndex == updatedObjectPrevFrameIndex) { mNextFrameRigidMeshUpdates[nextFrameUpdateIndex++] = { .MeshHandleIndex = updatedObjectPrevFrameIndex, .ObjectDataIndex = currFrameUpdateIndex }; } currFrameUpdateIndex++; } else if(updatedObjectPrevFrameIndex == updatedObjectToMergeIndex) { //Grab 1 update from objectUpdate into the current frame mCurrFrameRigidMeshUpdateIndices[currFrameUpdateIndex] = updatedObjectToMergeIndex; mCurrFrameDataToUpdate[currFrameUpdateIndex] = PackObjectData(rigidObjectUpdates[objectUpdateIndex++].NewObjectLocation); //Grab the same update for next (InFlightFrameCount - 1) frames for(int i = 1; i < Utils::InFlightFrameCount; i++) { mNextFrameRigidMeshUpdates[nextFrameUpdateIndex++] = { .MeshHandleIndex = updatedObjectToMergeIndex, .ObjectDataIndex = currFrameUpdateIndex }; } //The previous updates don't matter anymore, they get rewritten while(mPrevFrameRigidMeshUpdates[++prevFrameUpdateIndex].MeshHandleIndex == updatedObjectPrevFrameIndex); currFrameUpdateIndex++; } else if(updatedObjectPrevFrameIndex > updatedObjectToMergeIndex) { //Grab 1 update from objectUpdate into the current frame mCurrFrameRigidMeshUpdateIndices[currFrameUpdateIndex] = updatedObjectToMergeIndex; mCurrFrameDataToUpdate[currFrameUpdateIndex] = PackObjectData(rigidObjectUpdates[objectUpdateIndex++].NewObjectLocation); //Grab the same update for next (InFlightFrameCount - 1) frames for(int i = 1; i < Utils::InFlightFrameCount; i++) { mNextFrameRigidMeshUpdates[nextFrameUpdateIndex++] = { .MeshHandleIndex = updatedObjectToMergeIndex, .ObjectDataIndex = currFrameUpdateIndex }; } currFrameUpdateIndex++; } } mNextFrameRigidMeshUpdates[nextFrameUpdateIndex] = {.MeshHandleIndex = (uint32_t)(-1), .ObjectDataIndex = (uint32_t)(-1)}; std::swap(mPrevFrameRigidMeshUpdates, mNextFrameRigidMeshUpdates); mCurrFrameUpdatedObjectCount = currFrameUpdateIndex; uint32_t frameResourceIndex = frameNumber % Utils::InFlightFrameCount; for(uint32_t updateIndex = 0; updateIndex < mCurrFrameUpdatedObjectCount; updateIndex++) { uint32_t meshIndex = mCurrFrameRigidMeshUpdateIndices[updateIndex]; uint64_t objectDataOffset = GetUploadRigidObjectDataOffset(frameResourceIndex, meshIndex) - GetStaticObjectCount(); memcpy((std::byte*)mSceneUploadDataBufferPointer + objectDataOffset, &mCurrFrameDataToUpdate[updateIndex], sizeof(PerObjectData)); } std::swap(mPrevFrameDataToUpdate, mCurrFrameDataToUpdate); } uint64_t ModernRenderableScene::GetMaterialDataOffset(uint32_t materialIndex) const { return GetBaseMaterialDataOffset() + (uint64_t)materialIndex * mMaterialChunkDataSize; } uint64_t ModernRenderableScene::GetObjectDataOffset(uint32_t objectIndex) const { //All object data starts at GetBaseStaticObjectDataOffset() return GetBaseStaticObjectDataOffset() + (uint64_t)objectIndex * mObjectChunkDataSize; } uint64_t ModernRenderableScene::GetBaseMaterialDataOffset() const { //Material data is stored at the beginning of the static buffer return 0; } uint64_t ModernRenderableScene::GetBaseFrameDataOffset() const { //Frame data is stored right after material data return GetBaseMaterialDataOffset() + mMaterialDataSize; } uint64_t ModernRenderableScene::GetBaseStaticObjectDataOffset() const { //Object data is stored right after frame data return GetBaseFrameDataOffset() + mFrameDataSize; } uint64_t ModernRenderableScene::GetBaseRigidObjectDataOffset() const { //Rigid object data is stored right after static object data return GetBaseStaticObjectDataOffset() + mStaticObjectDataSize; } uint64_t ModernRenderableScene::GetUploadFrameDataOffset(uint32_t frameResourceIndex) const { //For each frame the frame data is stored in the beginning of this frame part of the dynamic buffer uint64_t wholeFrameResourceSize = (uint64_t)GetRigidObjectCount() * mObjectChunkDataSize + mFrameChunkDataSize; return frameResourceIndex * wholeFrameResourceSize; } uint64_t ModernRenderableScene::GetUploadRigidObjectDataOffset(uint32_t frameResourceIndex, uint32_t rigidObjectDataIndex) const { //For each frame the object data starts immediately after the frame data return GetUploadFrameDataOffset(frameResourceIndex) + mFrameChunkDataSize + (uint64_t)rigidObjectDataIndex * mObjectChunkDataSize; } uint32_t ModernRenderableScene::GetMaterialCount() const { return (uint32_t)(mMaterialDataSize / mMaterialChunkDataSize); } uint32_t ModernRenderableScene::GetStaticObjectCount() const { return (uint32_t)(mStaticObjectDataSize / mObjectChunkDataSize); } uint32_t ModernRenderableScene::GetRigidObjectCount() const { //Since mCurrFrameRigidMeshUpdates is allocated once and never shrinks, its size is equal to the total rigid object count return (uint32_t)mCurrFrameRigidMeshUpdateIndices.size(); }
40
139
0.806782
[ "object" ]
1c78a370e2c3fc0036a752c51a22f255e53e017b
810
hpp
C++
source/include/SevenMonkeys.hpp
jane8384/seven-monkeys
119cb7312f25d54e88f212a8710a512b893b046d
[ "MIT" ]
3
2017-11-16T01:54:09.000Z
2018-05-20T15:33:21.000Z
include/SevenMonkeys.hpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
null
null
null
include/SevenMonkeys.hpp
aitorfernandez/seven-monkeys
8f2440fd5ae7a9e86bb71dba800efe9424f3792e
[ "MIT" ]
3
2017-09-18T11:44:41.000Z
2019-12-25T11:30:26.000Z
// // SevenMonkeys.hpp // SevenMonkeys // #ifndef SevenMonkeys_hpp #define SevenMonkeys_hpp // Cocos2dx #include "cocos2d.h" #include "ui/CocosGUI.h" #include "SimpleAudioEngine.h" #include "external/json/document.h" #include "external/json/rapidjson.h" // C++ Standard Library #include <array> #include <iomanip> #include <iostream> #include <math.h> #include <mach/mach.h> #include <mach/mach_time.h> #include <random> #include <stdio.h> #include <string> #include <vector> // Seven Monkeys settings, utils... #include "Macros.hpp" #include "Constants.hpp" #include "Events.hpp" #include "Util.hpp" // SEVEN_MONKEYS / 1000 Major // SEVEN_MONKEYS / 100 % 10 Minor // SEVEN_MONKEYS % 10 Micro #define SEVEN_MONKEYS 501 #define SEVEN_MONKEYS_STR "0.5.1dev" #endif /* SevenMonkeys_hpp */
18.837209
36
0.714815
[ "vector" ]
cc5d5f30bdc5d2898a858cef88c70e890029f488
443
hpp
C++
src/Nazara/Utility/Formats/MD5MeshLoader.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
376
2015-01-09T03:14:48.000Z
2022-03-26T17:59:18.000Z
src/Nazara/Utility/Formats/MD5MeshLoader.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
252
2015-01-21T17:34:39.000Z
2022-03-20T16:15:50.000Z
src/Nazara/Utility/Formats/MD5MeshLoader.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
104
2015-01-18T11:03:41.000Z
2022-03-11T05:40:47.000Z
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_LOADERS_MD5MESH_HPP #define NAZARA_LOADERS_MD5MESH_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Utility/Mesh.hpp> namespace Nz::Loaders { MeshLoader::Entry GetMeshLoader_MD5Mesh(); } #endif // NAZARA_LOADERS_MD5MESH_HPP
23.315789
77
0.78781
[ "mesh" ]
cc60d76c8dbeaa7443d7e9b28a300bb84ad32b8f
5,053
cpp
C++
src/solved/problem408/problem408.cpp
bgwines/project-euler
06c0dd8e4b2de2909bb8f48e9b02d181de7a19b0
[ "BSD-3-Clause" ]
null
null
null
src/solved/problem408/problem408.cpp
bgwines/project-euler
06c0dd8e4b2de2909bb8f48e9b02d181de7a19b0
[ "BSD-3-Clause" ]
null
null
null
src/solved/problem408/problem408.cpp
bgwines/project-euler
06c0dd8e4b2de2909bb8f48e9b02d181de7a19b0
[ "BSD-3-Clause" ]
null
null
null
/* Let's call a lattice point (x, y) inadmissible if x, y and x + y are all positive perfect squares. For example, (9, 16) is inadmissible, while (0, 4), (3, 1) and (9, 4) are not. Consider a path from point (x1, y1) to point (x2, y2) using only unit steps north or east. Let's call such a path admissible if none of its intermediate points are inadmissible. P(n) be the number of admissible paths from (0, 0) to (n, n). It can be verified that P(5) = 252, P(16) = 596994440 and P(1000) mod 1 000 000 007 = 341920854. Find P(10 000 000) mod 1 000 000 007. Note: this solution requires FLINT (http://www.flintlib.org/) */ #include <vector> #include <map> #include <cmath> #include <stdlib.h> #include <stdio.h> #include "flint.h" #include "fmpz.h" #include "fmpz_mat.h" #include "arith.h" using namespace std; const long N = 10000000; const long K = 1000000007; typedef pair<long, long> point; point LIMIT_PT = point(N, N); point ORIGIN = point(0, 0); ////////////////////////////////////////// void fmpz_mul_mod(fmpz_t& result, const fmpz_t& a, const fmpz_t& b) { fmpz_mul(result, a, b); fmpz_mod_ui(result, result, K); } bool geq_ui(fmpz_t& a, long b) { return fmpz_cmp_ui(a, b) >= 0; } bool leq_ui(fmpz_t& a, long b) { return fmpz_cmp_ui(a, b) <= 0; } void fmpz_add_mod(fmpz_t& result, const fmpz_t& a, const fmpz_t& b) { fmpz_add(result, a, b); if (geq_ui(result, K)) { fmpz_sub_ui(result, result, K); } } void fmpz_sub_mod(fmpz_t& result, const fmpz_t& a, const fmpz_t& b) { fmpz_sub(result, a, b); if (leq_ui(result, 0)) { fmpz_add_ui(result, result, K); } } long div(long numerator_long, long denominator_long) { fmpz_t numerator; fmpz_init(numerator); fmpz_set_ui(numerator, numerator_long); fmpz_t denominator; fmpz_init(denominator); fmpz_set_ui(denominator, denominator_long); fmpz_t KK; fmpz_init(KK); fmpz_set_ui(KK, K); fmpz_invmod(denominator, denominator, KK); fmpz_t result; fmpz_init(result); fmpz_mul_mod(result, numerator, denominator); return fmpz_get_ui(result); } const int ADD = 0; const int SUB = 1; const int MUL = 2; long op(long a_long, long b_long, int op) { fmpz_t a; fmpz_init(a); fmpz_set_ui(a, a_long); fmpz_t b; fmpz_init(b); fmpz_set_ui(b, b_long); if (op == ADD) fmpz_add_mod(a, a, b); if (op == SUB) fmpz_sub_mod(a, a, b); if (op == MUL) fmpz_mul_mod(a, a, b); return fmpz_get_ui(a); } long mul(long a, long b) { return op(a, b, MUL); } long add(long a, long b) { return op(a, b, ADD); } long sub(long a, long b) { return op(a, b, SUB); } ////////////////////////////////////////// long abs(long n) { return (n < 0) ? (-1 * n) : n; } bool is_square(long n) { return sqrt(n) == floor(sqrt(n)); } // largest it will ever be called with is N*2, which is has << 64 bits map<long, long> fact_memo = map<long, long>(); long fact(long n) { return fact_memo[n]; } void fact_init() { fact_memo[0] = 1; for (long i=1; i<=2*N; i++) { fact_memo[i] = mul(i, fact(i - 1)); } } long choose(long n, long k) { return div(fact(n), mul(fact(k), fact(n-k))); } bool pt_eq(point& a, point& b) { return (a.first == b.first) && (a.second == b.second); } bool pt_less(point& a, point& b) { return (a.first <= b.first) && (a.second <= b.second) && !pt_eq(a, b); } vector<long> gen_squares() { vector<long> squares; for (long i=1; i<=sqrt(N); i++) { // N == 10 000 000, which is ~45 bits, so no % K needed squares.push_back(pow(i, 2)); } return squares; } vector<point> gen_inadmissable_points() { vector<long> squares = gen_squares(); vector<point> inadmissable_points; for (size_t i=0; i<squares.size(); i++) { for (size_t j=0; j<squares.size(); j++) { // 30 bits + 30 bits <= 31 bits, so no % K needed if (is_square(squares[i] + squares[j])) { inadmissable_points.push_back(point(squares[i], squares[j])); } } } return inadmissable_points; } long count_num_paths_from_pt_to_pt(point& p1, point& p2) { long num_steps = abs(p1.first - p2.first) + abs(p1.second - p2.second); return choose(num_steps, abs(p1.first - p2.first)); } point swap(point& p) { return point(p.second, p.first); } map<point, long> dp_cache; long count_num_admissible_paths_to( point& pt, vector<point>& inadmissable_points) { if (dp_cache.find(pt) != dp_cache.end()) { return dp_cache[pt]; } long npaths = count_num_paths_from_pt_to_pt(LIMIT_PT, pt); for (size_t j=0; j<inadmissable_points.size(); j++) { point inad_pt = inadmissable_points[j]; if (!pt_less(pt, inad_pt)) { continue; } npaths = sub( npaths, mul( count_num_admissible_paths_to(inad_pt, inadmissable_points), count_num_paths_from_pt_to_pt(inad_pt, pt) ) ); } dp_cache[pt] = npaths; dp_cache[swap(pt)] = npaths; return npaths; } int main(int argc, char const *argv[]) { fact_init(); vector<point> inadmissable_points = gen_inadmissable_points(); long npaths = count_num_admissible_paths_to(ORIGIN, inadmissable_points); printf("Number of admissable paths from (%lu, %lu) to origin: %lu\n", N, N, npaths); return 0; }
21.874459
77
0.65664
[ "vector" ]
cc6a7eee28fe33ea1b2939b6fb1053565af735c6
250,056
hpp
C++
cisco-nx-os/ydk/models/cisco_nx_os/fragmented/Cisco_NX_OS_device_8.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-nx-os/ydk/models/cisco_nx_os/fragmented/Cisco_NX_OS_device_8.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-nx-os/ydk/models/cisco_nx_os/fragmented/Cisco_NX_OS_device_8.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_NX_OS_DEVICE_8_ #define _CISCO_NX_OS_DEVICE_8_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> #include "Cisco_NX_OS_device_0.hpp" #include "Cisco_NX_OS_device_7.hpp" namespace cisco_nx_os { namespace Cisco_NX_OS_device { class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::EcommItems::RtItems : public ydk::Entity { public: RtItems(); ~RtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExtCommRtList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList ydk::YList extcommrt_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::EcommItems::RtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList : public ydk::Entity { public: ExtCommRtList(); ~ExtCommRtList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems : public ydk::Entity { public: LnkstattrItems(); ~LnkstattrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf lnkattrflags; //type: string ydk::YLeaf attrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList ydk::YList lnkstattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList : public ydk::Entity { public: LnkStAttrEntryList(); ~LnkStAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpLsAttrEntryType ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems : public ydk::Entity { public: PfxsidItems(); ~PfxsidItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfxsidattrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PfxSidAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList ydk::YList pfxsidattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList : public ydk::Entity { public: PfxSidAttrEntryList(); ~PfxSidAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpPfxSidAttrEntryType ydk::YLeaf len; //type: uint16 ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PmsiItems : public ydk::Entity { public: PmsiItems(); ~PmsiItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf flags; //type: string ydk::YLeaf tuntype; //type: BgpPmsiTunType ydk::YLeaf lbl; //type: uint32 ydk::YLeaf tunid; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LblrtItems::LblRouteList::PathItems::PathList::PmsiItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems : public ydk::Entity { public: LsrtItems(); ~LsrtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStRouteList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList ydk::YList lnkstroute_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList : public ydk::Entity { public: LnkStRouteList(); ~LnkStRouteList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfx; //type: string ydk::YLeaf nlritype; //type: BgpLsNlriType ydk::YLeaf protoid; //type: BgpLsProtoId ydk::YLeaf name; //type: string ydk::YLeaf ver; //type: uint32 ydk::YLeaf rtflags; //type: string ydk::YLeaf numpaths; //type: uint32 ydk::YLeaf bestpathid; //type: uint32 class PathItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems> path_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems : public ydk::Entity { public: PathItems(); ~PathItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList ydk::YList path_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList : public ydk::Entity { public: PathList(); ~PathList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer; //type: string ydk::YLeaf id; //type: uint32 ydk::YLeaf nh; //type: string ydk::YLeaf importedrd; //type: string ydk::YLeaf origimportedrd; //type: string ydk::YLeaf nhmetric; //type: uint32 ydk::YLeaf type; //type: BgpPathT ydk::YLeaf operst; //type: BgpPathSt ydk::YLeaf flags; //type: string ydk::YLeaf origin; //type: BgpOrigin ydk::YLeaf metric; //type: uint32 ydk::YLeaf localpref; //type: uint32 ydk::YLeaf weight; //type: uint16 ydk::YLeaf aggr; //type: string ydk::YLeaf aggras; //type: string ydk::YLeaf unknownattrdata; //type: string ydk::YLeaf unknownattrlen; //type: uint32 ydk::YLeaf regcomm; //type: string ydk::YLeaf extcomm; //type: string ydk::YLeaf aspath; //type: string ydk::YLeaf rcvdlbl; //type: string ydk::YLeaf originatorid; //type: string ydk::YLeaf clusterlst; //type: string ydk::YLeaf peerrtrid; //type: string ydk::YLeaf numimported; //type: uint16 ydk::YLeaf importedlst; //type: string ydk::YLeaf importedsrc; //type: string ydk::YLeaf origimportedsrc; //type: string class SegItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems class RcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems class EcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems class LnkstattrItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems class PfxsidItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems class PmsiItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PmsiItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems> seg_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems> rcomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems> ecomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems> lnkstattr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems> pfxsid_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PmsiItems> pmsi_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems : public ydk::Entity { public: SegItems(); ~SegItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsSegList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList ydk::YList asseg_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList : public ydk::Entity { public: AsSegList(); ~AsSegList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf type; //type: BgpAsSegT class AsnItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems> asn_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems : public ydk::Entity { public: AsnItems(); ~AsnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsItemList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList ydk::YList asitem_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList : public ydk::Entity { public: AsItemList(); ~AsItemList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems : public ydk::Entity { public: RcommItems(); ~RcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RegCommList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems::RegCommList ydk::YList regcomm_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems::RegCommList : public ydk::Entity { public: RegCommList(); ~RegCommList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::RcommItems::RegCommList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems : public ydk::Entity { public: EcommItems(); ~EcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf encap; //type: string ydk::YLeaf rtrmac; //type: string class RtItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems> rt_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems : public ydk::Entity { public: RtItems(); ~RtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExtCommRtList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList ydk::YList extcommrt_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList : public ydk::Entity { public: ExtCommRtList(); ~ExtCommRtList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems : public ydk::Entity { public: LnkstattrItems(); ~LnkstattrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf lnkattrflags; //type: string ydk::YLeaf attrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList ydk::YList lnkstattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList : public ydk::Entity { public: LnkStAttrEntryList(); ~LnkStAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpLsAttrEntryType ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems : public ydk::Entity { public: PfxsidItems(); ~PfxsidItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfxsidattrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PfxSidAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList ydk::YList pfxsidattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList : public ydk::Entity { public: PfxSidAttrEntryList(); ~PfxSidAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpPfxSidAttrEntryType ydk::YLeaf len; //type: uint16 ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PmsiItems : public ydk::Entity { public: PmsiItems(); ~PmsiItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf flags; //type: string ydk::YLeaf tuntype; //type: BgpPmsiTunType ydk::YLeaf lbl; //type: uint32 ydk::YLeaf tunid; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::LsrtItems::LnkStRouteList::PathItems::PathList::PmsiItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems : public ydk::Entity { public: EvpnrtItems(); ~EvpnrtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class EvpnRouteList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList ydk::YList evpnroute_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList : public ydk::Entity { public: EvpnRouteList(); ~EvpnRouteList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfx; //type: string ydk::YLeaf rd; //type: string ydk::YLeaf rttype; //type: BgpEvpnRtType ydk::YLeaf name; //type: string ydk::YLeaf ver; //type: uint32 ydk::YLeaf rtflags; //type: string ydk::YLeaf numpaths; //type: uint32 ydk::YLeaf bestpathid; //type: uint32 class PathItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems> path_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems : public ydk::Entity { public: PathItems(); ~PathItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList ydk::YList path_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList : public ydk::Entity { public: PathList(); ~PathList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer; //type: string ydk::YLeaf id; //type: uint32 ydk::YLeaf nh; //type: string ydk::YLeaf importedrd; //type: string ydk::YLeaf origimportedrd; //type: string ydk::YLeaf nhmetric; //type: uint32 ydk::YLeaf type; //type: BgpPathT ydk::YLeaf operst; //type: BgpPathSt ydk::YLeaf flags; //type: string ydk::YLeaf origin; //type: BgpOrigin ydk::YLeaf metric; //type: uint32 ydk::YLeaf localpref; //type: uint32 ydk::YLeaf weight; //type: uint16 ydk::YLeaf aggr; //type: string ydk::YLeaf aggras; //type: string ydk::YLeaf unknownattrdata; //type: string ydk::YLeaf unknownattrlen; //type: uint32 ydk::YLeaf regcomm; //type: string ydk::YLeaf extcomm; //type: string ydk::YLeaf aspath; //type: string ydk::YLeaf rcvdlbl; //type: string ydk::YLeaf originatorid; //type: string ydk::YLeaf clusterlst; //type: string ydk::YLeaf peerrtrid; //type: string ydk::YLeaf numimported; //type: uint16 ydk::YLeaf importedlst; //type: string ydk::YLeaf importedsrc; //type: string ydk::YLeaf origimportedsrc; //type: string class SegItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems class RcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems class EcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems class LnkstattrItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems class PfxsidItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems class PmsiItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PmsiItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems> seg_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems> rcomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems> ecomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems> lnkstattr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems> pfxsid_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PmsiItems> pmsi_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems : public ydk::Entity { public: SegItems(); ~SegItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsSegList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList ydk::YList asseg_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList : public ydk::Entity { public: AsSegList(); ~AsSegList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf type; //type: BgpAsSegT class AsnItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems> asn_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems : public ydk::Entity { public: AsnItems(); ~AsnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsItemList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList ydk::YList asitem_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList : public ydk::Entity { public: AsItemList(); ~AsItemList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems : public ydk::Entity { public: RcommItems(); ~RcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RegCommList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems::RegCommList ydk::YList regcomm_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems::RegCommList : public ydk::Entity { public: RegCommList(); ~RegCommList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::RcommItems::RegCommList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems : public ydk::Entity { public: EcommItems(); ~EcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf encap; //type: string ydk::YLeaf rtrmac; //type: string class RtItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems> rt_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems : public ydk::Entity { public: RtItems(); ~RtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExtCommRtList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList ydk::YList extcommrt_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList : public ydk::Entity { public: ExtCommRtList(); ~ExtCommRtList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems : public ydk::Entity { public: LnkstattrItems(); ~LnkstattrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf lnkattrflags; //type: string ydk::YLeaf attrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList ydk::YList lnkstattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList : public ydk::Entity { public: LnkStAttrEntryList(); ~LnkStAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpLsAttrEntryType ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems : public ydk::Entity { public: PfxsidItems(); ~PfxsidItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfxsidattrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PfxSidAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList ydk::YList pfxsidattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList : public ydk::Entity { public: PfxSidAttrEntryList(); ~PfxSidAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpPfxSidAttrEntryType ydk::YLeaf len; //type: uint16 ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PmsiItems : public ydk::Entity { public: PmsiItems(); ~PmsiItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf flags; //type: string ydk::YLeaf tuntype; //type: BgpPmsiTunType ydk::YLeaf lbl; //type: uint32 ydk::YLeaf tunid; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::EvpnrtItems::EvpnRouteList::PathItems::PathList::PmsiItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems : public ydk::Entity { public: MvpnrtItems(); ~MvpnrtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class MvpnRouteList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList ydk::YList mvpnroute_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList : public ydk::Entity { public: MvpnRouteList(); ~MvpnRouteList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfx; //type: string ydk::YLeaf rd; //type: string ydk::YLeaf rttype; //type: BgpMvpnRtType ydk::YLeaf name; //type: string ydk::YLeaf ver; //type: uint32 ydk::YLeaf rtflags; //type: string ydk::YLeaf numpaths; //type: uint32 ydk::YLeaf bestpathid; //type: uint32 class PathItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems> path_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems : public ydk::Entity { public: PathItems(); ~PathItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList ydk::YList path_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList : public ydk::Entity { public: PathList(); ~PathList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer; //type: string ydk::YLeaf id; //type: uint32 ydk::YLeaf nh; //type: string ydk::YLeaf importedrd; //type: string ydk::YLeaf origimportedrd; //type: string ydk::YLeaf nhmetric; //type: uint32 ydk::YLeaf type; //type: BgpPathT ydk::YLeaf operst; //type: BgpPathSt ydk::YLeaf flags; //type: string ydk::YLeaf origin; //type: BgpOrigin ydk::YLeaf metric; //type: uint32 ydk::YLeaf localpref; //type: uint32 ydk::YLeaf weight; //type: uint16 ydk::YLeaf aggr; //type: string ydk::YLeaf aggras; //type: string ydk::YLeaf unknownattrdata; //type: string ydk::YLeaf unknownattrlen; //type: uint32 ydk::YLeaf regcomm; //type: string ydk::YLeaf extcomm; //type: string ydk::YLeaf aspath; //type: string ydk::YLeaf rcvdlbl; //type: string ydk::YLeaf originatorid; //type: string ydk::YLeaf clusterlst; //type: string ydk::YLeaf peerrtrid; //type: string ydk::YLeaf numimported; //type: uint16 ydk::YLeaf importedlst; //type: string ydk::YLeaf importedsrc; //type: string ydk::YLeaf origimportedsrc; //type: string class SegItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems class RcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems class EcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems class LnkstattrItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems class PfxsidItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems class PmsiItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems> seg_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems> rcomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems> ecomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems> lnkstattr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems> pfxsid_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems> pmsi_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems : public ydk::Entity { public: SegItems(); ~SegItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsSegList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList ydk::YList asseg_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList : public ydk::Entity { public: AsSegList(); ~AsSegList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf type; //type: BgpAsSegT class AsnItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems> asn_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems : public ydk::Entity { public: AsnItems(); ~AsnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsItemList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList ydk::YList asitem_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList : public ydk::Entity { public: AsItemList(); ~AsItemList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems : public ydk::Entity { public: RcommItems(); ~RcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RegCommList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems::RegCommList ydk::YList regcomm_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems::RegCommList : public ydk::Entity { public: RegCommList(); ~RegCommList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems::RegCommList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems : public ydk::Entity { public: EcommItems(); ~EcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf encap; //type: string ydk::YLeaf rtrmac; //type: string class RtItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems> rt_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems : public ydk::Entity { public: RtItems(); ~RtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExtCommRtList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList ydk::YList extcommrt_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList : public ydk::Entity { public: ExtCommRtList(); ~ExtCommRtList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems : public ydk::Entity { public: LnkstattrItems(); ~LnkstattrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf lnkattrflags; //type: string ydk::YLeaf attrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList ydk::YList lnkstattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList : public ydk::Entity { public: LnkStAttrEntryList(); ~LnkStAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpLsAttrEntryType ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems : public ydk::Entity { public: PfxsidItems(); ~PfxsidItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfxsidattrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PfxSidAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList ydk::YList pfxsidattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList : public ydk::Entity { public: PfxSidAttrEntryList(); ~PfxSidAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpPfxSidAttrEntryType ydk::YLeaf len; //type: uint16 ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems : public ydk::Entity { public: PmsiItems(); ~PmsiItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf flags; //type: string ydk::YLeaf tuntype; //type: BgpPmsiTunType ydk::YLeaf lbl; //type: uint32 ydk::YLeaf tunid; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::NhItems::NextHopRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems : public ydk::Entity { public: MrttypeItems(); ~MrttypeItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class McastRtTypeRoutesList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList ydk::YList mcastrttyperoutes_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList : public ydk::Entity { public: McastRtTypeRoutesList(); ~McastRtTypeRoutesList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf rttype; //type: BgpMvpnRtType class MvpnrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems> mvpnrt_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems : public ydk::Entity { public: MvpnrtItems(); ~MvpnrtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class MvpnRouteList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList ydk::YList mvpnroute_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList : public ydk::Entity { public: MvpnRouteList(); ~MvpnRouteList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfx; //type: string ydk::YLeaf rd; //type: string ydk::YLeaf rttype; //type: BgpMvpnRtType ydk::YLeaf name; //type: string ydk::YLeaf ver; //type: uint32 ydk::YLeaf rtflags; //type: string ydk::YLeaf numpaths; //type: uint32 ydk::YLeaf bestpathid; //type: uint32 class PathItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems> path_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems : public ydk::Entity { public: PathItems(); ~PathItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList ydk::YList path_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList : public ydk::Entity { public: PathList(); ~PathList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer; //type: string ydk::YLeaf id; //type: uint32 ydk::YLeaf nh; //type: string ydk::YLeaf importedrd; //type: string ydk::YLeaf origimportedrd; //type: string ydk::YLeaf nhmetric; //type: uint32 ydk::YLeaf type; //type: BgpPathT ydk::YLeaf operst; //type: BgpPathSt ydk::YLeaf flags; //type: string ydk::YLeaf origin; //type: BgpOrigin ydk::YLeaf metric; //type: uint32 ydk::YLeaf localpref; //type: uint32 ydk::YLeaf weight; //type: uint16 ydk::YLeaf aggr; //type: string ydk::YLeaf aggras; //type: string ydk::YLeaf unknownattrdata; //type: string ydk::YLeaf unknownattrlen; //type: uint32 ydk::YLeaf regcomm; //type: string ydk::YLeaf extcomm; //type: string ydk::YLeaf aspath; //type: string ydk::YLeaf rcvdlbl; //type: string ydk::YLeaf originatorid; //type: string ydk::YLeaf clusterlst; //type: string ydk::YLeaf peerrtrid; //type: string ydk::YLeaf numimported; //type: uint16 ydk::YLeaf importedlst; //type: string ydk::YLeaf importedsrc; //type: string ydk::YLeaf origimportedsrc; //type: string class SegItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems class RcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems class EcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems class LnkstattrItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems class PfxsidItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems class PmsiItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems> seg_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems> rcomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems> ecomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems> lnkstattr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems> pfxsid_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems> pmsi_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems : public ydk::Entity { public: SegItems(); ~SegItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsSegList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList ydk::YList asseg_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList : public ydk::Entity { public: AsSegList(); ~AsSegList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf type; //type: BgpAsSegT class AsnItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems> asn_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems : public ydk::Entity { public: AsnItems(); ~AsnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsItemList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList ydk::YList asitem_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList : public ydk::Entity { public: AsItemList(); ~AsItemList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems : public ydk::Entity { public: RcommItems(); ~RcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RegCommList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems::RegCommList ydk::YList regcomm_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems::RegCommList : public ydk::Entity { public: RegCommList(); ~RegCommList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::RcommItems::RegCommList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems : public ydk::Entity { public: EcommItems(); ~EcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf encap; //type: string ydk::YLeaf rtrmac; //type: string class RtItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems> rt_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems : public ydk::Entity { public: RtItems(); ~RtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExtCommRtList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList ydk::YList extcommrt_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList : public ydk::Entity { public: ExtCommRtList(); ~ExtCommRtList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::EcommItems::RtItems::ExtCommRtList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems : public ydk::Entity { public: LnkstattrItems(); ~LnkstattrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf lnkattrflags; //type: string ydk::YLeaf attrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList ydk::YList lnkstattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList : public ydk::Entity { public: LnkStAttrEntryList(); ~LnkStAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpLsAttrEntryType ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems : public ydk::Entity { public: PfxsidItems(); ~PfxsidItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfxsidattrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PfxSidAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList ydk::YList pfxsidattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList : public ydk::Entity { public: PfxSidAttrEntryList(); ~PfxSidAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpPfxSidAttrEntryType ydk::YLeaf len; //type: uint16 ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems : public ydk::Entity { public: PmsiItems(); ~PmsiItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf flags; //type: string ydk::YLeaf tuntype; //type: BgpPmsiTunType ydk::YLeaf lbl; //type: uint32 ydk::YLeaf tunid; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::MrttypeItems::McastRtTypeRoutesList::MvpnrtItems::MvpnRouteList::PathItems::PathList::PmsiItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::DefrtleakItems : public ydk::Entity { public: DefrtleakItems(); ~DefrtleakItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf scope; //type: RtleakScope ydk::YLeaf rtmap; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::DefrtleakItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InterleakItems : public ydk::Entity { public: InterleakItems(); ~InterleakItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class InterLeakPList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InterleakItems::InterLeakPList ydk::YList interleakp_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InterleakItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InterleakItems::InterLeakPList : public ydk::Entity { public: InterLeakPList(); ~InterLeakPList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf proto; //type: RtleakProto ydk::YLeaf inst; //type: string ydk::YLeaf scope; //type: RtleakScope ydk::YLeaf rtmap; //type: string ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InterleakItems::InterLeakPList class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InjnameItems : public ydk::Entity { public: InjnameItems(); ~InjnameItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class InjLeakPList; //type: System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InjnameItems::InjLeakPList ydk::YList injleakp_list; }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InjnameItems class System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InjnameItems::InjLeakPList : public ydk::Entity { public: InjLeakPList(); ~InjLeakPList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf name; //type: string ydk::YLeaf rtmap; //type: string ydk::YLeaf copyattr; //type: BgpAdminSt ydk::YLeaf scope; //type: RtleakScope }; // System::BgpItems::InstItems::DomItems::DomList::AfItems::DomAfList::InjnameItems::InjLeakPList class System::BgpItems::InstItems::DomItems::DomList::BmpItems : public ydk::Entity { public: BmpItems(); ~BmpItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class BmpSvrList; //type: System::BgpItems::InstItems::DomItems::DomList::BmpItems::BmpSvrList ydk::YList bmpsvr_list; }; // System::BgpItems::InstItems::DomItems::DomList::BmpItems class System::BgpItems::InstItems::DomItems::DomList::BmpItems::BmpSvrList : public ydk::Entity { public: BmpSvrList(); ~BmpSvrList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf id; //type: uint8 ydk::YLeaf addr; //type: string ydk::YLeaf port; //type: uint16 ydk::YLeaf descr; //type: string ydk::YLeaf refreshintvldelay; //type: uint16 ydk::YLeaf refreshintvlskip; //type: boolean ydk::YLeaf delayintvl; //type: uint16 ydk::YLeaf statintvl; //type: uint16 ydk::YLeaf adminst; //type: BgpBmpSt ydk::YLeaf vrfname; //type: string ydk::YLeaf srcif; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::BmpItems::BmpSvrList class System::BgpItems::InstItems::DomItems::DomList::GrItems : public ydk::Entity { public: GrItems(); ~GrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf ctrl; //type: string ydk::YLeaf restartintvl; //type: uint16 ydk::YLeaf staleintvl; //type: uint16 }; // System::BgpItems::InstItems::DomItems::DomList::GrItems class System::BgpItems::InstItems::DomItems::DomList::GsItems : public ydk::Entity { public: GsItems(); ~GsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf shut; //type: boolean ydk::YLeaf rtmap; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::GsItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems : public ydk::Entity { public: PeerItems(); ~PeerItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PeerList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList ydk::YList peer_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList : public ydk::Entity { public: PeerList(); ~PeerList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf addr; //type: string ydk::YLeaf adminst; //type: NwAdminSt___ ydk::YLeaf asn; //type: string ydk::YLeaf lognbrchgs; //type: BgpLogNbrSt ydk::YLeaf peertype; //type: BgpPeerFabType ydk::YLeaf dynrtmap; //type: string ydk::YLeaf srcif; //type: string ydk::YLeaf password; //type: string ydk::YLeaf passwdtype; //type: BgpPwdType ydk::YLeaf ctrl; //type: string ydk::YLeaf ttl; //type: uint16 ydk::YLeaf kaintvl; //type: uint16 ydk::YLeaf holdintvl; //type: uint16 ydk::YLeaf connmode; //type: string ydk::YLeaf maxpeercnt; //type: uint32 ydk::YLeaf sessioncontimp; //type: string ydk::YLeaf peerimp; //type: string ydk::YLeaf privateasctrl; //type: BgpPrivateASControl ydk::YLeaf epe; //type: BgpAdminSt ydk::YLeaf epepeerset; //type: string ydk::YLeaf lowmemexempt; //type: BgpAdminSt ydk::YLeaf capsuppr4byteasn; //type: BgpAdminSt ydk::YLeaf affgrp; //type: uint16 ydk::YLeaf ttlscrtyhops; //type: uint16 ydk::YLeaf bmpsrvid1st; //type: BgpAdminSt ydk::YLeaf bmpsrvid2st; //type: BgpAdminSt ydk::YLeaf dscp; //type: BgpBgpDscp ydk::YLeaf maxpfxpeers; //type: uint64 ydk::YLeaf curpfxpeers; //type: uint64 ydk::YLeaf activepfxpeers; //type: uint64 ydk::YLeaf maxcurpeers; //type: uint64 ydk::YLeaf totalpfxpeers; //type: uint64 ydk::YLeaf gshutoperst; //type: BgpAdminSt ydk::YLeaf inheritcontpeerctrl; //type: string ydk::YLeaf name; //type: string class GsItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::GsItems class LocalasnItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::LocalasnItems class EntItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems class EpeItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems class AfItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::GsItems> gs_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::LocalasnItems> localasn_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems> ent_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems> epe_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems> af_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::GsItems : public ydk::Entity { public: GsItems(); ~GsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf shut; //type: boolean ydk::YLeaf rtmap; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::GsItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::LocalasnItems : public ydk::Entity { public: LocalasnItems(); ~LocalasnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf localasn; //type: string ydk::YLeaf asnpropagate; //type: BgpAsnPropagation }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::LocalasnItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems : public ydk::Entity { public: EntItems(); ~EntItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PeerEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList ydk::YList peerentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList : public ydk::Entity { public: PeerEntryList(); ~PeerEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf addr; //type: string ydk::YLeaf type; //type: BgpPeerType ydk::YLeaf rtrid; //type: string ydk::YLeaf operst; //type: BgpPeerOperSt ydk::YLeaf prevoperst; //type: BgpPeerOperSt ydk::YLeaf shutstqual; //type: BgpShutStQual ydk::YLeaf lastflapts; //type: one of uint64, string ydk::YLeaf maxconnretryintvl; //type: uint16 ydk::YLeaf flags; //type: string ydk::YLeaf advcap; //type: string ydk::YLeaf rcvcap; //type: string ydk::YLeaf connif; //type: string ydk::YLeaf holdintvl; //type: uint16 ydk::YLeaf kaintvl; //type: uint16 ydk::YLeaf localip; //type: string ydk::YLeaf localport; //type: uint16 ydk::YLeaf remoteport; //type: uint16 ydk::YLeaf connest; //type: uint16 ydk::YLeaf conndrop; //type: uint16 ydk::YLeaf updateelapsedts; //type: one of uint64, string ydk::YLeaf fd; //type: uint32 ydk::YLeaf peeridx; //type: uint16 ydk::YLeaf connattempts; //type: uint32 ydk::YLeaf streason; //type: BgpStReason ydk::YLeaf passwdset; //type: BgpPasswdSet class GrItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::GrItems class EvItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EvItems class EpeItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems class AfItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems class PeerstatsItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::PeerstatsItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::GrItems> gr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EvItems> ev_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems> epe_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems> af_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::PeerstatsItems> peerstats_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::GrItems : public ydk::Entity { public: GrItems(); ~GrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf operst; //type: BgpPeerGrSt ydk::YLeaf restartintvl; //type: uint16 ydk::YLeaf grts; //type: one of uint64, string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::GrItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EvItems : public ydk::Entity { public: EvItems(); ~EvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf majerrrstsent; //type: BgpMajNotifErr ydk::YLeaf minerrrstsent; //type: BgpMinNotifErr ydk::YLeaf lasterrvalsent; //type: uint32 ydk::YLeaf rstsentts; //type: one of uint64, string ydk::YLeaf majerrrstrsvd; //type: BgpMajNotifErr ydk::YLeaf minerrrstrsvd; //type: BgpMinNotifErr ydk::YLeaf lasterrvalrsvd; //type: uint32 ydk::YLeaf rstrsvdts; //type: one of uint64, string ydk::YLeaf lasterrlenrsvd; //type: uint8 ydk::YLeaf lasterrlensent; //type: uint8 ydk::YLeaf lasterrdatarsvd; //type: string ydk::YLeaf lasterrdatasent; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EvItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems : public ydk::Entity { public: EpeItems(); ~EpeItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf adminst; //type: BgpEgressPeerEng ydk::YLeaf sid; //type: uint32 ydk::YLeaf rpcsetid; //type: uint32 ydk::YLeaf peersetname; //type: string ydk::YLeaf peersetsid; //type: uint32 ydk::YLeaf peersetrpcsetid; //type: uint32 class EpeadjItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems> epeadj_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems : public ydk::Entity { public: EpeadjItems(); ~EpeadjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PeerEpeAdjList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems::PeerEpeAdjList ydk::YList peerepeadj_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems::PeerEpeAdjList : public ydk::Entity { public: PeerEpeAdjList(); ~PeerEpeAdjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf rpcsetid; //type: uint32 ydk::YLeaf localaddr; //type: string ydk::YLeaf remoteaddr; //type: string ydk::YLeaf ifindex; //type: string ydk::YLeaf sid; //type: uint32 }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::EpeItems::EpeadjItems::PeerEpeAdjList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems : public ydk::Entity { public: AfItems(); ~AfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PeerAfEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems::PeerAfEntryList ydk::YList peerafentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems::PeerAfEntryList : public ydk::Entity { public: PeerAfEntryList(); ~PeerAfEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpAfT ydk::YLeaf tblver; //type: uint32 ydk::YLeaf peertblver; //type: uint32 ydk::YLeaf tblst; //type: BgpTblSt ydk::YLeaf acceptedpaths; //type: uint32 ydk::YLeaf deniedpaths; //type: uint32 ydk::YLeaf withdrawnpaths; //type: uint32 ydk::YLeaf memaccpaths; //type: uint32 ydk::YLeaf flags; //type: string ydk::YLeaf pfxsent; //type: uint64 ydk::YLeaf pfxsaved; //type: uint64 ydk::YLeaf pfxflushed; //type: uint64 ydk::YLeaf lasteorrcvdts; //type: one of uint64, string ydk::YLeaf firsteorrcvdts; //type: one of uint64, string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::AfItems::PeerAfEntryList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::PeerstatsItems : public ydk::Entity { public: PeerstatsItems(); ~PeerstatsItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf opensent; //type: uint64 ydk::YLeaf openrcvd; //type: uint64 ydk::YLeaf updatesent; //type: uint64 ydk::YLeaf updatercvd; //type: uint64 ydk::YLeaf kasent; //type: uint64 ydk::YLeaf karcvd; //type: uint64 ydk::YLeaf routerefreshsent; //type: uint64 ydk::YLeaf routerefreshrcvd; //type: uint64 ydk::YLeaf capsent; //type: uint64 ydk::YLeaf caprcvd; //type: uint64 ydk::YLeaf notifsent; //type: uint64 ydk::YLeaf notifrcvd; //type: uint64 ydk::YLeaf msgsent; //type: uint64 ydk::YLeaf msgrcvd; //type: uint64 ydk::YLeaf bytesent; //type: uint64 ydk::YLeaf bytercvd; //type: uint64 ydk::YLeaf byteinsendq; //type: uint64 ydk::YLeaf byteinrecvq; //type: uint64 ydk::YLeaf connectretryts; //type: one of uint64, string ydk::YLeaf kats; //type: one of uint64, string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EntItems::PeerEntryList::PeerstatsItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems : public ydk::Entity { public: EpeItems(); ~EpeItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf adminst; //type: BgpEgressPeerEng ydk::YLeaf sid; //type: uint32 ydk::YLeaf rpcsetid; //type: uint32 ydk::YLeaf peersetname; //type: string ydk::YLeaf peersetsid; //type: uint32 ydk::YLeaf peersetrpcsetid; //type: uint32 class EpeadjItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems> epeadj_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems : public ydk::Entity { public: EpeadjItems(); ~EpeadjItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PeerEpeAdjList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems::PeerEpeAdjList ydk::YList peerepeadj_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems::PeerEpeAdjList : public ydk::Entity { public: PeerEpeAdjList(); ~PeerEpeAdjList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf rpcsetid; //type: uint32 ydk::YLeaf localaddr; //type: string ydk::YLeaf remoteaddr; //type: string ydk::YLeaf ifindex; //type: string ydk::YLeaf sid; //type: uint32 }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::EpeItems::EpeadjItems::PeerEpeAdjList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems : public ydk::Entity { public: AfItems(); ~AfItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PeerAfList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList ydk::YList peeraf_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList : public ydk::Entity { public: PeerAfList(); ~PeerAfList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpAfT ydk::YLeaf ctrl; //type: string ydk::YLeaf allowedselfascnt; //type: uint8 ydk::YLeaf softreconfigbackup; //type: BgpSoftReconfigBackup ydk::YLeaf advintvl; //type: uint16 ydk::YLeaf deforg; //type: BgpAdminSt ydk::YLeaf deforgrtmap; //type: string ydk::YLeaf capaddlpaths; //type: string ydk::YLeaf unsupprmap; //type: string ydk::YLeaf asoverride; //type: BgpAdminSt ydk::YLeaf nhthirdparty; //type: BgpAdminSt ydk::YLeaf wght; //type: string ydk::YLeaf soo; //type: string ydk::YLeaf sendcomstd; //type: BgpAdminSt ydk::YLeaf sendcomext; //type: BgpAdminSt ydk::YLeaf encapmpls; //type: BgpAdminSt ydk::YLeaf rewritertasn; //type: BgpAdminSt ydk::YLeaf advgwip; //type: NwAdminSt___ ydk::YLeaf advlocallblrt; //type: NwAdminSt___ ydk::YLeaf nhselfall; //type: boolean ydk::YLeaf inheritcontpeerpolicyctrl; //type: string ydk::YLeaf name; //type: string class MaxpfxpItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::MaxpfxpItems class AdvtmapItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::AdvtmapItems class RtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems class VpnrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems class LblrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::LblrtItems class LsrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::LsrtItems class EvpnrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::EvpnrtItems class MvpnrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::MvpnrtItems class AdvtdrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::AdvtdrtItems class RcvdrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RcvdrtItems class DamppathsrtItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::DamppathsrtItems class RtctrlItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtctrlItems class DefrtleakItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::DefrtleakItems class PfxctrlItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::PfxctrlItems class FltrctrlItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::FltrctrlItems class PolItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::PolItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::MaxpfxpItems> maxpfxp_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::AdvtmapItems> advtmap_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems> rt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems> vpnrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::LblrtItems> lblrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::LsrtItems> lsrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::EvpnrtItems> evpnrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::MvpnrtItems> mvpnrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::AdvtdrtItems> advtdrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RcvdrtItems> rcvdrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::DamppathsrtItems> damppathsrt_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtctrlItems> rtctrl_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::DefrtleakItems> defrtleak_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::PfxctrlItems> pfxctrl_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::FltrctrlItems> fltrctrl_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::PolItems> pol_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::MaxpfxpItems : public ydk::Entity { public: MaxpfxpItems(); ~MaxpfxpItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf maxpfx; //type: uint32 ydk::YLeaf thresh; //type: uint8 ydk::YLeaf action; //type: BgpMaxPfxAct ydk::YLeaf restarttime; //type: uint16 }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::MaxpfxpItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::AdvtmapItems : public ydk::Entity { public: AdvtmapItems(); ~AdvtmapItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf rtmap; //type: string ydk::YLeaf condition; //type: BgpAdvtMapCondition ydk::YLeaf condmap; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::AdvtmapItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems : public ydk::Entity { public: RtItems(); ~RtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RouteList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList ydk::YList route_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList : public ydk::Entity { public: RouteList(); ~RouteList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfx; //type: string ydk::YLeaf name; //type: string ydk::YLeaf ver; //type: uint32 ydk::YLeaf rtflags; //type: string ydk::YLeaf numpaths; //type: uint32 ydk::YLeaf bestpathid; //type: uint32 class PathItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems> path_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems : public ydk::Entity { public: PathItems(); ~PathItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList ydk::YList path_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList : public ydk::Entity { public: PathList(); ~PathList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer; //type: string ydk::YLeaf id; //type: uint32 ydk::YLeaf nh; //type: string ydk::YLeaf importedrd; //type: string ydk::YLeaf origimportedrd; //type: string ydk::YLeaf nhmetric; //type: uint32 ydk::YLeaf type; //type: BgpPathT ydk::YLeaf operst; //type: BgpPathSt ydk::YLeaf flags; //type: string ydk::YLeaf origin; //type: BgpOrigin ydk::YLeaf metric; //type: uint32 ydk::YLeaf localpref; //type: uint32 ydk::YLeaf weight; //type: uint16 ydk::YLeaf aggr; //type: string ydk::YLeaf aggras; //type: string ydk::YLeaf unknownattrdata; //type: string ydk::YLeaf unknownattrlen; //type: uint32 ydk::YLeaf regcomm; //type: string ydk::YLeaf extcomm; //type: string ydk::YLeaf aspath; //type: string ydk::YLeaf rcvdlbl; //type: string ydk::YLeaf originatorid; //type: string ydk::YLeaf clusterlst; //type: string ydk::YLeaf peerrtrid; //type: string ydk::YLeaf numimported; //type: uint16 ydk::YLeaf importedlst; //type: string ydk::YLeaf importedsrc; //type: string ydk::YLeaf origimportedsrc; //type: string class SegItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems class RcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems class EcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems class LnkstattrItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems class PfxsidItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems class PmsiItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PmsiItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems> seg_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems> rcomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems> ecomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems> lnkstattr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems> pfxsid_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PmsiItems> pmsi_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems : public ydk::Entity { public: SegItems(); ~SegItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsSegList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList ydk::YList asseg_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList : public ydk::Entity { public: AsSegList(); ~AsSegList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf type; //type: BgpAsSegT class AsnItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems> asn_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems : public ydk::Entity { public: AsnItems(); ~AsnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsItemList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList ydk::YList asitem_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList : public ydk::Entity { public: AsItemList(); ~AsItemList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems : public ydk::Entity { public: RcommItems(); ~RcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RegCommList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems::RegCommList ydk::YList regcomm_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems::RegCommList : public ydk::Entity { public: RegCommList(); ~RegCommList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::RcommItems::RegCommList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems : public ydk::Entity { public: EcommItems(); ~EcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf encap; //type: string ydk::YLeaf rtrmac; //type: string class RtItems_; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_ std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_> rt_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_ : public ydk::Entity { public: RtItems_(); ~RtItems_(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class ExtCommRtList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_::ExtCommRtList ydk::YList extcommrt_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_ class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_::ExtCommRtList : public ydk::Entity { public: ExtCommRtList(); ~ExtCommRtList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf community; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::EcommItems::RtItems_::ExtCommRtList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems : public ydk::Entity { public: LnkstattrItems(); ~LnkstattrItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf lnkattrflags; //type: string ydk::YLeaf attrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class LnkStAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList ydk::YList lnkstattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList : public ydk::Entity { public: LnkStAttrEntryList(); ~LnkStAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpLsAttrEntryType ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::LnkstattrItems::TlvItems::LnkStAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems : public ydk::Entity { public: PfxsidItems(); ~PfxsidItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfxsidattrlen; //type: uint16 class TlvItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems> tlv_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems : public ydk::Entity { public: TlvItems(); ~TlvItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PfxSidAttrEntryList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList ydk::YList pfxsidattrentry_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList : public ydk::Entity { public: PfxSidAttrEntryList(); ~PfxSidAttrEntryList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf type; //type: BgpPfxSidAttrEntryType ydk::YLeaf len; //type: uint16 ydk::YLeaf val; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PfxsidItems::TlvItems::PfxSidAttrEntryList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PmsiItems : public ydk::Entity { public: PmsiItems(); ~PmsiItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf flags; //type: string ydk::YLeaf tuntype; //type: BgpPmsiTunType ydk::YLeaf lbl; //type: uint32 ydk::YLeaf tunid; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::RtItems::RouteList::PathItems::PathList::PmsiItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems : public ydk::Entity { public: VpnrtItems(); ~VpnrtItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class VpnRouteList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList ydk::YList vpnroute_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList : public ydk::Entity { public: VpnRouteList(); ~VpnRouteList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf pfx; //type: string ydk::YLeaf rd; //type: string ydk::YLeaf name; //type: string ydk::YLeaf ver; //type: uint32 ydk::YLeaf rtflags; //type: string ydk::YLeaf numpaths; //type: uint32 ydk::YLeaf bestpathid; //type: uint32 class PathItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems> path_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems : public ydk::Entity { public: PathItems(); ~PathItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class PathList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList ydk::YList path_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList : public ydk::Entity { public: PathList(); ~PathList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf peer; //type: string ydk::YLeaf id; //type: uint32 ydk::YLeaf nh; //type: string ydk::YLeaf importedrd; //type: string ydk::YLeaf origimportedrd; //type: string ydk::YLeaf nhmetric; //type: uint32 ydk::YLeaf type; //type: BgpPathT ydk::YLeaf operst; //type: BgpPathSt ydk::YLeaf flags; //type: string ydk::YLeaf origin; //type: BgpOrigin ydk::YLeaf metric; //type: uint32 ydk::YLeaf localpref; //type: uint32 ydk::YLeaf weight; //type: uint16 ydk::YLeaf aggr; //type: string ydk::YLeaf aggras; //type: string ydk::YLeaf unknownattrdata; //type: string ydk::YLeaf unknownattrlen; //type: uint32 ydk::YLeaf regcomm; //type: string ydk::YLeaf extcomm; //type: string ydk::YLeaf aspath; //type: string ydk::YLeaf rcvdlbl; //type: string ydk::YLeaf originatorid; //type: string ydk::YLeaf clusterlst; //type: string ydk::YLeaf peerrtrid; //type: string ydk::YLeaf numimported; //type: uint16 ydk::YLeaf importedlst; //type: string ydk::YLeaf importedsrc; //type: string ydk::YLeaf origimportedsrc; //type: string class SegItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems class RcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::RcommItems class EcommItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::EcommItems class LnkstattrItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::LnkstattrItems class PfxsidItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::PfxsidItems class PmsiItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::PmsiItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems> seg_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::RcommItems> rcomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::EcommItems> ecomm_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::LnkstattrItems> lnkstattr_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::PfxsidItems> pfxsid_items; std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::PmsiItems> pmsi_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems : public ydk::Entity { public: SegItems(); ~SegItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsSegList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList ydk::YList asseg_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList : public ydk::Entity { public: AsSegList(); ~AsSegList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf type; //type: BgpAsSegT class AsnItems; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems std::shared_ptr<cisco_nx_os::Cisco_NX_OS_device::System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems> asn_items; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems : public ydk::Entity { public: AsnItems(); ~AsnItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class AsItemList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList ydk::YList asitem_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList : public ydk::Entity { public: AsItemList(); ~AsItemList(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf order; //type: uint16 ydk::YLeaf asn; //type: string }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::SegItems::AsSegList::AsnItems::AsItemList class System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::RcommItems : public ydk::Entity { public: RcommItems(); ~RcommItems(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; class RegCommList; //type: System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::RcommItems::RegCommList ydk::YList regcomm_list; }; // System::BgpItems::InstItems::DomItems::DomList::PeerItems::PeerList::AfItems::PeerAfList::VpnrtItems::VpnRouteList::PathItems::PathList::RcommItems } } #endif /* _CISCO_NX_OS_DEVICE_8_ */
63.353433
252
0.715952
[ "vector" ]
cc8efa8f983c2d2bbe5ce04b18f892a47ece440d
634
cpp
C++
universal-problems/6.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
1
2020-07-19T15:37:01.000Z
2020-07-19T15:37:01.000Z
universal-problems/6.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
null
null
null
universal-problems/6.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
null
null
null
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; vector <vector <char> > res; res.resize(numRows); int p = numRows + numRows - 2; for (int i = 0; i < s.size(); i += p) { for (int j = 0; i + j < s.size() && j < numRows; ++ j) res[j].push_back(s[i + j]); for (int j = numRows, k = numRows - 2; i + j < s.size() && j < p; ++ j, -- k) res[k].push_back(s[i + j]); } string ans = ""; for (auto &x : res) for (auto &t : x) ans += t; return ans; } };
33.368421
89
0.422713
[ "vector" ]
cc915c81c05b641be2fdaacfbf2e22dbaeeef40b
1,789
cc
C++
tensorflow/noscope/test/noscope_others.cc
jingjunLi/tensorflow-multi-stream
d3b75ab179e1a62300739084b48816d2467b0cee
[ "Apache-2.0" ]
null
null
null
tensorflow/noscope/test/noscope_others.cc
jingjunLi/tensorflow-multi-stream
d3b75ab179e1a62300739084b48816d2467b0cee
[ "Apache-2.0" ]
null
null
null
tensorflow/noscope/test/noscope_others.cc
jingjunLi/tensorflow-multi-stream
d3b75ab179e1a62300739084b48816d2467b0cee
[ "Apache-2.0" ]
1
2020-02-11T10:29:06.000Z
2020-02-11T10:29:06.000Z
std::string video_name("/home/li/opensource/stanford-futuredata/data/videos/jackson-town-square.mp4"); const size_t kSkip = 300; const size_t kNbFrames = 10000; const size_t kStartFrom = 5; std::string graph("/home/li/opensource/stanford-futuredata/data/cnn-models/jackson-town-square_convnet_128_32_0.pb"); std::string avg_name("/home/li/opensource/stanford-futuredata/data/cnn-avg/jackson-town-square.txt"); std::shared_ptr<noscope::SimpleQueue<noscope::Frame* > > fQueue(new noscope::SimpleQueue<noscope::Frame*>); const size_t stream_id = 0; const bool kUseBlocked = 0; const bool kSkipDiffDetection = 0; const float lower_thresh = 0.0; const float upper_thresh = 10000000; const bool const_ref = 0; const size_t kRef = 0; const float distill_thresh_lower = 0.197155194194; const float distill_thresh_upper = 0.622490004004; tensorflow::Session *session = InitSession(graph); noscope::NoscopeStream stream_test(video_name, kSkip, kNbFrames, kStartFrom, session, avg_name, fQueue, stream_id, kUseBlocked, kSkipDiffDetection, lower_thresh, upper_thresh, const_ref, kRef, distill_thresh_lower, distill_thresh_upper); std::this_thread::sleep_for(std::chrono::milliseconds(500)); //std::vector<std::unique_ptr<noscope::NoscopeStream > > nStreams; //for (int i = 0; i < video_num; ++i) { //auto gQueue = std::shared_ptr<noscope::SimpleQueue<noscope::Frame*> >(new noscope::SimpleQueue<noscope::Frame *>); //std::shared_ptr<noscope::SimpleQueue<noscope::Frame* > > gQueue(new noscope::SimpleQueue<noscope::Frame* >()); //gQueues.push_back(gQueue); //std::unique_ptr<noscope::NoscopeStream > nStream(new noscope::SimpleQueue<noscope::NoscopeStream>()); //nStreams.push_back(nStream); //}
51.114286
122
0.730017
[ "vector" ]
cc9310c50a3f19f866d619dd4c900fd2fe63829b
18,846
cpp
C++
display/source/CursesDisplay.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
1
2020-05-24T22:44:03.000Z
2020-05-24T22:44:03.000Z
display/source/CursesDisplay.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
display/source/CursesDisplay.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
#include <cctype> #include <iostream> #include <sstream> #include <vector> #include <boost/tokenizer.hpp> #include "Animation.hpp" #include "Colours.hpp" #include "Conversion.hpp" #include "DisplaySettings.hpp" #include "EquipmentTextKeys.hpp" #include "Game.hpp" #include "Log.hpp" #include "MapUtils.hpp" #include "Screen.hpp" #include "DisplayConstants.hpp" #include "CursesDisplay.hpp" #include "MapDisplayArea.hpp" #include "OptionsComponent.hpp" #include "Serialize.hpp" #include "Setting.hpp" #include "StringTable.hpp" #include "TextKeys.hpp" #include "TextMessages.hpp" using namespace std; uint CursesDisplay::TERMINAL_MAX_ROWS = 25; uint CursesDisplay::TERMINAL_MAX_COLS = 80; const int CURSES_NUM_BASE_COLOURS = 8; const int CURSES_NUM_TOTAL_COLOURS = 16; void CursesDisplay::set_spritesheets(const map<string, pair<string, unordered_map<string, Coordinate>>>& spritesheets) { // Curses doesn't use sprites. } // Assumption: screens is empty (prototype object), and so this is safe. Display* CursesDisplay::clone() { return new CursesDisplay(*this); } CursesDisplay::CursesDisplay() : message_buffer_screen(nullptr) { } bool CursesDisplay::operator==(const CursesDisplay& cd) const { bool result = true; result = result && Display::operator==(cd); result = result && (screens.size() == cd.screens.size()); if (result) { for (uint i = 0; i < screens.size(); i++) { WINDOW* screen = screens.at(i); WINDOW* cd_screen = cd.screens.at(i); result = result && screen && cd_screen && (memcmp(screen, cd_screen, sizeof(*screen)) == 0); } } result = result && (prompt_processor == cd.prompt_processor); return result; } // Get the current display width unsigned int CursesDisplay::get_width() const { return TERMINAL_MAX_COLS; } // Get the current display height unsigned int CursesDisplay::get_height() const { return TERMINAL_MAX_ROWS; } // Create a screen and return it. WINDOW* CursesDisplay::create_screen(int height, int width, int start_row, int start_col) { WINDOW* screen; screen = newwin(height, width, start_row, start_col); keypad(screen, TRUE); // Because screens don't display the player (or have any other meaningful reason to have // the cursor present), turn off the cursor. curs_set(0); wrefresh(screen); return screen; } // Delete the given window. void CursesDisplay::destroy_screen(WINDOW *screen) { Log::instance().debug("CursesDisplay::destroy_screen - destroying current screen."); delwin(screen); screen = nullptr; } void CursesDisplay::draw_tile_init() { curs_set(0); } // Initialize the base ncurses colours. void CursesDisplay::initialize_colours() { vector<short int> colours{COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW, COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE}; short int pair_counter = 1; for (auto bg_colour : colours) { for (auto fg_colour : colours) { init_pair(pair_counter, fg_colour, bg_colour); pair_counter++; } pair_counter += CURSES_NUM_BASE_COLOURS; } } void CursesDisplay::enable_colour(const Colour colour) { enable_colour(static_cast<int>(colour), stdscr); } void CursesDisplay::disable_colour(const Colour colour) { disable_colour(static_cast<int>(colour), stdscr); } // Turn on colour using attron. // // Note that the enable/disable colour need to match! Don't pass different colours! void CursesDisplay::enable_colour(const int selected_colour, WINDOW* window) { if (uses_colour()) { set_colour(selected_colour, window); } else { init_mono_if_necessary(); set_colour(static_cast<int>(mono_colour), window); } } // Set the display colour without actually checking for monochrome. void CursesDisplay::set_colour(const int selected_colour, WINDOW* window) { if ((selected_colour % CURSES_NUM_TOTAL_COLOURS) > static_cast<int>(Colour::COLOUR_WHITE)) { int actual_colour = selected_colour - static_cast<int>(Colour::COLOUR_BOLD_BLACK); wattron(window, COLOR_PAIR(actual_colour + 1)); wattron(window, A_BOLD); return; } wattron(window, COLOR_PAIR(selected_colour + 1)); } // Turn off colour using attroff. void CursesDisplay::disable_colour(const int selected_colour, WINDOW* window) { if (uses_colour()) { if ((selected_colour % CURSES_NUM_TOTAL_COLOURS) > static_cast<int>(Colour::COLOUR_WHITE)) { int actual_colour = selected_colour - static_cast<int>(Colour::COLOUR_BOLD_BLACK); wattroff(window, COLOR_PAIR(actual_colour+1)); wattroff(window, A_BOLD); return; } wattroff(window, COLOR_PAIR(selected_colour+1)); } } // The Display function - hooks up to clear_message_buffer void CursesDisplay::clear_messages() { clear_message_buffer(); } // Clear the message buffer and reset the cursor. The message buffer is always lines 0 and 1. int CursesDisplay::clear_message_buffer() { int return_val; WINDOW* screen = get_message_buffer_screen(); wmove(screen, 0, 0); wclrtoeol(screen); wmove(screen, 1, 0); return_val = wclrtoeol(screen); // Reset the internal state msg_buffer_last_y = 0; msg_buffer_last_x = 0; // Reset cursor to original position wmove(screen, msg_buffer_last_y, msg_buffer_last_x); return return_val; } WINDOW* CursesDisplay::get_message_buffer_screen() { WINDOW* screen = stdscr; if (message_buffer_screen != nullptr) { screen = message_buffer_screen; } return screen; } // Halt processing and force user input to continue. void CursesDisplay::halt_messages() { WINDOW* screen = get_message_buffer_screen(); wmove(screen, msg_buffer_last_y, msg_buffer_last_x); wrefresh(screen); wgetch(screen); } // Refresh the display's size. // // // JCD FIXME: This doesn't seem to work. // // Fix this up once SOTW is compiling on Linux/FreeBSD and I can // resize terminals. // void CursesDisplay::refresh_terminal_size() { getmaxyx(stdscr, TERMINAL_MAX_ROWS, TERMINAL_MAX_COLS); } // Set up the Curses-based display. bool CursesDisplay::create() { bool creation_success = true; initscr(); keypad(stdscr, TRUE); nl(); noecho(); // Don't echo the user input. raw(); // pass control characters to the program. curs_set(0); // Cursor invisible. Doesn't seem to work in Cygwin. Just like colour redefinition. Fucking Cygwin. if (has_colors() == TRUE) { start_color(); initialize_colours(); } refresh_terminal_size(); if ((TERMINAL_MAX_ROWS < 25) || (TERMINAL_MAX_COLS < 80)) { printw("Shadow of the Wyrm requires a terminal of 80x25 or larger.\n"); creation_success = false; } refresh(); return creation_success; } // Do anything necessary to tear down the Curses-based display. void CursesDisplay::tear_down() { refresh(); endwin(); } // Clear the display (in practice, stdscr). void CursesDisplay::clear_display() { clear(); } void CursesDisplay::clear_to_bottom(const int row) { move(row, 0); clrtobot(); } void CursesDisplay::add_alert(const string& message, const bool require_input) { message_buffer_screen = get_current_screen(); int prev_curs_state = curs_set(1); clear_message_buffer(); add_message(message, Colour::COLOUR_BOLD_RED, false); wrefresh(message_buffer_screen); if (require_input) { wgetch(message_buffer_screen); clear_message_buffer(); } curs_set(prev_curs_state); message_buffer_screen = nullptr; } // Clear the message buffer, and then add a message to display to // the user. If it's very long, "..." it. void CursesDisplay::add_message(const string& to_add_message, const Colour colour, const bool reset_cursor) { string message = to_add_message; WINDOW* screen = get_message_buffer_screen(); // Replace any single instances of "%", as these will cause a crash when // the corresponding parameters are not present in printw. boost::replace_all(message, "%", "%%"); int orig_curs_y, orig_curs_x; getyx(screen, orig_curs_y, orig_curs_x); uint cur_y, cur_x; if (reset_cursor) { clear_message_buffer(); wmove(screen, 0, 0); } else { wmove(screen, msg_buffer_last_y, msg_buffer_last_x); } boost::char_separator<char> separator(" ", " ", boost::keep_empty_tokens); // Keep the tokens! boost::tokenizer<boost::char_separator<char>> tokens(message, separator); enable_colour(static_cast<int>(colour), screen); for (boost::tokenizer<boost::char_separator<char>>::iterator t_iter = tokens.begin(); t_iter != tokens.end(); t_iter++) { getyx(screen, msg_buffer_last_y, msg_buffer_last_x); string current_token = *t_iter; getyx(screen, cur_y, cur_x); if (cur_y == 0) { if ((cur_x + current_token.length()) > (TERMINAL_MAX_COLS-1)) { // Move to the second line of the buffer wmove(screen, 1, 0); getyx(screen, cur_y, cur_x); } } else { if ((cur_x + current_token.length()) > (TERMINAL_MAX_COLS) - 4) { wmove(screen, 1, TERMINAL_MAX_COLS-4); disable_colour(static_cast<int>(colour), screen); wprintw(screen, "..."); wgetch(screen); enable_colour(static_cast<int>(colour), screen); clear_message_buffer(); getyx(screen, cur_y, cur_x); } } // If the user presses enter if (cur_y > DisplayConstants::MESSAGE_BUFFER_END_ROW) { cur_y--; } if (cur_x == 0) { if (String::is_whitespace(current_token)) { // If we're at the start of a new line in the buffer, and the string // is entirely whitespace, skip it. continue; } } wprintw(screen, current_token.c_str()); } // Ensure that the last coordinates from the message buffer are up to date. getyx(screen, msg_buffer_last_y, msg_buffer_last_x); // Reset the cursor. if (reset_cursor) { wmove(screen, orig_curs_y, orig_curs_x); } disable_colour(static_cast<int>(colour), screen); // This is commented out because every so often I wonder why and it's always // because if I include it, the cursor jumps to the message buffer and back, // which is ugly. // wrefresh(screen); } string CursesDisplay::add_message_with_prompt(const string& message, const Colour colour, const bool reset_prompt) { string prompt_result; // Add the message and then get the prompt value. // The assumption is that this should only ever (ever! EVAR!) get called // from stdscr, since that's where the message manager is actually // displayed! add_message(message, colour, reset_prompt); prompt_result = prompt_processor.get_user_string(stdscr, true /* allow arbitrary non-alphanumeric characters */); return prompt_result; } void CursesDisplay::redraw_cursor(const DisplayMap& current_map, const CursorSettings& cs, const uint map_rows) { Coordinate cursor_coord = current_map.get_cursor_coordinate(); // Since we're drawing the map (with, presumably, the player) we need the cursor present to show the // position of the player's character. curs_set(get_cursor_mode(cs)); move(cursor_coord.first + DisplayConstants::MAP_START_ROW, cursor_coord.second + DisplayConstants::MAP_START_COL); wredrawln(stdscr, DisplayConstants::MAP_START_ROW, map_rows); } void CursesDisplay::refresh_display_parameters() { refresh_terminal_size(); } // Refreshes the contents of the current window. void CursesDisplay::redraw() { if (screens.empty()) { refresh(); } else { wrefresh(screens.back()); } } void CursesDisplay::draw_coordinate(const DisplayTile& display_tile, const unsigned int terminal_row, const unsigned int terminal_col) { int colour = display_tile.get_colour(); // Maps are always drawn on ncurses' stdscr. enable_colour(colour, stdscr); mvprintw(terminal_row, terminal_col, "%c", display_tile.get_symbol().get_symbol()); disable_colour(colour, stdscr); } // Get the size of the map display in "tiles" MapDisplayArea CursesDisplay::get_map_display_area() { MapDisplayArea map_display_area; map_display_area.set_width(TERMINAL_MAX_COLS); map_display_area.set_height(TERMINAL_MAX_ROWS - DisplayConstants::ROWS_FOR_MESSAGE_BUFFER_AND_SYNOPSIS); return map_display_area; } void CursesDisplay::refresh_and_clear_window() { WINDOW* win = get_current_screen(); wrefresh(win); // We've shown the prompt, the user has intervened, and so // now we need to clear the window, reset the current row // back to 0 and keep displaying stuff from the screen. wclear(win); } string CursesDisplay::get_prompt_value(const Screen& current_screen, const MenuWrapper& wrapper, const int current_row, const int current_col) { WINDOW* screen_window = get_current_screen(); PromptPtr prompt = current_screen.get_prompt(); prompt_processor.show_prompt(screen_window, prompt, current_row, current_col, TERMINAL_MAX_ROWS, TERMINAL_MAX_COLS); string result = prompt_processor.get_prompt(screen_window, wrapper, prompt); return result; } void CursesDisplay::display_header(const string& header_text, const int current_row) { WINDOW* screen_window = get_current_screen(); display_header(header_text, screen_window, current_row); } void CursesDisplay::setup_new_screen() { refresh_terminal_size(); WINDOW* screen_window = create_screen(TERMINAL_MAX_ROWS, TERMINAL_MAX_COLS, 0, 0); screens.push_back(screen_window); } void CursesDisplay::refresh_current_window() { WINDOW* current_screen = get_current_screen(); wrefresh(current_screen); } void CursesDisplay::display_text_component(int* row, int* col, TextComponentPtr text, const uint line_incr) { WINDOW* screen_window = get_current_screen(); display_text_component(screen_window, row, col, text, line_incr); } void CursesDisplay::display_options_component(int* row, int* col, OptionsComponentPtr options) { WINDOW* screen_window = get_current_screen(); display_options_component(screen_window, row, col, options); } int CursesDisplay::get_max_rows() const { return TERMINAL_MAX_ROWS; } int CursesDisplay::get_max_cols() const { return TERMINAL_MAX_COLS; } void CursesDisplay::display_text_component(WINDOW* window, int* row, int* col, TextComponentPtr tc, const uint line_incr) { int cur_col = *col; if (tc != nullptr) { vector<pair<string, Colour>> current_text = tc->get_text(); vector<Symbol> symbols = tc->get_symbols(); for (auto& text_line : current_text) { string cur_text = text_line.first; boost::replace_all(cur_text, "%", "%%"); for (const Symbol& s : symbols) { boost::replace_first(cur_text, "%%s", Char::to_string(s.get_symbol())); } enable_colour(static_cast<int>(text_line.second), window); mvwprintw(window, *row, cur_col, cur_text.c_str()); disable_colour(static_cast<int>(text_line.second), window); cur_col += cur_text.size(); } *row += line_incr; } } void CursesDisplay::display_options_component(WINDOW* window, int* row, int* col, OptionsComponentPtr oc) { vector<Option> options = oc->get_options(); vector<string> option_descriptions = oc->get_option_descriptions(); bool show_desc = oc->get_show_option_descriptions(); size_t num_options = options.size(); size_t num_option_desc = option_descriptions.size(); int options_added = 0; if (!options.empty()) { int temp_row = *row; for (unsigned int i = 0; i < num_options; i++) { Option current_option = options.at(i); Colour option_colour = current_option.get_colour(); TextComponentPtr option_text = current_option.get_description(); string option_desc; // Only get the description if we should show one and if one has been set. if (show_desc && (i < num_option_desc)) { option_desc = option_descriptions.at(i); if (!option_desc.empty()) { option_text->add_text(" - "); option_text->add_text(option_desc); } } enable_colour(static_cast<int>(option_colour), window); ostringstream display_option; display_option << " [" << current_option.get_id_char() << "] "; int ocol = *col; string display_option_s = display_option.str(); boost::replace_all(display_option_s, "%", "%%"); mvwprintw(window, *row, ocol, display_option_s.c_str()); getyx(window, *row, ocol); TextComponentPtr text = current_option.get_description(); display_text_component(window, row, &ocol, text, DisplayConstants::OPTION_SPACING); disable_colour(static_cast<int>(option_colour), window); options_added++; temp_row++; } } // No need to update *row // It will have been taken care of when displaying the TextComponent. } // set_title() does nothing. curses can't set the terminal title. void CursesDisplay::set_title(const string& title) { } // show()/hide() do nothing currently. The curses display is always visible. void CursesDisplay::show() { } void CursesDisplay::hide() { } void CursesDisplay::clear_screen() { if (!screens.empty()) { WINDOW* current_screen_window = screens.back(); wclear(current_screen_window); wrefresh(current_screen_window); destroy_screen(current_screen_window); screens.pop_back(); } } void CursesDisplay::display_text(const int row, const int col, const string& text) { string txt = text; boost::replace_all(txt, "%", "%%"); mvprintw(row, col, txt.c_str()); } void CursesDisplay::display_header(const string& header_text, WINDOW* window, const int display_line) { int white = static_cast<int>(Colour::COLOUR_WHITE); enable_colour(white, window); string header = header_text; boost::replace_all(header, "%", "%%"); string full_header = TextMessages::get_full_header_text(header, get_max_cols()); mvwprintw(window, display_line, 0, full_header.c_str()); disable_colour(white, window); } WINDOW* CursesDisplay::get_current_screen() { WINDOW* screen = stdscr; if (!screens.empty()) { screen = screens.back(); } return screen; } bool CursesDisplay::serialize(ostream& stream) const { Display::serialize(stream); // Screens are not serialized. Saving can only be done on the main screen, // which will be reconstructed based on the game's map/etc data. // CursesPromptProcessor is stateless; don't write it. return true; } bool CursesDisplay::deserialize(istream& stream) { Display::deserialize(stream); // Screens are not serialized. Saving can only be done on the main screen, // which will be reconstructed based on the game's map/etc data. // CursesPromptProcessor is stateless; don't load it. return true; } ClassIdentifier CursesDisplay::internal_class_identifier() const { return ClassIdentifier::CLASS_ID_CURSES_DISPLAY; } #ifdef UNIT_TESTS #include "unit_tests/CursesDisplay_test.cpp" #endif
25.745902
142
0.711132
[ "object", "vector" ]
cc9441442a0588acb95cf572eae570b8f9d07a8d
2,376
hpp
C++
engine/math/include/matrix.hpp
redstrate/prism
acb6c5306c6f60088744191f3d3d8713fc6950bd
[ "MIT" ]
18
2020-08-11T18:13:49.000Z
2022-03-08T21:42:54.000Z
engine/math/include/matrix.hpp
redstrate/prism
acb6c5306c6f60088744191f3d3d8713fc6950bd
[ "MIT" ]
11
2020-08-27T12:37:48.000Z
2022-02-21T05:17:03.000Z
engine/math/include/matrix.hpp
redstrate/prism
acb6c5306c6f60088744191f3d3d8713fc6950bd
[ "MIT" ]
1
2020-12-08T14:01:48.000Z
2020-12-08T14:01:48.000Z
#pragma once #include "vector.hpp" // m = rows // n = columns // row major storage mode? template<class T, std::size_t M, std::size_t N> class Matrix { public: constexpr Matrix(const T diagonal = T(1)) { for(std::size_t i = 0; i < (M * N); i++) unordered_data[i] = ((i / M) == (i % N) ? diagonal : T(0)); } constexpr Matrix(const prism::float4 m1_, const prism::float4 m2_, const prism::float4 m3_, const prism::float4 m4_) { columns[0] = m1_; columns[1] = m2_; columns[2] = m3_; columns[3] = m4_; } constexpr inline void operator*=(Matrix rhs); using VectorType = prism::Vector<N, T>; constexpr VectorType& operator[](const size_t index) { return columns[index]; } constexpr VectorType operator[](const size_t index) const { return columns[index]; } union { VectorType columns[M]; T data[M][N]; T unordered_data[M * N] = {}; }; }; using Matrix4x4 = Matrix<float, 4, 4>; using Matrix3x3 = Matrix<float, 3, 3>; constexpr inline Matrix4x4 operator*(const Matrix4x4 lhs, const Matrix4x4 rhs) { Matrix4x4 tmp(0.0f); for(int j = 0; j < 4; j++) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 4; k++) tmp.data[j][i] += lhs.data[k][i] * rhs.data[j][k]; } } return tmp; } constexpr inline prism::float4 operator*(const Matrix4x4 lhs, const prism::float4 rhs) { prism::float4 tmp; for(int r = 0; r < 4; r++) { for(int c = 0; c < 4; c++) tmp[r] += lhs.data[c][r] * rhs.data[c]; } return tmp; } constexpr inline Matrix4x4 operator/(const Matrix4x4 lhs, const float rhs) { Matrix4x4 tmp(0.0f); for(int j = 0; j < 4; j++) { for(int i = 0; i < 4; i++) { for(int k = 0; k < 4; k++) tmp.data[k][i] = lhs.data[k][i] / rhs; } } return tmp; } constexpr inline Matrix4x4 operator*(const Matrix4x4 lhs, const float rhs) { Matrix4x4 tmp(0.0f); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { for (int k = 0; k < 4; k++) tmp.data[k][i] = lhs.data[k][i] * rhs; } } return tmp; } template<typename T, std::size_t M, std::size_t N> constexpr void Matrix<T, M, N>::operator*=(const Matrix<T, M, N> rhs) { *this = *this * rhs; }
27
122
0.536616
[ "vector" ]
ccb24234088879e1ddb72d8b8350acabfcf13834
2,204
cpp
C++
codeforce/490/E.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
5
2019-03-17T01:33:19.000Z
2021-06-25T09:50:45.000Z
codeforce/490/E.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
codeforce/490/E.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
/** Those who cannot acknowledge themselves will eventually fail. */ #include <bits/stdc++.h> #define forn(i, l, r) for(int i=l;i<=r;i++) #define all(v) v.begin(),v.end() #define pb push_back #define nd second #define st first #define debug(x) cout<<#x<<" -> "<<x<< endl #define kakimasu(x) cout << x << '\n' #define sz(x) (int)x.size() #define UNIQUE(v) (v).resize(unique(all(v)) - (v).begin()) //need to sort first b4 using unique using namespace std; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<bool> vb; typedef vector<string> vs; typedef vector<double> vd; typedef vector<long long> vll; typedef vector<vector<int> > vvi; typedef vector<vll> vvll; typedef vector<pair<int, int> > vpi; typedef vector<vpi> vvpi; typedef pair<int, int> pi; typedef pair<ll, ll> pll; typedef vector<pll> vpll; const int INF = 1 << 30; /** Start coding from here */ #define DFS_WHITE -1 // normal DFS, do not change this with other values (other than 0), because we usually use memset with conjunction with DFS_WHITE #define DFS_BLACK 1 const int maxn = 5003; int vis[maxn]; int dfs_num[maxn]; unordered_map<int, vi> g; void dfs1(int index) { for (auto &v : g[index]) { if (!vis[v]++) dfs1(v); } } vi topoSort; // global vector to store the toposort in reverse order void dfs2(int u) { // change function name to differentiate with original dfs dfs_num[u] = DFS_BLACK; for (auto &v : g[u]) if (dfs_num[v] == DFS_WHITE) dfs2(v); topoSort.push_back(u); } // that is, this is the only change int main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifdef LOCAL_PROJECT freopen("input.txt","r",stdin); #endif memset(vis, 0, sizeof vis); int n,m,s; cin>>n>>m>>s; forn(i, 1, m) { int a, b; cin>>a>>b; g[a].pb(b); } memset(dfs_num, -1, sizeof dfs_num); for (int i = 1; i <= n; i++) // this part is the same as finding CCs if (dfs_num[i] == DFS_WHITE) dfs2(i); reverse(topoSort.begin(), topoSort.end()); // reverse topoSort vis[s]++; dfs1(s); int ans = 0; for (auto &i : topoSort) { if (!vis[i]++) { ans++; dfs1(i); } } cout<<ans<<'\n'; return 0; }
25.045455
150
0.633848
[ "vector" ]
ccb7183e39a05ac0c13d6c02d0da29e29c8ed4a5
1,609
cpp
C++
HackerRankEulerProblems/40/P039_IntegerRightTriangles.cpp
wingkinl/HackerRankEulerProblems
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
[ "Apache-2.0" ]
null
null
null
HackerRankEulerProblems/40/P039_IntegerRightTriangles.cpp
wingkinl/HackerRankEulerProblems
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
[ "Apache-2.0" ]
null
null
null
HackerRankEulerProblems/40/P039_IntegerRightTriangles.cpp
wingkinl/HackerRankEulerProblems
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
[ "Apache-2.0" ]
null
null
null
#include "P039_IntegerRightTriangles.h" #include <iostream> #include <vector> #include <libs/numeric.h> P039_IntegerRightTriangles::P039_IntegerRightTriangles(unsigned int max_perimeter) { std::vector<uint32_t> perimeter_count(max_perimeter + 1); // https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple // a = m^2 - n^2, b = 2mn, c = m^2 + n^2 // p = a + b + c = 2m^2 + 2mn = 2m(m+n) for (uint64_t m = 2; 2 * m * (m + 1) <= max_perimeter; ++m) { for (uint64_t n = 1; n < m; ++n) { if (m & 1 && n & 1) continue; if (hackerrank_euler::gcd(m, n) > 1) continue; auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto p = a + b + c; for (int32_t k = 1; k <= max_perimeter / p; ++k) { auto pp = p * k; if (pp > max_perimeter) break; auto& count = perimeter_count[(uint32_t)pp]; ++count; } } } uint32_t max_count = 0; for (size_t pp = 0; pp < perimeter_count.size(); ++pp) { if (perimeter_count[pp] > max_count) { max_count = perimeter_count[pp]; max_perimeters.insert((uint32_t)pp); } } } unsigned int P039_IntegerRightTriangles::Solve(unsigned int n) { auto it = max_perimeters.upper_bound(n); --it; return *it; } void P039_IntegerRightTriangles::main() { std::ios_base::sync_with_stdio(false); uint32_t T = 1; std::cin >> T; std::vector<uint32_t> vn(T); uint32_t max_n = 0; for (uint32_t ii = 0; ii < T; ++ii) { auto& n = vn[ii]; std::cin >> n; if (n > max_n) max_n = n; } P039_IntegerRightTriangles p(max_n); for (auto n : vn) std::cout << p.Solve(n) << "\n"; }
21.743243
82
0.602859
[ "vector" ]
ccc0f80703c0bc24b57e318469c4662c1e52ca2d
7,444
hpp
C++
example_apps/matrix_factorization/als.hpp
hcj666/grachi-initial
8ed22668d963ec3c3b0e9607b094eea32271d745
[ "MIT" ]
null
null
null
example_apps/matrix_factorization/als.hpp
hcj666/grachi-initial
8ed22668d963ec3c3b0e9607b094eea32271d745
[ "MIT" ]
null
null
null
example_apps/matrix_factorization/als.hpp
hcj666/grachi-initial
8ed22668d963ec3c3b0e9607b094eea32271d745
[ "MIT" ]
null
null
null
/** * @file * @author Aapo Kyrola <akyrola@cs.cmu.edu> * @version 1.0 * * @section LICENSE * * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @section DESCRIPTION * * Common code for ALS implementations. */ #ifndef DEF_ALSHPP #define DEF_ALSHPP #include <assert.h> #include <cmath> #include <errno.h> #include <string> #include <stdint.h> #include "matrixmarket/mmio.h" #include "matrixmarket/mmio.c" #include "api/chifilenames.hpp" #include "api/vertex_aggregator.hpp" #include "preprocessing/sharder.hpp" // See note above about Eigen #include "Eigen/Dense" #define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET #include "Eigen/Sparse" #include "Eigen/Cholesky" #include "Eigen/Eigenvalues" #include "Eigen/SVD" using namespace Eigen; typedef MatrixXd mat; typedef VectorXd vec; typedef VectorXi ivec; typedef MatrixXi imat; typedef SparseVector<double> sparse_vec; using namespace graphchi; #ifndef NLATENT #define NLATENT 5 // Dimension of the latent factors. You can specify this in compile time as well (in make). #endif double LAMBDA = 0.065; /// RMSE computation double rmse=0.0; mutex rmselock; // Hackish: we need to count the number of left // and right vertices in the bipartite graph ourselves. vid_t max_left_vertex =0 ; vid_t max_right_vertex = 0; struct latentvec_t { double d[NLATENT]; latentvec_t() { } void init() { for(int k=0; k < NLATENT; k++) d[k] = 0.001 * (std::rand() % 1000); } double & operator[] (int idx) { return d[idx]; } bool operator!=(const latentvec_t &oth) const { for(int i=0; i<NLATENT; i++) { if (d[i] != oth.d[i]) return true; } return false; } double dot(latentvec_t &oth) const { double x=0; for(int i=0; i<NLATENT; i++) x+= oth.d[i]*d[i]; return x; } }; struct als_factor_and_weight { latentvec_t factor; float weight; als_factor_and_weight() {} als_factor_and_weight(float obs) { weight = obs; factor.init(); } }; /** * Create a bipartite graph from a matrix. Each row corresponds to vertex * with the same id as the row number (0-based), but vertices correponsing to columns * have id + num-rows. */ template <typename als_edge_type> int convert_matrixmarket_for_ALS(std::string base_filename) { // Note, code based on: http://math.nist.gov/MatrixMarket/mmio/c/example_read.c int ret_code; MM_typecode matcode; FILE *f; int M, N, nz; /** * Create sharder object */ int nshards; if ((nshards = find_shards<als_edge_type>(base_filename, get_option_string("nshards", "auto")))) { logstream(LOG_INFO) << "File " << base_filename << " was already preprocessed, won't do it again. " << std::endl; logstream(LOG_INFO) << "If this is not intended, please delete the shard files and try again. " << std::endl; return nshards; } sharder<als_edge_type> sharderobj(base_filename); sharderobj.start_preprocessing(); if ((f = fopen(base_filename.c_str(), "r")) == NULL) { logstream(LOG_ERROR) << "Could not open file: " << base_filename << ", error: " << strerror(errno) << std::endl; exit(1); } if (mm_read_banner(f, &matcode) != 0) { logstream(LOG_ERROR) << "Could not process Matrix Market banner. File: " << base_filename << std::endl; logstream(LOG_ERROR) << "Matrix must be in the Matrix Market format. " << std::endl; exit(1); } /* This is how one can screen matrix types if their application */ /* only supports a subset of the Matrix Market data types. */ if (mm_is_complex(matcode) || !mm_is_sparse(matcode)) { logstream(LOG_ERROR) << "Sorry, this application does not support complex values and requires a sparse matrix." << std::endl; logstream(LOG_ERROR) << "Market Market type: " << mm_typecode_to_str(matcode) << std::endl; exit(1); } /* find out size of sparse matrix .... */ if ((ret_code = mm_read_mtx_crd_size(f, &M, &N, &nz)) !=0) { logstream(LOG_ERROR) << "Failed reading matrix size: error=" << ret_code << std::endl; exit(1); } logstream(LOG_INFO) << "Starting to read matrix-market input. Matrix dimensions: " << M << " x " << N << ", non-zeros: " << nz << std::endl; if (M < 5 || N < 5 || nz < 10) { logstream(LOG_ERROR) << "File is suspiciously small. Something wrong? File: " << base_filename << std::endl; assert(M < 5 || N < 5 || nz < 10); } if (!sharderobj.preprocessed_file_exists()) { for (int i=0; i<nz; i++) { int I, J; double val; fscanf(f, "%d %d %lg\n", &I, &J, &val); I--; /* adjust from 1-based to 0-based */ J--; sharderobj.preprocessing_add_edge(I, M + J, als_edge_type((float)val)); } sharderobj.end_preprocessing(); } else { logstream(LOG_INFO) << "Matrix already preprocessed, just run sharder." << std::endl; } if (f !=stdin) fclose(f); logstream(LOG_INFO) << "Now creating shards." << std::endl; // Shard with a specified number of shards, or determine automatically if not defined nshards = sharderobj.execute_sharding(get_option_string("nshards", "auto")); return nshards; } struct MMOutputter : public VCallback<latentvec_t> { FILE * outf; MMOutputter(std::string fname, vid_t nvertices) { MM_typecode matcode; mm_initialize_typecode(&matcode); mm_set_matrix(&matcode); mm_set_array(&matcode); mm_set_real(&matcode); outf = fopen(fname.c_str(), "w"); assert(outf != NULL); mm_write_banner(outf, matcode); mm_write_mtx_array_size(outf, NLATENT, nvertices); // Column major } void callback(vid_t vertex_id, latentvec_t &vec) { for(int i=0; i < NLATENT; i++) { fprintf(outf, "%lf\n", vec.d[i]); } } ~MMOutputter() { if (outf != NULL) fclose(outf); } }; void output_als_result(std::string filename, vid_t numvertices, vid_t max_left_vertex) { MMOutputter mmoutput_left(filename + "_U.mm", max_left_vertex + 1); foreach_vertices<latentvec_t>(filename, 0, max_left_vertex + 1, mmoutput_left); MMOutputter mmoutput_right(filename + "_V.mm", numvertices - max_left_vertex - 1); foreach_vertices<latentvec_t>(filename, max_left_vertex + 1, numvertices, mmoutput_right); logstream(LOG_INFO) << "ALS output files (in matrix market format): " << filename + "_U.mm" << ", " << filename + "_V.mm" << std::endl; } #endif
28.630769
133
0.624933
[ "object" ]
ccc4556044f31a1fbbb58433fe9874a53d042fb5
5,058
cpp
C++
apps/ctpn/main.cpp
fireae/caffe_latte
a28559481c2864c79d4b393e91869eb77c0a75fe
[ "Intel", "BSD-2-Clause" ]
7
2018-02-06T13:48:17.000Z
2019-04-08T13:56:22.000Z
apps/ctpn/main.cpp
fireae/caffe_latte
a28559481c2864c79d4b393e91869eb77c0a75fe
[ "Intel", "BSD-2-Clause" ]
null
null
null
apps/ctpn/main.cpp
fireae/caffe_latte
a28559481c2864c79d4b393e91869eb77c0a75fe
[ "Intel", "BSD-2-Clause" ]
null
null
null
#define SIMPLE_EXPORT #include <caffe/caffe.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "graph.hpp" #include "ployfit.hpp" using namespace cv; using namespace caffe; using namespace std; void clipBoxes(vector<float>& box, int height, int width) { if (box[0] < 0) { box[0] = 0; } if (box[0] > width - 1) { box[0] = width - 1; } if (box[2] < 0) { box[2] = 0; } if (box[2] > width - 1) { box[2] = width - 1; } if (box[1] < 0) { box[1] = 0; } if (box[1] > height - 1) { box[1] = height - 1; } if (box[3] < 0) { box[3] = 0; } if (box[3] > height - 1) { box[3] = height - 1; } } int main(int argc, char* argv) { Caffe::set_mode(Caffe::CPU); string model_file = "D:\\BaiduNetdiskDownload\\ctpn/deploy.prototxt"; string trained_file = "D:\\BaiduNetdiskDownload\\ctpn/ctpn_trained_model.caffemodel"; string image_name = "D:\\tests/5.jpg"; shared_ptr<Net<float>> net(new Net<float>(model_file, TEST)); net->CopyTrainedLayersFrom(trained_file); shared_ptr<Blob<float>> blob_data = net->blob_by_name("data"); shared_ptr<Blob<float>> im_info = net->blob_by_name("im_info"); // 102.9801, 115.9465, 122.7717 cv::Mat im = cv::imread(image_name); cv::Mat image; im.convertTo(image, CV_32FC3); image -= cv::Scalar(102.9801, 115.9465, 122.7717); int width = image.cols; int height = image.rows; blob_data->Reshape(1, 3, height, width); float* blob_data_ptr = blob_data->mutable_cpu_data(); for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { blob_data_ptr[(0 * height + h) * width + w] = float(image.at<cv::Vec3f>(cv::Point(w, h))[0]); blob_data_ptr[(1 * height + h) * width + w] = float(image.at<cv::Vec3f>(cv::Point(w, h))[1]); blob_data_ptr[(2 * height + h) * width + w] = float(image.at<cv::Vec3f>(cv::Point(w, h))[2]); } } float* im_data = im_info->mutable_cpu_data(); im_data[0] = height; im_data[1] = width; net->Forward(); shared_ptr<Blob<float>> rois = net->blob_by_name("rois"); shared_ptr<Blob<float>> scores = net->blob_by_name("scores"); float min_score = 0.7; float* scores_data = scores->mutable_cpu_data(); float* rois_data = rois->mutable_cpu_data(); vector<vector<float>> text_proposals; vector<float> vec_scores; for (int i = 0; i < scores->shape()[0]; i++) { if (scores_data[i] > min_score) { vector<float> vec_roi; vec_roi.push_back(rois_data[i * 4 + 0]); vec_roi.push_back(rois_data[i * 4 + 1]); vec_roi.push_back(rois_data[i * 4 + 2]); vec_roi.push_back(rois_data[i * 4 + 3]); clipBoxes(vec_roi, height, width); text_proposals.push_back(vec_roi); vec_scores.push_back(scores_data[i]); } } vector<int> im_size(2); im_size[0] = height; im_size[1] = width; TextProposalGraphBuilder builder; Graph g = builder.build_graph(text_proposals, vec_scores, im_size); vector<vector<int>> tp_groups = g.sub_graphs_connected(); cv::Mat show_image = im.clone(); vector<vector<float>> text_lines; for (int i = 0; i < tp_groups.size(); i++) { vector<int> tp_group = tp_groups[i]; vector<vector<float>> text_line_boxes; float x0 = 100000.0; float x1 = 0.0; vector<float> lt_x0; vector<float> rt_y0; vector<float> lb_x0; vector<float> rb_y0; for (int j = 0; j < tp_group.size(); j++) { int index = tp_group[j]; text_line_boxes.push_back(text_proposals[index]); if (text_proposals[index][0] < x0) { x0 = text_proposals[index][0]; } if (text_proposals[index][2] > x1) { x1 = text_proposals[index][2]; } lt_x0.push_back(text_proposals[index][0]); rt_y0.push_back(text_proposals[index][1]); lb_x0.push_back(text_proposals[index][0]); rb_y0.push_back(text_proposals[index][3]); } float offset = (text_line_boxes[0][2] - text_line_boxes[0][0]) * 0.5; czy::Fit fitline; fitline.polyfit(lt_x0, rt_y0, 1); vector<double> factor; fitline.getFactor(factor); float lt_y = factor[1] * (x0 + offset) + factor[0]; float rt_y = factor[1] * (x1 - offset) + factor[0]; fitline.polyfit(lb_x0, rb_y0, 1); fitline.getFactor(factor); float lb_y = factor[1] * (x0 + offset) + factor[0]; float rb_y = factor[1] * (x1 - offset) + factor[0]; vector<float> text_line(5); text_line[0] = (x0); text_line[1] = std::min((lt_y), (rt_y)); text_line[2] = (x1); text_line[3] = std::max((lb_y), (rb_y)); cv::rectangle( show_image, cv::Rect(text_line[0], text_line[1], text_line[2] - text_line[0], text_line[3] - text_line[1]), cv::Scalar(0, 255, 0), 2); double sum = 0.0; for (int j = 0; j < tp_group.size(); j++) { sum += vec_scores[tp_group[j]]; } text_line[4] = (sum / tp_group.size()); text_lines.push_back(text_line); } cv::imwrite("show.png", show_image); return 0; }
30.287425
73
0.609529
[ "shape", "vector" ]
ccd8161f87c69bb0635b24e20d2e9b9bf39615ac
3,576
cpp
C++
src/c++/lib/alignment/templateBuilder/UngappedAligner.cpp
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/lib/alignment/templateBuilder/UngappedAligner.cpp
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/lib/alignment/templateBuilder/UngappedAligner.cpp
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file UngappedAligner.cpp ** ** \brief See UngappedAligner.hh ** ** \author Roman Petrovski **/ #include "alignment/templateBuilder/UngappedAligner.hh" #include "alignment/Mismatch.hh" namespace isaac { namespace alignment { namespace templateBuilder { UngappedAligner::UngappedAligner( const bool collectMismatchCycles, const AlignmentCfg &alignmentCfg) : AlignerBase(collectMismatchCycles, alignmentCfg) { } unsigned UngappedAligner::alignUngapped( FragmentMetadata &fragmentMetadata, Cigar &cigarBuffer, const flowcell::ReadMetadata &readMetadata, const templateBuilder::FragmentSequencingAdapterClipper &adapterClipper, const reference::ContigList &contigList ) const { const unsigned cigarOffset = cigarBuffer.size(); // Don't reset alignment to preserve the seed-based anchors. // fragmentMetadata.resetAlignment(); ISAAC_ASSERT_MSG(!fragmentMetadata.isAligned(), "alignUngapped is expected to be performed on a clean fragment"); fragmentMetadata.resetClipping(); // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(fragmentMetadata.getCluster().getId(), "alignUngapped: after resetClipping: " << fragmentMetadata); const reference::Contig &contig = contigList[fragmentMetadata.contigId]; const Read &read = fragmentMetadata.getRead(); const bool reverse = fragmentMetadata.reverse; const std::vector<char> &sequence = read.getStrandSequence(reverse); const reference::Contig &reference = contig; std::vector<char>::const_iterator sequenceBegin = sequence.begin(); std::vector<char>::const_iterator sequenceEnd = sequence.end(); adapterClipper.clip(contig, fragmentMetadata, sequenceBegin, sequenceEnd); // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(fragmentMetadata.getCluster().getId(), "alignUngapped: after adapterClipper.clip: " << fragmentMetadata); clipReadMasking(read, fragmentMetadata, sequenceBegin, sequenceEnd); // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(fragmentMetadata.getCluster().getId(), "alignUngapped: after clipReadMasking: " << fragmentMetadata); clipReference(reference.size(), fragmentMetadata.position, sequenceBegin, sequenceEnd); const unsigned firstMappedBaseOffset = std::distance(sequence.begin(), sequenceBegin); if (firstMappedBaseOffset) { cigarBuffer.addOperation(firstMappedBaseOffset, Cigar::SOFT_CLIP); } const unsigned mappedBases = std::distance(sequenceBegin, sequenceEnd); if (mappedBases) { const Cigar::OpCode opCode = Cigar::ALIGN; cigarBuffer.addOperation(mappedBases, opCode); } const unsigned clipEndBases = std::distance(sequenceEnd, sequence.end()); if (clipEndBases) { cigarBuffer.addOperation(clipEndBases, Cigar::SOFT_CLIP); } const unsigned ret = updateFragmentCigar( readMetadata, contigList, //contigAnnotations, fragmentMetadata, fragmentMetadata.reverse, fragmentMetadata.contigId, fragmentMetadata.position, cigarBuffer, cigarOffset); if (!ret) { fragmentMetadata.setUnaligned(); } return ret; } } // namespace templateBuilder } // namespace alignment } // namespace isaac
34.384615
150
0.740492
[ "vector" ]
ccda927da98e83edb564dc25e250e2861ea0a999
1,212
cpp
C++
source/addmenuentry.cpp
Robz8/GridLauncher
d28e93b8358b7e2ba34652f8c2df0c97e7fab6df
[ "MIT" ]
3
2019-01-19T00:11:11.000Z
2019-04-11T09:37:28.000Z
source/addmenuentry.cpp
Robz8/GridLauncher
d28e93b8358b7e2ba34652f8c2df0c97e7fab6df
[ "MIT" ]
null
null
null
source/addmenuentry.cpp
Robz8/GridLauncher
d28e93b8358b7e2ba34652f8c2df0c97e7fab6df
[ "MIT" ]
1
2021-09-23T05:03:10.000Z
2021-09-23T05:03:10.000Z
#include "addmenuentry.h" #include <cstdio> #include <cstring> #include <string> #include <vector> #include <algorithm> extern "C" { #include "shortcut.h" #include "filesystem.h" } bool comparisonFunc(const char *c1, const char *c2) { char * d1 = new char[strlen(c1)+1]; char * d2 = new char[strlen(c2)+1]; strcpy(d1, c1); strcpy(d2, c2); char *p; for (p = d1; *p != '\0'; ++p) { *p = tolower(*p); } for (p = d2; *p != '\0'; ++p) { *p = tolower(*p); } return strcmp(d1, d2) < 0; } void addMenuEntries(char paths[1024][1024], int totalEntries, int pathLength, menu_s* m, bool sortAlpha) { std::vector<char*>vPaths; int i; for (i=0; i<totalEntries; i++) { char *path = paths[i]; vPaths.push_back(path); } if (sortAlpha) { std::sort(vPaths.begin(), vPaths.end(), comparisonFunc); } unsigned int j; for (j=0; j < vPaths.size(); j++) { char * path = vPaths.at(j); int n = strlen(path); //File is a .3dsx if(n>5 && !strcmp(".3dsx", &path[n-5])){ addExecutableToMenu(m, path); } //File is a shortcut else if(n>4 && !strcmp(".xml", &path[n-4])){ addShortcutToMenu(m, path); } //File is a directory else { addDirectoryToMenu(m, path); } } }
17.070423
106
0.594059
[ "vector" ]
ef9aae25cb92b89b3bc974e83721d12477e3911d
1,397
cpp
C++
BOJ_solve/10131.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
BOJ_solve/10131.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
null
null
null
BOJ_solve/10131.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 1e18; const long long mod = 1e9+7; const long long hashmod = 100003; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; ll sz[500005],mx[500005],c[500005]; ll d[500005]; int n; vec v[500005],v2[500005]; // d[x] : x 노드의 서브트리의 노드들을 방문했을때 각 노드별로 게임 시작 시간의 최대 값 bool cmp(int x,int y) { return d[x]-2*sz[x] > d[y]-2*sz[y]; } void pre_dfs(int x,int pr) { for(int i : v2[x]) { if(i == pr) continue; pre_dfs(i,x); v[x].pb(i); } } void dfs(int x,int pr) { sz[x] = 1; d[x] = c[x]; for(int i : v[x]) { dfs(i,x); sz[x] += sz[i]; //d[x] = max(d[x],d[i]); } sort(all(v[x]),cmp); ll ti = 0; for(int i : v[x]) { ti++; d[x] = max(d[x],d[i]+ti); ti += sz[i]*2-1; } //cout <<x << ' ' << d[x] << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 1;i <= n;i++) cin >> c[i]; for(int i = 1;i < n;i++) { int x,y; cin >> x >> y; v2[x].pb(y), v2[y].pb(x); } pre_dfs(1,-1); dfs(1,-1); cout << max(d[1],(n*2-2)+c[1]); }
19.957143
54
0.57194
[ "vector" ]
efbf24b9ecb1a0c82b7b8653e3d4f15dfa041d90
6,196
cpp
C++
src/CCore/Path.cpp
Sidesplitter/Informatica-Olympiade-2016-2017
83704415c6c2febdcbb71116f86619950c8c1e6c
[ "MIT" ]
null
null
null
src/CCore/Path.cpp
Sidesplitter/Informatica-Olympiade-2016-2017
83704415c6c2febdcbb71116f86619950c8c1e6c
[ "MIT" ]
null
null
null
src/CCore/Path.cpp
Sidesplitter/Informatica-Olympiade-2016-2017
83704415c6c2febdcbb71116f86619950c8c1e6c
[ "MIT" ]
null
null
null
#include <vector> #include "Path.h" void Path::calculatePath(std::tuple<Point, Point> searchArea, bool squareOptimization, int minimalLength, int maximumPoints) { // The starting point is not a gaussian prime, we can stop already if (!this->primalityTester->isGaussianPrime(this->startingPoint)) { return; } // The length of a side (Only used when squareOptimization is true) int sideLength = 0; // The total length of the loop int length = 0; // The current point we are staying on // This is not necessary a gaussian point. Point point = this->startingPoint; point.setDirection(Direction::DOWN); //Continue till we have found the maximum amount of points while (maximumPoints == 0 || this->points.size() < maximumPoints) { //We are outside the X range if (point.getX() < std::get<0>(searchArea).getX() || point.getX() > std::get<1>(searchArea).getX()) { break; } //We are outside the Y range if (point.getY() < std::get<0>(searchArea).getY() || point.getY() > std::get<1>(searchArea).getY()) { break; } if (this->primalityTester->isGaussianPrime(point)) { // Add the point to the list of points this->points.push_back(point); // We found a loop: The coordinates are equal and we are currently going down, // which means that we will turn right soon (and thus go into a loop) if (this->points.size() > 1 && point == this->startingPoint && point.getDirection() == Direction::DOWN) { this->loop = true; // The loop is a square when it has five points (The first and the last point are added separately) // and when the first two points have the same length as the second and the third point if (this->points.size() == 5) { this->square = this->points[0].getDistance(this->points[1]) == this->points[1].getDistance(this->points[2]); if (this->square) { this->sideLength = length / 4; } } break; } //These optimizations can only take place if we are looking for a square if (squareOptimization) { // We no exactly one side, if this side is smaller than the minimal length we can stop. // We can also determine the length of a a side if (this->points.size() == 2) { sideLength = this->points[0].getDistance(point); // The length of the side is smaller than the requirement if (sideLength < minimalLength) { break; } // Check if the third point (upper right) is a gaussian prime if (!this->primalityTester->isGaussianPrime(point.translate(Direction::UP, sideLength))) { break; } // Check if the fourth point (upper left) is a gaussian prime if (!this->primalityTester->isGaussianPrime(startingPoint.translate(Direction::UP, sideLength))) { break; } } // We have more than two sides, that means that we can compare the sides with eachother else if (this->points.size() > 2) { // If the length of the last point to the previous point is not the // Length of one of our sides, it is not a square if (this->points[this->points.size() - 1].getDistance(points[points.size() - 2]) != sideLength) { break; } } // We have more points than a square should have if (this->points.size() >= 5) { break; } } //Since we have found a point, we must change from direction switch (point.getDirection()) { case Direction::UP: point.setDirection(Direction::LEFT); break; case Direction::LEFT: point.setDirection(Direction::DOWN); break; case Direction::DOWN: point.setDirection(Direction::RIGHT); break; case Direction::RIGHT: point.setDirection(Direction::UP); break; } } // Move one along point = point.translate(point.getDirection(), 1); length++; } this->length = length; } const Point &Path::getStartingPoint() const { return startingPoint; } void Path::setStartingPoint(const Point &startingPoint) { Path::startingPoint = startingPoint; } PrimalityTester *Path::getPrimalityTester() const { return this->primalityTester; } void Path::setPrimalityTester(PrimalityTester &primalityTester) { this->primalityTester = &primalityTester; } bool Path::isLoop() const { return loop; } bool Path::isSquare() const { return square; } int Path::getLength() const { return length; } Path::Path(const Point &startingPoint, PrimalityTester *primalityTester) : startingPoint(startingPoint), primalityTester(primalityTester) { this->startingPoint = startingPoint; this->primalityTester = primalityTester; } Path::Path() {} const bool Path::operator<(const Path &path) const { // We are larger if (path.length < this->length) { return false; } // We are of the same length if (path.length == this->length) { Point origin = Point(0, 0); return path.getStartingPoint().getDistance(origin) < this->getStartingPoint().getDistance(origin); } return true; } int Path::getSideLength() const { return sideLength; } const std::vector<Point> &Path::getPoints() const { return points; }
32.783069
118
0.547127
[ "vector" ]
efcd646d2159dea9b2b7509df2859ca18caec1b5
29,762
cc
C++
src/cxx/mr/libmr2d/MR_VisRecIter.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
src/cxx/mr/libmr2d/MR_VisRecIter.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
src/cxx/mr/libmr2d/MR_VisRecIter.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
//---------------------------------------------------------- // Copyright (C) 1996 OCA-CEA //---------------------------------------------------------- // UNIT // // Version: // // Author: Frederic Rue & Benoit VANDAME & Jean-Luc Starck // // Date: 05/04/96 // // File: MR_VisRecIter.C // //---------------------------------------------------------- #include "IM_Obj.h" #include "MR_Obj.h" #include "IM_VisTool.h" #include "MR_VisElem.h" #include "MR_VisTree.h" #include "MR_NoiseModel.h" #include "MR_ListObj.h" #include "MR_Deconv.h" //---------------------------------------------------------- // Calcul_masque // Calcul masque Min suivant W0 //---------------------------------------------------------- static Icomplex_f Psf_cf; void calcul_masque (MultiResol& W0, MultiResol & Min) { int NScale = W0.nbr_band(); int i,j,Nb_ech = NScale - 1; Min.band(Nb_ech).init (0.0); for (int n=0; n< Nb_ech; n++) { int Nls = W0.size_band_nl(n); int Ncs = W0.size_band_nc(n); for (i=0 ; i<Nls ; i++) for (j=0 ; j<Ncs ; j++) { if (W0(n,i,j)) Min(n,i,j) = 1.; else Min(n,i,j) = 0.; } } } //---------------------------------------------------------- // Rec_iter_grad // reconstruction iterative utilisant la methode du gradient //---------------------------------------------------------- void rec_iter_grad (MultiResol& W0, Ifloat &Im_rec, int Nb_iter, double& Erreur,float eps) { float w; double Erreur0=0., num, den; int s,i,j,n = 0; int Nl = W0.size_ima_nl(); int Nc = W0.size_ima_nc(); int NScale = W0.nbr_scale(); type_transform Trans = W0.Type_Transform; MultiResol V (Nl, Nc, NScale, Trans, "V rec_iter_grad"); MultiResol Min(Nl, Nc, NScale, Trans, "min rec_iter_grad"); Ifloat I0(Nl, Nc, "grad I0"); Ifloat temp(Nl, Nc, "grad I0"); Ifloat Ir(Nl, Nc, "Ir I0"); calcul_masque (W0, Min); W0.rec_adjoint (Im_rec, False); for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { Erreur0 += Im_rec(i,j)*Im_rec(i,j); temp(i,j) = (Im_rec(i,j) > 0.) ? Im_rec(i,j) : 0.; } Erreur0 = sqrt (Erreur0); I0 = Im_rec; do { n++; // TO IMAGE RECONSTRUITE V.transform (temp); for (s=0; s < V.nbr_band()-1; s++) for (i=0; i< V.size_band_nl(s); i++) for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); //---- CALCUL IMAGE RESIDUE // rec_adjoint (V, temp); V.rec_adjoint(temp, False); Ir = I0 - temp; // Erreur = sqrt(energy(Ir)) / Erreur0; // cout << n << ": Resi = " << Erreur << endl; Erreur = 0.; for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) Erreur += Ir(i,j)*Ir(i,j); Erreur = sqrt (Erreur) / Erreur0; //---- CALCUL PARAMETRE DE CONVERGENCE V.transform (Ir); for (s=0; s < V.nbr_band()-1; s++) for (i=0; i< V.size_band_nl(s); i++) for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); V.rec_adjoint(temp, False); num = 0.; den = 0.; for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { num += Ir(i,j)*temp(i,j); den += temp(i,j)*temp(i,j); } if(!den) w = 1.0; else w = MAX (1.0, num/den); //---- CALCUL NOUVELLE SOLUTION for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { Im_rec(i,j) += w * Ir(i,j); temp(i,j) = (Im_rec(i,j) > 0.) ? Im_rec(i,j) : 0.; } } while(n < Nb_iter && Erreur > eps); threshold(Im_rec); } //---------------------------------------------------------- // Rec_iter_grad_conj // reconstruction iterative utilisant // la methode du gradient conjugue //---------------------------------------------------------- void rec_iter_grad_conj (MultiResol& W0, Ifloat &Im_rec, int Nb_iter, double& Erreur, float eps) { float a, b; double Erreur0, num, den; int s,i,j,n = 0; int Nl = W0.size_ima_nl(); int Nc = W0.size_ima_nc(); int NScale = W0.nbr_scale(); type_transform Trans = W0.Type_Transform; MultiResol V (Nl, Nc, NScale, Trans, "V rec_iter_grad"); MultiResol Min(Nl, Nc, NScale, Trans, "min rec_iter_grad"); Ifloat I0(Nl, Nc, "grad I0"); Ifloat temp(Nl, Nc, "grad I0"); Ifloat Ir(Nl, Nc, "Ir I0"); Ifloat Ierr(Nl, Nc, "Ierr"); Ifloat Iint1(Nl, Nc, "Iint1"); Ifloat Iint2(Nl, Nc, "Iint2"); calcul_masque (W0, Min); W0.rec_adjoint (Im_rec,False); // rec_adjoint(W0, Im_rec); Erreur0 = 0.; for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { Erreur0 += Im_rec(i,j)*Im_rec(i,j); temp(i,j) = (Im_rec(i,j) > 0.) ? Im_rec(i,j) : 0.; } Erreur0 = sqrt (Erreur0); I0 = Im_rec; Ir.init (0.0); a = b = 0.0; do { n++; //---- TO IMAGE RECONSTRUITE V.transform (temp); for (s=0; s < V.nbr_band()-1; s++) for (i=0; i< V.size_band_nl(s); i++) for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); //---- CALCUL IMAGE RESIDUE V.rec_adjoint (temp, False); // rec_adjoint(V, temp); for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) Ierr(i,j) = I0(i,j) - temp(i,j); V.transform(Ierr); for (s=0; s < V.nbr_band()-1; s++) for (i=0; i< V.size_band_nl(s); i++) for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); if (n > 1) { V.rec_adjoint (Iint1, False); // rec_adjoint(V, Iint1); num = den = 0.; for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { num += Iint1(i,j)*Iint2(i,j); den += Iint2(i,j)*Iint2(i,j); } if (!den) b = 0.0; else b = MIN (1, fabs (-num / den)); } Erreur =0.; for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { Erreur += Ierr(i,j)*Ierr(i,j); } Erreur = sqrt (Erreur) / Erreur0; //---- CALCUL IMAGE RESIDUE for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { temp(i,j) = b * Ir(i,j); Ir(i,j) = Ierr(i,j) + temp(i,j); } //---- CALCUL DE A V.transform (Ir); for (s=0; s < V.nbr_band()-1; s++) for (i=0; i< V.size_band_nl(s); i++) for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); V.rec_adjoint (Iint2, False); // rec_adjoint(V, Iint2); num = den = 0.; for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { num += Ierr(i,j)*Iint2(i,j); den += Iint2(i,j)*Iint2(i,j); } if (!den) a = 1.0; else a = MAX (1.0, num / den); //---- CALCUL NOUVELLE SOLUTION for (i=0; i< Nl; i++) for (j=0; j< Nc; j++) { Im_rec(i,j) += a * Ir(i,j); temp(i,j) = (Im_rec(i,j) > 0.) ? Im_rec(i,j) : 0.; } //---- AFFICHAGE RESULTATS } while(n < Nb_iter && Erreur > eps); // cout << n << ": Error = " << Erreur << endl; threshold(Im_rec); } /***************************************************************/ void mr_sm_recons_obj (MultiResol& MR_Data, Ifloat &Imag, int Nb_iter, double& Error, float eps) { int i,j,s,Iter = 0; int Nl = Imag.nl(); int Nc = Imag.nc(); int NbrScale = MR_Data.nbr_scale(); double Error0; float Val; Ifloat Resi (Nl, Nc, "Resi"); Ifloat Sol0 (Nl, Nc, "Sol0"); MRNoiseModel NoiseModel(NOISE_GAUSSIAN, Nl, Nc, MR_Data.nbr_scale(), MR_Data.Type_Transform); // model noise initialization for (s = 0; s < NbrScale-1; s++) for (i = 0; i < MR_Data.size_scale_nl(s); i++) for (j = 0; j < MR_Data.size_scale_nc(s); j++) { if (ABS(MR_Data(s,i,j)) > FLOAT_EPSILON) NoiseModel.support(s,i,j) = VAL_SupOK; else NoiseModel.support(s,i,j) = VAL_SupNull; } MR_Data.rec_adjoint (Resi, False); // MR_Data.band(NbrScale-1).init(); // MR_Data.recons (Resi); Error0 = sqrt(energy(Resi)); Imag = Resi; Sol0 = Resi; threshold(Imag); do { MR_Data.transform (Imag); NoiseModel.threshold(MR_Data, False); MR_Data.rec_adjoint (Resi, False); // MR_Data.band(NbrScale-1).init(); // MR_Data.recons (Resi); Error=0.; for (i = 0; i < Nl; i++) for (j = 0; j < Nc; j++) { Val = Sol0(i,j) - Resi(i,j); Error += Val*Val; Imag(i,j) += Val; if (Imag(i,j) < 0.) Imag(i,j) = 0.; } Error = sqrt(Error) / Error0; Iter ++; } while ((Iter < Nb_iter) && (Error > eps)); // cout << "Iter = " << Iter << " Error = " << Error << endl; } /***************************************************************/ static void im_reduce(Ifloat &Imag, Ifloat &ImagOut, float Zoom) { int Nl = Imag.nl(); int Nc = Imag.nc(); int Nlz = (Zoom > 1.) ? (int)(Nl/Zoom): Nl; int Ncz = (Zoom > 1.) ? (int)(Nc/Zoom): Nc; int i,j,k,l; if ( (ImagOut.nl() != Nlz) || (ImagOut.nc() != Ncz)) ImagOut.resize(Nlz, Ncz); for (i=0;i<Nlz;i++) for (j=0;j<Ncz;j++) { int c=0; int Depi=(int)(i*Zoom); int Endi=(int)((i+1)*Zoom); int Depj=(int)(j*Zoom); int Endj=(int)((j+1)*Zoom); ImagOut(i,j) = 0.; for (k=Depi; k<Endi;k++) for (l=Depj; l<Endj;l++) { if ((k<Nl) && (l<Nc)) { ImagOut(i,j) += Imag(k,l); c++; } } if (c != 0) ImagOut(i,j) /= (float) c; } // INFO(Imag,"Imag"); // INFO(ImagOut, "Imag out"); } /******************************************************************/ static void im_reduce(Ifloat &Imag, float Zoom) { int Nl = Imag.nl(); int Nc = Imag.nc(); int Nlz = (Zoom > 1.) ? (int)(Nl/Zoom): Nl; int Ncz = (Zoom > 1.) ? (int)(Nc/Zoom): Nc; Ifloat ImagOut(Nlz,Ncz,"zoom out"); im_reduce(Imag, ImagOut, Zoom); Imag.resize(Nlz, Ncz); Imag = ImagOut; } /******************************************************************/ void mr_psf_recons_obj (MultiResol& MR_Data, Ifloat &Result, Ifloat &Psf, int Nb_iter, double& Error, float eps, float Fwhm, Ifloat &IMGauss, Bool Deconv, float Zoom) // Reconstruct a deconvolved object from its wavelet transform and the // corresponding PSF. // If Zoom > 1, the PSF is must be oversampled, when compared to thr data // i.e. the pixel size in the PSF is smaller than in the data, and in // this case, we reconstrct an object with the same pixel size as the PSF { int i,j,s,Iter = 0; int NbrScale = MR_Data.nbr_band(); int Nl = MR_Data.size_ima_nl(); // size of the reconstructed image int Nc = MR_Data.size_ima_nc(); Ifloat Imag (Nl, Nc, "Imag"); // Imag = Object * PSF Ifloat Resi (Nl, Nc, "Residual"); Ifloat RecIma (Nl, Nc, "RecIma"); MultiResol MRAux(Nl, Nc, MR_Data.nbr_scale(), MR_Data.Type_Transform, "Aux"); MRAux.Border = MR_Data.Border; int Nlo = Result.nl(); // size of the reconstructed object int Nco = Result.nc(); // Nlo = Nl * Zoom and Nco = Nc * Zoom if (Zoom > 1) { Nlo = (int) (Nlo*Zoom); Nco = (int) (Nco*Zoom); Result.resize(Nlo,Nco); } Ifloat Temp (Nlo, Nco, "Temp"); MR_Data.recons(RecIma); // io_write_ima_float("xx_rec.fits", RecIma); // Calculate the Fourier transform of the PSF psf_get(Psf, Psf_cf, Nlo, Nco, True); // Calculate the starting point solution if (Zoom > 1) im_bilinear_interp (RecIma, Result); else Result = RecIma; float CoefFlux; double FluxData = total(RecIma); double FluxIma, Error0 = sqrt(energy(Result)); do { // solution in image space if (Zoom > 1) { psf_convol(Result, Psf_cf, Temp); im_reduce(Temp, Imag, Zoom); } else psf_convol (Result, Psf_cf, Imag); // INFO(Imag, "Imag"); // Flux Constraint // FluxIma=0.; // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) // if (RecIma(i,j) > FLOAT_EPSILON) FluxIma += Imag(i,j); // CoefFlux = (float) (FluxData / FluxIma); // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) Imag(i,j) *= CoefFlux; // for (i = 0; i < Nlo; i++) // for (j = 0; j < Nco; j++) Result(i,j) *= CoefFlux; // Apply the WT to the rec. object reconvolved with the PSF // and extract the difference with data wavelet coefficient // MRAux.transform (Imag); MRAux.transform (Imag); if (MRAux.Type_Transform != TO_PAVE_BSPLINE) { MRAux.band(NbrScale-1).init(); MRAux.recons(Resi); FluxIma = total(Resi); } else FluxIma = 0.; for (s = 0; s < NbrScale-1; s++) for (i = 0; i < MR_Data.size_band_nl(s); i++) for (j = 0; j < MR_Data.size_band_nc(s); j++) { if (ABS(MR_Data(s,i,j)) > FLOAT_EPSILON) { if (MRAux.Type_Transform == TO_PAVE_BSPLINE) FluxIma += MRAux(s,i,j); MRAux(s,i,j) = MR_Data(s,i,j) - MRAux(s,i,j); } else MRAux(s,i,j) = 0.; // if (ABS(MR_Data(s,i,j)) < FLOAT_EPSILON) MRAux(s,i,j) = 0.; // else FluxIma += MRAux(s,i,j); } MRAux.rec_adjoint(Resi, False); //MRAux.rec_adjoint(Imag, False); // MRAux.band(NbrScale-1).init(); // MRAux.recons(Resi); // Flux Constraint if (Iter > 3) { // CoefFlux = (float) (FluxData / total(Imag)); CoefFlux = (float) (FluxData / FluxIma); for (i = 0; i < Nl; i++) for (j = 0; j < Nc; j++) Imag(i,j) *= CoefFlux; for (i = 0; i < Nlo; i++) for (j = 0; j < Nco; j++) Result(i,j) *= CoefFlux; } // for (i = 0; i < Nl; i++) //for (j = 0; j < Nc; j++) Resi(i,j) = RecIma(i,j) - Imag(i,j); if (Zoom > 1) { im_bilinear_interp (Resi, Temp); Result += Temp; threshold(Result); for (i = 0; i < Nl; i++) for (j = 0; j < Nc; j++) Error += Resi(i,j) * Resi(i,j); } else { Error = 0.; for (i = 0; i < Nl; i++) for (j = 0; j < Nc; j++) { Result(i,j) += Resi(i,j); if (Result(i,j) < 0.) Result(i,j) = 0.; Error += Resi(i,j) * Resi(i,j); } } Error = sqrt(Error); Iter ++; // cout << Iter << " Error = " << Error << " Flux = " << flux(Result) << // " Sigma = " << sigma(Resi) << " Min = " << min(Result) << " Max = " << max(Result) << " CoefFlux = " << CoefFlux << endl; } while ((Iter < Nb_iter) && (Error/Error0 > eps)); // io_write_ima_float("xx_data.fits", RecIma); // io_write_ima_float("xx_sol.fits", Result); // io_write_ima_float("xx_resi.fits", Resi); // MR_Data.write("xx.mr"); // MRAux.write("xx1.mr"); psf_convol (Result, Psf_cf, Imag); // io_write_ima_float("xx_ima.fits", Imag); // io_write_ima_float("xx_psf.fits", Psf); // cout << "Nl psf = " << Psf_cf.nl() << " Nc psf = " << Psf_cf.nc() << endl; // cout << "Nl Data " << Result.nl() << " Nc Data = " << Result.nc() << endl; // cout << "psf = " << Psf_cf(Psf_cf.nl()/2, Psf_cf.nc()/2).real() << " " << Psf_cf(Psf_cf.nl()/2, Psf_cf.nc()/2).imag() << endl; // cout << "psf = " << Psf_cf(Psf_cf.nl()/2-1, Psf_cf.nc()/2-1).real() << " " << Psf_cf(Psf_cf.nl()/2, Psf_cf.nc()/2).imag() << endl; // cout << "Iter = " << Iter << " Error = " << Error << endl; } /***************************************************************/ #define SQR(a) (a)*(a) void xmm_get_psf (float x, float y, /* target x,y position in pixels */ Ifloat &Image) /* PSF output image */ /* calculates XMM off-axis PSF (normalized surface brightness) * The XMM QM PSF has been fit with 4 Gaussians , and normalized, * so that Integral 2*PI*r*dr*f(r) from 0 to infinity = 1 [1/arcsec2] */ { int nx,ny,nqx,nqy; double sum=0.0,sig2, argum1,argum2, sig_blur; double th2, sscale, mscale, xc, yc, rr2, xqc, yqc; double offsg=0.0324; /* PSF blurring */ /* following are the norms after integrating each component to 1.00 */ float norm[] = {0.4169, 0.3470, 0.1279, 0.1082}; float sigma[] = {4.1450, 8.6218, 22.372, 66.698}; /* Assuming 512x512 image and scale of 4"/px */ /* NOTE! It is XMM-pn specific */ nx = 512; ny = 512; sscale = 4.0; /* scale in "/pixel */ mscale = sscale/60.0; /* scale in '/pixel */ /* centre of the field of view, assuming in the centre of the pixel */ xc = nx/2.0; yc = ny/2.0; /* Off-axis angle in arcmin */ th2 = mscale*mscale*(SQR(x-xc) + SQR(y-yc)); sig_blur=offsg*th2; /* For PSF image we don't need more than 51x51 pixels */ /* I should make it adaptive!!! */ nqx = XMM_PSF_NL; nqy = XMM_PSF_NC; Image.resize(nqy,nqx); xqc = nqx/2; yqc = nqy/2; double Flux=0.; int i,j; for (i=0; i< nqx; i++) for (j=0; j< nqy; j++) { /* distance from the source position in arcsec */ rr2 = sscale*sscale*(SQR(i-xqc) + SQR(j-yqc)); sum = 0; for(int k=0; k<4; k++) { sig2=sigma[k]*sigma[k]+sig_blur*sig_blur; if (sig2 > 0) { argum1 = rr2/(2.0*sig2); argum2 = norm[k]/(2.0*M_PI*sig2); sum += argum2*exp(-argum1); } } if (sum < 1e-4) sum = 0.; Image(j,i) = (float) sum; Flux += sum; } for (i=0; i< nqx; i++) for (j=0; j< nqy; j++) Image(j,i) = (float) (Image(j,i) / Flux); //cout << "PSF " << x << " " << y << " Flux = " << Flux << endl; //INFO(Image, "PSF"); //io_write_ima_float("xx_psf.fits", Image); } /*********************************************************************/ void ListObj2D::recons_obj(MultiResol& W, Ifloat &Im_rec, double & Erreur, double & Flux, t_Gauss_2D & Gauss, float PosX, float PosY) { double X,Y; if ((W.Type_Transform == TM_TO_PYR) || (W.Type_Transform == TM_TO_SEMI_PYR)) { if (ReconsMethod == GRAD_PSF) { cerr << "Error: the PSF cannot be used for the reconstruction " << endl; cerr << " with this transform ... " << endl; exit(-1); } // W.recons(Im_rec); Erreur = 0.; } else switch(ReconsMethod) { case GRAD_OPTI_STEP: rec_iter_grad (W, Im_rec, Nb_iter_rec, Erreur, ErrorRec); break; case GRAD_CONJUG: rec_iter_grad_conj (W, Im_rec, Nb_iter_rec, Erreur, ErrorRec); break; case GRAD_FIX_STEP: mr_sm_recons_obj(W, Im_rec, Nb_iter_rec, Erreur, ErrorRec); break; case GRAD_PSF: if (Psf.n_elem() == 0) { cerr << "Error: the PSF is not defined... " << endl; exit(-1); } mr_psf_recons_obj(W, Im_rec, Psf, Nb_iter_rec, Erreur, ErrorRec, Fwhm, IMGauss, Deconv, ZoomPSF); // if Fwhm > 0 the resolutiuon is limited if (Fwhm > 0) psf_convol (Im_rec, IMGauss); break; case GRAD_PSF_XMM: if (Psf.n_elem() == 0) Psf.alloc(XMM_PSF_NL,XMM_PSF_NC,"XMM PSF"); X = PosX - Nc / 2. + 256; Y = PosY - Nl / 2. + 256; // cout << "XMM PSF Pos = " << X << " " << Y << endl; xmm_get_psf (X, Y, Psf); // io_write_ima_float("xx_psf.fits", Psf); if ((IMGauss.nl() == Psf.nl()) || (IMGauss.nc() == Psf.nc())) { IMGauss = im_gaussian(Psf.nl(), Psf.nc(), Fwhm*ZoomPSF); norm_flux(IMGauss); psf_convol (Psf, IMGauss); } // rec_psf_iter_grad(W, Im_rec, Psf, Nb_iter_rec, Erreur, ErrorRec); mr_psf_recons_obj(W, Im_rec, Psf, Nb_iter_rec, Erreur, ErrorRec, Fwhm, IMGauss, Deconv, ZoomPSF); // if Fwhm > 0 the resolutiuon is limited if (Fwhm > 0) psf_convol (Im_rec, IMGauss); break; default: cerr << "Error: unknown reconstruction method ... "<<endl; exit(-1); break; } // find Gaussian parameters Estime_param_gauss_2D(Gauss, Im_rec); if ((ReconsMethod == GRAD_PSF) || (ReconsMethod == GRAD_PSF_XMM)) { // Test if a deconvolution is wanted if (Deconv == False) { // cout << "Reconv " << endl; // psf_convol (Im_rec, Psf); psf_convol (Im_rec, Psf_cf); threshold(Im_rec); } // Test if the deconvolved image is oversampled if (ZoomPSF > 1) { im_reduce(Im_rec, ZoomPSF); } } Gauss.sX /= ZoomPSF; Gauss.sY /= ZoomPSF; Gauss.mx /= ZoomPSF; Gauss.my /= ZoomPSF; // Gauss.amp = ValPixMax Flux = total(Im_rec); } /******************************************************************/ /******************************************************************/ /******************************************************************/ // // Flux Constraint // FluxIma=0.; // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) // if (RecIma(i,j) > FLOAT_EPSILON) FluxIma += Imag(i,j); // CoefFlux = (float) (FluxData / FluxIma); // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) Imag(i,j) *= CoefFlux; // for (i = 0; i < Nlo; i++) // for (j = 0; j < Nco; j++) Result(i,j) *= CoefFlux; // void rec_psf_iter_grad (MultiResol& W0, Ifloat &Im_rec, Ifloat &Psf, int Nb_iter, // double& Erreur,float eps) // { // float w; // double Erreur0=0., num, den; // int s,i,j,n = 0; // int Nl = W0.size_ima_nl(); // int Nc = W0.size_ima_nc(); // int NScale = W0.nbr_scale(); // type_transform Trans = W0.Type_Transform; // MultiResol V (Nl, Nc, NScale, Trans, "V rec_iter_grad"); // MultiResol Min(Nl, Nc, NScale, Trans, "min rec_iter_grad"); // Ifloat I0(Nl, Nc, "grad I0"); // Ifloat temp(Nl, Nc, "grad I0"); // Ifloat Ir(Nl, Nc, "Ir I0"); // // Icomplex_f Psf_cf; // psf_get(Psf, Psf_cf, Nl, Nc, True); // // calcul_masque (W0, Min); // W0.rec_adjoint (Im_rec, False); // // for (i=0; i< Nl; i++) // for (j=0; j< Nc; j++) // { // Erreur0 += Im_rec(i,j)*Im_rec(i,j); // temp(i,j) = (Im_rec(i,j) > 0.) ? Im_rec(i,j) : 0.; // } // Erreur0 = sqrt (Erreur0); // // I0 = Im_rec; // // do { // n++; // // // TO IMAGE RECONSTRUITE // psf_convol(temp, Psf_cf); // V.transform (temp); // for (s=0; s < V.nbr_band()-1; s++) // for (i=0; i< V.size_band_nl(s); i++) // for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); // // //---- CALCUL IMAGE RESIDUE // V.rec_adjoint(temp, False); // Ir = I0 - temp; // // Erreur = 0.; // for (i=0; i< Nl; i++) // for (j=0; j< Nc; j++) Erreur += Ir(i,j)*Ir(i,j); // Erreur = sqrt (Erreur) / Erreur0; // // //---- CALCUL PARAMETRE DE CONVERGENCE // V.transform (Ir); // for (s=0; s < V.nbr_band()-1; s++) // for (i=0; i< V.size_band_nl(s); i++) // for (j=0; j< V.size_band_nc(s); j++) V(s,i,j) *= Min(s,i,j); // V.rec_adjoint(temp, False); // // num = 0.; // den = 0.; // for (i=0; i< Nl; i++) // for (j=0; j< Nc; j++) // { // num += Ir(i,j)*temp(i,j); // den += temp(i,j)*temp(i,j); // } // if(!den) w = 1.0; // else w = MAX (1.0, num/den); // // //---- CALCUL NOUVELLE SOLUTION // // for (i=0; i< Nl; i++) // for (j=0; j< Nc; j++) // { // Im_rec(i,j) += w * Ir(i,j); // temp(i,j) = (Im_rec(i,j) > 0.) ? Im_rec(i,j) : 0.; // } // cout << n << " w = " << w << " Error = " << Erreur << " Flux = " << flux(temp) << " Max = " << max(temp) << endl; // // } while(n < Nb_iter && Erreur > eps); // // threshold(Im_rec); // io_write_ima_float("xx_sol.fits", Im_rec); // // } //---------------------------------------------------------- // Rec_iter // Reconstruction image a partir de sa T.O //---------------------------------------------------------- // void mr_recons_obj (MultiResol& W, Ifloat &Im_rec, type_objrec_method Meth, // int Nb_iter, double& Erreur, float eps, Ifloat & Psf, // Bool Deconv, float Alpha, float Zoom) // { // if ((W.Type_Transform == TM_TO_PYR) || (W.Type_Transform == TM_TO_SEMI_PYR)) // { // if (Meth == GRAD_PSF) // { // cerr << "Error: the PSF cannot be used for the reconstruction " << endl; // cerr << " with this transform ... " << endl; // exit(-1); // } // W.recons(Im_rec); // Erreur = 0.; // } // else // switch(Meth) // { // case GRAD_OPTI_STEP: // rec_iter_grad (W, Im_rec, Nb_iter, Erreur, eps); // break; // case GRAD_CONJUG: // rec_iter_grad_conj (W, Im_rec, Nb_iter, Erreur, eps); // break; // case GRAD_FIX_STEP: // mr_sm_recons_obj(W, Im_rec, Nb_iter, Erreur, eps); // break; // case GRAD_PSF: // if (Psf.n_elem() == 0) // { // cerr << "Error: the PSF is not defined... " << endl; // exit(-1); // } // rec_psf_iter_grad_conj(W, Im_rec, Psf, Nb_iter, Erreur, eps); // //mr_psf_recons_obj(W, Im_rec, Psf, // // Nb_iter, Erreur, eps, Deconv, // // Alpha, Zoom); // break; // default: // cerr << "Error: unknown reconstruction method ... "<<endl; // exit(-1); // break; // } // } /******************************************************************/ // void test_mr_psf_recons_obj (MultiResol& MR_Data, Ifloat &Result, Ifloat &Psf, // int Nb_iter, double& Error, float eps, Bool Deconv, // float Alpha, float Zoom) // { // int i,j,s,Iter = 0; // int Nl = Result.nl(); // int Nc = Result.nc(); // int NbrScale = MR_Data.nbr_band(); // double Error0; // int Nlz = (Zoom > 1.) ? (int)(Nl/Zoom): Nl; // int Ncz = (Zoom > 1.) ? (int)(Nc/Zoom): Nc; // Ifloat Resi (Nlz, Ncz, "Residual"); // Ifloat Data (Nl, Nc, "Residual"); // Ifloat Imag (Nl, Nc, "Residual"); // Ifloat Temp (Nl, Nc, "Temp"); // // cout << " TEST RECONS OBJ " << endl; // mr_sm_recons_obj(MR_Data, Data, 10, Error, eps); // // io_write_ima_float("xx_data.fits", Result); // MultiResol MRAux(Nlz, Ncz, MR_Data.nbr_scale(), MR_Data.Type_Transform, "Aux"); // // Icomplex_f Psf_cf; // psf_get(Psf, Psf_cf, Nl, Nc, True); // //INFO(Psf,"PSF"); // //cout << "PP = " << Psf_cf(Nl/2,Nc/2).real() << endl; // io_write_ima_float("xx_psf.fits", Psf); // // Result = Data; // float CoefFlux, FluxIma,FluxData = flux(Data); // Error0 = sqrt(energy(Result)); // INFO(Result, "INIT"); // MR_Data.write("xx.mr"); // do { // // solution in image space // psf_convol (Result, Psf_cf, Imag); // io_write_ima_float("xx_ima.fits", Result); // // Flux Constraint // FluxIma=0.; // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) // if (Data(i,j) > FLOAT_EPSILON) FluxIma += Imag(i,j); // CoefFlux = FluxData / FluxIma; // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) // { // Imag(i,j) *= CoefFlux; // Result(i,j) *= CoefFlux; // } // // MRAux.transform (Imag); // for (s = 0; s < NbrScale-1; s++) // for (i = 0; i < MR_Data.size_band_nl(s); i++) // for (j = 0; j < MR_Data.size_band_nc(s); j++) // { // if (ABS(MR_Data(s,i,j)) > FLOAT_EPSILON) // MRAux(s,i,j) = MR_Data(s,i,j) - MRAux(s,i,j); // else MRAux(s,i,j) = 0.; // // if (ABS(MR_Data(s,i,j)) < FLOAT_EPSILON) MRAux(s,i,j) = 0.; // // } // MRAux.band(NbrScale-1).init(); // // MRAux.rec_adjoint(Resi); // // MRAux.recons(Resi); // //INFO(Data-Resi,"Resi"); // // Resi = Imag; // // Error = 0.; // for (i = 0; i < Nl; i++) // for (j = 0; j < Nc; j++) // { // // Resi(i,j) = Data(i,j) - Imag(i,j); // Result(i,j) += Resi(i,j); // Error += Resi(i,j) * Resi(i,j); // // if (Data(i,j) == 0) Result(i,j) = 0.; // if (Result(i,j) < 0.) Result(i,j) = 0.; // } // // io_write_ima_float("xx_resi.fits", Resi); // // Error = sqrt(Error) / Error0; // // Iter ++; // cout << Iter << " Error = " << Error << " Flux = " << flux(Result) << // " Sigma = " << sigma(Resi) << " Min = " << min(Result) << " Max = " << max(Result) << endl; // } while ((Iter < Nb_iter) && (Error > eps)); // // INFO(Result, "BEF CONV"); // psf_convol (Result, Psf_cf, Imag); // INFO(Imag, "AF CONV"); // // // cout << "Iter = " << Iter << " Error = " << Error << endl; // io_write_ima_float("xx_sol.fits", Result); // io_write_ima_float("xx_resi.fits", Resi); // // }
31.229801
139
0.465695
[ "object", "model", "transform" ]
efd2a252ca2fb3e541e78a657a7e68bdc9101469
10,168
cpp
C++
Btraj/src/a_star.cpp
JCrime/Park_Inspection
524d8286424e363a4bd3d77cf10df8f7eb3c3c6f
[ "Apache-2.0" ]
11
2019-08-24T08:28:17.000Z
2021-04-28T05:23:42.000Z
fm_Btraj/src/Btraj/src/a_star.cpp
lvhualong/motion_Planning
ea127de8cd8f32e9994538416d0c74b99054214f
[ "MIT" ]
null
null
null
fm_Btraj/src/Btraj/src/a_star.cpp
lvhualong/motion_Planning
ea127de8cd8f32e9994538416d0c74b99054214f
[ "MIT" ]
6
2019-08-24T08:28:19.000Z
2020-10-19T12:47:20.000Z
#include "a_star.h" using namespace std; using namespace Eigen; using namespace sdf_tools; void gridPathFinder::initGridNodeMap(double _resolution, Vector3d global_xyz_l) { gl_xl = global_xyz_l(0); gl_yl = global_xyz_l(1); gl_zl = global_xyz_l(2); resolution = _resolution; inv_resolution = 1.0 / _resolution; GridNodeMap = new GridNodePtr ** [GLX_SIZE]; for(int i = 0; i < GLX_SIZE; i++){ GridNodeMap[i] = new GridNodePtr * [GLY_SIZE]; for(int j = 0; j < GLY_SIZE; j++){ GridNodeMap[i][j] = new GridNodePtr [GLZ_SIZE]; for( int k = 0; k < GLZ_SIZE;k++){ Vector3i tmpIdx(i,j,k); Vector3d pos = gridIndex2coord(tmpIdx); GridNodeMap[i][j][k] = new GridNode(tmpIdx, pos); } } } } void gridPathFinder::linkLocalMap(CollisionMapGrid * local_map, Vector3d xyz_l) { Vector3d coord; for(int64_t i = 0; i < X_SIZE; i++) { for(int64_t j = 0; j < Y_SIZE; j++) { for(int64_t k = 0; k < Z_SIZE; k++) { coord(0) = xyz_l(0) + (double)(i + 0.5) * resolution; coord(1) = xyz_l(1) + (double)(j + 0.5) * resolution; coord(2) = xyz_l(2) + (double)(k + 0.5) * resolution; Vector3i index = coord2gridIndex(coord); if( index(0) >= GLX_SIZE || index(1) >= GLY_SIZE || index(2) >= GLZ_SIZE || index(0) < 0 || index(1) < 0 || index(2) < 0 ) continue; GridNodePtr ptr = GridNodeMap[index(0)][index(1)][index(2)]; ptr->id = 0; ptr->occupancy = local_map->Get(i, j, k ).first.occupancy; } } } } void gridPathFinder::resetLocalMap() { //ROS_WARN("expandedNodes size : %d", expandedNodes.size()); for(auto tmpPtr:expandedNodes) { tmpPtr->occupancy = 0; // forget the occupancy tmpPtr->id = 0; tmpPtr->cameFrom = NULL; tmpPtr->gScore = inf; tmpPtr->fScore = inf; } for(auto ptr:openSet) { GridNodePtr tmpPtr = ptr.second; tmpPtr->occupancy = 0; // forget the occupancy tmpPtr->id = 0; tmpPtr->cameFrom = NULL; tmpPtr->gScore = inf; tmpPtr->fScore = inf; } expandedNodes.clear(); //ROS_WARN("local map reset finish"); } GridNodePtr gridPathFinder::pos2gridNodePtr(Vector3d pos) { Vector3i idx = coord2gridIndex(pos); GridNodePtr grid_ptr = new GridNode(idx, pos); return grid_ptr; } Vector3d gridPathFinder::gridIndex2coord(Vector3i index) { Vector3d pt; //cell_x_size_ * ((double)x_index + 0.5), cell_y_size_ * ((double)y_index + 0.5), cell_z_size_ * ((double)z_index + 0.5) pt(0) = ((double)index(0) + 0.5) * resolution + gl_xl; pt(1) = ((double)index(1) + 0.5) * resolution + gl_yl; pt(2) = ((double)index(2) + 0.5) * resolution + gl_zl; /*pt(0) = (double)index(0) * resolution + gl_xl + 0.5 * resolution; pt(1) = (double)index(1) * resolution + gl_yl + 0.5 * resolution; pt(2) = (double)index(2) * resolution + gl_zl + 0.5 * resolution;*/ return pt; } Vector3i gridPathFinder::coord2gridIndex(Vector3d pt) { Vector3i idx; idx << min( max( int( (pt(0) - gl_xl) * inv_resolution), 0), GLX_SIZE - 1), min( max( int( (pt(1) - gl_yl) * inv_resolution), 0), GLY_SIZE - 1), min( max( int( (pt(2) - gl_zl) * inv_resolution), 0), GLZ_SIZE - 1); return idx; } double gridPathFinder::getDiagHeu(GridNodePtr node1, GridNodePtr node2) { double dx = abs(node1->index(0) - node2->index(0)); double dy = abs(node1->index(1) - node2->index(1)); double dz = abs(node1->index(2) - node2->index(2)); double h; int diag = min(min(dx, dy), dz); dx -= diag; dy -= diag; dz -= diag; if (dx == 0) { h = 1.0 * sqrt(3.0) * diag + sqrt(2.0) * min(dy, dz) + 1.0 * abs(dy - dz); } if (dy == 0) { h = 1.0 * sqrt(3.0) * diag + sqrt(2.0) * min(dx, dz) + 1.0 * abs(dx - dz); } if (dz == 0) { h = 1.0 * sqrt(3.0) * diag + sqrt(2.0) * min(dx, dy) + 1.0 * abs(dx - dy); } return h; } double gridPathFinder::getManhHeu(GridNodePtr node1, GridNodePtr node2) { double dx = abs(node1->index(0) - node2->index(0)); double dy = abs(node1->index(1) - node2->index(1)); double dz = abs(node1->index(2) - node2->index(2)); return dx + dy + dz; } double gridPathFinder::getEuclHeu(GridNodePtr node1, GridNodePtr node2) { return (node2->index - node1->index).norm(); } double gridPathFinder::getHeu(GridNodePtr node1, GridNodePtr node2) { return tie_breaker * getDiagHeu(node1, node2); //return tie_breaker * getEuclHeu(node1, node2); } vector<GridNodePtr> gridPathFinder::retrievePath(GridNodePtr current) { vector<GridNodePtr> path; path.push_back(current); while(current->cameFrom != NULL) { current = current -> cameFrom; path.push_back(current); } return path; } vector<GridNodePtr> gridPathFinder::getVisitedNodes() { vector<GridNodePtr> visited_nodes; for(int i = 0; i < GLX_SIZE; i++) for(int j = 0; j < GLY_SIZE; j++) for(int k = 0; k < GLZ_SIZE; k++) { if(GridNodeMap[i][j][k]->id != 0) //if(GridNodeMap[i][j][k]->id == -1) visited_nodes.push_back(GridNodeMap[i][j][k]); } ROS_WARN("visited_nodes size : %d", visited_nodes.size()); return visited_nodes; } /*bool gridPathFinder::minClearance() { neighborPtr->occupancy > 0.5 } */ void gridPathFinder::AstarSearch(Eigen::Vector3d start_pt, Eigen::Vector3d end_pt) { ros::Time time_1 = ros::Time::now(); GridNodePtr startPtr = pos2gridNodePtr(start_pt); GridNodePtr endPtr = pos2gridNodePtr(end_pt); openSet.clear(); GridNodePtr neighborPtr = NULL; GridNodePtr current = NULL; startPtr -> gScore = 0; startPtr -> fScore = getHeu(startPtr, endPtr); startPtr -> id = 1; //put start node in open set startPtr -> coord = start_pt; openSet.insert( make_pair(startPtr -> fScore, startPtr) ); //put start in open set double tentative_gScore; int num_iter = 0; while ( !openSet.empty() ) { num_iter ++; current = openSet.begin() -> second; if(current->index(0) == endPtr->index(0) && current->index(1) == endPtr->index(1) && current->index(2) == endPtr->index(2) ) { ROS_WARN("[Astar]Reach goal.."); //cout << "goal coord: " << endl << current->real_coord << endl; cout << "total number of iteration used in Astar: " << num_iter << endl; ros::Time time_2 = ros::Time::now(); ROS_WARN("Time consume in A star path finding is %f", (time_2 - time_1).toSec() ); gridPath = retrievePath(current); return; } openSet.erase(openSet.begin()); current -> id = -1; //move current node from open set to closed set. expandedNodes.push_back(current); for(int dx = -1; dx < 2; dx++) for(int dy = -1; dy < 2; dy++) for(int dz = -1; dz < 2; dz++) { if(dx == 0 && dy == 0 && dz ==0) continue; Vector3i neighborIdx; neighborIdx(0) = (current -> index)(0) + dx; neighborIdx(1) = (current -> index)(1) + dy; neighborIdx(2) = (current -> index)(2) + dz; if( neighborIdx(0) < 0 || neighborIdx(0) >= GLX_SIZE || neighborIdx(1) < 0 || neighborIdx(1) >= GLY_SIZE || neighborIdx(2) < 0 || neighborIdx(2) >= GLZ_SIZE){ continue; } neighborPtr = GridNodeMap[neighborIdx(0)][neighborIdx(1)][neighborIdx(2)]; /* if(minClearance() == false){ continue; }*/ if(neighborPtr -> occupancy > 0.5){ continue; } if(neighborPtr -> id == -1){ continue; //in closed set. } double static_cost = sqrt(dx * dx + dy * dy + dz * dz); tentative_gScore = current -> gScore + static_cost; if(neighborPtr -> id != 1){ //discover a new node neighborPtr -> id = 1; neighborPtr -> cameFrom = current; neighborPtr -> gScore = tentative_gScore; neighborPtr -> fScore = neighborPtr -> gScore + getHeu(neighborPtr, endPtr); neighborPtr -> nodeMapIt = openSet.insert( make_pair(neighborPtr->fScore, neighborPtr) ); //put neighbor in open set and record it. continue; } else if(tentative_gScore <= neighborPtr-> gScore){ //in open set and need update neighborPtr -> cameFrom = current; neighborPtr -> gScore = tentative_gScore; neighborPtr -> fScore = tentative_gScore + getHeu(neighborPtr, endPtr); openSet.erase(neighborPtr -> nodeMapIt); neighborPtr -> nodeMapIt = openSet.insert( make_pair(neighborPtr->fScore, neighborPtr) ); //put neighbor in open set and record it. } } } ros::Time time_2 = ros::Time::now(); ROS_WARN("Time consume in A star path finding is %f", (time_2 - time_1).toSec() ); } vector<Vector3d> gridPathFinder::getPath() { vector<Vector3d> path; for(auto ptr: gridPath) path.push_back(ptr->coord); reverse(path.begin(), path.end()); return path; } void gridPathFinder::resetPath() { gridPath.clear(); }
32.8
155
0.531176
[ "vector" ]
efd9bb3da3dcd4b2f9f7a6c2250f0b2d6c85f5f4
1,526
cpp
C++
AtCoder/ABC131/E.cpp
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
1
2018-11-25T04:15:45.000Z
2018-11-25T04:15:45.000Z
AtCoder/ABC131/E.cpp
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
null
null
null
AtCoder/ABC131/E.cpp
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
2
2018-08-08T13:01:14.000Z
2018-11-25T12:38:36.000Z
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<complex> #include<bitset> #include<stack> #include<unordered_map> #include<utility> #include<cassert> using namespace std; const int MOD = 1000000007; typedef pair<int, int> P; typedef long long ll; #define rep(i, n) for(int i=0;i<n;i++) #define rep2(i, m, n) for(int i=m;i<n;i++) #define rrep(i, n, m) for(int i=n;i>=m;i--) using Graph = vector<vector<int>>; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; int main() { int N, K; cin >> N >> K; int ans = (N - 1) * (N - 2) / 2; vector<pair<int, int>> res; rep2(i, 2, N + 1) { res.emplace_back(make_pair(1, i)); } if (ans < K) { cout << -1 << endl; return 0; } if (ans != K) { for (int i = 2; i <= N; ++i) { for (int j = i + 1; j <= N; ++j) { if (i == j) { continue; } else { res.emplace_back(make_pair(i, j)); ans -= 1; if (ans == K) { break; } } } if (ans == K) { break; } } } cout << res.size() << endl; rep(i, res.size()) { cout << res[i].first << " " << res[i].second << endl; } }
22.441176
61
0.465269
[ "vector" ]
efd9e06f0912370ca1f402390a14a2a2af9eacbd
2,025
cc
C++
old/rangeop2.cc
SnapDragon64/ContestLibrary
d590db2470447b9ee519985cbd662c35c32c7f76
[ "MIT" ]
26
2015-06-18T17:42:09.000Z
2021-09-25T20:46:17.000Z
old/rangeop2.cc
SnapDragon64/ContestLibrary
d590db2470447b9ee519985cbd662c35c32c7f76
[ "MIT" ]
null
null
null
old/rangeop2.cc
SnapDragon64/ContestLibrary
d590db2470447b9ee519985cbd662c35c32c7f76
[ "MIT" ]
8
2018-06-02T14:52:01.000Z
2021-09-25T20:46:19.000Z
// Structure that takes O(N) setup time, O(N) memory, then allows for O(logN) // calculation of a given associative operation on arbitrary ranges. Also // has constant amortized time when successively incrementing the front // and/or back of ranges. template<class T = int> class RangeOp { public: vector<vector<T> > tree; T (*op)(const T &, const T &); T def; // should have the property that op(x, def) == x == op(def, x) // internal cache that allows for amortized runtimes vector<int> cs, ce; vector<T> cache; // pass in start/end iterators, the (associative) operation, and (if // necessary) a default (identity) T value for empty ranges template<class it> RangeOp(it s, it e, T (*op)(const T &, const T &), T def = T()) : op(op), def(def) { tree.push_back(vector<T>()); for( ; s != e; s++ ) tree[0].push_back(*s); for( int depth = 1, i; tree[depth-1].size() > 1; depth++ ) { tree.push_back(vector<T>((tree[depth-1].size()+1)/2)); for( i = 0; i+1 < tree[depth-1].size(); i += 2 ) tree[depth][i>>1] = op(tree[depth-1][i], tree[depth-1][i+1]); if( i < tree[depth-1].size() ) tree[depth][i>>1] = tree[depth-1][i]; } cs = ce = vector<int>(tree.size()+1); cache = vector<T>(tree.size()+1, def); } // takes O(log(e-s)) time (and possibly constant time, amortized) T dorange(int s, int e) { if( s >= e ) return def; int depth, curs, cure; for( depth = 0; ; depth++ ) { curs = ((s+(1<<depth)-1)>>depth); cure = (e>>depth); if( curs == cure ) { cache[depth] = def; cs[depth] = curs; ce[depth] = cure; } if( curs == cs[depth] && cure == ce[depth] ) break; } for( depth--; depth >= 0; depth-- ) { curs <<= 1; cure <<= 1; int &v = cache[depth]; v = cache[depth+1]; if( ((curs-1)<<depth) >= s ) v = op(tree[depth][--curs], v); if( ((cure+1)<<depth) <= e ) v = op(v, tree[depth][cure++]); cs[depth] = curs; ce[depth] = cure; } return cache[0]; } };
34.322034
78
0.559506
[ "vector" ]
efdaa441d7df57a235a12019564b42de78ff3bb6
8,258
hpp
C++
include/Lintel/HashMap.hpp
sbu-fsl/Lintel
b9e603aaec630c8d3fae2f21fc156582d11d84c9
[ "BSD-3-Clause" ]
null
null
null
include/Lintel/HashMap.hpp
sbu-fsl/Lintel
b9e603aaec630c8d3fae2f21fc156582d11d84c9
[ "BSD-3-Clause" ]
1
2020-10-05T21:20:36.000Z
2020-10-05T21:56:51.000Z
include/Lintel/HashMap.hpp
sbu-fsl/Lintel
b9e603aaec630c8d3fae2f21fc156582d11d84c9
[ "BSD-3-Clause" ]
null
null
null
/* -*-C++-*- */ /* (c) Copyright 2003-2005, Hewlett-Packard Development Company, LP See the file named COPYING for license details */ /** @file \brief Header for the HashMap class. A "map" using the HashTable class. You may want to read the warning in HashTable.H about the types of values that you can safely use. */ #ifndef LINTEL_HASH_MAP_HPP #define LINTEL_HASH_MAP_HPP #if __GNUG__ == 3 && __GNUC_MINOR == 3 #include <ext/stl_hash_fun.h> #endif #if __GNUG__ == 3 && __GNUC_MINOR == 4 #include <ext/hash_fun.h> #endif #include <functional> #include <boost/static_assert.hpp> #include <Lintel/HashFns.hpp> #include <Lintel/HashTable.hpp> // propagate things into the global namespace /// \brief Base class for hash functions, intended to be overridden. template <class K> struct HashMap_hash : lintel::Hash<K> { // uint32_t operator()(const K &a) const; }; /// \cond DEPRECATED // TODO: deprecate these as obsolete relative to the lintel::Pointer* variants. template<typename T> struct PointerHashMapHash : lintel::PointerHash<T> { }; template<typename T> struct PointerHashMapEqual : lintel::PointerEqual<T> { }; /// \endcond // TODO: add test for proper destruction of things in the hash map. /// \brief The HashMap class, a std::map-like structure using an underlying HashTable. /// HashMap class; in our testing almost as fast as the google dense /// map, but uses almost as little memory as the sparse map. Note /// that class K can't be const, see src/tests/hashmap.cpp for /// details. /// /// To create a hashmap on a separate type, you need to define two /// additional operations. For example, with: /// \code /// struct example { /// int32_t x, y; /// std::string str; /// bool operator==(const example &rhs) const; /// uint32_t hash() const; /// } /// \endcode /// you would need to define a hash function and operator == for /// struct example. The operator definition can be seen above. There are /// two options for the hash function. Either it is a hash method on the /// object itself, with the signature shown above. Or it is a /// hashType(const Example &v) function defined in the same namespace as /// the underlying type or the lintel namespace. So you could write either: /// \code /// uint32_t example::hash() const { /// uint32_t partial_hash = BobJenkinsHashMix3(a.x, a.y, 2001); /// return HasHTable_hashbytes(a.str().data, a.str.size(), partial_hash); /// } /// \endcode /// or /// \code /// uint32_t hashType(const example &v) { /// uint32_t partial_hash = BobJenkinsHashMix3(a.x, a.y, 2001); /// return HasHTable_hashbytes(a.str().data, a.str.size(), partial_hash); /// } /// \endcode /// If both are defined, the hash function on the object takes precedence. /// /// To define operator ==, you can either define it as part of the /// class as shown above in the structure example (normally you would /// define it inline), or you can define an external operator == as in: /// \code /// bool operator==(const example &a, const example &b) { /// return a.x == b.x && a.y == b.y && a.str == b.str; /// } /// \endcode /// /// Then you can define your hash map: /// HashMap<example, int> example_to_int; template <class K, class V, class KHash = HashMap_hash<const K>, class KEqual = std::equal_to<const K> > class HashMap { public: /// \cond SEMI_INTERNAL_CLASSES typedef std::pair<K,V> value_type; struct value_typeHash { KHash khash; uint32_t operator()(const value_type &hmv) const { return khash(hmv.first); } }; struct value_typeEqual { KEqual kequal; bool operator()(const value_type &a, const value_type &b) const { return kequal(a.first,b.first); } }; /// \endcond V *lookup(const K &k) { return internalLookup<V, value_type>(this, k); } const V *lookup(const K &k) const { return internalLookup<const V, const value_type>(this, k); } /// Returns the value associated with the key, if it exists. Otherwise, /// creates an entry initialized with the default value. V &operator[] (const K &k) { value_type fullval; fullval.first = k; value_type *v = hashtable.lookup(fullval); if (v == NULL) { return hashtable.add(fullval)->second; } else { return v->second; } } /// Add the key to the map if the key doesn't already exist, otherwise leave the existing /// key-value pair unchanged. Returns true if new key is added, otherwise return false. bool addUnlessExist(const K &k) { value_type fullval; fullval.first = k; value_type *v = hashtable.lookup(fullval); if (v == NULL) { hashtable.add(fullval); return true; } else { return false; } } /// Const get; will error out if you attempt to get a value that /// isn't present in the hash table because creating the entry is /// a non-const operation. const V &cGet(const K &k) const { value_type fullval; fullval.first = k; const value_type *v = hashtable.lookup(fullval); if (v == NULL) { FATAL_ERROR(boost::format("Unable to get missing entry %1% from hash table") % k); } else { return v->second; } } /// Const "default" get returning default value if entry is missing in table. const V &dGet(const K &k) const { value_type fullval; fullval.first = k; const value_type *v = hashtable.lookup(fullval); if (v == NULL) { static V default_v; return default_v; } else { return v->second; } } bool exists(const K &k) const { return lookup(k) != NULL; } /** returns true if something was removed */ bool remove(const K &k, bool must_exist = true) { value_type fullval; fullval.first = k; return hashtable.remove(fullval, must_exist); } void clear() { hashtable.clear(); } uint32_t size() const { return hashtable.size(); } size_t capacity() const { return hashtable.capacity(); } bool empty() const { return hashtable.empty(); } typedef HashTable<value_type,value_typeHash,value_typeEqual> HashTableT; typedef typename HashTableT::iterator iterator; typedef typename HashTableT::const_iterator const_iterator; iterator begin() { return hashtable.begin(); } iterator end() { return hashtable.end(); } const_iterator begin() const { return hashtable.begin(); } const_iterator end() const { return hashtable.end(); } iterator find(const K &k) { value_type fullval; fullval.first = k; return hashtable.find(fullval); } const_iterator find(const K &k) const { value_type fullval; fullval.first = k; return hashtable.find(fullval); } // TODO: try to find someone with enough C++ STL magic foo to explain why // this isn't const &. void erase(iterator it) { hashtable.erase(it); } explicit HashMap(double target_chain_length) : hashtable(target_chain_length) { } HashMap() { } HashMap(const HashMap &__in) { hashtable = __in.hashtable; } HashMap & operator=(const HashMap &__in) { hashtable = __in.hashtable; return *this; } void reserve(uint32_t nentries) { hashtable.reserve(nentries); } uint32_t available() { return hashtable.available(); } std::vector<K> keys() const { std::vector<K> ret; ret.reserve(size()); for(const_iterator i = begin(); i != end(); ++i) { ret.push_back(i->first); } return ret; } size_t memoryUsage() const { return hashtable.memoryUsage(); } /// Get statistics for the chain lengths of all the chains in the /// underlying hash table. Useful for detecting a bad hash /// function. void chainLengthStats(Stats &stats) { return hashtable.chainLengthStats(stats); } // primiarily here so that you can get at unsafeGetRawDataVector, with // all the caveats that go with that function. HashTableT &getHashTable() { return hashtable; } private: template<class R, class VT, class C> static inline R *internalLookup(C *me, const K &k) { value_type fullval; fullval.first = k; VT *v = me->hashtable.lookup(fullval); if (v == NULL) { return NULL; } else { return &v->second; } } HashTableT hashtable; }; #endif
27.526667
93
0.661056
[ "object", "vector" ]
efebf517f76e126febdbd1ded359283e10c5c86c
4,425
cpp
C++
Source/Grid/Grid.cpp
KwenaMashamaite/Centipede
745b9792da15482db7697e3b86f93c75754ebd64
[ "MIT" ]
2
2021-09-08T11:03:39.000Z
2022-02-17T10:09:14.000Z
Source/Grid/Grid.cpp
KwenaMashamaite/Centipede
745b9792da15482db7697e3b86f93c75754ebd64
[ "MIT" ]
null
null
null
Source/Grid/Grid.cpp
KwenaMashamaite/Centipede
745b9792da15482db7697e3b86f93c75754ebd64
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Centipede clone // // Copyright (c) 2021 Kwena Mashamaite (kwena.mashamaite1@gmail.com) // // 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 "Source/Grid/Grid.h" #include <cassert> namespace centpd { /////////////////////////////////////////////////////////////// Grid::Grid(ime::TileMap& tileMap, ime::GameObjectContainer& gameObjects) : m_grid{tileMap}, m_gameObjects{gameObjects} { // By default, IME sorts render layers by the order in which they are created m_grid.renderLayers().create("GameObject"); // ime::GameObject instances go to this layer m_grid.renderLayers().create("Bullet"); m_grid.renderLayers().create("Mushroom"); m_grid.renderLayers().create("CentipedeSegment"); m_grid.renderLayers().create("Scorpion"); m_grid.renderLayers().create("Player"); m_grid.renderLayers().create("Flea"); } /////////////////////////////////////////////////////////////// void Grid::create(unsigned int rows, unsigned int cols) { m_grid.construct(ime::Vector2u{rows, cols}, '.'); #ifndef NDEBUG m_grid.getRenderer().setVisible(true); #else m_grid.getRenderer().setVisible(false); #endif } /////////////////////////////////////////////////////////////// ime::GameObject* Grid::addActor(ime::GameObject::Ptr object, ime::Index index) { assert(object && "Object must not be a nullptr"); m_grid.addChild(object.get(), index); std::string renderLayer = object->getClassName(); const std::string& group = renderLayer; return m_gameObjects.add(group, std::move(object), 0, renderLayer); } /////////////////////////////////////////////////////////////// void Grid::addActor(ime::GameObject *actor, ime::Index index) { m_grid.addChild(actor, index); } /////////////////////////////////////////////////////////////// ime::Index Grid::getActorTile(ime::GameObject *actor) { return m_grid.getTileOccupiedByChild(actor).getIndex(); } /////////////////////////////////////////////////////////////// unsigned int Grid::getRows() const { return m_grid.getSizeInTiles().y; } /////////////////////////////////////////////////////////////// unsigned int Grid::getCols() const { return m_grid.getSizeInTiles().x; } /////////////////////////////////////////////////////////////// bool Grid::isCellOccupied(const ime::Index &index) const { return m_grid.isTileOccupied(index); } /////////////////////////////////////////////////////////////// bool Grid::isMushroomInCell(const ime::Index &index) const { bool hasMushroom = false; m_grid.forEachChildInTile(m_grid.getTile(index), [&hasMushroom](ime::GameObject* gameObject) { // IME v2.3.0 has no way of terminating loop early :( if (hasMushroom) return; if (gameObject->getClassName() == "Mushroom") hasMushroom = true; }); return hasMushroom; } /////////////////////////////////////////////////////////////// ime::Scene &Grid::getScene() { return m_grid.getScene(); } }
40.227273
102
0.545085
[ "render", "object" ]
efed06d0346095141a67d4d567602bd81697bb16
3,531
cpp
C++
src/projects/corridor/ChCollisionLidar.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
[ "BSD-3-Clause" ]
1
2020-03-05T13:00:41.000Z
2020-03-05T13:00:41.000Z
src/projects/corridor/ChCollisionLidar.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
[ "BSD-3-Clause" ]
null
null
null
src/projects/corridor/ChCollisionLidar.cpp
rserban/chrono
bee5e30b2ce3b4ac62324799d1366b6db295830e
[ "BSD-3-Clause" ]
1
2022-03-27T15:12:24.000Z
2022-03-27T15:12:24.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Asher Elmquist // ============================================================================= // // // ============================================================================= #include "ChCollisionLidar.h" using namespace chrono; // Constructor for a ChRaySensor ChCollisionLidar::ChCollisionLidar (std::shared_ptr<ChBody> parent, double updateRate, bool visualize) :ChSensor(parent,updateRate,visualize){ } ChCollisionLidar::~ChCollisionLidar(){ m_rays.clear(); } // Initialize the ChRaySensor void ChCollisionLidar::Initialize(chrono::ChCoordsys<double> offsetPose, int aboutYSamples, int aboutZSamples, double aboutYMinAngle, double aboutYMaxAngle, double aboutZMinAngle, double aboutZMaxAngle, double minRange, double maxRange){ m_minRange = minRange; m_maxRange = maxRange; if(aboutZSamples < 1) aboutZSamples = 1; if(aboutYSamples < 1) aboutYSamples = 1; chrono::ChVector<double> start, end, axis; double yawAngle, pitchAngle; chrono::ChQuaternion<double> ray; double yDiff = aboutYMaxAngle - aboutYMinAngle; double pDiff = aboutZMaxAngle - aboutZMinAngle; for(int j=0; j< aboutZSamples; ++j){ for(int i=0; i<aboutYSamples; ++i){ yawAngle = (aboutYSamples == 1) ? 0 : i * yDiff / (aboutYSamples - 1) + aboutYMinAngle; pitchAngle = (aboutZSamples == 1) ? 0 : j * pDiff / (aboutZSamples - 1) + aboutZMinAngle; //Yaw, Roll, Pitch according to ChQuaternion.h ray.Q_from_NasaAngles(chrono::ChVector<double>(yawAngle, 0.0, -pitchAngle)); axis = (offsetPose.rot * ray).Rotate(chrono::ChVector<double>(1.0,0,0)); start = (axis * minRange) + offsetPose.pos; end = (axis * maxRange) + offsetPose.pos; AddRay(start,end); } } } void ChCollisionLidar::UpdateRays(){ } void ChCollisionLidar::AddRay(const chrono::ChVector<double> &start, const chrono::ChVector<double> &end){ std::shared_ptr<ChCollisionLidarRay> ray = chrono_types::make_shared<ChCollisionLidarRay>(m_parent, m_visualize); ray->SetPoints(start, end); m_rays.push_back(ray); } double ChCollisionLidar::GetRange(unsigned int index){ if(index >= m_rays.size()){ return -1; } //add min range because we measured from min range return m_minRange + m_rays[index]->GetLength(); } std::vector<double> ChCollisionLidar::Ranges(){ std::vector<double> ranges = std::vector<double>(); for(int i=0; i<m_rays.size(); i++){ ranges.push_back(m_minRange + m_rays[i]->GetLength()); } return ranges; } void ChCollisionLidar::Update(){ double fullRange = m_maxRange - m_minRange; bool updateCollisions = false; if(m_parent->GetChTime()>=m_timeLastUpdated + 1.0/m_updateRate){ updateCollisions = true; m_timeLastUpdated = m_parent->GetChTime(); for(int i = 0; i<m_rays.size(); i++){ m_rays[i]->SetLength(fullRange); if(!m_visualize) m_rays[i]->Update(updateCollisions); } } // need to update the rays regardless so that they move with the entity // they are attached to if(m_visualize){ for(int i=0; i<m_rays.size(); i++){ m_rays[i]->Update(updateCollisions); } } }
28.248
114
0.649958
[ "vector" ]
effb12badb8effcbdd806c8f4ed6537a2bfb57a9
4,095
cpp
C++
src/python/light_pcapng.cpp
stricaud/LightPcapNg
a76c83e09338d51a661596522b85c4fe80100fc9
[ "MIT" ]
null
null
null
src/python/light_pcapng.cpp
stricaud/LightPcapNg
a76c83e09338d51a661596522b85c4fe80100fc9
[ "MIT" ]
null
null
null
src/python/light_pcapng.cpp
stricaud/LightPcapNg
a76c83e09338d51a661596522b85c4fe80100fc9
[ "MIT" ]
null
null
null
#include <iostream> #include <time.h> #include <pybind11/pybind11.h> #include <pybind11/functional.h> #include <pybind11/stl.h> #include <light_pcapng.h> #include <light_pcapng_ext.h> #include <light_blocks.h> #include "light_pcapng.hpp" #include "light_pcapng_fileinfo.hpp" namespace py = pybind11; PcapNg::PcapNg(void) { _pcapng = NULL; filename = NULL; compression_level = 10; } PcapNg::~PcapNg(void) { if (_pcapng) { light_pcapng_close(_pcapng); } } int PcapNg::OpenRead(char *file, int flag) { _pcapng = light_pcapng_open_read(file, LIGHT_FALSE); filename = file; return 0; } int PcapNg::OpenWrite(char *file, PcapNgFileInfo *info) { _pcapng = light_pcapng_open_write(file, info->get_fileinfo(), compression_level); filename = file; return 0; } // FIXME: Use this as soon as pybind11 supports conversion from bytes to vectors -> int PcapNg::WritePacket(const std::vector<uint8_t> &data, const std::string &comment) int PcapNg::WritePacket(py::bytes data, const std::string &comment) { light_packet_header header; timespec timestamp; int frame_length; int retval; py::buffer_info info(py::buffer(data).request()); uint8_t *data_bytes = reinterpret_cast<uint8_t *>(info.ptr); size_t data_len = static_cast<size_t>(info.size); header.captured_length = data_len; header.original_length = data_len; // Frame length retval = clock_gettime(CLOCK_MONOTONIC, &header.timestamp); header.data_link = LIGHT_LINKTYPE_ETHERNET; // get link layer type header.interface_id = 0; header.comment = NULL; header.comment_length = 0; if (!comment.empty()) { header.comment = (char *)comment.c_str(); header.comment_length = static_cast<uint16_t>(comment.size()); } light_write_packet(_pcapng, &header, data_bytes); return 0; } int PcapNg::WriteCustomPacket(py::bytes data, const std::string &comment) { light_custom_block_t *cb; py::buffer_info info(py::buffer(data).request()); uint8_t *data_bytes = reinterpret_cast<uint8_t *>(info.ptr); size_t data_len = static_cast<size_t>(info.size); cb = light_custom_block_new(); cb->block_total_length = 17; cb->pen = 123; light_custom_block_write(_pcapng, data_bytes, data_len); // light_packet_header header; // timespec timestamp; // int frame_length; // int retval; // py::buffer_info info(py::buffer(data).request()); // uint8_t *data_bytes = reinterpret_cast<uint8_t *>(info.ptr); // size_t data_len = static_cast<size_t>(info.size); // header.captured_length = data_len; // header.original_length = data_len; // Frame length // retval = clock_gettime(CLOCK_MONOTONIC, &header.timestamp); // header.data_link = LIGHT_LINKTYPE_ETHERNET; // get link layer type // header.interface_id = 0; // header.comment = NULL; // header.comment_length = 0; // if (!comment.empty()) { // header.comment = (char *)comment.c_str(); // header.comment_length = static_cast<uint16_t>(comment.size()); // } // light_write_custom_block_packet(_pcapng, &header, data_bytes); // return 0; } PYBIND11_MODULE(pycapng, m) { m.doc() = "LightPcapNG Python Bindings"; py::class_<PcapNg>(m, "PcapNg") .def(py::init<>()) .def("OpenRead", &PcapNg::OpenRead) .def("OpenWrite", &PcapNg::OpenWrite) .def("WritePacket", &PcapNg::WritePacket) .def("WriteCustomPacket", &PcapNg::WriteCustomPacket); py::class_<PcapNgFileInfo>(m, "PcapNgFileInfo") .def(py::init<>()) .def(py::init<const std::string &, const std::string &,const std::string &,const std::string &>()) .def("ReadFile", &PcapNgFileInfo::ReadFile) .def("WriteFile", &PcapNgFileInfo::WriteFile) .def("GetFileComment", &PcapNgFileInfo::GetFileComment) .def("GetOSDesc", &PcapNgFileInfo::GetOSDesc) .def("GetHardwareDesc", &PcapNgFileInfo::GetHardwareDesc) .def("GetUserAppDesc", &PcapNgFileInfo::GetUserAppDesc) .def("GetFileInfoMajorVersion", &PcapNgFileInfo::GetFileInfoMajorVersion) .def("GetFileInfoMinorVersion", &PcapNgFileInfo::GetFileInfoMinorVersion); }
30.110294
169
0.699878
[ "vector" ]