hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a4681f2ed9330f8764e9119be68fef59dc06dba5
1,938
cpp
C++
Stacks/Stack with L.L.cpp
pritbab/Data-Structures
644d6fe16b7c63eda2449e9e0da32a3d9e411487
[ "MIT" ]
null
null
null
Stacks/Stack with L.L.cpp
pritbab/Data-Structures
644d6fe16b7c63eda2449e9e0da32a3d9e411487
[ "MIT" ]
null
null
null
Stacks/Stack with L.L.cpp
pritbab/Data-Structures
644d6fe16b7c63eda2449e9e0da32a3d9e411487
[ "MIT" ]
null
null
null
// Task : // // Stack using Singly Linked List #include <iostream> using namespace std; struct node { int data; struct node* next; }; class list { node *head, *tail; public: list() { head = NULL; tail = NULL; } node *create_node(int value); void push(int value); void display(); void pop(); }; node* list :: create_node(int value) { node *temp = new node; temp -> data = value; temp -> next = NULL; return temp; } void list :: push(int value) { node *p; p = create_node(value); if(head == NULL) { head = p; } else { p -> next = head; head = p; } } void list :: display() { node *temp = new node; temp = head; if(head == NULL) { cout<<"Empty Stack"<<endl; } else { temp = head; cout<<"Elements in Stack : "<<endl; while(temp != NULL) { cout<<temp -> data<<"\t"; temp = temp -> next; } cout<<endl; } } void list :: pop() { int flag = 0; if(head == NULL) { cout<<"Underflow"<<endl; } node* temp = new node; temp = head; head = head->next; delete temp; } int main() { list l; int x,num; cout<<"Enter Steps : "; cin>>x; int choice; cout<<"Enter Choice : \n1 for push\t2 for pop : "<<endl; for(int i=0; i<x; i++) { cout<<"Enter Your Choice : "; cin>>choice; while(choice < 1 && choice > 2) { cout<<"Wrong Choice Entered... TRY AGAIN"<<endl; cout<<"Enter Your Choice : "; cin>>choice; } if(choice == 1) { cout<<"Enter Number : "; cin>>num; l.push(num); } else { l.pop(); } } l.display(); return 0; }
16.285714
60
0.438596
pritbab
a46b5564e9a7bbf65a57cd60ee0c91911babb72c
989
cpp
C++
codechef/Chef and Dice.cpp
itsjaysuthar/CPpractice
820cf84ea7079ef3b34a604fd56672811f64f4dc
[ "MIT" ]
null
null
null
codechef/Chef and Dice.cpp
itsjaysuthar/CPpractice
820cf84ea7079ef3b34a604fd56672811f64f4dc
[ "MIT" ]
null
null
null
codechef/Chef and Dice.cpp
itsjaysuthar/CPpractice
820cf84ea7079ef3b34a604fd56672811f64f4dc
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------------------- //-------------------Author : itsjaysuthar ---------------------------------------------- //--------------------------------------------------------------------------------------- #include<bits/stdc++.h> using namespace std; #define ll long long int main() { int t; cin>>t; while(t--) { ll n; cin>>n; if(n==1) cout<<20<<endl; else if(n==2) cout<<36<<endl; else if(n==3) cout<<51<<endl; else if(n==4) cout<<60<<endl; else { ll sum = 0; ll rem = n%4; sum = n*11; if(rem == 1) sum += 21; else if(rem == 2) sum += 22; else if(rem==3) sum += 22; else sum += 16; cout<<sum<<endl; } } return 0; }
21.5
89
0.256825
itsjaysuthar
a475e578e9b49c87e671bad219114c154bb3df1d
7,542
hpp
C++
commonobjects/shm_common/SharedPCClient.hpp
Khoronus/CommonObjects
98a2c37923529333fecc2cf0b6103d2db9fdaa97
[ "MIT" ]
null
null
null
commonobjects/shm_common/SharedPCClient.hpp
Khoronus/CommonObjects
98a2c37923529333fecc2cf0b6103d2db9fdaa97
[ "MIT" ]
null
null
null
commonobjects/shm_common/SharedPCClient.hpp
Khoronus/CommonObjects
98a2c37923529333fecc2cf0b6103d2db9fdaa97
[ "MIT" ]
null
null
null
/** * @file SharedPCClient.hpp * @brief Class to allocate the memory and structure for the shared memory. * * @section LICENSE * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR/AUTHORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author uknown * @bug No known bugs. * @version 0.2.0.0 * */ #ifndef COMMONOBJECTS_SHMCOMMON_SHAREDPCCLIENT_HPP__ #define COMMONOBJECTS_SHMCOMMON_SHAREDPCCLIENT_HPP__ #include <map> #include <thread> #include <mutex> #include <memory> #include "doc_managedmemory_shared_data_v2.hpp" #include "../string_common/StringOp.hpp" #include <Windows.h> namespace co { namespace shm { // Size of each point in bytes typedef int SizeOfEachPointBytes; // Total number of points for an object typedef int NumberOfPoints; /** @brief Function for callback */ //typedef std::function<void(void* data, size_t num_points, pcl::PointCloud<PointType>::Ptr &point_cloud_ptr, bool clear)> registration_callback_function; typedef std::function<void(SharedMemoryManager &smm)> registration_callback_function; /** @brief Class to manage a shared data The shared objects contains the information of 3D cloud points that are shared among applications. The maximum number of points and the number of valid points is contained in the int_vector as follow [0]: maximum number of points [1]: valid points The points are defined as follow xyz (float) rgb (unsigned char) */ class SharedDataClient { public: SharedDataClient() { memory_to_allocate_bytes_ = 0; } ~SharedDataClient() { stop(); } /** @brief It creates the memory which will contain the structured data. It creates the memory which will contain the structured data. @param[in] name_shm Shared memory name @param[in] definition Container wit the size of the points (3float + 3 uchar), and the number of points */ void create( const std::string &name_shm, const std::vector<std::pair<SizeOfEachPointBytes, NumberOfPoints>> &definition) { // copy the name of the shared memory name_shm_ = name_shm; // Allocate the container for the points size_t kNumSources = definition.size(); for (auto & it : definition) { // xyz rgb int size_point = it.first; // number of the points int num_points = it.second; // size byte int size_byte = num_points * size_point; // total bytes memory_to_allocate_bytes_ += size_byte; v_.push_back(size_byte); information_size_.push_back(std::vector<int>({ num_points, 0 })); } // Create the memory space int memory_buffer = 4096; if (!smm_.create(name_shm_, memory_to_allocate_bytes_ + memory_buffer)) { std::cout << "Unable to create: " << name_shm_ << std::endl; return; } // Instantiate the objects smm_.instantiate(v_); // Set the information for each shared object for (int i = 0; i < smm_.num_items(); ++i) { // set the maximum number of points and other information smm_.set(i, information_size_[i]); // set object name smm_.set(i, "pcl"); } } /** @brief It detects the memory which will contain the structured data. It detects the memory which will contain the structured data. @param[in] name_shm Shared memory name */ bool detect(const std::string &name_shm) { // copy the name of the shared memory name_shm_ = name_shm; if (!smm_.detect(name_shm_)) { std::cout << "Unable to detect: " << name_shm << std::endl; return false; } return true; } /** @brief It starts the worker */ void start() { t_process_ = std::thread(&SharedDataClient::process, this); } /** @brief It stops a running worker */ void stop() { std::cout << "<SharedPCClient::stop>" << std::endl; do_continue_ = false; if (t_process_.joinable()) { t_process_.join(); } std::cout << "</SharedPCClient::stop>" << std::endl; } /** @brief If started from the function "start()" it will run in a separated thread. */ void process() { try { do_continue_ = true; // <INFO> if the solution is multithread, this make sense //std::vector<interprocess_mutex*> vmtx; //for (size_t i = 0; i < smm.num_items(); ++i) { // std::string name = "mtx" + std::to_string(i); // vmtx.push_back(smm.find_or_create_mutex(name)); //} //std::vector<interprocess_condition*> vcnd; //for (size_t i = 0; i < smm.num_items(); ++i) { // std::string name = "cnd" + std::to_string(i); // vcnd.push_back(smm.find_or_create_condition(name)); //} //std::vector<scoped_lock<interprocess_mutex>> vlock; //for (auto &it : vmtx) { // vlock.push_back(scoped_lock<interprocess_mutex>(*it)); //} // <INFO> for a single thread, this solution is better boost::interprocess::interprocess_mutex *mtx = smm_.find_or_create_mutex("mtx"); boost::interprocess::interprocess_condition *cnd = smm_.find_or_create_condition("cnd"); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock{ *mtx }; bool noTimeout = true; // Increase the thread priority SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN); int speed = 1; int num_sources = smm_.num_items(); // image used to close the program while (do_continue_) { //std::cout << "Internal : " << num_sources << std::endl; // callback here if (m_callback_ != nullptr) { m_callback_(smm_); is_new_data_ = true; } //// Notify //cnd->notify_all(); ////cnd->wait(lock); if use the timeout //boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(1000); //noTimeout = cnd->timed_wait(lock, timeout); //// timeout //if (!noTimeout) //{ // std::cout << "timeout!" << std::endl; //} } // Notify (multithread) //vcnd[i]->notify_all(); cnd->notify_all(); std::cout << "</SharedDataServer::process>" << std::endl; } catch (boost::interprocess::interprocess_exception &ex) { std::cout << ex.what() << std::endl; return; } } /** @brief It register the callback function */ void registerCallback(registration_callback_function &&callback) { m_callback_ = callback; } bool is_new_data() { return is_new_data_; } void set_is_new_data(bool is_new_data) { is_new_data_ = is_new_data; } private: /** @brief Shared memory */ SharedMemoryManager smm_; std::string name_shm_; std::vector<int> v_; // container with the bytes for each image std::vector<std::vector<int>> information_size_; /** @brief Total allocated memory */ int memory_to_allocate_bytes_; /** @brief If true it continue to process the internal thread */ bool do_continue_; /** @brief Thread of the process */ std::thread t_process_; /** @brief Container with the callback functions */ registration_callback_function m_callback_; /** @brief If true is a new data */ bool is_new_data_; }; } // namespace shm } // namespace co #endif // COMMONOBJECTS_SHMCOMMON_SHAREDPCCLIENT_HPP__
28.141791
154
0.697163
Khoronus
a476e7298668ea3e9d185613a28f89ee837af341
3,637
cpp
C++
test/unit/algo/convert_zip.cpp
microblink/eve
26d50d59190d3e2817c3ca95614e3e74f6c6f30a
[ "MIT" ]
null
null
null
test/unit/algo/convert_zip.cpp
microblink/eve
26d50d59190d3e2817c3ca95614e3e74f6c6f30a
[ "MIT" ]
null
null
null
test/unit/algo/convert_zip.cpp
microblink/eve
26d50d59190d3e2817c3ca95614e3e74f6c6f30a
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "unit/algo/algo_test.hpp" #include <eve/algo/views/convert.hpp> #include <eve/algo/views/zip.hpp> #include "unit/algo/udt.hpp" TTS_CASE("convert zip iter") { std::vector<int> const v{1, 2, 3, 4}; std::vector<std::int8_t> c{'a', 'b', 'c', 'd'}; using v_it = std::vector<int>::const_iterator; using c_it = std::vector<std::int8_t>::iterator; using c_to_v = eve::algo::views::converting_iterator<c_it, int>; using zip_v_c_to_v = eve::algo::views::zip_iterator<v_it, c_to_v>; using zip_v_c_to_v_as_point = eve::algo::views::converting_iterator<zip_v_c_to_v, udt::point2D>; // tuple and point { auto zipped = eve::algo::views::zip(v.begin(), c.begin()); auto as_int_int = eve::algo::views::convert(zipped, eve::as<kumi::tuple<int, int>>{}); TTS_TYPE_IS(decltype(as_int_int), zip_v_c_to_v); // As product auto as_point2D = eve::algo::views::convert(zipped, eve::as<udt::point2D>{}); TTS_TYPE_IS(decltype(as_point2D), zip_v_c_to_v_as_point); } // Line { using expected = eve::algo::views::converting_iterator< eve::algo::views::zip_iterator<v_it,c_to_v,v_it,v_it>, udt::line2D >; auto actual1 = eve::algo::views::convert( eve::algo::views::zip(v.begin(), c.begin(), v.begin(), v.begin()), eve::as<udt::line2D>{} ); TTS_TYPE_IS(decltype(actual1), expected); #if 0 // FIX-918 auto actual2 = eve::algo::views::convert( eve::algo::views::zip( eve::algo::views::convert(eve::algo::views::zip(v, c), eve::as<udt::point2D>{}), eve::algo::views::convert(eve::algo::views::zip(v, v), eve::as<udt::point2D>{}) ), eve::as<udt::line2D>{}); TTS_TYPE_IS(decltype(actual2), expected); #endif } } TTS_CASE("convert zip range") { std::vector<int> const v{1, 2, 3, 4}; std::vector<std::int8_t> c{'a', 'b', 'c', 'd'}; using v_ref = eve::algo::range_ref_wrapper<std::vector<int> const>; using c_ref = eve::algo::range_ref_wrapper<std::vector<std::int8_t>>; using c_to_v = eve::algo::views::converting_range<c_ref, int>; using zip_v_c_to_v = eve::algo::views::zip_range<v_ref, c_to_v>; using zip_v_c_to_v_as_point = eve::algo::views::converting_range<zip_v_c_to_v, udt::point2D>; // tuple and point { auto zipped = eve::algo::views::zip(v, c); auto as_int_int = eve::algo::views::convert(zipped, eve::as<kumi::tuple<int, int>>{}); TTS_TYPE_IS(decltype(as_int_int), zip_v_c_to_v); // As product auto as_point2D = eve::algo::views::convert(zipped, eve::as<udt::point2D>{}); TTS_TYPE_IS(decltype(as_point2D), zip_v_c_to_v_as_point); } // Line { using expected = eve::algo::views::converting_range< eve::algo::views::zip_range<v_ref,c_to_v,v_ref,v_ref>, udt::line2D >; auto actual1 = eve::algo::views::convert( eve::algo::views::zip(v, c, v, v), eve::as<udt::line2D>{} ); TTS_TYPE_IS(decltype(actual1), expected); #if 0 // FIX-918 auto actual2 = eve::algo::views::convert( eve::algo::views::zip( eve::algo::views::convert(eve::algo::views::zip(v, c), eve::as<udt::point2D>{}), eve::algo::views::convert(eve::algo::views::zip(v, v), eve::as<udt::point2D>{}) ), eve::as<udt::line2D>{}); TTS_TYPE_IS(decltype(actual2), expected); #endif } }
33.366972
100
0.601595
microblink
a47fc6f87622e76b7dce5895031bf62b0bcb8059
498
cpp
C++
Pemrograman Dasar/AgakPrima.cpp
bayusamudra5502/PustakaCpp
ac67e47374740b4923dd135d67f4bf987d4010b4
[ "MIT" ]
null
null
null
Pemrograman Dasar/AgakPrima.cpp
bayusamudra5502/PustakaCpp
ac67e47374740b4923dd135d67f4bf987d4010b4
[ "MIT" ]
null
null
null
Pemrograman Dasar/AgakPrima.cpp
bayusamudra5502/PustakaCpp
ac67e47374740b4923dd135d67f4bf987d4010b4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int n; scanf("%d", &n); for(int i = 1; i <= n; i++){ int x, f = 0; scanf("%d", &x); for(int j = 1; j <= x; j++){ if(x % j == 0){ f++; } if(f > 4) break; //BIAR GA TLE :v } if(f > 4){ printf("BUKAN\n"); }else{ printf("YA\n"); } } return 0; }
17.785714
40
0.295181
bayusamudra5502
a48424fb376bf62e0a2e1c795d7822efa3a52145
630
cpp
C++
Engine/source/console/stringStack.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
null
null
null
Engine/source/console/stringStack.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
null
null
null
Engine/source/console/stringStack.cpp
fr1tz/alux3d
249a3b51751ce3184d52879b481f83eabe89e7e3
[ "MIT" ]
1
2018-10-26T03:18:22.000Z
2018-10-26T03:18:22.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "console/stringStack.h" void StringStack::getArgcArgv(StringTableEntry name, U32 *argc, const char ***in_argv, bool popStackFrame /* = false */) { U32 startStack = mFrameOffsets[mNumFrames-1] + 1; U32 argCount = getMin(mStartStackSize - startStack, (U32)MaxArgs - 1); *in_argv = mArgV; mArgV[0] = name; for(U32 i = 0; i < argCount; i++) mArgV[i+1] = mBuffer + mStartOffsets[startStack + i]; argCount++; *argc = argCount; if(popStackFrame) popFrame(); }
28.636364
120
0.671429
fr1tz
a489cf42db67be9f00c94e5fc37c7450de4dc674
21,007
cpp
C++
src/core/Board.cpp
AlexKent3141/OnePunchGo
a86caaf421c8122222f72316171702617c519d28
[ "MIT" ]
3
2018-05-14T12:32:19.000Z
2021-04-20T23:11:56.000Z
src/core/Board.cpp
AlexKent3141/OnePunchGo
a86caaf421c8122222f72316171702617c519d28
[ "MIT" ]
1
2018-03-30T18:44:49.000Z
2018-03-31T15:57:49.000Z
src/core/Board.cpp
AlexKent3141/OnePunchGo
a86caaf421c8122222f72316171702617c519d28
[ "MIT" ]
null
null
null
#include "Board.h" #include "patterns/PatternMatcher.h" #include <iostream> Board::Board(int boardSize) { InitialiseEmpty(boardSize); } Board::Board(Colour colourToMove, const std::vector<std::string>& s) { InitialiseEmpty(s.size()); // Ensure that it's square. assert(s.size() == s[0].size()); int loc; char c; for (int i = 0; i < _boardSize; i++) { for (int j = 0; j < _boardSize; j++) { loc = (_boardSize-i-1)*_boardSize + j; c = s[i][j]; Colour col = c == 'B' ? Black : c == 'W' ? White : None; if (col != None) MakeMove({ col, loc, 0 }); } } _colourToMove = colourToMove; } Board::Board(Colour colourToMove, int boardSize, const MoveHistory& history) { assert(boardSize > 0 && boardSize < MaxBoardSize); InitialiseEmpty(boardSize); auto moves = history.Moves(); for (Move move : moves) MakeMove(move); _colourToMove = colourToMove; } Board::~Board() { if (_points != nullptr) { for (int i = 0; i < _boardArea; i++) { Point pt = _points[i]; delete pt.Orthogonals; delete pt.Diagonals; } delete[] _points; _points = nullptr; } if (_blackStones != nullptr) { delete _blackStones; _blackStones = nullptr; } if (_whiteStones != nullptr) { delete _whiteStones; _whiteStones = nullptr; } if (_empty != nullptr) { delete _empty; _empty = nullptr; } for (StoneChain& sc : _chains) { if (sc.Stones != nullptr) { delete sc.Stones; sc.Stones = nullptr; } if (sc.Neighbours != nullptr) { delete sc.Neighbours; sc.Neighbours = nullptr; } } } // Clone fields from other. void Board::CloneFrom(const Board& other) { assert(_boardSize == other._boardSize); // Delete the existing chains for (size_t i = 0; i < _chains.size(); i++) { const StoneChain& c = _chains[i]; delete c.Stones; delete c.Neighbours; } _chains.clear(); _colourToMove = other._colourToMove; _turnNumber = other._turnNumber; _lastMove = other._lastMove; _hashes = other._hashes; memcpy(_passes, other._passes, 2*sizeof(bool)); // Copy the stones for each player. _empty->Copy(*other._empty); _blackStones->Copy(*other._blackStones); _whiteStones->Copy(*other._whiteStones); // Copy the stone chains. for (size_t i = 0; i < other._chains.size(); i++) { const StoneChain& oc = other._chains[i]; BitSet* stones = new BitSet(*oc.Stones); BitSet* neighbours = new BitSet(*oc.Neighbours); StoneChain c = { oc.Col, oc.Liberties, stones, neighbours, oc.Hash, oc.Ignore }; _chains.push_back(c); } // Map the points to their stone chains. for (int i = 0; i < _boardArea; i++) { const Point& op = other._points[i]; _points[i].Col = op.Col; _points[i].ChainId = op.ChainId; } } // Check for potential eyes. // All orthogonals must be the same colour and there is also a constraint on diagonals. bool Board::IsEye(Colour col, int loc, int orth) const { const Point& pt = _points[loc]; bool isEye = pt.Col == None; if (isEye) { const BitSet* const enemy = col == Black ? _whiteStones : _blackStones; int enemyDiag = pt.Diagonals->CountAndSparse(*enemy); size_t n = pt.Neighbours.size(); isEye = n == 2 ? orth == 2 && enemyDiag == 0: n == 3 ? orth == 3 && enemyDiag == 0: n == 4 ? orth == 4 && enemyDiag <= 1: false; } return isEye; } // Check the legality of the specified move in this position. MoveInfo Board::CheckMove(int loc) const { return CheckMove(_colourToMove, loc); } // Check the legality of the specified move in this position. MoveInfo Board::CheckMove(Colour col, int loc) const { // Passing is always legal. if (loc == PassCoord) return Legal; // Check occupancy. const Point& pt = _points[loc]; MoveInfo res = pt.Col == None ? Legal : Occupied; if (res == Legal) { // Check for suicide and ko. int liberties = 0; int captureLoc; size_t capturesWithRepetition = 0; // Note: captured neighbours could be in the same group! size_t friendlyOrthogonals = 0; size_t safeFriendlyOrthogonals = 0; // Keep track of two chain ids. int chainId1 = -1; int chainId2 = -1; bool friendInAtari = false; bool isAtari = false; bool isLocal = false; for (const Point* const n : pt.Neighbours) { if (n->Col == None) { ++liberties; continue; } const StoneChain& c = _chains[n->ChainId]; int nlibs = c.Liberties; if (n->Col == col) { liberties += nlibs-1; ++friendlyOrthogonals; safeFriendlyOrthogonals += nlibs > 1 ? 1 : 0; friendInAtari = friendInAtari || nlibs == 1; if (chainId1 == -1) chainId1 = n->ChainId; else if (chainId2 == -1 && n->ChainId != chainId1) chainId2 = n->ChainId; } else { if (nlibs == 1) { ++liberties; captureLoc = n->Coord; capturesWithRepetition += CountChainSize(n->ChainId); } else if (nlibs == 2) { isAtari = true; } isLocal |= n->Coord == _lastMove.Coord; } } bool suicide = liberties == 0; bool repetition = capturesWithRepetition == 1 && IsKoRepetition(col, loc, captureLoc); res = suicide ? Suicide : repetition ? Repetition : Legal; if (res & Legal) { // Do some extra work to further classify the move. bool koCapture = capturesWithRepetition == 1 && liberties == 1 && friendlyOrthogonals == 0; if (isAtari) res |= Atari; if (liberties == 1 && !koCapture) res |= SelfAtari; if (capturesWithRepetition > 0) res |= Capture; if (friendInAtari && liberties > 1) res |= Save; if (IsEye(col, loc, safeFriendlyOrthogonals)) res |= FillsEye; if (isLocal) res |= Local; if (chainId2 != -1) res |= Connection; // Check whether this point is making eye shape. if (friendlyOrthogonals == 0) { // Check for friendly diagonals. const BitSet* const friendly = col == Black ? _blackStones : _whiteStones; int friendlyDiag = pt.Diagonals->CountAndSparse(*friendly); if (friendlyDiag >= 3) res |= EyeShape; } } } return res; } // Get all moves available for the current colour. std::vector<Move> Board::GetMoves(bool duringPlayout) const { std::vector<Move> moves; moves.reserve(_empty->Count()); if (!GameOver()) { for (int i = 0; i < _boardArea; i++) { MoveInfo info = CheckMove(i); if ((info & Legal) && !(info & FillsEye)) { moves.push_back({_colourToMove, i, info}); } } // Passing is always legal but don't consider it during a playout unless there // are no other moves available. if (!duringPlayout || moves.size() == 0) { moves.push_back({_colourToMove, PassCoord, Legal}); } } return moves; } // Get n random (legal) moves. std::vector<Move> Board::GetRandomLegalMoves(size_t n, RandomGenerator& gen) const { std::vector<Move> moves; moves.reserve(n); if (!GameOver()) { // Can easily generate candidate moves by looking at the empty locations. int numEmpty = _empty->Count(); assert(numEmpty != 0); int maxAttempts = 5*n; int a = 0, loc; BitSelector bsl(*_empty); while (a++ < maxAttempts && moves.size() < n) { // Check a random empty point for validity. loc = bsl[gen.Next(numEmpty)]; MoveInfo info = CheckMove(loc); bool legal = info & Legal; bool fillsEye = info & FillsEye; if (legal && !fillsEye) { moves.push_back({_colourToMove, loc, info}); } } } // If no legal moves have been found then fall back on full moves search to ensure that the // game is played out fully. if (moves.empty()) { moves = GetMoves(true); } return moves; } // Find a global move that is adjacent to an enemy group with the specified number of liberties. Move Board::GetRandomMoveAttackingLiberties(size_t liberties, RandomGenerator& gen) const { std::vector<Move> attackingMoves; for (const auto& chain : _chains) { if (!chain.Ignore && chain.Col != _colourToMove && chain.Liberties == liberties) { FindLegalLibertyMoves(chain, attackingMoves); } } return attackingMoves.empty() ? BadMove : attackingMoves[gen.Next(attackingMoves.size())]; } // Find a global move that is adjacent to a friendly group with only one liberty. Move Board::GetRandomMoveSaving(RandomGenerator& gen) const { std::vector<Move> savingMoves; for (const auto& chain : _chains) { if (!chain.Ignore && chain.Col == _colourToMove && chain.Liberties == 1) { FindLegalLibertyMoves(chain, savingMoves); } } return savingMoves.empty() ? BadMove : savingMoves[gen.Next(savingMoves.size())]; } // Find a move that is local to the previous move and is considered urgent. // Note: Adjacent includes moves that fill liberties on the last move's chain. Move Board::GetRandomMoveLocal(int c, MoveInfo urgent, RandomGenerator& gen) const { assert(c != PassCoord); std::vector<Move> localMoves; // Use the "old" method for now. const Point& pt = _points[c]; int m; BitIterator it(*pt.Orthogonals); while ((m = it.Next()) != BitIterator::NoBit) { // Test this location. MoveInfo info = CheckMove(m); if ((info & Legal) && (info & urgent)) { localMoves.push_back({_colourToMove, m, info}); } } // "New" method which crashes sometimes... //const StoneChain& chain = _chains[_points[lastCoord].ChainId]; //FindLegalLibertyMoves(chain, localMoves, urgent); return localMoves.empty() ? BadMove : localMoves[gen.Next(localMoves.size())]; } // Find the legal moves that are adjacent to the specified chain. void Board::FindLegalLibertyMoves(const StoneChain& chain, std::vector<Move>& moves, MoveInfo urgent) const { BitSet libs(*chain.Neighbours); libs &= *_empty; int bit; BitIterator it(libs); while ((bit = it.Next()) != BitIterator::NoBit) { MoveInfo info = CheckMove(bit); if (info & Legal) { if (urgent == 0 || (info & urgent)) { moves.push_back({_colourToMove, bit, info}); } } } } // Update the board state with the specified move. void Board::MakeMove(const Move& move) { assert(!GameOver()); assert(CheckMove(move.Col, move.Coord) & Legal); auto z = Zobrist::Instance(); uint64_t nextHash = _hashes[_turnNumber-1]; if (move.Coord != PassCoord) { Point& pt = _points[move.Coord]; pt.Col = move.Col; // Iterate through the chains which are affected by this move. std::vector<int> neighbourChains, enemyChains; for (Point* const n : pt.Neighbours) { int nc = n->ChainId; if (nc != NoChain) { const StoneChain& c = _chains[nc]; if (n->Col != move.Col && c.Liberties == 1) { // Capture this enemy group. nextHash ^= CaptureChain(nc); } else if (n->Col == move.Col) { // Friendly chain - need to merge. if (std::find(neighbourChains.begin(), neighbourChains.end(), nc) == neighbourChains.end()) neighbourChains.push_back(nc); } else if (n->Col != None) { // Enemy chain. if (std::find(enemyChains.begin(), enemyChains.end(), nc) == enemyChains.end()) enemyChains.push_back(nc); } } } uint64_t moveHash = z->Key(move.Col, move.Coord); nextHash ^= moveHash; // Update the cached BitSets. BitSet* friendly = move.Col == Black ? _blackStones : _whiteStones; friendly->Set(move.Coord); _empty->UnSet(move.Coord); // If there are friendly neighbouring chains then combine them. CombineChainsForMove(move, moveHash, neighbourChains, enemyChains); } // Update the colour to move. if (move.Col == _colourToMove) { _colourToMove = _colourToMove == Black ? White : Black; nextHash ^= CurrentRules.Ko == Situational ? z->BlackTurn() : 0; } _hashes.push_back(nextHash); _passes[(int)move.Col-1] = move.Coord == PassCoord; _lastMove = move; ++_turnNumber; } // Compute the score of the current position. // Area scoring is used and we assume that all empty points are fully surrounded by one // colour. // The score is determined from black's perspective (positive score indicates black win). int Board::Score() const { double score = -CurrentRules.Komi; for (int i = 0; i < _boardArea; i++) { const Point& pt = _points[i]; if (pt.Col == None) { // Look at a neighbour. Point const* const n = pt.Neighbours[0]; score += n->Col == Black ? 1 : -1; } else { score += pt.Col == Black ? 1 : -1; } } return score > 0 ? 1 : score < 0 ? -1 : 0; } std::string Board::ToString() const { std::string s; Colour col; for (int r = _boardSize-1; r >= 0; r--) { for (int c = 0; c < _boardSize; c++) { col = _points[r*_boardSize+c].Col; s += col == None ? '.' : col == Black ? 'B' : 'W'; } s += '\n'; } return s; } // Initialise an empty board of the specified size. void Board::InitialiseEmpty(int boardSize) { assert(boardSize > 0 && boardSize < MaxBoardSize); _colourToMove = Black; _boardSize = boardSize; _boardArea = _boardSize*_boardSize; _empty = new BitSet(_boardArea); _empty->Invert(); _blackStones = new BitSet(_boardArea); _whiteStones = new BitSet(_boardArea); _points = new Point[_boardArea]; for (int i = 0; i < _boardArea; i++) _points[i] = { None, i, {}, nullptr, nullptr, NoChain }; InitialiseNeighbours(); _hashes.push_back(CurrentRules.Ko == Situational ? Zobrist::Instance()->BlackTurn() : 0); } // Initialise the neighbours for each point. void Board::InitialiseNeighbours() { int r, c; for (int i = 0; i < _boardArea; i++) { r = i / _boardSize, c = i % _boardSize; _points[i].Coord = i; _points[i].Neighbours.clear(); _points[i].Orthogonals = new BitSet(_boardArea); _points[i].Diagonals = new BitSet(_boardArea); // Setup the orthogonals. // Also fill in the neighbours vector at this point. if (r > 0) { _points[i].Neighbours.push_back(&_points[i-_boardSize]); _points[i].Orthogonals->Set(i-_boardSize); } if (r < _boardSize-1) { _points[i].Neighbours.push_back(&_points[i+_boardSize]); _points[i].Orthogonals->Set(i+_boardSize); } if (c > 0) { _points[i].Neighbours.push_back(&_points[i-1]); _points[i].Orthogonals->Set(i-1); } if (c < _boardSize-1) { _points[i].Neighbours.push_back(&_points[i+1]); _points[i].Orthogonals->Set(i+1); } // Setup the diagonals. if (r > 0 && c > 0) _points[i].Diagonals->Set(i-1-_boardSize); if (r > 0 && c < _boardSize-1) _points[i].Diagonals->Set(i+1-_boardSize); if (r < _boardSize-1 && c > 0) _points[i].Diagonals->Set(i-1+_boardSize); if (r < _boardSize-1 && c < _boardSize-1) _points[i].Diagonals->Set(i+1+_boardSize); } } // Check whether the specified move and capture would result in a board repetition. bool Board::IsKoRepetition(Colour col, int loc, int captureLoc) const { Colour enemyCol = col == Black ? White : Black; auto z = Zobrist::Instance(); uint64_t nextHash = _hashes[_turnNumber-1] ^ z->Key(col, loc) ^ z->Key(enemyCol, captureLoc) ^ (CurrentRules.Ko == Situational ? z->BlackTurn() : 0); // Has this hash occurred previously? bool repeat = false; for (int i = _turnNumber-1; i >= 0 && !repeat; i--) repeat = _hashes[i] == nextHash; return repeat; } int Board::CountChainLiberties(int id) const { const StoneChain& chain = _chains[id]; return chain.Neighbours->CountAnd(*_empty); } int Board::CountChainSize(int id) const { const StoneChain& chain = _chains[id]; return chain.Stones->Count(); } uint64_t Board::CaptureChain(int id) { StoneChain& chain = _chains[id]; int bit; BitIterator it(*chain.Stones); while ((bit = it.Next()) != BitIterator::NoBit) { Point& pt = _points[bit]; pt.Col = None; pt.ChainId = NoChain; _blackStones->UnSet(bit); _whiteStones->UnSet(bit); _empty->Set(bit); } chain.Ignore = true; // TODO: Update liberties of neighbouring chains. for (size_t i = 0; i < _chains.size(); i++) { StoneChain& c = _chains[i]; if (!c.Ignore) { c.Liberties = c.Neighbours->CountAnd(*_empty); } } return chain.Hash; } void Board::CreateNewChainForMove(const Move& move, uint64_t moveHash) { Point& pt = _points[move.Coord]; BitSet* neighbours = new BitSet(*pt.Orthogonals); BitSet* stones = new BitSet(_boardArea); stones->Set(move.Coord); StoneChain c = { move.Col, (size_t)neighbours->CountAnd(*_empty), stones, neighbours, moveHash, false }; _chains.push_back(c); pt.ChainId = _chains.size()-1; } void Board::CombineChainsForMove(const Move& move, uint64_t moveHash, const std::vector<int>& neighbourChains, const std::vector<int>& enemyChains) { // Reduce the liberties of the enemy chains. for (int i : enemyChains) { StoneChain& c = _chains[i]; --c.Liberties; } if (neighbourChains.empty()) { CreateNewChainForMove(move, moveHash); } else { Point& pt = _points[move.Coord]; // Combine everything onto the first neighbour chain. int nc = neighbourChains.front(); StoneChain& base = _chains[nc]; // Add the newly placed stone. base.Stones->Set(move.Coord); base.Neighbours->Set(*pt.Orthogonals); base.Hash ^= moveHash; pt.ChainId = nc; // Add any other neighbouring chains. for (size_t i = 1; i < neighbourChains.size(); i++) { StoneChain& n = _chains[neighbourChains[i]]; // Update stones & neighbours. base.Stones->Set(*n.Stones); base.Neighbours->Set(*n.Neighbours); base.Hash ^= n.Hash; // Change the labels on the stones in the neighbour chain. int bit; BitIterator it(*n.Stones); while ((bit = it.Next()) != BitIterator::NoBit) { Point& pt = _points[bit]; pt.ChainId = nc; } n.Ignore = true; } // Remove potential overlap of neighbours and stones. base.Neighbours->UnSet(*base.Stones); // Reassess the liberties. base.Liberties = base.Neighbours->CountAnd(*_empty); } } void Board::LogPointDetails(int coord) const { const Point& pt = _points[coord]; std::cout << pt.Coord << " " << pt.Col << " " << pt.ChainId << std::endl; if (pt.ChainId != NoChain) { const StoneChain& c = _chains[pt.ChainId]; std::cout << "Liberties: " << c.Liberties << std::endl; std::cout << "Hash: " << c.Hash << std::endl; std::cout << "Ignore: " << c.Ignore << std::endl; } }
28.619891
147
0.557719
AlexKent3141
a48d673230c4eb33530740975cbadb994ef3f381
1,512
hpp
C++
CookieEngine/include/Core/Math/Vec2.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Core/Math/Vec2.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Core/Math/Vec2.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef __VEC2_HPP__ #define __VEC2_HPP__ #include <iostream> namespace Cookie { namespace Core { namespace Math { union Vec2 { struct { float x; float y; }; struct { float u; float v; }; float e[2]; inline void Debug() const; inline static void DebugAllTest(); inline Vec2 operator-() const; inline Vec2 operator+(const Vec2& other) const; inline Vec2 operator-(const Vec2& other) const; inline Vec2 operator*(const Vec2& other) const; inline Vec2 operator/(const Vec2& other) const; inline Vec2 operator+(float other) const; inline Vec2 operator-(float other) const; inline Vec2 operator*(float other) const; inline Vec2 operator/(float other) const; inline Vec2& operator+=(const Vec2& other); inline Vec2& operator-=(const Vec2& other); inline Vec2& operator*=(const Vec2& other); inline Vec2& operator/=(const Vec2& other); inline Vec2& operator+=(float other); inline Vec2& operator-=(float other); inline Vec2& operator*=(float other); inline Vec2& operator/=(float other); inline float Length() const; }; } } } #include "Vec2.inl" #endif
27.490909
63
0.513228
qbleuse
a48f5e17c50192e4bd7bcf233aeee67173f62de8
1,707
cpp
C++
src/QMCWaveFunctions/SPOInfo.cpp
kryczko/qmcpack
92f4885eac810b5aa7bece4b30a03395d74f5598
[ "NCSA" ]
null
null
null
src/QMCWaveFunctions/SPOInfo.cpp
kryczko/qmcpack
92f4885eac810b5aa7bece4b30a03395d74f5598
[ "NCSA" ]
null
null
null
src/QMCWaveFunctions/SPOInfo.cpp
kryczko/qmcpack
92f4885eac810b5aa7bece4b30a03395d74f5598
[ "NCSA" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory // // File created by: Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory ////////////////////////////////////////////////////////////////////////////////////// #include "SPOInfo.h" #include <limits> namespace qmcplusplus { typedef QMCTraits::RealType RealType; const int SPOInfo::no_index = -1; const int SPOInfo::no_degeneracy = -1; const RealType SPOInfo::no_energy = std::numeric_limits<RealType>::max(); SPOInfo::SPOInfo() { index = no_index; degeneracy = no_degeneracy; energy = no_energy; } SPOInfo::SPOInfo(int orb_index, RealType en) { index = orb_index; degeneracy = no_degeneracy; energy = en; } void SPOInfo::report(const std::string& pad) { if (has_index()) app_log() << pad << "index = " << index << std::endl; else app_log() << pad << "index = not assigned" << std::endl; if (has_energy()) app_log() << pad << "energy = " << energy << std::endl; else app_log() << pad << "energy = not assigned" << std::endl; if (has_degeneracy()) app_log() << pad << "degeneracy = " << degeneracy << std::endl; else app_log() << pad << "degeneracy = not assigned" << std::endl; app_log().flush(); } } // namespace qmcplusplus
29.947368
88
0.581136
kryczko
a49453d42152f3235deabe818cb2f6951d150e35
706
cpp
C++
1203/spj.cpp
openoj/data
f217c30f0cb0ac0a93fd7229c40bfb011ce21bc0
[ "Apache-2.0" ]
null
null
null
1203/spj.cpp
openoj/data
f217c30f0cb0ac0a93fd7229c40bfb011ce21bc0
[ "Apache-2.0" ]
null
null
null
1203/spj.cpp
openoj/data
f217c30f0cb0ac0a93fd7229c40bfb011ce21bc0
[ "Apache-2.0" ]
null
null
null
#include "testlib.h" #define MAXN 100010 using namespace std; int n,k,stdk,usr[MAXN]; bool not_prime[MAXN],f; int main(int argc, char *argv[]) { registerTestlibCmd(argc, argv); n = inf.readInt(); k = ouf.readInt(); stdk = ans.readInt(); if (k!=stdk) { quitf(_wa, "Your solution is worse than the standard one!QAQ"); } else { for (int i=2;i<=n+1;i++) usr[i]=ouf.readInt(1,k); for (int i=2;i<=n+1&&!f;i++) { if (not_prime[i]) continue; for (int j=(i<<1);j<=n+1&&!f;j+=i) { not_prime[j]=true; if (usr[i]==usr[j]) f=true; } } if (f) quitf(_wa, "Wrong Answer!QAQ"); else quitf(_ok, "Your solution is acceptable!^ ^"); } return 0; }
20.764706
66
0.563739
openoj
a4970c0b0e62030e9bfac389c08e5c743c393ec6
5,748
cpp
C++
libraries/connectivity/connectivity.cpp
jobehrens/mne-cpp
5156f578736bbb67cc9ae1fc41a7cefba3b10f7a
[ "BSD-3-Clause" ]
130
2015-02-01T23:47:07.000Z
2022-03-21T01:46:11.000Z
libraries/connectivity/connectivity.cpp
jobehrens/mne-cpp
5156f578736bbb67cc9ae1fc41a7cefba3b10f7a
[ "BSD-3-Clause" ]
519
2015-01-05T12:44:04.000Z
2022-03-07T18:12:52.000Z
libraries/connectivity/connectivity.cpp
jobehrens/mne-cpp
5156f578736bbb67cc9ae1fc41a7cefba3b10f7a
[ "BSD-3-Clause" ]
138
2015-04-02T12:42:12.000Z
2022-01-27T13:21:25.000Z
//============================================================================================================= /** * @file connectivity.cpp * @author Daniel Strohmeier <Daniel.Strohmeier@tu-ilmenau.de>; * Lorenz Esch <lesch@mgh.harvard.edu>; * Faris Yahya <mfarisyahya@gmail.com> * @since 0.1.0 * @date March, 2017 * * @section LICENSE * * Copyright (C) 2017, Daniel Strohmeier, Lorenz Esch, Faris Yahya. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Connectivity class definition. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "connectivity.h" #include "connectivitysettings.h" #include "network/network.h" #include "metrics/correlation.h" #include "metrics/crosscorrelation.h" #include "metrics/coherence.h" #include "metrics/imagcoherence.h" #include "metrics/phaselagindex.h" #include "metrics/phaselockingvalue.h" #include "metrics/weightedphaselagindex.h" #include "metrics/unbiasedsquaredphaselagindex.h" #include "metrics/debiasedsquaredweightedphaselagindex.h" //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> #include <QFutureSynchronizer> #include <QtConcurrent> //============================================================================================================= // EIGEN INCLUDES //============================================================================================================= //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace CONNECTIVITYLIB; //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= Connectivity::Connectivity() { } //============================================================================================================= QList<Network> Connectivity::calculate(ConnectivitySettings& connectivitySettings) { QStringList lMethods = connectivitySettings.getConnectivityMethods(); QList<Network> results; QElapsedTimer timer; timer.start(); if(lMethods.contains("WPLI")) { results.append(WeightedPhaseLagIndex::calculate(connectivitySettings)); } if(lMethods.contains("USPLI")) { results.append(UnbiasedSquaredPhaseLagIndex::calculate(connectivitySettings)); } if(lMethods.contains("COR")) { results.append(Correlation::calculate(connectivitySettings)); } if(lMethods.contains("XCOR")) { results.append(CrossCorrelation::calculate(connectivitySettings)); } if(lMethods.contains("PLI")) { results.append(PhaseLagIndex::calculate(connectivitySettings)); } if(lMethods.contains("COH")) { results.append(Coherence::calculate(connectivitySettings)); } if(lMethods.contains("IMAGCOH")) { results.append(ImagCoherence::calculate(connectivitySettings)); } if(lMethods.contains("PLV")) { results.append(PhaseLockingValue::calculate(connectivitySettings)); } if(lMethods.contains("DSWPLI")) { results.append(DebiasedSquaredWeightedPhaseLagIndex::calculate(connectivitySettings)); } qWarning() << "Total" << timer.elapsed(); qDebug() << "Connectivity::calculateMultiMethods - Calculated"<< lMethods <<"for" << connectivitySettings.size() << "trials in"<< timer.elapsed() << "msecs."; return results; }
42.577778
162
0.531141
jobehrens
a4981d43fd57b6fd4948c1c1d797c202025a6ef3
4,006
cpp
C++
s32v234_sdk/kernels/apu/sample_geometry_kernels/src/remap_nearest_acf.cpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
null
null
null
s32v234_sdk/kernels/apu/sample_geometry_kernels/src/remap_nearest_acf.cpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
null
null
null
s32v234_sdk/kernels/apu/sample_geometry_kernels/src/remap_nearest_acf.cpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
2
2021-01-21T02:06:16.000Z
2021-01-28T10:47:37.000Z
/***************************************************************************** * * NXP Confidential Proprietary * * Copyright (c) 2013 Freescale Semiconductor; * Copyright (c) 2017-2018 NXP * * All Rights Reserved * ***************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /*! * \file remap_nearest_acf.cpp * \addtogroup geometry * \addtogroup remap_nearest Remap nearest * \ingroup geometry * @{ * \brief Element-wise nearest neighbor interpolation */ #ifdef APEX2_EMULATE #include "acf_kernel.hpp" // if using the ACF emulation library using namespace APEX2; #endif #ifdef ACF_KERNEL_METADATA #include "remap_nearest_acf.h" /****************************************************************************/ /*! GrayScale interpolation kernel metadata. Interpolates between neighboring pixels of a grayscale image. Outputs 8bit unsigned interpolation result. \param REMAP_NEAREST_GRAY_KN Define for Kernel name \param 4 Number of ports \param "Port REMAP_NEAREST_KN_DST" Define for name of interpolation result (unsigned 8bit). \param "Port REMAP_NEAREST_KN_SRC" Define for name of first input image (unsigned 8bit) \param "Port REMAP_NEAREST_KN_OFFS" Define for name of input offsets (unsigned 16bit) *****************************************************************************/ KERNEL_INFO kernelInfoConcat(REMAP_NEAREST_GRAY_K) ( REMAP_NEAREST_GRAY_KN, 3, __port(__index(0), __identifier(REMAP_NEAREST_KN_DST), __attributes(ACF_ATTR_VEC_OUT), __spatial_dep(0,0,0,0), // bot and right dependencies are contained in data, not ACF __e0_data_type(d08u), __e0_size(1, 1), __ek_size(1, 1)), __port(__index(1), __identifier(REMAP_NEAREST_KN_SRC), __attributes(ACF_ATTR_VEC_IN), __spatial_dep(0,0,0,0), __e0_data_type(d08u), __e0_size(1, 1), __ek_size(1, 1)), // source block size // todo currently does not match 32 bit size in code, but I think 16 bit is correct __port(__index(2), __identifier(REMAP_NEAREST_KN_OFFS), __attributes(ACF_ATTR_VEC_IN), __spatial_dep(0,0,0,0), __e0_data_type(d16u), __e0_size(1, 1), __ek_size(1, 1)) ); #endif //#ifdef ACF_KERNEL_METADATA #ifdef ACF_KERNEL_IMPLEMENTATION #ifdef APEX2_EMULATE #include "apu_lib.hpp" // if using the APU emulation library using namespace APEX2; #endif #include "remap_nearest_apu.h" void remap_nearest_grayscale( kernel_io_desc dst_param, kernel_io_desc src_param, kernel_io_desc offset_param) { vec08u* dst = (vec08u*)dst_param.pMem; vec08u* src = (vec08u*)src_param.pMem; vec16u* offset = (vec16u*)offset_param.pMem; int sstride = src_param.chunkSpan / sizeof(vec08u); // stride of the src array in cmem int dstride = dst_param.chunkSpan / sizeof(vec08u); // stride of the src array in cmem int bw = dst_param.chunkWidth; int bh = dst_param.chunkHeight; remap_nearest_grayscale_impl(dst, src, offset, sstride, dstride, bw, bh); } #endif //#ifdef ACF_KERNEL_IMPLEMENTATION /*! @} */
32.836066
103
0.645781
intesight
a498957bd4f43d9d0891dbe843a6f86d9025f8e6
534
cxx
C++
test/t1125.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
10
2018-03-26T07:41:44.000Z
2021-11-06T08:33:24.000Z
test/t1125.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
null
null
null
test/t1125.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
1
2020-11-17T03:17:00.000Z
2020-11-17T03:17:00.000Z
/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <stdio.h> enum BIT {ZERO,ONE,X}; void f(BIT* x) { printf("f((BIT*))\n"); } int main(){ BIT *a; a=new BIT[3]; // memory leak, G__alloc_newarraylist void *p = a; BIT *b; b = (BIT*)p; f((BIT*)p); delete[] a; return(0); }
18.413793
74
0.400749
paulwratt
a49a1667e90cda44c415f698ca7417385aa21d43
19,072
cpp
C++
test/mugenassignmentevaluatortest.cpp
CaptainDreamcast/DolmexicaInfinite
3891114b7307bcd99591d3e00d2a4b23aa68c9bc
[ "MIT" ]
14
2019-05-13T03:17:23.000Z
2021-10-04T15:43:27.000Z
test/mugenassignmentevaluatortest.cpp
CaptainDreamcast/DolmexicaInfinite
3891114b7307bcd99591d3e00d2a4b23aa68c9bc
[ "MIT" ]
3
2019-12-25T08:02:16.000Z
2020-05-16T11:53:20.000Z
test/mugenassignmentevaluatortest.cpp
CaptainDreamcast/DolmexicaInfinite
3891114b7307bcd99591d3e00d2a4b23aa68c9bc
[ "MIT" ]
3
2019-08-30T14:53:35.000Z
2020-04-24T04:03:11.000Z
#include <gtest/gtest.h> #include <prism/wrapper.h> #include "mugenassignmentevaluator.h" class MugenAssignmentEvaluatorTest : public ::testing::Test { protected: MemoryStack mMemoryStack; void SetUp() override { initMemoryHandler(); mMemoryStack = createMemoryStack(1024 * 1024 * 3); setupDreamAssignmentReader(&mMemoryStack); setupDreamAssignmentEvaluator(); } void TearDown() override { shutdownMemoryHandler(); } }; static const auto FLOAT_EPSILON = 1e-5f; TEST_F(MugenAssignmentEvaluatorTest, LogicalNegation) { auto assignment = parseDreamMugenAssignmentFromString("!0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("!!0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("!4"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("!!4"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, BitwiseInversion) { auto assignment = parseDreamMugenAssignmentFromString("~0"); ASSERT_EQ(0xFFFFFFFF, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("~~0"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("~15"); ASSERT_EQ(0xFFFFFFF0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("~~15"); ASSERT_EQ(15, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, UnaryMinus) { auto assignment = parseDreamMugenAssignmentFromString("-5"); ASSERT_EQ(-5, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("--5"); ASSERT_EQ(5, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("-0.5"); ASSERT_NEAR(-0.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("--0.5"); ASSERT_NEAR(0.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); } TEST_F(MugenAssignmentEvaluatorTest, Power) { auto assignment = parseDreamMugenAssignmentFromString("5 ** 2"); ASSERT_EQ(25, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("-5 ** 2"); ASSERT_EQ(25, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 ** 2 * 2"); ASSERT_EQ(50, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("2 * 5 ** 2"); ASSERT_EQ(50, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, Multiplication) { auto assignment = parseDreamMugenAssignmentFromString("2 * 2"); ASSERT_EQ(4, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0.5 * 0.5"); ASSERT_NEAR(0.25, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("1 * 0.5"); ASSERT_NEAR(0.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 * 2"); ASSERT_NEAR(1.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 * 3 * 2.0"); ASSERT_NEAR(3.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); } TEST_F(MugenAssignmentEvaluatorTest, Division) { auto assignment = parseDreamMugenAssignmentFromString("4 / 2"); ASSERT_EQ(2, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("3.0 / 0.5"); ASSERT_NEAR(6.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("1 / 4.0"); ASSERT_NEAR(0.25, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 / 4"); ASSERT_NEAR(0.125, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 / 10 / 2.0"); ASSERT_NEAR(0.025, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); } TEST_F(MugenAssignmentEvaluatorTest, Modulo) { auto assignment = parseDreamMugenAssignmentFromString("4 % 4"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("3 % 5"); ASSERT_EQ(3, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("6 % 4"); ASSERT_EQ(2, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("3 % 8 % 3"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, Addition) { auto assignment = parseDreamMugenAssignmentFromString("1 + 1"); ASSERT_EQ(2, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0.5 + 0.5"); ASSERT_NEAR(1.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("1 + 0.5"); ASSERT_NEAR(1.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 + 1"); ASSERT_NEAR(1.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 + 1 + 0.5"); ASSERT_NEAR(2.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); std::string result; assignment = parseDreamMugenAssignmentFromString("f30 + 5"); evaluateDreamAssignmentAndReturnAsString(result, &assignment, NULL); ASSERT_EQ("isinotherfilef 35", result); assignment = parseDreamMugenAssignmentFromString("s20 + 5"); evaluateDreamAssignmentAndReturnAsString(result, &assignment, NULL); ASSERT_EQ("isinotherfiles 25", result); } TEST_F(MugenAssignmentEvaluatorTest, GreaterThan) { auto assignment = parseDreamMugenAssignmentFromString("1 > 2"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 > 3"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("7 > 7"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("4 > 7 > 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, GreaterThanEqual) { auto assignment = parseDreamMugenAssignmentFromString("1 >= 2"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 >= 3"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("7 >= 7"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("4 >= 7 >= 0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, LessThan) { auto assignment = parseDreamMugenAssignmentFromString("1 < 2"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 < 3"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("7 < 7"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("4 < 7 < 1"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, LessThanEqual) { auto assignment = parseDreamMugenAssignmentFromString("1 <= 2"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 <= 3"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("7 <= 7"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("4 <= 7 <= 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, Comparison) { auto assignment = parseDreamMugenAssignmentFromString("1 = 2"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 = 5 = 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 = 5 = 5"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, Inequality) { auto assignment = parseDreamMugenAssignmentFromString("1 != 2"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 != 5 != 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 != 5 != 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, BitwiseAnd) { auto assignment = parseDreamMugenAssignmentFromString("1 & 2"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("15 & 7 & 3"); ASSERT_EQ(3, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("15 & 15 & 15"); ASSERT_EQ(15, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, BitwiseXor) { auto assignment = parseDreamMugenAssignmentFromString("7 ^ 3"); ASSERT_EQ(4, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("8 ^ 7"); ASSERT_EQ(15, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 ^ 0"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("15 ^ 15"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("15 ^ 15 ^ 7"); ASSERT_EQ(7, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, BitwiseOr) { auto assignment = parseDreamMugenAssignmentFromString("15 | 3"); ASSERT_EQ(15, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("3 | 4"); ASSERT_EQ(7, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 | 0"); ASSERT_EQ(0, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("15 | 15"); ASSERT_EQ(15, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 | 2 | 4 | 8 | 16"); ASSERT_EQ(31, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, Subtraction) { auto assignment = parseDreamMugenAssignmentFromString("2 - 1"); ASSERT_EQ(1, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0.5 - 0.5"); ASSERT_NEAR(0.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("1 - 0.5"); ASSERT_NEAR(0.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 - 1"); ASSERT_NEAR(-0.5, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("0.5 - 1 - 0.5"); ASSERT_NEAR(-1.0, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); } TEST_F(MugenAssignmentEvaluatorTest, LogicalAnd) { auto assignment = parseDreamMugenAssignmentFromString("1 && 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 && 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 && 1"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 && 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 && 0 && 1"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 && 1 && 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 && 1 && \"StringNearEndDoesNotCauseIssues\""); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, LogicalOr) { auto assignment = parseDreamMugenAssignmentFromString("1 || 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 || 0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 || 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 || 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 || 0 || 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 || 0 || 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, LogicalXor) { auto assignment = parseDreamMugenAssignmentFromString("1 ^^ 1"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 ^^ 0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 ^^ 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 ^^ 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 ^^ 0 ^^ 1 ^^ 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 ^^ 1 ^^ 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 ^^ 1 ^^ 1 ^^ 1"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, SameLevelPrecedence) { auto assignment = parseDreamMugenAssignmentFromString("4 + 2 - 3 + 5"); ASSERT_EQ(8, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("2.0 * 3.0 / 10.0 * 4.0 / 2.0"); ASSERT_NEAR(1.2, evaluateDreamAssignmentAndReturnAsFloat(&assignment, NULL), FLOAT_EPSILON); assignment = parseDreamMugenAssignmentFromString("4 * 8 / 2 * 10 / 5 * 10 % 7"); ASSERT_EQ(5, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("4 * 8 / 2 * 10 % 7 * 10 % 7"); ASSERT_EQ(4, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("-!!~1"); ASSERT_EQ(-1, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 > 6 >= 1 < 0 <= 0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 != 6 = 1 != 0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, DifferentLevelPrecedence) { auto assignment = parseDreamMugenAssignmentFromString("-4 ** 2"); ASSERT_EQ(16, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("4 ** 2 * 2"); ASSERT_EQ(32, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("2 * 4 ** 2"); ASSERT_EQ(32, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 + 2 * 4 + 3 * 6 - 2 * 8 - 5 * 5"); ASSERT_EQ(-10, evaluateDreamAssignmentAndReturnAsInteger(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 + 2 >= 5 + 4"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 + 5 >= 5 + 4"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("5 >= 5 & 3 <= 2"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 ^ 4 & 2 ^ 1 ^ 1 & 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 ^ 1 ^ 1 ^ 1 | 0 ^ 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 && 1 | 0 && 1"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("1 && 1 ^^ 1 && 0"); ASSERT_TRUE(evaluateDreamAssignment(&assignment, NULL)); assignment = parseDreamMugenAssignmentFromString("0 || 1 ^^ 1 || 0"); ASSERT_FALSE(evaluateDreamAssignment(&assignment, NULL)); } TEST_F(MugenAssignmentEvaluatorTest, MemoryLeaks) { setupDreamAssignmentReader(NULL); const auto prevAllocations = getAllocatedMemoryBlockAmount(); auto assignment = parseDreamMugenAssignmentFromString("1 + 1 / 2 * 4 , 5 * (3 - 4)"); ASSERT_NE(prevAllocations, getAllocatedMemoryBlockAmount()); destroyDreamMugenAssignment(assignment); ASSERT_EQ(prevAllocations, getAllocatedMemoryBlockAmount()); } TEST_F(MugenAssignmentEvaluatorTest, OperatorVector) { auto assignment = parseDreamMugenAssignmentFromString("animelem = 9,=0"); ASSERT_EQ(assignment->mType, MUGEN_ASSIGNMENT_TYPE_COMPARISON); DreamMugenDependOnTwoAssignment* comparison = (DreamMugenDependOnTwoAssignment*)assignment; auto vectorAssignment = comparison->b; ASSERT_EQ(vectorAssignment->mType, MUGEN_ASSIGNMENT_TYPE_VECTOR); DreamMugenDependOnTwoAssignment* vector = (DreamMugenDependOnTwoAssignment*)vectorAssignment; ASSERT_EQ(vector->b->mType, MUGEN_ASSIGNMENT_TYPE_OPERATOR_ARGUMENT); } TEST_F(MugenAssignmentEvaluatorTest, AnimElemTimeArray) { auto assignment = parseDreamMugenAssignmentFromString("animelemtime(2)=-1"); ASSERT_EQ(assignment->mType, MUGEN_ASSIGNMENT_TYPE_COMPARISON); DreamMugenDependOnTwoAssignment* comparison = (DreamMugenDependOnTwoAssignment*)assignment; ASSERT_EQ(comparison->a->mType, MUGEN_ASSIGNMENT_TYPE_ARRAY); ASSERT_EQ(comparison->b->mType, MUGEN_ASSIGNMENT_TYPE_UNARY_MINUS); }
51.967302
99
0.799916
CaptainDreamcast
a49ad9ae8e7db4b2298917fc7fc5bc72e83c4235
1,354
cpp
C++
Algorithms/arrays/leftShift/LeftShift.cpp
sejalsingh417/Open-DSA
dd2228abd3022f0899ded08ff3f710e51b74649f
[ "MIT" ]
1
2021-10-05T15:45:42.000Z
2021-10-05T15:45:42.000Z
Algorithms/arrays/leftShift/LeftShift.cpp
sejalsingh417/Open-DSA
dd2228abd3022f0899ded08ff3f710e51b74649f
[ "MIT" ]
17
2021-10-05T13:47:01.000Z
2021-11-06T13:15:42.000Z
Algorithms/arrays/leftShift/LeftShift.cpp
sejalsingh417/Open-DSA
dd2228abd3022f0899ded08ff3f710e51b74649f
[ "MIT" ]
9
2021-10-05T07:21:09.000Z
2021-10-20T08:31:03.000Z
#include<bits/stdc++.h> using namespace std; //METHOD 1 void leftRotate(int arr[], int n, int d){ //NAIVE O(n*d) while(d--){ int temp = arr[0]; for(int i=1; i<n;i++) arr[i-1] = arr[i]; arr[n-1] = temp; } } //METHOD 2 void leftRotate2(int arr[], int n, int d){ // TIME=O(n) space=O(d) int temp[d]; //copy first d elements to d for(int i=0; i<d; i++){ temp[i] = arr[i]; } //leftRotate next (n-d) elements d times for(int i=d; i<n; i++){ arr[i-d] = arr[i]; } //copy ele from temp to arr from d+1 pos to end for(int i=0; i<d; i++){ arr[n-d+i] = temp[i]; } } //METHOD 3 void reverseArr(int arr[], int start, int end){ // time=O(n) space O(1) while(end > start){ swap(arr[end], arr[start]); end--; start++; } } void leftRotate3(int arr[], int n, int d){ reverseArr(arr,0,d-1); reverseArr(arr,d,n-1); reverseArr(arr,0,n-1); } int main(){ int arr[] = {1,2,3,4,5}; int n = 5; // leftRotate(arr,n,2); // for(int i=0; i<n;i++){ // cout<<arr[i]<<" "; // } // leftRotate2(arr,n,2); // for(int i=0; i<n;i++){ // cout<<arr[i]<<" "; // } leftRotate3(arr,n,2); for(int i=0; i<n;i++){ cout<<arr[i]<<" "; } return 0; }
20.830769
72
0.465288
sejalsingh417
a49c014310a6de2a210887e748357733612ed58e
1,934
cpp
C++
cnes/src/otb/GeographicEphemeris.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
12
2016-09-09T01:24:12.000Z
2022-01-09T21:45:58.000Z
cnes/src/otb/GeographicEphemeris.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
5
2016-02-04T16:10:40.000Z
2021-06-29T05:00:29.000Z
cnes/src/otb/GeographicEphemeris.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
20
2015-11-17T11:46:22.000Z
2021-11-12T19:23:54.000Z
//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include <otb/GeographicEphemeris.h> #include <otb/GalileanEphemeris.h> #include <otb/GMSTDateTime.h> #include <cmath> namespace ossimplugins { GeographicEphemeris::GeographicEphemeris() : Ephemeris() { } GeographicEphemeris::~GeographicEphemeris() { } GeographicEphemeris::GeographicEphemeris(JSDDateTime date, double pos[3], double speed[3]) : Ephemeris(date, pos, speed) { } GeographicEphemeris::GeographicEphemeris(const GeographicEphemeris& rhs) : Ephemeris(rhs) { } GeographicEphemeris& GeographicEphemeris::operator=(const GeographicEphemeris& rhs) { ((Ephemeris)*this) = ((Ephemeris)rhs); return *this; } void GeographicEphemeris::ToGalilean(GalileanEphemeris* vGal) { const double OMEGATERRE = 6.28318530717958647693 / 86164.09054 ; GMSTDateTime h; h.set_origine(GMSTDateTime::AN1950); double s,c; _date.AsGMSTDateTime(&h) ; c = cos (h.get_tms()) ; s = sin (h.get_tms()) ; vGal->set_date(_date); double pos[3]; double speed[3]; pos[0] = _position[0] * c - _position[1] * s ; pos[1] = _position[0] * s + _position[1] * c ; pos[2] = _position[2] ; speed[0] = _speed[0] * c - _speed[1] * s - OMEGATERRE * (_position[0] * s + _position[1] * c) ; speed[1] = _speed[0] * s + _speed[1] * c + OMEGATERRE * (_position[0] * c - _position[1] * s) ; speed[2] = _speed[2] ; vGal->set_position(pos); vGal->set_speed(speed); } GeographicEphemeris::operator GalileanEphemeris() { GalileanEphemeris rhs; ToGalilean(&rhs); return rhs; } GeographicEphemeris::GeographicEphemeris(GalileanEphemeris& rhs) { rhs.ToGeographic(this); } }
22.488372
120
0.62668
dardok
a49cae03eb194069cc8c15103e9f066b8fb1a80c
1,200
cpp
C++
Lesson02/CyclicRotation/CyclicRotation/main.cpp
rlan/CodilityLessons
6ce4b1a19e7ce90fce39f9ec7fc207e620662676
[ "MIT" ]
null
null
null
Lesson02/CyclicRotation/CyclicRotation/main.cpp
rlan/CodilityLessons
6ce4b1a19e7ce90fce39f9ec7fc207e620662676
[ "MIT" ]
null
null
null
Lesson02/CyclicRotation/CyclicRotation/main.cpp
rlan/CodilityLessons
6ce4b1a19e7ce90fce39f9ec7fc207e620662676
[ "MIT" ]
null
null
null
// // Codility // Lesson 2 // CyclicRotation // https://codility.com/programmers/lessons/2-arrays/cyclic_rotation/ // // 100% score // https://codility.com/demo/results/trainingW3ATGD-489/ // // Created by Rick Lan on 3/28/17. // See LICENSE. // #include <iostream> #include <vector> using namespace std; vector<int> solution(vector<int> &A, int K) { if (A.size()==0) return A; vector<int> out(A.size()); unsigned long N = A.size(); K = K % N; int jj = 0; for (unsigned long ii = N-K; ii < N; ii++) out[jj++] = A[ii]; for (unsigned long ii = 0; ii < N-K; ii++) out[jj++] = A[ii]; return out; } int main(int argc, const char * argv[]) { vector<int> A; int K, N; cout << "K: "; cin >> K; cout << "N: "; cin >> N; if (N > 0) { A.resize(N); for (int ii = 0; ii < N; ii++) { cout << "A[" << ii << "]: "; cin >> A[ii]; } } vector<int> out = solution(A, K); cout << "Solution:" << endl; for (int ii = 0; ii < A.size(); ii++) { cout << "S[" << ii << "] = " << out[ii] << endl; } return 0; }
19.047619
70
0.463333
rlan
a49cc63ab392374c52a455065fffed8164e9247e
6,774
cpp
C++
render/src/pipeline/DescriptorSet.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
render/src/pipeline/DescriptorSet.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
render/src/pipeline/DescriptorSet.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #include <storm/render/core/Device.hpp> #include <storm/render/core/Enums.hpp> #include <storm/render/pipeline/DescriptorPool.hpp> #include <storm/render/pipeline/DescriptorSet.hpp> #include <storm/render/resource/HardwareBuffer.hpp> #include <storm/render/resource/Sampler.hpp> #include <storm/render/resource/Texture.hpp> using namespace storm; using namespace storm::render; ///////////////////////////////////// ///////////////////////////////////// DescriptorSet::DescriptorSet(const DescriptorPool &pool, std::vector<DescriptorType> types, RAIIVkDescriptorSet set) : m_device { &pool.device() }, m_pool { &pool }, m_types { std::move(types) }, m_vk_descriptor_set { std::move(set) } { } ///////////////////////////////////// ///////////////////////////////////// DescriptorSet::~DescriptorSet() = default; ///////////////////////////////////// ///////////////////////////////////// DescriptorSet::DescriptorSet(DescriptorSet &&) = default; ///////////////////////////////////// ///////////////////////////////////// DescriptorSet &DescriptorSet::operator=(DescriptorSet &&) = default; ///////////////////////////////////// ///////////////////////////////////// void DescriptorSet::update(core::span<const render::Descriptor> descriptors) { STORMKIT_EXPECTS(!std::empty(descriptors)); auto vk_buffer_infos = std::vector<std::tuple<core::Int32, vk::DescriptorBufferInfo, vk::DescriptorType>> {}; auto vk_image_infos = std::vector<std::tuple<core::Int32, vk::DescriptorImageInfo, vk::DescriptorType>> {}; for (const auto &descriptor_proxy : descriptors) { if (std::holds_alternative<BufferDescriptor>(descriptor_proxy)) { const auto &descriptor = std::get<BufferDescriptor>(descriptor_proxy); const auto buffer_info = vk::DescriptorBufferInfo {} .setBuffer(*descriptor.buffer) .setOffset(descriptor.offset) .setRange(descriptor.range); vk_buffer_infos.emplace_back(descriptor.binding, std::move(buffer_info), toVK(descriptor.type)); } else if (std::holds_alternative<TextureDescriptor>(descriptor_proxy)) { const auto &descriptor = std::get<TextureDescriptor>(descriptor_proxy); auto image_info = vk::DescriptorImageInfo {} .setImageView(*descriptor.texture_view) .setImageLayout(toVK(descriptor.layout)); if (descriptor.sampler != nullptr) image_info.setSampler(*descriptor.sampler); vk_image_infos.emplace_back(descriptor.binding, std::move(image_info), toVK(descriptor.type)); } } auto vk_write_infos = std::vector<vk::WriteDescriptorSet> {}; vk_write_infos.reserve(std::size(vk_buffer_infos) + std::size(vk_image_infos)); for (const auto &[binding, vk_buffer_info, type] : vk_buffer_infos) { const auto write_info = vk::WriteDescriptorSet {} .setDstSet(*m_vk_descriptor_set) .setDstBinding(binding) .setDstArrayElement(0) .setDescriptorCount(1) .setDescriptorType(type) .setPBufferInfo(&vk_buffer_info); vk_write_infos.emplace_back(std::move(write_info)); } for (const auto &[binding, vk_image_info, type] : vk_image_infos) { const auto write_info = vk::WriteDescriptorSet {} .setDstSet(*m_vk_descriptor_set) .setDstBinding(binding) .setDstArrayElement(0) .setDescriptorCount(1) .setDescriptorType(type) .setPImageInfo(&vk_image_info); vk_write_infos.emplace_back(std::move(write_info)); } m_device->updateVkDescriptorSets(vk_write_infos, {}); } namespace std { core::Hash64 hash<BufferDescriptor>::operator()(const BufferDescriptor &descriptor) const noexcept { auto hash = core::Hash64 { 0 }; core::hashCombine(hash, descriptor.type); core::hashCombine(hash, descriptor.binding); core::hashCombine(hash, descriptor.buffer); core::hashCombine(hash, descriptor.range); core::hashCombine(hash, descriptor.offset); return hash; } core::Hash64 hash<TextureDescriptor>::operator()(const TextureDescriptor &descriptor) const noexcept { auto hash = core::Hash64 { 0 }; core::hashCombine(hash, descriptor.type); core::hashCombine(hash, descriptor.binding); core::hashCombine(hash, descriptor.layout); core::hashCombine(hash, descriptor.texture_view); core::hashCombine(hash, descriptor.sampler); return hash; } core::Hash64 hash<Descriptor>::operator()(const Descriptor &descriptor_proxy) const noexcept { auto hash = core::Hash64 { 0 }; std::visit(core::overload { [&hash](auto &descriptor) { core::hashCombine(hash, descriptor); } }, descriptor_proxy); return hash; } core::Hash64 hash<DescriptorArray>::operator()(const DescriptorArray &descriptors) const noexcept { auto hash = core::Hash64 { 0 }; for (const auto &descriptor : descriptors) core::hashCombine(hash, descriptor); return hash; } core::Hash64 hash<DescriptorSpan>::operator()(const DescriptorSpan &descriptors) const noexcept { auto hash = core::Hash64 { 0 }; for (const auto &descriptor : descriptors) core::hashCombine(hash, descriptor); return hash; } core::Hash64 hash<DescriptorConstSpan>::operator()( const DescriptorConstSpan &descriptors) const noexcept { auto hash = core::Hash64 { 0 }; for (const auto &descriptor : descriptors) core::hashCombine(hash, descriptor); return hash; } } // namespace std
40.08284
99
0.548716
Arthapz
a49eab3a182f5f01fbbf0687365a4a22905e8e7d
2,777
cpp
C++
contracts/system/_dispatcher.cpp
EOSPowerNetwork/system-epn
dfa836101f6b148916b08b3c2988b591ed92ce9e
[ "MIT" ]
null
null
null
contracts/system/_dispatcher.cpp
EOSPowerNetwork/system-epn
dfa836101f6b148916b08b3c2988b591ed92ce9e
[ "MIT" ]
null
null
null
contracts/system/_dispatcher.cpp
EOSPowerNetwork/system-epn
dfa836101f6b148916b08b3c2988b591ed92ce9e
[ "MIT" ]
null
null
null
#include <tuple> #include "core/fixedprops.hpp" #include "interface/include/donationsIntf.hpp" #include "donations.hpp" #include "paycontracts.hpp" #include "ricardians.hpp" #define EXEC_ACTION(CLASS_NAME, ACTION_NAME) \ case eosio::hash_name(#ACTION_NAME): \ executed = eosio::execute_action(eosio::name(receiver), eosio::name(code), &CLASS_NAME::ACTION_NAME); \ break; namespace system_epn { namespace actions { using contract_c1 = paycontracts; using contract_c2 = donations; using fixedProps::contract_account; template <typename F> void for_each_action(F&& f) { f("addasset"_h, eosio::action_type_wrapper<&contract_c1::addasset>{}, ricardians::paycontract::addasset_ricardian, "type", "contract", "minAmount", "maxAmount"); f("draftdon"_h, eosio::action_type_wrapper<&contract_c2::draftdon>{}, ricardians::donation::draftdon_ricardian, "owner", "contractID", "memoSuffix"); f("signdon"_h, eosio::action_type_wrapper<&contract_c2::signdon>{}, ricardians::donation::signdon_ricardian, "signer", "drafter", "contractID", "quantity", "frequency", "signerMemo"); } inline bool eosio_apply(uint64_t receiver, uint64_t code, uint64_t action) { bool executed = false; if (code == receiver) { switch (action) { EXEC_ACTION(paycontracts, addasset) EXEC_ACTION(donations, draftdon) EXEC_ACTION(donations, signdon) } eosio::check(executed == true, "unknown action"); } return executed; } /* Would be nice if there was a simple clsdk dispatcher helper * macro for multi-class contracts, for example: EOSIO_ACTIONS("contractname"_n, ( paycontracts, action(sayhi, name, ricardian_contract(sayhi_ricardian)) ),( donations, action(saybye, name, ricardian_contract(saybye_ricardian)) )) */ } // namespace actions } // namespace system_epn // Final part of the dispatcher EOSIO_ACTION_DISPATCHER(system_epn::actions) // Things to populate the ABI with EOSIO_ABIGEN(actions(system_epn::actions), table("donsigners"_n, system_epn::DonationSignature), table("dondrafts"_n, system_epn::DonationDraft), ricardian_clause("Paycontracts clause", ricardians::paycontract::ricardian_clause), ricardian_clause("Donations clause", ricardians::donation::ricardian_clause))
39.671429
180
0.601728
EOSPowerNetwork
a49fd0bd1d0ea99be7ff7ace123dacdc579e2a49
1,633
cc
C++
apps/run.cc
CS126SP20/final-project-jlwang3
82e1d02133e02f2b020248d1054d3cedbc94224a
[ "MIT" ]
null
null
null
apps/run.cc
CS126SP20/final-project-jlwang3
82e1d02133e02f2b020248d1054d3cedbc94224a
[ "MIT" ]
null
null
null
apps/run.cc
CS126SP20/final-project-jlwang3
82e1d02133e02f2b020248d1054d3cedbc94224a
[ "MIT" ]
null
null
null
// Copyright (c) 2020 [Your Name]. All rights reserved. #include <cinder/app/App.h> #include <cinder/app/RendererGl.h> #include "my_app.h" #include <gflags/gflags.h>> using cinder::app::App; using cinder::app::RendererGl; namespace myapp { DEFINE_uint32(difficulty, 40, "difficulty level"); DEFINE_uint32(width, 10, "the number of tiles in each row"); DEFINE_uint32(height,20,"the number of tiles in each column"); DEFINE_uint32(tilesize, 40, "the size of each tile"); DEFINE_uint32(speed, 200, "the speed (delay) of the game"); DEFINE_string(name, "CS126SP20", "the name of the player"); const int kSamples = 8; void ParseArgs(vector<string>* args) { gflags::SetUsageMessage( "Play a game of Snake. Pass --helpshort for options."); int argc = static_cast<int>(args->size()); vector<char*> argvs; for (string& str : *args) { argvs.push_back(&str[0]); } char** argv = argvs.data(); gflags::ParseCommandLineFlags(&argc, &argv, true); } void SetUp(App::Settings* settings) { vector<string> args = settings->getCommandLineArgs(); ParseArgs(&args); const int width = static_cast<int>(FLAGS_width * FLAGS_tilesize); const int height = static_cast<int>(FLAGS_height * FLAGS_tilesize); settings->setWindowSize(width, height); settings->setResizable(false); settings->setTitle("CS 126 Tetris"); } } // namespace myapp // This is a macro that runs the application. CINDER_APP(myapp::MyApp, RendererGl(RendererGl::Options().msaa(myapp::kSamples)), myapp::SetUp)
29.160714
71
0.655848
CS126SP20
a4a0c042b51cb3b0b2cf0b6feb02fa20412104c1
218
cpp
C++
src/RE/hkpWorldObject.cpp
powerof3/CommonLibVR
c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f
[ "MIT" ]
6
2020-04-05T04:37:42.000Z
2022-03-19T17:42:24.000Z
src/RE/hkpWorldObject.cpp
kassent/CommonLibSSE
394231b44ba01925fef9d01ea2b0b29c2fff601c
[ "MIT" ]
3
2021-11-08T09:31:20.000Z
2022-03-02T19:22:42.000Z
src/RE/hkpWorldObject.cpp
kassent/CommonLibSSE
394231b44ba01925fef9d01ea2b0b29c2fff601c
[ "MIT" ]
6
2020-04-10T18:11:46.000Z
2022-01-18T22:31:25.000Z
#include "RE/hkpWorldObject.h" namespace RE { const hkpCollidable* hkpWorldObject::GetCollidable() const { return &collidable; } hkpCollidable* hkpWorldObject::GetCollidableRW() { return &collidable; } }
12.823529
59
0.729358
powerof3
a4a3be19fed6d463a4aea6cd32c10279c3da9e0b
2,418
cpp
C++
solved/l-n/liar-or-not-liar-that-is-the/liar.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/l-n/liar-or-not-liar-that-is-the/liar.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/l-n/liar-or-not-liar-that-is-the/liar.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cmath> #include <cstdio> #define MAXPSOL 50 #define IsComp(n) (_c[n>>6]&(1<<((n>>1)&31))) #define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31)) const int MAXP = 10000000; // 10^7 const int SQRP = 3163; // sqrt(MAX) const int MAX_NP = 781731; // 1.26 * MAXP/log(MAXP) int _c[(MAXP>>6)+1]; int primes[MAX_NP]; int nprimes; bool is_p4[MAX_NP]; // is_p4[i]: true iff primes[i] is 4k+3 for some k int p4s[MAX_NP]; int np4s; void prime_sieve() { for (int i = 3; i <= SQRP; i += 2) if (!IsComp(i)) for (int j = i*i; j <= MAXP; j+=i+i) SetComp(j); primes[nprimes++] = 2; for (int i=3; i <= MAXP; i+=2) if (!IsComp(i)) { if ((i - 3) % 4 == 0) { is_p4[nprimes] = true; p4s[np4s++] = i; } primes[nprimes++] = i; } } // Calculates the highest exponent of prime p that divides n! int pow_div_fact(int n, int p) { int sd = 0; for (int N=n; N; N /= p) sd += N % p; return (n-sd)/(p-1); } int N; bool is_fact; int psol[MAXPSOL]; int npsol; bool solve_n() { npsol = 0; int sn = sqrt(N); for (int i = 0; i < nprimes; ++i) { int &p = primes[i]; if (p > sn) break; if (N % p != 0) continue; int e = 0; while (N % p == 0) ++e, N /= p; if (is_p4[i] && e % 2 != 0) return false; sn = sqrt(N); } if (N > 1 && (N - 3) % 4 == 0) return false; return true; } bool solve_fact() { npsol = 0; for (int i = 0; i < np4s; ++i) { int &p = p4s[i]; if (p > N) break; int e = pow_div_fact(N, p); if (e % 2 == 0) continue; psol[npsol++] = p; if (npsol == MAXPSOL) return false; } return npsol == 0; } bool solve() { if (is_fact) return solve_fact(); return solve_n(); } int main() { prime_sieve(); bool first = true; while (true) { char c; if (scanf("%d%c", &N, &c) != 2) break; is_fact = c == '!'; if (first) first = false; else putchar('\n'); if (solve()) puts("He might be honest."); else { puts("He is a liar."); if (npsol > 0) { printf("%d", psol[0]); for (int i = 1; i < npsol; ++i) printf(" %d", psol[i]); putchar('\n'); } } } return 0; }
21.026087
74
0.449132
abuasifkhan
a4a53df93a4c51d49f7f96f0c4c195cb02951c3e
4,483
cpp
C++
fpsgame/gui/tex/tex_tga.cpp
mrlitong/CPP-Game-engine-usage
95697c4bfb507cfb38dbe0f632740e2a7eac71fb
[ "MIT" ]
186
2017-07-26T12:53:29.000Z
2021-09-10T04:00:39.000Z
fpsgame/gui/tex/tex_tga.cpp
mrlitong/CPP-Game-engine-usage
95697c4bfb507cfb38dbe0f632740e2a7eac71fb
[ "MIT" ]
1
2017-08-15T13:12:27.000Z
2017-08-16T06:14:57.000Z
fpsgame/gui/tex/tex_tga.cpp
mrlitong/CPP-Game-engine-usage
95697c4bfb507cfb38dbe0f632740e2a7eac71fb
[ "MIT" ]
6
2017-02-15T10:19:26.000Z
2017-03-15T03:17:15.000Z
/* Copyright (c) 2010 Wildfire Games * * 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. */ /* * TGA codec. */ #include "precompiled.h" #include "lib/byte_order.h" #include "tex_codec.h" #include "lib/bits.h" #pragma pack(push, 1) enum TgaImgType { TGA_TRUE_COLOR = 2, // uncompressed 24 or 32 bit direct RGB TGA_GREY = 3 // uncompressed 8 bit direct greyscale }; enum TgaImgDesc { TGA_RIGHT_TO_LEFT = BIT(4), TGA_TOP_DOWN = BIT(5), }; typedef struct { u8 img_id_len; // 0 - no image identifier present u8 color_map_type; // 0 - no color map present u8 img_type; // see TgaImgType u8 color_map[5]; // unused u16 x_origin; // unused u16 y_origin; // unused u16 w; u16 h; u8 bpp; // bits per pixel u8 img_desc; } TgaHeader; // TGA file: header [img id] [color map] image data #pragma pack(pop) Status TexCodecTga::transform(Tex* UNUSED(t), size_t UNUSED(transforms)) const { return INFO::TEX_CODEC_CANNOT_HANDLE; } bool TexCodecTga::is_hdr(const u8* file) const { TgaHeader* hdr = (TgaHeader*)file; // the first TGA header doesn't have a magic field; // we can only check if the first 4 bytes are valid // .. not direct color if(hdr->color_map_type != 0) return false; // .. wrong color type (not uncompressed greyscale or RGB) if(hdr->img_type != TGA_TRUE_COLOR && hdr->img_type != TGA_GREY) return false; // note: we can't check img_id_len or color_map[0] - they are // undefined and may assume any value. return true; } bool TexCodecTga::is_ext(const OsPath& extension) const { return extension == L".tga"; } size_t TexCodecTga::hdr_size(const u8* file) const { size_t hdr_size = sizeof(TgaHeader); if(file) { TgaHeader* hdr = (TgaHeader*)file; hdr_size += hdr->img_id_len; } return hdr_size; } // requirements: uncompressed, direct color, bottom up Status TexCodecTga::decode(rpU8 data, size_t UNUSED(size), Tex* RESTRICT t) const { const TgaHeader* hdr = (const TgaHeader*)data; const u8 type = hdr->img_type; const size_t w = read_le16(&hdr->w); const size_t h = read_le16(&hdr->h); const size_t bpp = hdr->bpp; const u8 desc = hdr->img_desc; size_t flags = 0; flags |= (desc & TGA_TOP_DOWN)? TEX_TOP_DOWN : TEX_BOTTOM_UP; if(desc & 0x0F) // alpha bits flags |= TEX_ALPHA; if(bpp == 8) flags |= TEX_GREY; if(type == TGA_TRUE_COLOR) flags |= TEX_BGR; // sanity checks // .. storing right-to-left is just stupid; // we're not going to bother converting it. if(desc & TGA_RIGHT_TO_LEFT) WARN_RETURN(ERR::TEX_INVALID_LAYOUT); t->m_Width = w; t->m_Height = h; t->m_Bpp = bpp; t->m_Flags = flags; return INFO::OK; } Status TexCodecTga::encode(Tex* RESTRICT t, DynArray* RESTRICT da) const { u8 img_desc = 0; if(t->m_Flags & TEX_TOP_DOWN) img_desc |= TGA_TOP_DOWN; if(t->m_Bpp == 32) img_desc |= 8; // size of alpha channel TgaImgType img_type = (t->m_Flags & TEX_GREY)? TGA_GREY : TGA_TRUE_COLOR; size_t transforms = t->m_Flags; transforms &= ~TEX_ORIENTATION; // no flip needed - we can set top-down bit. transforms ^= TEX_BGR; // TGA is native BGR. const TgaHeader hdr = { 0, // no image identifier present 0, // no color map present (u8)img_type, {0,0,0,0,0}, // unused (color map) 0, 0, // unused (origin) (u16)t->m_Width, (u16)t->m_Height, (u8)t->m_Bpp, img_desc }; const size_t hdr_size = sizeof(hdr); return tex_codec_write(t, transforms, &hdr, hdr_size, da); }
25.471591
81
0.696186
mrlitong
a4ac126a30577ea28ebc66080d23d784bd9b6bd8
374
cpp
C++
DataFromImage/GUI/GUIElement.cpp
AlekseyShashkov/DataFromImage
a074098d9f9b44c049c39f5f4299e818401cba31
[ "MIT" ]
null
null
null
DataFromImage/GUI/GUIElement.cpp
AlekseyShashkov/DataFromImage
a074098d9f9b44c049c39f5f4299e818401cba31
[ "MIT" ]
null
null
null
DataFromImage/GUI/GUIElement.cpp
AlekseyShashkov/DataFromImage
a074098d9f9b44c049c39f5f4299e818401cba31
[ "MIT" ]
null
null
null
#include "GUIElement.h" GUIElement::~GUIElement() { ::SelectObject(m_PanelDC, m_PanelBitmapDefault); ::SelectObject(m_PanelBasicDC, m_PanelBasicBitmapDefault); ::DeleteObject(m_PanelBitmap); ::DeleteObject(m_PanelBasicBitmap); ::DeleteDC(m_PanelDC); ::DeleteDC(m_PanelBasicDC); } HDC GUIElement::GetHandlePanel() const { return m_PanelDC; }
23.375
64
0.724599
AlekseyShashkov
a4af802acb5d5e86977a374ac170072fd8cebf8a
8,766
cpp
C++
Code/CmLib/Saliency/CmSaliencyGC.cpp
JessicaGiven/SalBenchmark_Analysis_Given
0b0d8c3373be9105e9e94bc20b0eeb0bd7c06198
[ "MIT" ]
1
2018-10-07T00:56:57.000Z
2018-10-07T00:56:57.000Z
Code/CmLib/Saliency/CmSaliencyGC.cpp
JessicaGiven/SalBenchmark_Analysis_Given
0b0d8c3373be9105e9e94bc20b0eeb0bd7c06198
[ "MIT" ]
null
null
null
Code/CmLib/Saliency/CmSaliencyGC.cpp
JessicaGiven/SalBenchmark_Analysis_Given
0b0d8c3373be9105e9e94bc20b0eeb0bd7c06198
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CmSaliencyGC.h" CmSaliencyGC::CmSaliencyGC(CMat &img3f, CStr &outName, bool GET_CSD) :_gmm(DEFAULT_GMM_NUM), _img3f(img3f), _nameNE(outName), _GET_CSD(GET_CSD) { } const int CmSaliencyGC::DEFAULT_GMM_NUM = 15; void CmSaliencyGC::HistgramGMMs() { // Color quantization Mat _colorNums1f, _binBGR3f; CmColorQua::D_Quantize(_img3f, _HistBinIdx1i, _binBGR3f, _colorNums1f); //CmShow::HistBins(_binBGR3f, _colorNums1i, _nameNE + "_QT.jpg", true); _colorNums1f.convertTo(_colorNums1f, CV_32F); // Train GMMs Mat gmmIdx1i; _gmm.BuildGMMs(_binBGR3f, gmmIdx1i, _colorNums1f); _NUM = _gmm.RefineGMMs(_binBGR3f, gmmIdx1i, _colorNums1f); _PixelSalCi1f.resize(_NUM); _HistBinSalCi1f.resize(_NUM); _gmmClrs.resize(_NUM); _gmmW.resize(_NUM); _csd.resize(_NUM); _gu.resize(_NUM); _fSal.resize(_NUM); // Assign GMM color means and weights for (int i = 0; i < _NUM; i++) _gmmClrs[i] = _gmm.getMean(i), _gmmW[i] = _gmm.getWeight(i); // Assign GMMs for each components _gmm.GetProbs(_binBGR3f, _HistBinSalCi1f); #pragma omp parallel for for (int c = 0; c < _NUM; c++){ _PixelSalCi1f[c].create(_img3f.size(), CV_32FC1); float *prob = (float*)(_HistBinSalCi1f[c].data); for (int y = 0; y < _HistBinIdx1i.rows; y++){ const int *_idx = _HistBinIdx1i.ptr<int>(y); float* probCI = _PixelSalCi1f[c].ptr<float>(y); for (int x = 0; x < _HistBinIdx1i.cols; x++) probCI[x] = prob[_idx[x]]; } blur(_PixelSalCi1f[c], _PixelSalCi1f[c], Size(3, 3)); } } Mat CmSaliencyGC::GetSaliencyCues() { vecD d; Mat salMatCSD; if (_GET_CSD){ GetCSD(_csd, d); salMatCSD = GetSalFromGMMs(_csd); } GetGU(_gu, d, 0.4, 15); Mat salMatGU = GetSalFromGMMs(_gu); if (_GET_CSD) return SpatialVar(salMatCSD) < SpatialVar(salMatGU) ? salMatCSD : salMatGU; else return salMatGU; } void CmSaliencyGC::MergeGMMs() { _ClusteredIdx.resize(_NUM); for (int i = 0; i < _NUM; i++) _ClusteredIdx[i] = i; CmAPCluster apCluter; CmAPCluster::apcluster32 apFun = apCluter.GetApFun(); unsigned int N = _NUM * _NUM; if (apFun != NULL){ Mat_<double> cor = Mat_<double>::zeros(_NUM, _NUM); for (int y = 0; y < _img3f.rows; y++) { for (int x = 0; x < _img3f.cols; x++){ vector<CostfIdx> pIdx; pIdx.reserve(_NUM); for (int c = 0;c < _NUM; c++) pIdx.push_back(make_pair(_PixelSalCi1f[c].at<float>(y, x), c)); sort(pIdx.begin(), pIdx.end(), std::greater<CostfIdx>()); int i1 = pIdx[0].second, i2 = pIdx[1].second; float cost = min(pIdx[0].first, pIdx[1].first); cor(i1, i2) += cost; cor(i2, i1) += cost; } } double scale = _img3f.rows*_img3f.cols * 7 / 1e4; // Scale values for better illustration for (int i = 0; i < _NUM; i++) for (int j = 0; j < i; j++) cor(i, j) = cor(j, i) = log(1 + cor(i, j) / (scale * min(_gmmW[i], _gmmW[j]) + 1E-4)) - 1; //CmShow::Correlation(_gmmClrs, cor, _nameNE + "_MCOR.png", 20); double preference = 4*sum(cor).val[0]/(cor.cols*cor.rows); for (int i = 0; i < _NUM; i++) cor(i, i) = preference; // Preference for apcluster double netSim = 0; apFun(cor.ptr<double>(0), NULL, NULL, N, &_ClusteredIdx[0], &netSim, &apCluter.apoptions); } _NUM_Merged = CmAPCluster::ReMapIdx(_ClusteredIdx); _pciM1f.resize(_NUM_Merged); if (apFun != NULL){ for (int i = 0; i < _NUM_Merged; i++) _pciM1f[i] = Mat::zeros(_img3f.size(), CV_32FC1); for (int i = 0; i < _NUM; i++) _pciM1f[_ClusteredIdx[i]] += _PixelSalCi1f[i]; } else{ for (int i = 0; i < _NUM; i++) _pciM1f[i] = _PixelSalCi1f[i]; } } // Return the center distance and spatial variance of X and Y direction. Pixel locations are normalized to [0, 1] double CmSaliencyGC::SpatialVar(CMat& map1f, double &cD) { // Find centroid of the map const int h = map1f.rows, w = map1f.cols; const double H = h, W = w; double xM = 0, yM = 0, sumP = EPS; for (int y = 0; y < h; y++) { const float* prob = map1f.ptr<float>(y); for (int x = 0; x < w; x++) sumP += prob[x], xM += prob[x] * x, yM += prob[x] * y; } xM /= sumP, yM /= sumP; // Find variance of X and Y direction double vX = 0, vY = 0; cD = 0; // average center distance for (int y = 0; y < h; y++) { const float* prob = map1f.ptr<float>(y); for (int x = 0; x < w; x++){ double p = prob[x]; vX += p * sqr(x - xM), vY += p * sqr(y - yM); cD += p * sqrt(sqr(x/W - 0.5) + sqr(y/H - 0.5)); } } cD /= sumP; return vX/sumP + vY/sumP; } void CmSaliencyGC::GetCSD(vecD &_csd, vecD &_cD) { MergeGMMs(); vecD csd, cD; int num = (int)_pciM1f.size(); // Number of Gaussian Size imgSz = _pciM1f[0].size(); double centerX = imgSz.width / 2, centerY = imgSz.height / 2; cD.resize(num); vecD V(num), D(num); #pragma omp parallel for for (int i = 0; i < num; i++) V[i] = SpatialVar(_pciM1f[i], cD[i]); normalize(V, V, 0, 1, CV_MINMAX); normalize(cD, D, 0, 1, CV_MINMAX); csd.resize(num); for (int i = 0; i < num; i++) csd[i] = (1-V[i])*(1-D[i]); normalize(csd, csd, 0, 1, CV_MINMAX); _csd.resize(_NUM); _cD.resize(_NUM); for (int i = 0; i < _NUM; i++) _csd[i] = csd[_ClusteredIdx[i]], _cD[i] = cD[_ClusteredIdx[i]]; } void CmSaliencyGC::ViewValues(vecD &vals, CStr &ext) { int K = _NUM; Mat_<Vec3f> color3f(1, K); Mat_<double> weight1d(1, K), cov1d(1, K); for (int i = 0; i < K; i++) { color3f(0, i) = _gmm.getMean(i); weight1d(0, i) = vals[i]; cov1d(0, i) = sqrt(_gmm.GetGaussians()[i].det); } //CmShow::HistBins(color3f, weight1d, _nameNE + ext, false, cov1d); } void CmSaliencyGC::GetGU(vecD& gc, vecD &d, double sigmaDist, double dominate) { if (d.size() == 0){ d.resize(_NUM); #pragma omp parallel for for (int i = 0; i < _NUM; i++) SpatialVar(_PixelSalCi1f[i], d[i]); } Mat_<double> clrDist; clrDist = Mat_<double>::zeros(_NUM, _NUM); vector<Vec3f> gmmClrs(_NUM); cvtColor(_gmmClrs, gmmClrs, CV_BGR2Lab); vecD maxDist(_NUM); for (int i = 0; i < _NUM; i++) for (int j = 0; j < i; j++){ double dCrnt = vecDist(gmmClrs[i], gmmClrs[j]); clrDist(i, j) = clrDist(j, i) = dCrnt; maxDist[i] = max(maxDist[i], dCrnt); maxDist[j] = max(maxDist[j], dCrnt); } for (int i = 0; i < _NUM; i++) { gc[i] = 0; for (int j = 0; j < _NUM; j++) gc[i] += _gmmW[j] * clrDist(i, j) / maxDist[i]; //min(clrDist(i, j), dominate); } for (int i = 0; i < _NUM; i++) _gu[i] = _gu[i] * exp(-9.0 * sqr(d[i])); // normalize(_gu, _gu, 0, 1, CV_MINMAX); } void CmSaliencyGC::ReScale(vecD& salVals, double minRatio) { while (1){ double sumW = 0, maxCrnt = 0; for (int i = 0; i < _NUM; i++) if (salVals[i] > 0.95) sumW += _gmmW[i]; else maxCrnt = max(maxCrnt, salVals[i]); if (sumW < minRatio && maxCrnt > EPS) for (int i = 0; i < _NUM; i++) salVals[i] = min(salVals[i]/maxCrnt, 1.0); else break; } } Mat CmSaliencyGC::GetSalFromGMMs(vecD &val, bool bNormlize) { ReScale(val); Mat binSal = Mat::zeros(_HistBinSalCi1f[0].size(), CV_32F); int num = (int)_HistBinSalCi1f.size(), type = _HistBinSalCi1f[0].type(); for (int c = 0; c < num; c++){ Mat tmp; _HistBinSalCi1f[c].convertTo(tmp, type, val[c]); add(binSal, tmp, binSal); } normalize(binSal, binSal, -4, 4, NORM_MINMAX); float *bVal = binSal.ptr<float>(0); for(int i = 0; i < binSal.cols; i++) bVal[i] = 1 / (1 + exp(-bVal[i])); // Sigmoid if (bNormlize) normalize(binSal, binSal, 0, 1, NORM_MINMAX); Mat salMat(_HistBinIdx1i.size(), CV_32F); float* binSalVal = (float*)(binSal.data); #pragma omp parallel for for (int r = 0; r < _HistBinIdx1i.rows; r++){ const int* idx = _HistBinIdx1i.ptr<int>(r); float* sal = salMat.ptr<float>(r); for (int c = 0; c < _HistBinIdx1i.cols; c++) sal[c] = binSalVal[idx[c]]; } blur(salMat, salMat, Size(3, 3)); normalize(salMat, salMat, 0, 1, NORM_MINMAX); return salMat; } // See my CVPR 11 paper http://mmcheng.net/SalObj/ for source code used to generate // nice statistical plots, many comparison figures and latex (see supplemental material). int CmSaliencyGC::Demo(CStr imgW, CStr salDir) { CmFile::MkDir(salDir); vecS namesNE, des; string imgDir, ext; int imgNum = CmFile::GetNamesNE(imgW, namesNE, imgDir, ext); CmTimer tm("Maps"); tm.Start(); printf("%d images found in %s\n", imgNum, _S(imgDir + "*.jpg")); #pragma omp parallel for for (int i = 0; i < imgNum; i++){ Mat img = imread(imgDir + namesNE[i] + ".jpg"); CStr outName = salDir + namesNE[i]; img.convertTo(img, CV_32FC3, 1.0/255); CmSaliencyGC sGC(img, outName, true); sGC.HistgramGMMs(); Mat sal1f = sGC.GetSaliencyCues(); imwrite(outName + "_GC.png", sal1f*255); } tm.Stop(); printf("Speed of GC method: %g seconds = %g fps\n", tm.TimeInSeconds()/imgNum, imgNum/tm.TimeInSeconds()); des.push_back("GC"); CmEvaluation::Evaluate(imgDir + "*.png", salDir, salDir + "Eval.m", des); return 0; }
29.614865
113
0.630504
JessicaGiven
a4b12270171987184379a3e1d5c0c6e882b341e9
318
c++
C++
Codeforces/RatingLessThan1300/drinks.c++
padmaja-22/CP
0fc2648ead9a993398e3aa2f6e0b028e67c4c148
[ "MIT" ]
null
null
null
Codeforces/RatingLessThan1300/drinks.c++
padmaja-22/CP
0fc2648ead9a993398e3aa2f6e0b028e67c4c148
[ "MIT" ]
null
null
null
Codeforces/RatingLessThan1300/drinks.c++
padmaja-22/CP
0fc2648ead9a993398e3aa2f6e0b028e67c4c148
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <iomanip> using namespace std; int main(){ int n; double sum=0; int arr[100]; cin>>n; for(int i=0;i<n;i++){ cin>>arr[i]; sum+=arr[i]; } double res = (double)sum / n; cout<<fixed<<setprecision(12)<<res<<endl; return 0; }
18.705882
42
0.556604
padmaja-22
a4b149f052f60683cef92b494491d6bef192a52e
29,029
cc
C++
projects/Skeleton/code/exampleapp.cc
Destinum/S0008E
25344cc26c92ee022d7d7eac7428a113aa0be3a2
[ "MIT" ]
null
null
null
projects/Skeleton/code/exampleapp.cc
Destinum/S0008E
25344cc26c92ee022d7d7eac7428a113aa0be3a2
[ "MIT" ]
null
null
null
projects/Skeleton/code/exampleapp.cc
Destinum/S0008E
25344cc26c92ee022d7d7eac7428a113aa0be3a2
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // exampleapp.cc // (C) 2015-2018 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "config.h" #include "exampleapp.h" #include "NAX3parser.h" #include "nvx2fileformatstructs.h" //#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <cstring> #include <sstream> const GLchar* vs = "#version 430\n" "layout(location=0) in vec4 pos;\n" "layout(location=1) in vec4 color;\n" "layout(location=2) in vec2 InTexture;\n" "layout(location=3) in vec4 Weights;\n" "layout(location=4) in ivec4 Indices;\n" "layout(location=5) in vec4 Normals;\n" "layout(location=6) in vec4 Tangents;\n" "layout(location=7) in vec4 Bitangents;\n" "out vec2 TextureCoordinates;\n" "out vec4 VertexPosition;\n" "out mat3 TBN;\n" "uniform mat4 MVP;\n" "uniform mat4 ListOfJoints[21];\n" "uniform int ListOfIndices[21];\n" "uniform mat4 ScaleMatrix;\n" "uniform int JointIndex;\n" "void main()\n" "{\n" " vec4 Weights2 = Weights / 255.0;\n" " mat4 BoneTransformation = ListOfJoints[ListOfIndices[Indices[0]]] * Weights2[0];\n" " BoneTransformation += ListOfJoints[ListOfIndices[Indices[1]]] * Weights2[1];\n" " BoneTransformation += ListOfJoints[ListOfIndices[Indices[2]]] * Weights2[2];\n" " BoneTransformation += ListOfJoints[ListOfIndices[Indices[3]]] * Weights2[3];\n" //Use these 5 lines to apply animation " vec4 ThePos = BoneTransformation * pos;\n" " vec3 T = normalize((BoneTransformation * Tangents).xyz);\n" " vec3 B = normalize((BoneTransformation * Bitangents).xyz);\n" " vec3 N = normalize((BoneTransformation * Normals).xyz);\n" " TBN = transpose(mat3(T, B, N));\n" /* //Use these 5 lines to remove animation " vec4 ThePos = pos;\n" " vec3 T = normalize(Tangents.xyz);\n" " vec3 B = normalize(Bitangents.xyz);\n" " vec3 N = normalize(Normals.xyz);\n" " TBN = transpose(mat3(T, B, N));\n" */ " gl_Position = MVP * ThePos;\n" " VertexPosition = ThePos;\n" " TextureCoordinates = InTexture;\n" "}\n"; const GLchar* ps = "#version 430\n" "out vec4 color;\n" "struct Material\n" "{\n" " sampler2D diffuse;\n" " sampler2D specular;\n" " sampler2D normal;\n" "};\n" "struct Light\n" "{\n" " vec4 position;\n" " vec4 ambient;\n" " vec4 diffuse;\n" " vec4 specular;\n" " float LightStrength;\n" "};\n" "in vec2 TextureCoordinates;\n" "in vec4 VertexPosition;\n" "in mat3 TBN;\n" "uniform Material TheMaterial;\n" "uniform Light LightSource;\n" "uniform vec4 CameraPosition;\n" "void main()\n" "{\n" // normal " vec3 normal = normalize(texture(TheMaterial.normal, TextureCoordinates).rgb * 2.0 - 1.0);\n" // ambient " vec4 TheColor = texture(TheMaterial.diffuse, TextureCoordinates);\n" " vec4 ambient = LightSource.ambient * TheColor;\n" // diffuse " vec3 LightDirection = normalize(TBN * LightSource.position.xyz - TBN * VertexPosition.xyz);\n" " float diff = max(dot(normal, LightDirection), 0.0);\n" " vec4 diffuse = LightSource.diffuse * LightSource.LightStrength * diff * TheColor;\n" // specular " vec3 ViewDirection = normalize(TBN * CameraPosition.xyz - TBN * VertexPosition.xyz);\n" " vec3 ReflectDirection = reflect(-LightDirection, normal);\n" " float spec = pow(max(dot(ViewDirection, ReflectDirection), 0.0), 64.0);\n" " vec4 specular = LightSource.specular * spec * texture(TheMaterial.specular, TextureCoordinates);\n" " color = ambient + diffuse + specular;\n" "}\n"; using namespace Display; namespace Example { //------------------------------------------------------------------------------ /** */ ExampleApp::ExampleApp() { // empty } //------------------------------------------------------------------------------ /** */ ExampleApp::~ExampleApp() { // empty } //------------------------------------------------------------------------------ /** */ bool ExampleApp::Open() { App::Open(); this->window = new Display::Window; // window->SetKeyPressFunction([this](int32, int32, int32, int32) // { // this->window->Close(); // }); /* GLfloat buf[] = { -0.5f, -0.5f, -1, 1, // pos 0 0, 0.5f, -1, 1, // pos 1 0.5f, -0.5f, -1, 1 // pos 2 }; GLfloat bufColor[] = { 1, 0, 0, 1, // color 0 0, 1, 0, 1, // color 1 0, 0, 1, 1 // color 2 }; */ if (this->window->Open()) { // set clear color to gray glClearColor(0.1f, 0.1f, 0.1f, 1.0f); // setup vertex shader this->vertexShader = glCreateShader(GL_VERTEX_SHADER); GLint length = std::strlen(vs); glShaderSource(this->vertexShader, 1, &vs, &length); glCompileShader(this->vertexShader); // get error log GLint shaderLogSize; glGetShaderiv(this->vertexShader, GL_INFO_LOG_LENGTH, &shaderLogSize); if (shaderLogSize > 0) { GLchar* buf = new GLchar[shaderLogSize]; glGetShaderInfoLog(this->vertexShader, shaderLogSize, NULL, buf); printf("[SHADER COMPILE ERROR]: %s", buf); delete[] buf; } // setup pixel shader this->pixelShader = glCreateShader(GL_FRAGMENT_SHADER); length = std::strlen(ps); glShaderSource(this->pixelShader, 1, &ps, &length); glCompileShader(this->pixelShader); // get error log //shaderLogSize; glGetShaderiv(this->pixelShader, GL_INFO_LOG_LENGTH, &shaderLogSize); if (shaderLogSize > 0) { GLchar* buf = new GLchar[shaderLogSize]; glGetShaderInfoLog(this->pixelShader, shaderLogSize, NULL, buf); printf("[SHADER COMPILE ERROR]: %s", buf); delete[] buf; } // create a program object this->program = glCreateProgram(); glAttachShader(this->program, this->vertexShader); glAttachShader(this->program, this->pixelShader); glLinkProgram(this->program); glGetProgramiv(this->program, GL_INFO_LOG_LENGTH, &shaderLogSize); if (shaderLogSize > 0) { GLchar* buf = new GLchar[shaderLogSize]; glGetProgramInfoLog(this->program, shaderLogSize, NULL, buf); printf("[PROGRAM LINK ERROR]: %s", buf); delete[] buf; } this->MatrixID = glGetUniformLocation(this->program, "MVP"); //Added stuff this->CameraPositionID = glGetUniformLocation(this->program, "CameraPosition"); this->TheJoints = glGetUniformLocation(this->program, "ListOfJoints"); /* //setup vbo glGenBuffers(1, &this->triangle); glBindBuffer(GL_ARRAY_BUFFER, this->triangle); glBufferData(GL_ARRAY_BUFFER, sizeof(buf), buf, GL_STATIC_DRAW); glGenBuffers(1, &this->color); glBindBuffer(GL_ARRAY_BUFFER, this->color); glBufferData(GL_ARRAY_BUFFER, sizeof(bufColor), bufColor, GL_STATIC_DRAW); */ glBindBuffer(GL_ARRAY_BUFFER, 0); return true; } return false; } //------------------------------------------------------------------------------ /** */ // // // void ExampleApp::computeMatricesFromInputs(){ // glfwGetTime is called only once, the first time this function is called static double theLastTime = glfwGetTime(); // Compute time difference between current and last frame double theCurrentTime = glfwGetTime(); float theDeltaTime = float(theCurrentTime - theLastTime); //cout << theDeltaTime << endl; // Get mouse position double xpos, ypos; glfwGetCursorPos(this->window->window, &xpos, &ypos); // Reset mouse position for next frame glfwSetCursorPos(this->window->window, 1024/2, 768/2); // Compute new orientation horizontalAngle += mouseSpeed * float(1024/2 - xpos ); verticalAngle += mouseSpeed * float( 768/2 - ypos ); // Direction : Spherical coordinates to Cartesian coordinates conversion Vector3D direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle), 0 ); // Right vector Vector3D right( sin(horizontalAngle - 3.14f/2.0f), 0, cos(horizontalAngle - 3.14f/2.0f), 0 ); // Up vector Vector3D up = right.CrossProduct(direction); // Move forward if (glfwGetKey( window->window, GLFW_KEY_UP ) == GLFW_PRESS || glfwGetKey( window->window, GLFW_KEY_W ) == GLFW_PRESS){ position = position + direction * theDeltaTime * speed; } // Move backward if (glfwGetKey( window->window, GLFW_KEY_DOWN ) == GLFW_PRESS || glfwGetKey( window->window, GLFW_KEY_S ) == GLFW_PRESS){ position = position - direction * theDeltaTime * speed; } // Strafe right if (glfwGetKey( window->window, GLFW_KEY_RIGHT ) == GLFW_PRESS || glfwGetKey( window->window, GLFW_KEY_D ) == GLFW_PRESS){ position = position + right * theDeltaTime * speed; } // Strafe left if (glfwGetKey( window->window, GLFW_KEY_LEFT ) == GLFW_PRESS || glfwGetKey( window->window, GLFW_KEY_A ) == GLFW_PRESS){ position = position - right * theDeltaTime * speed; } this->Projection = Projection.ProjectionMatrix(initialFoV, 4.0f/3.0f, 0.1f, 100.0f); this->View = View.ViewMatrix(position, position + direction, up); this->MVP = Projection * View; glUniformMatrix4fv(this->MatrixID, 1, GL_FALSE, &(this->MVP).matris[0][0]); glUniform4f(this->CameraPositionID, position.vektor[0], position.vektor[1], position.vektor[2], position.vektor[3]); // For the next frame, the "last time" will be "now" theLastTime = theCurrentTime; } // // // vector<float> SplitAndConvertToFloat(std::string strToSplit, char delimeter) { std::stringstream ss(strToSplit); string item; //char* end = delimiter; std::vector<float> splittedStringsAsFloats; while (std::getline(ss, item, delimeter)) { const char* itemAsChar = item.c_str(); float value = atof(itemAsChar); splittedStringsAsFloats.push_back(value); } return splittedStringsAsFloats; } void ExampleApp::AssignElementToJoint(const tinyxml2::XMLElement* theElement) { int index; theElement->QueryIntAttribute("index", &index); int ParentIndex; //theElement->QueryIntAttribute("parent", &ListOfJoints[index].parent); theElement->QueryIntAttribute("parent", &ParentIndex); ListOfJoints[index].parent = ParentIndex; if (ParentIndex >= 0) ListOfJoints[ParentIndex].ListOfChildren.push_back(index); const char* JointName; theElement->QueryStringAttribute("name", &JointName); ListOfJoints[index].name = JointName; const char* title; theElement->QueryStringAttribute("position", &title); ListOfJoints[index].VectorOfCoordinates = SplitAndConvertToFloat(title, ','); theElement->QueryStringAttribute("rotation", &title); vector<float> VectorOfRotations = SplitAndConvertToFloat(title, ','); ListOfJoints[index].rotation.vektor[0] = VectorOfRotations[0]; ListOfJoints[index].rotation.vektor[1] = VectorOfRotations[1]; ListOfJoints[index].rotation.vektor[2] = VectorOfRotations[2]; ListOfJoints[index].rotation.vektor[3] = VectorOfRotations[3]; Matrix3D TranslationMatrix; TranslationMatrix.matris[3][0] = ListOfJoints[index].VectorOfCoordinates[0]; TranslationMatrix.matris[3][1] = ListOfJoints[index].VectorOfCoordinates[1]; TranslationMatrix.matris[3][2] = ListOfJoints[index].VectorOfCoordinates[2]; if (index > 0) { TranslationMatrix = ListOfJoints[ListOfJoints[index].parent].coordinates * TranslationMatrix; } Matrix3D RotationMatrix = RotationMatrix.QuaternionToMatrix(ListOfJoints[index].rotation); ListOfJoints[index].coordinates = TranslationMatrix * RotationMatrix; ListOfJoints[index].InverseBindPose = ListOfJoints[index].coordinates.inverse(); } bool ExampleApp::loadOBJ(const char * path, vector<Vector3D> & out_vertices, vector<Vector2D> & out_uvs, vector<Vector3D> & out_normals) { printf("Loading OBJ file %s...\n", path); vector<unsigned int> vertexIndices, uvIndices, normalIndices; vector<Vector3D> temp_vertices; vector<Vector2D> temp_uvs; vector<Vector3D> temp_normals; FILE * file = fopen(path, "r"); if( file == NULL ){ printf("Impossible to open the file ! Are you in the right path ? See Tutorial 1 for details\n"); getchar(); return false; } while( 1 ){ char lineHeader[128]; // read the first word of the line int res = fscanf(file, "%s", lineHeader); if (res == EOF) break; // EOF = End Of File. Quit the loop. // else : parse lineHeader if ( strcmp( lineHeader, "v" ) == 0 ){ Vector3D vertex; fscanf(file, "%f %f %f\n", &vertex.vektor[0], &vertex.vektor[1], &vertex.vektor[2]); temp_vertices.push_back(vertex); }else if ( strcmp( lineHeader, "vt" ) == 0 ){ Vector2D uv; fscanf(file, "%f %f\n", &uv.vektor[0], &uv.vektor[1]); uv.vektor[1] = -uv.vektor[1]; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders. temp_uvs.push_back(uv); }else if ( strcmp( lineHeader, "vn" ) == 0 ){ Vector3D normal; fscanf(file, "%f %f %f\n", &normal.vektor[0], &normal.vektor[1], &normal.vektor[2] ); temp_normals.push_back(normal); }else if ( strcmp( lineHeader, "f" ) == 0 ){ string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], normalIndex[3]; int matches = fscanf(file, "%d//%d %d//%d %d//%d\n", &vertexIndex[0], &normalIndex[0], &vertexIndex[1], &normalIndex[1], &vertexIndex[2], &normalIndex[2] ); if (matches != 6){ printf("File can't be read by our simple parser :-( Try exporting with other options\n"); fclose(file); return false; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); // uvIndices.push_back(uvIndex[0]); // uvIndices.push_back(uvIndex[1]); // uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); }else{ // Probably a comment, eat up the rest of the line char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } // For each vertex of each triangle for( unsigned int i=0; i<vertexIndices.size(); i++ ){ // Get the indices of its attributes unsigned int vertexIndex = vertexIndices[i]; //unsigned int uvIndex = uvIndices[i]; unsigned int normalIndex = normalIndices[i]; // Get the attributes thanks to the index Vector3D vertex = temp_vertices[ vertexIndex-1 ]; //Vector2D uv = temp_uvs[ uvIndex-1 ]; Vector3D normal = temp_normals[ normalIndex-1 ]; // Put the attributes in buffers out_vertices.push_back(vertex); //out_uvs.push_back(uv); out_normals.push_back(normal); } fclose(file); return true; } void ExampleApp::UpdateChildren(int index) { for (size_t i = 0; i < ListOfJoints[index].ListOfChildren.size(); i++) { int ChildIndex = ListOfJoints[index].ListOfChildren[i]; Matrix3D TranslationMatrix; TranslationMatrix.matris[3][0] = ListOfJoints[ChildIndex].VectorOfCoordinates[0]; TranslationMatrix.matris[3][1] = ListOfJoints[ChildIndex].VectorOfCoordinates[1]; TranslationMatrix.matris[3][2] = ListOfJoints[ChildIndex].VectorOfCoordinates[2]; TranslationMatrix = ListOfJoints[index].coordinates * TranslationMatrix; Matrix3D RotationMatrix = RotationMatrix.QuaternionToMatrix(ListOfJoints[ChildIndex].rotation); ListOfJoints[ChildIndex].coordinates = TranslationMatrix * RotationMatrix; UpdateChildren(ChildIndex); } } void ExampleApp::ChangeAnimation(int* AnimationIndex, int* AnimationFrame) { if (glfwGetKey( window->window, GLFW_KEY_1 ) == GLFW_PRESS && *AnimationIndex != 0) { *AnimationIndex = 0; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_2 ) == GLFW_PRESS && *AnimationIndex != 1) { *AnimationIndex = 1; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_3 ) == GLFW_PRESS && *AnimationIndex != 2) { *AnimationIndex = 2; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_4 ) == GLFW_PRESS && *AnimationIndex != 3) { *AnimationIndex = 3; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_5 ) == GLFW_PRESS && *AnimationIndex != 4) { *AnimationIndex = 4; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_6 ) == GLFW_PRESS && *AnimationIndex != 5) { *AnimationIndex = 5; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_7 ) == GLFW_PRESS && *AnimationIndex != 6) { *AnimationIndex = 6; *AnimationFrame = 0; } else if (glfwGetKey( window->window, GLFW_KEY_8 ) == GLFW_PRESS && *AnimationIndex != 7) { *AnimationIndex = 7; *AnimationFrame = 0; } } unsigned int ExampleApp::LoadTexture(char const* filepath) { unsigned int texture; glGenTextures(1, &texture); // load and generate the texture int width, height, nrChannels; unsigned char *data = stbi_load(filepath, &width, &height, &nrChannels, 0); if (data) { glBindTexture(GL_TEXTURE_2D, texture); if (nrChannels == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); return texture; } Vector3D ExampleApp::Slerp(Vector3D Quaternion1, Vector3D Quaternion2, float t) { Vector3D Out; float theta, mult1, mult2; float dotProduct = Quaternion1.vektor[0] * Quaternion2.vektor[0] + Quaternion1.vektor[1] * Quaternion2.vektor[1] + Quaternion1.vektor[2] * Quaternion2.vektor[2] + Quaternion1.vektor[3] * Quaternion2.vektor[3]; if(dotProduct < 0.0) { Quaternion2 = Quaternion2 * -1.0; Quaternion2.vektor[3] *= -1.0; dotProduct *= -1.0; } theta = acos(dotProduct); if (theta > 0.0) { mult1 = sin((1.0-t) * theta) / sin(theta); mult2 = sin(t * theta) / sin(theta); } else { mult1 = 1.0 - t; mult2 = t; } Out.vektor[0] = mult1*Quaternion1.vektor[0] + mult2*Quaternion2.vektor[0]; Out.vektor[1] = mult1*Quaternion1.vektor[1] + mult2*Quaternion2.vektor[1]; Out.vektor[2] = mult1*Quaternion1.vektor[2] + mult2*Quaternion2.vektor[2]; Out.vektor[3] = mult1*Quaternion1.vektor[3] + mult2*Quaternion2.vektor[3]; return Out; } void ExampleApp::Run() { glUseProgram(this->program); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); tinyxml2::XMLDocument doc; const char* filepath = "../projects/Skeleton/footman/Unit_Footman.constants"; tinyxml2::XMLError eResult = doc.LoadFile(filepath); if (eResult != tinyxml2::XML_SUCCESS) cout << "No loaded file" << endl; const tinyxml2::XMLElement* theElement = doc.FirstChildElement()->FirstChildElement()->FirstChildElement()->FirstChildElement()->FirstChildElement(); for(int i = 0; i < 21; i++) { theElement = theElement->NextSiblingElement(); AssignElementToJoint(theElement); } GLint ListOfIndexes[21]; theElement = doc.FirstChildElement()->FirstChildElement()->FirstChildElement()->NextSiblingElement()->FirstChildElement()->FirstChildElement()->FirstChildElement(); const char* str = theElement->GetText(); vector<float> VectorOfIndexes = SplitAndConvertToFloat(str, ','); for (int i = 0; i < 21; i++) ListOfIndexes[i] = VectorOfIndexes[i]; glUniform1iv(glGetUniformLocation(this->program, "ListOfIndices"), 21, &ListOfIndexes[0]); // Read the .obj file const char* filepathOfObject = "../projects/Skeleton/Mesh/sphere.obj"; vector<Vector3D> vertices; vector<Vector2D> uvs; vector<Vector3D> normals; // Won't be used at the moment. //bool res = ExampleApp::loadOBJ(filepathOfObject, vertices, uvs, normals); ExampleApp::loadOBJ(filepathOfObject, vertices, uvs, normals); int SizeOfList = vertices.size()*4; float *ListToBuffer = new float[SizeOfList]; for (size_t i = 0; i < vertices.size(); i++) { int n = i*4; ListToBuffer[n] = vertices[i].vektor[0]; ListToBuffer[n + 1] = vertices[i].vektor[1]; ListToBuffer[n + 2] = vertices[i].vektor[2]; ListToBuffer[n + 3] = vertices[i].vektor[3]; } GLuint ObjectVertexBuffer; glGenBuffers(1, &ObjectVertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, ObjectVertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(ListToBuffer), ListToBuffer, GL_STATIC_DRAW); delete [] ListToBuffer; GLuint LinesBuffer; glGenBuffers(1, &LinesBuffer); const char* nvx2filepath = "../projects/Skeleton/footman/Unit_Footman.nvx2"; CoreGraphics::nvx2parser ModelParser; ModelParser.SetupFromNvx2(nvx2filepath); const char* NAX3filepath = "../projects/Skeleton/footman/Unit_Footman.nax3"; CoreAnimation::NAX3parser AnimationParser; AnimationParser.SetupFromNax3(NAX3filepath); //int First = AnimationParser.ListOfClips.size(); //int Second = AnimationParser.ListOfKeys.size(); //int Third = AnimationParser.ListOfCurves.size(); unsigned int diffuse = LoadTexture("../projects/Skeleton/footman/Footman_Diffuse.tga"); unsigned int specular = LoadTexture("../projects/Skeleton/footman/Footman_Specular.tga"); unsigned int normal = LoadTexture("../projects/Skeleton/footman/Footman_Normal.tga"); glUniform1i(glGetUniformLocation(this->program, "TheMaterial.diffuse"), 0); glUniform1i(glGetUniformLocation(this->program, "TheMaterial.specular"), 1); glUniform1i(glGetUniformLocation(this->program, "TheMaterial.normal"), 2); Vector3D ThisLightPosition(-2.0f, 4.0f, 0.0f, 1.0); glUniform4f(glGetUniformLocation(this->program, "LightSource.position"), -2.0f, 4.0f, 0.0f, 1.0); glUniform4f(glGetUniformLocation(this->program, "LightSource.ambient"), 0.01f, 0.01f, 0.01f, 1.0); glUniform4f(glGetUniformLocation(this->program, "LightSource.diffuse"), 1.0f, 1.0f, 1.0f, 1.0); glUniform4f(glGetUniformLocation(this->program, "LightSource.specular"), 10.0f, 10.0f, 10.0f, 1.0); glUniform1f(glGetUniformLocation(this->program, "LightSource.LightStrength"), 1.5f); float TimeBetweenFrames = 0.1; while (this->window->IsOpen()) { static int AnimationIndex = 6; static double lastTime = glfwGetTime(); static int AnimationFrame = 0; ChangeAnimation(&AnimationIndex, &AnimationFrame); // Compute time difference between current and last frame double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); if (deltaTime > TimeBetweenFrames) { deltaTime = TimeBetweenFrames; } float t = deltaTime*10.0; for (int index = 0; index < 21; index++) { int currentKeyIndex = (AnimationParser.CurrentAnimationPosition[AnimationIndex] + AnimationFrame) * 84 + index * 4; //- 1 ?????????? int nextKeyIndex; if (AnimationFrame + 1 >= AnimationParser.ListOfClips[AnimationIndex].numKeys) nextKeyIndex = AnimationParser.CurrentAnimationPosition[AnimationIndex] * 84 + index * 4; else nextKeyIndex = (AnimationParser.CurrentAnimationPosition[AnimationIndex] + AnimationFrame + 1) * 84 + index * 4; //- 1 ?????????? Matrix3D TranslationMatrix; ListOfJoints[index].VectorOfCoordinates[0] = TranslationMatrix.matris[3][0] = AnimationParser.ListOfKeys[currentKeyIndex].vektor[0] + t*(AnimationParser.ListOfKeys[nextKeyIndex].vektor[0] - AnimationParser.ListOfKeys[currentKeyIndex].vektor[0]); ListOfJoints[index].VectorOfCoordinates[1] = TranslationMatrix.matris[3][1] = AnimationParser.ListOfKeys[currentKeyIndex].vektor[1] + t*(AnimationParser.ListOfKeys[nextKeyIndex].vektor[1] - AnimationParser.ListOfKeys[currentKeyIndex].vektor[1]); ListOfJoints[index].VectorOfCoordinates[2] = TranslationMatrix.matris[3][2] = AnimationParser.ListOfKeys[currentKeyIndex].vektor[2] + t*(AnimationParser.ListOfKeys[nextKeyIndex].vektor[2] - AnimationParser.ListOfKeys[currentKeyIndex].vektor[2]); if (index > 0) TranslationMatrix = ListOfJoints[ListOfJoints[index].parent].coordinates * TranslationMatrix; Vector3D RotationVectorCurrent(AnimationParser.ListOfKeys[currentKeyIndex + 1].vektor[0], AnimationParser.ListOfKeys[currentKeyIndex + 1].vektor[1], AnimationParser.ListOfKeys[currentKeyIndex + 1].vektor[2], AnimationParser.ListOfKeys[currentKeyIndex + 1].vektor[3]); Vector3D RotationVectorNext(AnimationParser.ListOfKeys[nextKeyIndex + 1].vektor[0], AnimationParser.ListOfKeys[nextKeyIndex + 1].vektor[1], AnimationParser.ListOfKeys[nextKeyIndex + 1].vektor[2], AnimationParser.ListOfKeys[nextKeyIndex + 1].vektor[3]); Vector3D RotationVectorSlerped = Slerp(RotationVectorCurrent, RotationVectorNext, t); Matrix3D RotationMatrix = RotationMatrix.QuaternionToMatrix(RotationVectorSlerped); ListOfJoints[index].coordinates = TranslationMatrix * RotationMatrix; } if (deltaTime >= TimeBetweenFrames) { lastTime = currentTime; /* Matrix3D RotationMatrix = RotationMatrix.QuaternionToMatrix(Vector3D( 0.0174524, 0, 0, 0.9998477)); ListOfJoints[5].coordinates = ListOfJoints[5].coordinates * RotationMatrix; UpdateChildren(5); ListOfJoints[9].coordinates = ListOfJoints[9].coordinates * RotationMatrix; UpdateChildren(9); */ AnimationFrame += 1; if(AnimationFrame >= AnimationParser.ListOfClips[AnimationIndex].numKeys) { AnimationFrame = 0; } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); this->window->Update(); // do stuff computeMatricesFromInputs(); glEnableVertexAttribArray(0); int JointsRendered = 21; Matrix3D *JointCoordinates = new Matrix3D[JointsRendered]; for (int i = 0; i < JointsRendered; i++) { JointCoordinates[i] = ListOfJoints[i].coordinates * ListOfJoints[i].InverseBindPose; } glUniformMatrix4fv(this->TheJoints, JointsRendered, GL_FALSE, &(JointCoordinates[0]).matris[0][0]); delete [] JointCoordinates; /* glBindBuffer(GL_ARRAY_BUFFER, ObjectVertexBuffer); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); Matrix3D ScaleMatrix; ScaleMatrix.matris[0][0] = ScaleMatrix.matris[1][1] = ScaleMatrix.matris[2][2] = 0.03; glUniformMatrix4fv(glGetUniformLocation(this->program, "ScaleMatrix"), 1, GL_FALSE, &ScaleMatrix.matris[0][0]); for(int i = 1; i < JointsRendered; i++) { //glUniformMatrix4fv(this->MatrixID, 1, GL_FALSE, &(this->MVP * ListOfJoints[i].coordinates * ScaleMatrix).matris[0][0]); glUniform1i(glGetUniformLocation(program, "JointIndex"), i); glDrawArrays(GL_TRIANGLES, 0, vertices.size()); } glBindBuffer(GL_ARRAY_BUFFER, LinesBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); Matrix3D ScaleMatrix2; glUniformMatrix4fv(glGetUniformLocation(this->program, "ScaleMatrix"), 1, GL_FALSE, &ScaleMatrix2.matris[0][0]); for(int i = 2; i < JointsRendered; i++) { GLfloat lineVertices[] = { 0, 0, 0, ListOfJoints[i].VectorOfCoordinates[0], ListOfJoints[i].VectorOfCoordinates[1], ListOfJoints[i].VectorOfCoordinates[2] //ListOfJoints[i].coordinates.matris[3][0], ListOfJoints[i].coordinates.matris[3][1], ListOfJoints[i].coordinates.matris[3][2] }; glBufferData(GL_ARRAY_BUFFER, sizeof(lineVertices), lineVertices, GL_STATIC_DRAW); //glUniformMatrix4fv(this->MatrixID, 1, GL_FALSE, &(this->MVP * ListOfJoints[ ListOfJoints[i].parent].coordinates).matris[0][0]); glUniform1i(glGetUniformLocation(program, "JointIndex"), ListOfJoints[i].parent); glDrawArrays(GL_LINES, 0, 2); } /*/ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuse); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specular); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, normal); //glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); glEnableVertexAttribArray(7); glBindBuffer(GL_ARRAY_BUFFER, ModelParser.VertexBuffer); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 10 * sizeof(float), NULL); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 10 * sizeof(float), (void*)( 4 * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, ModelParser.BoneDataBuffer); glVertexAttribPointer(3, 4, GL_UNSIGNED_BYTE, GL_TRUE, 2 * sizeof(float), NULL); glVertexAttribIPointer(4, 4, GL_UNSIGNED_BYTE, 2 * sizeof(float), (void*)(sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, ModelParser.NormalsBuffer); glVertexAttribPointer(5, 4, GL_BYTE, GL_TRUE, 3 * sizeof(float), NULL); glVertexAttribPointer(6, 4, GL_BYTE, GL_TRUE, 3 * sizeof(float), (void*)(sizeof(float))); glVertexAttribPointer(7, 4, GL_BYTE, GL_TRUE, 3 * sizeof(float), (void*)(2 * sizeof(float))); glDrawArrays(GL_TRIANGLES, 0, ModelParser.vertices.size()); //glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); glDisableVertexAttribArray(5); glDisableVertexAttribArray(6); glDisableVertexAttribArray(7); glBindBuffer(GL_ARRAY_BUFFER, 0); //int index; glDisableVertexAttribArray(0); this->window->SwapBuffers(); //int index; } } } // namespace Example
31.247578
270
0.703434
Destinum
8a53496390cef3ad8175cb63e031a0dfd9f59a5f
3,667
ipp
C++
include/boost/url/impl/query_params_view.ipp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
include/boost/url/impl/query_params_view.ipp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
include/boost/url/impl/query_params_view.ipp
madmongo1/url
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/CPPAlliance/url // #ifndef BOOST_URL_IMPL_QUERY_PARAMS_VIEW_IPP #define BOOST_URL_IMPL_QUERY_PARAMS_VIEW_IPP #include <boost/url/query_params_view.hpp> #include <boost/url/error.hpp> #include <boost/url/rfc/query_bnf.hpp> #include <boost/url/rfc/detail/query_params_bnf.hpp> #include <boost/url/detail/except.hpp> namespace boost { namespace urls { query_params_view:: query_params_view() noexcept : s_("") , n_(0) { } query_params_view:: iterator:: iterator( string_view s) : next_(s.data()) , end_(s.data() + s.size()) { if(next_ == end_) { next_ = nullptr; return; } error_code ec; query_param t; detail:: query_params_bnf::begin( next_, end_, ec, t); if(ec) detail::throw_system_error( ec, BOOST_CURRENT_LOCATION); v_.k_ = t.key; if(t.value.has_value()) v_.v_ = *t.value; else v_.v_ = {}; } auto query_params_view:: iterator:: operator++() noexcept -> iterator& { error_code ec; query_param t; detail:: query_params_bnf::increment( next_, end_, ec, t); if(ec == error::end) { next_ = nullptr; return *this; } if(ec) detail::throw_system_error( ec, BOOST_CURRENT_LOCATION); v_.k_ = t.key; if(t.value.has_value()) v_.v_ = *t.value; else v_.v_ = {}; return *this; } //------------------------------------------------ auto query_params_view:: begin() const noexcept -> iterator { return iterator(s_); } auto query_params_view:: end() const noexcept -> iterator { return iterator( s_.data() + s_.size()); } bool query_params_view:: contains( string_view key) const noexcept { for(auto e : *this) if(key_equal_encoded( key, e.k_)) return true; return false; } std::size_t query_params_view:: count( string_view key) const noexcept { std::size_t n = 0; for(auto e : *this) if(key_equal_encoded( key, e.k_)) ++n; return n; } auto query_params_view:: find( string_view key) const noexcept -> iterator { auto it = begin(); for(auto const last = end(); it != last; ++it) if(key_equal_encoded( key, it->k_)) break; return it; } auto query_params_view:: find( iterator after, string_view key) const noexcept -> iterator { auto it = after; auto const last = end(); if(it != last) while(++it != last) if(key_equal_encoded( key, it->k_)) break; return it; } std::string query_params_view:: operator[](string_view key) const { auto const it = find(key); if(it == end()) return {}; return it->value(); } //------------------------------------------------ query_params_view parse_query_params( string_view s, error_code& ec) { using bnf::parse; bnf::range< query_param> t; if(! parse(s, ec, query_bnf{t})) return {}; return query_params_view( t.str(), t.size()); } query_params_view parse_query_params( string_view s) { error_code ec; auto qp = parse_query_params(s, ec); detail::maybe_throw(ec, BOOST_CURRENT_LOCATION); return qp; } } // urls } // boost #endif
18.243781
79
0.571312
madmongo1
8a566f4d950308abfecf489f13ed83efccfcf6da
1,824
cxx
C++
osprey/wgen/wgen_tracing.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/wgen/wgen_tracing.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/wgen/wgen_tracing.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2007 Google, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation, either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public License along * with this program; if not, write the Free Software Foundation, Inc., 59 * Temple Place - Suite 330, Boston MA 02111-1307, USA. * */ /************************************************************ * Tracing framework for wgen. * Outputs GIMPLE/WHIRL nodes to the trace file as * they are read/created. ************************************************************/ extern "C" { #include "gspin-wgen-interface.h" } #include <stdio.h> #include "tracing.h" #include "opcode.h" #include "mtypes.h" #include "wn.h" #include "ir_reader.h" #include "wgen_tracing.h" int WGEN_TRACE::gimple_depth = 0; static void print_indent(FILE *fp); static void print_indent(FILE *fp) { for (int i=0; i<WGEN_TRACE::gimple_depth; i++) { fprintf(fp, " "); } } void WGEN_TRACE::trace_gs(gs_t n) { if (Get_Trace(TKIND_IR, TP_WGEN)) { gs_code_t c = gs_tree_code(n); print_indent(TFile); fprintf(TFile, "--- %s\n", gs_code_name(c)); } } WN* WGEN_Trace_wn(WN *wn) { if (Get_Trace(TKIND_IR, TP_WGEN)) { print_indent(TFile); const char * fmt_str = (sizeof(INTPTR) == 8) ? "+++ (0x%016x) " : "+++ (0x%08x) "; fprintf(TFile, fmt_str, (INTPTR) wn); fdump_wn(TFile, wn); } return wn; }
26.823529
74
0.626096
sharugupta
8a5a0becb2b007360fbae6a5815ccee72605a31f
323
cpp
C++
tools/castdb.cpp
WatorVapor/wai.native.wator
e048df159e2952c143f8832264b20da20dcd88fa
[ "MIT" ]
null
null
null
tools/castdb.cpp
WatorVapor/wai.native.wator
e048df159e2952c143f8832264b20da20dcd88fa
[ "MIT" ]
null
null
null
tools/castdb.cpp
WatorVapor/wai.native.wator
e048df159e2952c143f8832264b20da20dcd88fa
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <list> #include <map> #include <string> #include <thread> #include <vector> using namespace std; #include "log.hpp" #include "parrotword.hpp" int main(int ac, char *av[]) { if(ac < 2) { return 0; } ParrotWord parrot(av[1]); parrot.loadMaster(); return 0; }
15.380952
30
0.659443
WatorVapor
8a5b032e14092f20dc627d58891152130540c7a0
3,998
cpp
C++
src/add-ons/media/plugins/asf_reader/ASFIndex.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
4
2016-03-29T21:45:21.000Z
2016-12-20T00:50:38.000Z
src/add-ons/media/plugins/asf_reader/ASFIndex.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
null
null
null
src/add-ons/media/plugins/asf_reader/ASFIndex.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
/* * Copyright (c) 2009, David McPaul * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ASFIndex.h" #include <stdio.h> void IndexEntry::Clear() { frameNo=0; noPayloads=0; dataSize=0; pts=0; keyFrame=false; } void IndexEntry::AddPayload(uint32 pdataSize) { noPayloads++; dataSize += pdataSize; } StreamEntry::StreamEntry() { lastID = 0; frameCount = 0; maxPTS = 0; duration = 0; } StreamEntry::~StreamEntry() { index.clear(); } void StreamEntry::setDuration(bigtime_t pduration) { duration = pduration; } IndexEntry StreamEntry::GetIndex(uint32 frameNo) { IndexEntry indexEntry; for (std::vector<IndexEntry>::iterator itr = index.begin(); itr != index.end(); ++itr) { if (itr->frameNo == frameNo) { indexEntry = *itr; break; } } return indexEntry; } bool StreamEntry::HasIndex(uint32 frameNo) { if (!index.empty()) { for (std::vector<IndexEntry>::iterator itr = index.begin(); itr != index.end(); ++itr) { if (itr->frameNo == frameNo) { return true; } } } return false; } IndexEntry StreamEntry::GetIndex(bigtime_t pts) { IndexEntry indexEntry; for (std::vector<IndexEntry>::iterator itr = index.begin(); itr != index.end(); ++itr) { if (pts <= itr->pts) { indexEntry = *itr; break; } } return indexEntry; } bool StreamEntry::HasIndex(bigtime_t pts) { if (!index.empty()) { for (std::vector<IndexEntry>::iterator itr = index.begin(); itr != index.end(); ++itr) { if (pts <= itr->pts) { return true; } } } return false; } /* Combine payloads with the same id into a single IndexEntry When isLast flag is set then no more payloads are available (ie add current entry to index) */ void StreamEntry::AddPayload(uint32 id, bool keyFrame, bigtime_t pts, uint32 dataSize, bool isLast) { if (isLast) { maxPTS = indexEntry.pts; if (frameCount > 0) { index.push_back(indexEntry); // printf("Stream %d added Index %ld PTS %Ld payloads %d\n",streamIndex, indexEntry.frameNo, indexEntry.pts, indexEntry.noPayloads); printf("Stream Index Loaded for Stream %d Max Frame %ld Max PTS %Ld size %ld\n",streamIndex, frameCount-1, maxPTS, index.size()); } } else { if (id != lastID) { if (frameCount != 0) { // add indexEntry to Index index.push_back(indexEntry); // printf("Stream %d added Index %ld PTS %Ld payloads %d\n",streamIndex, indexEntry.frameNo, indexEntry.pts, indexEntry.noPayloads); } lastID = id; indexEntry.Clear(); indexEntry.frameNo = frameCount++; indexEntry.keyFrame = keyFrame; indexEntry.pts = pts; indexEntry.dataSize = dataSize; indexEntry.noPayloads = 1; indexEntry.id = id; } else { indexEntry.AddPayload(dataSize); } } }
24.9875
135
0.6991
axeld
8a684dc8cf1b19a1411cea71cb87b24d86407f53
1,262
cpp
C++
render/Mesh.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
1
2021-07-25T15:10:39.000Z
2021-07-25T15:10:39.000Z
render/Mesh.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
null
null
null
render/Mesh.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
null
null
null
#include "Mesh.h" #include "IDriver3D.h" #include "RenderQue.h" #include "VertexBuffer.h" #include "IndexBuffer.h" #include "../world/Object.h" #include <assert.h> #include <stdlib.h> #include <memory.h> Mesh::Mesh() { m_pVB = NULL; m_pIB = NULL; m_pMaterials = NULL; m_nMtlCnt = 0; m_bLoaded = false; } Mesh::~Mesh() { if (m_pVB) { delete m_pVB; } if (m_pIB) { delete m_pIB; } SafeDeleteArr(m_pMaterials); } void Mesh::Render(Object *pObj, IDriver3D *pDriver, float fIntensity, const Vector3& vOffset) { for (int m=0; m<m_nMtlCnt; m++) { MaterialEntry *pEntry = RenderQue::GetEntry(RBUCKET_OPAQUE); if ( pEntry ) { pEntry->hTex = m_pMaterials[m].hTex; pEntry->startIndex = m_pMaterials[m].uIndexOffset; pEntry->primCount = m_pMaterials[m].uPrimCount; pEntry->pVB = m_pVB; pEntry->pIB = m_pIB; pEntry->mWorld = pObj->GetMatrixPtr(); pEntry->worldX = pObj->GetWorldX(); pEntry->worldY = pObj->GetWorldY(); } } } void Mesh::GetBounds(Vector3& vMin, Vector3& vMax) { vMin = m_Bounds[0]; vMax = m_Bounds[1]; }
22.535714
93
0.561807
kcat
8a6fd25118124aa9670922882a4e21dbd6785a30
8,770
cc
C++
src/cpu/ee/jit/jit.cc
GPUCode/ps2_emu
295e6def1ea0d58f1bf520332f986df5c8c92e02
[ "MIT" ]
10
2022-01-05T15:04:56.000Z
2022-02-23T05:59:44.000Z
src/cpu/ee/jit/jit.cc
GPUCode/ps2_emu
295e6def1ea0d58f1bf520332f986df5c8c92e02
[ "MIT" ]
null
null
null
src/cpu/ee/jit/jit.cc
GPUCode/ps2_emu
295e6def1ea0d58f1bf520332f986df5c8c92e02
[ "MIT" ]
null
null
null
#include <cpu/ee/jit/jit.h> #include <cpu/ee/ee.h> #include <fmt/core.h> namespace ee { namespace jit { JITCompiler::JITCompiler(EmotionEngine* parent) : ee(parent), irbuilder(parent) { } JITCompiler::~JITCompiler() { delete code; delete builder; } void JITCompiler::reset() { code = new asmjit::CodeHolder; code->init(runtime.environment()); code->setLogger(&logger); builder = new asmjit::x86::Assembler(code); /* Emit block dispatcher */ emit_block_dispatcher(); if (auto error = runtime.add(&entry, code); error) { common::Emulator::terminate("[JIT] Could not compile entry function!\n"); } fmt::print("{}\n", logger.data()); } void JITCompiler::emit_register_flush() { static asmjit::x86::Gp preserved[] = { asmjit::x86::rbx, asmjit::x86::r12, asmjit::x86::r13, asmjit::x86::r14, asmjit::x86::r15 }; for (auto& reg : preserved) builder->push(reg); } void JITCompiler::emit_register_restore() { static asmjit::x86::Gp preserved[] = { asmjit::x86::r15, asmjit::x86::r14, asmjit::x86::r13, asmjit::x86::r12, asmjit::x86::rbx }; for (auto& reg : preserved) builder->pop(reg); } void __attribute__((noinline)) test() { return; } BlockFunc JITCompiler::emit_native(IRBlock& block) { BlockFunc handler = nullptr; logger.clear(); /* Init the asmjit code buffer */ code->reset(); code->init(runtime.environment()); code->setLogger(&logger); code->attach(builder); auto block_end = builder->newLabel(); auto block_epilogue = builder->newLabel(); auto dec_pc = builder->newLabel(); /* Push new stack frame for our block */ builder->push(asmjit::x86::rbp); builder->mov(asmjit::x86::rbp, asmjit::x86::rsp); //builder->sub(asmjit::x86::rsp, 0x1B8); //emit_register_flush(); /* Set EE PC to the start of the block */ builder->mov(asmjit::x86::rbx, asmjit::x86::rdi); auto pc_ptr = asmjit::x86::dword_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, pc)); builder->mov(pc_ptr, block.pc); for (int i = 0; i < block.size(); i++) { auto& instr = block[i]; switch (instr.operation) { case IROperation::None: break; default: emit_fallback(instr); } /* Normally in the interpreter the pc is always 2 instructions ahead of the * one currently being executed, assuming no branches. This causes problems * in the JIT if the instruction uses fetch_next() to direct jump, as that * increments the pc, causing the JIT to skip the first instruction of the branch. */ if (block[i].operation == IROperation::ExceptionReturn || block[i].operation == IROperation::Syscall) { builder->sub(pc_ptr, 4); } /* When a branch likely instructions fails the delay slot is skipped! */ if (block[i].operation == IROperation::BranchLikely) { auto skip_ptr = asmjit::x86::byte_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, skip_branch_delay)); builder->cmp(skip_ptr, 1); builder->mov(skip_ptr, 0); builder->je(dec_pc); } } builder->bind(block_epilogue); /* Decrement cycles counter in the EE */ auto cycles_ptr = asmjit::x86::dword_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, cycles_to_execute)); builder->sub(cycles_ptr, block.total_cycles); /* Move the PC forward by the block size, ONLY if a jump didn't occur */ auto taken_ptr = asmjit::x86::byte_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, branch_taken)); builder->cmp(taken_ptr, 1); builder->mov(taken_ptr, 0); builder->je(block_end); builder->mov(pc_ptr, block.pc + block.instructions.size() * 4); builder->bind(block_end); /* Clean up stack before exiting */ //emit_register_restore(); //builder->add(asmjit::x86::rsp, 0x1B8); builder->pop(asmjit::x86::rbp); builder->ret(); /* Decrement pc to account for the call to fetch_next and * jump directly to the epilogue */ builder->bind(dec_pc); builder->sub(pc_ptr, 4); builder->jmp(block_epilogue); /* Build! */ if (auto error = runtime.add(&handler, code); error) { common::Emulator::terminate("[JIT] Could not compile block at PC: {:#x}\n", block.pc); } //fmt::print("{}\n", logger.data()); return handler; } void JITCompiler::emit_fallback(IRInstruction& instr) { /* The interpreter functions were written to not depend too much on internal * state, so we only need to update the instr to make sure branches read correct * values */ auto instr_pc_ptr = asmjit::x86::dword_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, instr) + offsetof(Instruction, pc)); auto instr_value_ptr = asmjit::x86::dword_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, instr) + offsetof(Instruction, value)); builder->mov(instr_pc_ptr, instr.pc); builder->mov(instr_value_ptr, instr.value); builder->call(reinterpret_cast<uint64_t>(instr.handler)); builder->mov(asmjit::x86::rdi, asmjit::x86::rbx); /* Sometimes an instruction might write to GPR[0]. To avoid branches, reset the register each time */ //builder->mov(asmjit::x86::qqword_ptr(asmjit::x86::rdi, offsetof(EmotionEngine, gpr[0])), 0); } /* Look up the block cache for the block */ BlockFunc lookup_next_block(EmotionEngine* ee) { uint32_t pc = ee->pc; JITCompiler* compiler = ee->compiler; //fmt::print("[JIT] Searching for block at PC: {:#x}\n", pc); BlockFunc block = nullptr; if (auto result = compiler->block_cache.find(pc); result == compiler->block_cache.end()) { /* Block not found, recompile it */ IRBlock ir_block = compiler->irbuilder.generate(pc); block = compiler->emit_native(ir_block); compiler->block_cache[pc] = block; } else { block = result->second; } return block; } void JITCompiler::run() { entry(ee); } /* This function is responsible for emitting a dispatcher that attempts to find and directly execute the next block in the instruction stream. */ void JITCompiler::emit_block_dispatcher() { asmjit::Label loop_start = builder->newLabel(); /* do { BlockFunc block = lookup_next_block(ee); block(ee); } while (ee->cycles_to_execute > 0); */ auto cycles_ptr = asmjit::x86::dword_ptr(asmjit::x86::rbx, offsetof(EmotionEngine, cycles_to_execute)); builder->push(asmjit::x86::rbx); builder->mov(asmjit::x86::rbx, asmjit::x86::rdi); builder->bind(loop_start); /* Call lookup_next_block */ builder->mov(asmjit::x86::rdi, asmjit::x86::rbx); builder->call(reinterpret_cast<uint64_t>(lookup_next_block)); builder->mov(asmjit::x86::rdi, asmjit::x86::rbx); builder->call(asmjit::x86::rax); builder->cmp(cycles_ptr, 0); builder->jg(loop_start); builder->pop(asmjit::x86::rbx); builder->ret(); } } }
36.239669
120
0.513683
GPUCode
8a7cb17b4de37c1fb1adbddaf6410a71b4414e53
582
cpp
C++
solutions/1123/20110410T130623Z-3528299.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
11
2019-10-29T15:34:53.000Z
2022-03-14T14:45:09.000Z
solutions/1123/20110410T130623Z-3528299.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
null
null
null
solutions/1123/20110410T130623Z-3528299.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
6
2018-06-30T12:06:55.000Z
2021-03-20T08:46:33.000Z
#include <stdio.h> #include <iostream> #include <string> using namespace std; int n; string s; void foo(int k){ if(s[k]=='9') { for(int i=k; i<s.length(); i++) s[i]='0'; foo(k-1); } else { s[k]++; for(int i=k+1; i<s.length(); i++) s[i]='0'; } } int main() { cin >> s; n=(s.length()+1)/2; for(int i=n, j=n-1-s.length()%2; i<s.length(); i++,j--) { if(s[i]>s[j]) { foo(n-1); break; } else if(s[i]!=s[j]) break; } for(int i=s.length()-1, j=0; i>=n; i--,j++) { s[i]=s[j]; } cout << s; system("pause"); return 0; }
17.117647
59
0.457045
Mistereo
8a8228898202665dc9ab210d25a6227d9230b5bd
10,787
cpp
C++
src/main.cpp
gruppe-adler/grad_replay_intercept
000dcf97b113a8e139d0d7d099d4477401b5c480
[ "MIT" ]
null
null
null
src/main.cpp
gruppe-adler/grad_replay_intercept
000dcf97b113a8e139d0d7d099d4477401b5c480
[ "MIT" ]
null
null
null
src/main.cpp
gruppe-adler/grad_replay_intercept
000dcf97b113a8e139d0d7d099d4477401b5c480
[ "MIT" ]
null
null
null
#include <intercept.hpp> #include "ReplayPart.h" #include <nlohmann/json.hpp> #include <cpr/cpr.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> // Gzip #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <string> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <ctime> #include <chrono> #include <filesystem> #include <memory> #include <algorithm> #include "../addons/main/script_version.hpp" static inline std::string GRAD_REPLAY_USER_AGENT = "grad_replay_intercept/" + std::to_string(MAJOR) + "." + std::to_string(MINOR) + "." + std::to_string(PATCHLVL) + "." + std::to_string(BUILD); namespace nl = nlohmann; namespace fs = std::filesystem; namespace bi = boost::iostreams; using namespace intercept; using namespace grad::replay; using SQFPar = game_value_parameter; std::string url = ""; std::string token = ""; std::chrono::system_clock::time_point missionStart; fs::path basePath; static inline std::map<int, std::array<float_t, 4>> defaultColorMap { {0, std::array<float_t, 4> {0.0f, 0.3f, 0.6f, 1.0f}}, // 0: WEST {1, std::array<float_t, 4> {0.5f, 0.0f, 0.0f, 1.0f}}, // 1: EAST {2, std::array<float_t, 4> {0.0f, 0.5f, 0.0f, 1.0f}}, // 2: INDEPENDENT {3, std::array<float_t, 4> {0.4f, 0.0f, 0.5f, 1.0f}}, // 3: CIVILIAN {4, std::array<float_t, 4> {0.7f, 0.6f, 0.0f, 1.0f}}, // 4: SIDEEMPTY {5, std::array<float_t, 4> {0.0f, 0.3f, 0.6f, 0.5f}}, // 5: WEST unconscious {6, std::array<float_t, 4> {0.5f, 0.0f, 0.0f, 0.5f}}, // 6: EAST unconscious {7, std::array<float_t, 4> {0.0f, 0.5f, 0.0f, 0.5f}}, // 7: INDEPENDENT unconscious {8, std::array<float_t, 4> {0.4f, 0.0f, 0.5f, 0.5f}}, // 8: CIVILIAN unconscious {9, std::array<float_t, 4> {0.7f, 0.6f, 0.0f, 0.5f}}, // 9: SIDEEMPTY unconscious {10, std::array<float_t, 4> {0.2f, 0.2f, 0.2f, 0.5f}}, // 10: dead unit {11, std::array<float_t, 4> {1.0f, 0.0f, 0.0f, 1.0f}} // 11: funkwagen-red when sending, speciality for "breaking contact" }; std::string timePointToString(std::chrono::system_clock::time_point timePoint) { std::time_t missionStartInTimeT = std::chrono::system_clock::to_time_t(timePoint); std::stringstream timeStream; timeStream << std::put_time(std::gmtime(&missionStartInTimeT), "%F %T"); return timeStream.str(); } int intercept::api_version() { return INTERCEPT_SDK_API_VERSION; } void intercept::register_interfaces() {} void intercept::pre_init() { std::stringstream strVersion; strVersion << "[GRAD] (replay_intercept) INFO: Running ("; strVersion << MAJOR << "." << MINOR << "." << PATCHLVL << "." << BUILD << ")"; intercept::sqf::diag_log(sqf::text(strVersion.str())); } std::map<int, std::array<float_t, 4>> constructColorMap(types::auto_array<types::game_value> colorArray) { // not sure why this is a map std::map<int, std::array<float_t, 4>> colorMap; for (size_t i = 0; i < colorArray.size(); i++) { auto rgba = colorArray[i].to_array(); colorMap.insert({ (int)i, { (float_t)rgba[0], (float_t)rgba[1], (float_t)rgba[2], (float_t)rgba[3]} }); } return colorMap; } nl::json constructData(types::auto_array<types::game_value> parameters) { if (parameters.size() == 2) { std::map<int, std::array<float_t, 4>> colorMap; if (parameters[1].is_nil()) { client::invoker_lock thread_lock; sqf::diag_log(sqf::text("[GRAD] (replay_intercept) WARNING: GRAD_REPLAY_COLORS is nil, using default colors!")); colorMap = defaultColorMap; } else { colorMap = constructColorMap(parameters[1].to_array()); } types::auto_array rootArray = parameters[0].to_array(); std::vector<std::shared_ptr<ReplayPart>> replayParts; replayParts.reserve(rootArray.size()); std::shared_ptr<ReplayPart> prevReplayPart; for (int i = 0; i < rootArray.size(); i++) { auto replayPart = std::make_shared<ReplayPart>(rootArray[i].to_array(), prevReplayPart, colorMap); replayParts.push_back(replayPart); prevReplayPart = replayPart; } auto result = nl::json(); for (auto& replayPart : replayParts) { result.push_back(*replayPart); } return result; } client::invoker_lock thread_lock; sqf::diag_log(sqf::text("[GRAD] (replay_intercept) ERROR: Old syntax is no longer supported!")); return nl::json(); } void dumpReplayAsJson(const std::chrono::system_clock::time_point& now, const nlohmann::json& obj) { auto path = std::string(timePointToString(now)).append(".json"); std::replace(path.begin(), path.end(), ':', '-'); std::ofstream o(basePath / path); o << std::setw(4) << obj << std::endl; } game_value sendReplay(game_state& gs, SQFPar right_arg) { try { // Construct JSON Object auto obj = nl::json(); obj["missionName"] = sqf::briefing_name(); obj["date"] = timePointToString(missionStart); auto now = std::chrono::system_clock::now(); obj["duration"] = std::chrono::duration_cast<std::chrono::seconds>(now - missionStart).count(); //auto worldName = std::string(sqf::world_name()); //std::transform(worldName.begin(), worldName.end(), worldName.begin(), ::tolower); obj["worldName"] = sqf::world_name(); // worldName; // Config auto gradReplayConfig = sqf::config_entry(sqf::mission_config_file()) >> ("GRAD_replay"); auto precision = (int)sqf::get_number(gradReplayConfig >> ("precision")); auto trackedSidesArr = sqf::get_array(gradReplayConfig >> ("trackedSides")).to_array(); auto trackedSides = std::vector<std::string>(); for (auto& trackedSide : trackedSidesArr) { trackedSides.push_back(trackedSide); } auto stepsPerTick = (int)sqf::get_number(gradReplayConfig >> ("stepsPerTick")); auto trackedVehicles = (bool)sqf::get_number(gradReplayConfig >> ("trackedVehicles")); auto trackedAI = (bool)sqf::get_number(gradReplayConfig >> ("trackedAI")); auto sendingChunkSize = (int)sqf::get_number(gradReplayConfig >> ("sendingChunkSize")); auto trackShots = (bool)sqf::get_number(gradReplayConfig >> ("trackShots")); obj["config"] = { {"precision", precision }, {"trackedSides", trackedSides}, {"stepsPerTick", stepsPerTick}, {"trackedVehicles", trackedVehicles}, {"trackedAI", trackedAI}, {"sendingChunkSize", sendingChunkSize}, {"trackShots", trackShots} }; // Replay obj["data"] = constructData(right_arg.to_array()); if (obj["data"].empty()) { return false; } std::thread sendReplayThread([obj, now]() { try { std::stringstream inputStream(obj.dump()); bi::filtering_istream fis; fis.push(bi::gzip_compressor(bi::gzip_params(bi::gzip::best_compression))); fis.push(inputStream); std::stringstream outputStream; bi::copy(fis, outputStream); std::string outputString(outputStream.str()); auto header = cpr::Header { { "Content-Type", "application/json" }, { "Content-Encoding", "gzip" }, { "Content-Length", std::to_string(outputString.size()) }, { "Connection", "close" }, { "Authorization", std::string("Bearer ").append(token) }, { "User-Agent", GRAD_REPLAY_USER_AGENT } }; cpr::Response response = cpr::Post( cpr::Url{ url }, header, cpr::Body(outputString), cpr::Timeout(60000) ); if (response.status_code != 201) { dumpReplayAsJson(now, obj); } std::stringstream responseLog; responseLog << "[GRAD] (replay_intercept) INFO: POST Request Status Code: " << response.status_code << " Request time: " << response.elapsed; client::invoker_lock thread_lock; sqf::diag_log(sqf::text(responseLog.str())); } catch (std::exception& ex) { dumpReplayAsJson(now, obj); std::stringstream exceptionLog; exceptionLog << "[GRAD] (replay_intercept) INFO: Exception during POST Request " << ex.what(); client::invoker_lock thread_lock; sqf::diag_log(sqf::text(exceptionLog.str())); } }); sendReplayThread.detach(); } catch (std::exception& ex) { std::stringstream responseLog; responseLog << "[GRAD] (replay_intercept) CRASH: " << ex.what(); sqf::diag_log(sqf::text(responseLog.str())); } return true; } game_value startRecord() { missionStart = std::chrono::system_clock::now(); return true; } void intercept::pre_start() { // load token from config boost::property_tree::ptree pt; auto path = std::filesystem::path("grad_replay_intercept_config.ini").string(); try { boost::property_tree::ini_parser::read_ini(path, pt); url = pt.get<std::string>("Config.ReplayUrl"); token = pt.get<std::string>("Config.BearerToken"); } catch (boost::property_tree::ini_parser_error ex) { sqf::diag_log(sqf::text("[GRAD] (replay_intercept) WARNING: Couldn't parse grad_replay_intercept_config.ini, writing a new one")); pt.add<std::string>("Config.ReplayUrl", "https://replay.gruppe-adler.de/"); pt.add<std::string>("Config.BearerToken", "InsertYourBearerTokenHere"); boost::property_tree::ini_parser::write_ini(path, pt); } basePath = "grad_replay_intercept"; if (!fs::exists(basePath)) { fs::create_directories(basePath); } static auto grad_replay_intercept_replay_send = client::host::register_sqf_command("gradReplayInterceptSendReplay", "Sends the replay", sendReplay, game_data_type::BOOL, game_data_type::ARRAY); } void intercept::post_init() { if ((bool)sqf::get_number(sqf::config_entry(sqf::mission_config_file()) >> ("GRAD_replay") >> ("upload"))) { startRecord(); sqf::call(sqf::compile("['GRAD_replay_stopped', { gradReplayInterceptSendReplay [GRAD_REPLAY_DATABASE, GRAD_REPLAY_COLORS] }] call CBA_fnc_addEventHandler")); } }
37.454861
166
0.606285
gruppe-adler
8a8912a87d36fe6699a71a488bacd80101d180b5
529
hpp
C++
include/clement/clement.hpp
knejadfard/server
cdc555145589bc54dac40b0db1e90538a3b83d9d
[ "BSL-1.0" ]
2
2020-11-04T18:05:51.000Z
2021-12-12T01:05:03.000Z
include/clement/clement.hpp
knejadfard/clement
cdc555145589bc54dac40b0db1e90538a3b83d9d
[ "BSL-1.0" ]
10
2020-09-06T18:41:47.000Z
2021-01-31T16:00:50.000Z
include/clement/clement.hpp
knejadfard/server
cdc555145589bc54dac40b0db1e90538a3b83d9d
[ "BSL-1.0" ]
null
null
null
#ifndef CLEMENT_CLEMENT_HPP #define CLEMENT_CLEMENT_HPP #include "clement/core/constants.hpp" #include "clement/core/http_server.hpp" #include "clement/core/logger.hpp" #include "clement/core/path.hpp" #include "clement/core/request.hpp" #include "clement/core/response_builder.hpp" #include "clement/core/route.hpp" #include "clement/core/router.hpp" #include "clement/core/utility.hpp" #include "clement/core/writer.hpp" #include <boost/beast/http.hpp> namespace clement { namespace http = boost::beast::http; } #endif
24.045455
44
0.773157
knejadfard
8a8c5963e4797d3d8bf7b94f8b6b58310cac5d3f
382
cpp
C++
problems/944.delete-columns-to-make-sorted.cpp
bigfishi/leetcode
3e512f2822a742349384a0bdd7954696f5867683
[ "MIT" ]
null
null
null
problems/944.delete-columns-to-make-sorted.cpp
bigfishi/leetcode
3e512f2822a742349384a0bdd7954696f5867683
[ "MIT" ]
null
null
null
problems/944.delete-columns-to-make-sorted.cpp
bigfishi/leetcode
3e512f2822a742349384a0bdd7954696f5867683
[ "MIT" ]
null
null
null
// 需要注意行和列的区别,第一次错在比对的是行不是列,第二次错在行列的循环终点颠倒了,第三次才改对 class Solution { public: int minDeletionSize(vector<string>& A) { if (!A.size() || !A[0].size()) return 0; int n = A.size(); int m = A[0].size(); int res = 0; for (size_t i = 0; i < m; i++) { for (size_t j = 1; j < n; j++) { if (A[j-1][i]>A[j][i]) { res++; break; } } } return res; } };
18.190476
50
0.507853
bigfishi
8a8f5eb4be8ab082efff070579d2ffd40bb46bbc
4,704
cpp
C++
source/omni/ui/syntax_input.cpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
33
2015-03-21T04:12:45.000Z
2021-04-18T21:44:33.000Z
source/omni/ui/syntax_input.cpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
null
null
null
source/omni/ui/syntax_input.cpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
2
2016-03-05T12:57:05.000Z
2017-09-12T10:11:52.000Z
#include <omni/ui/syntax_input.hpp> #include <omni/ui/suggestion_text_edit.hpp> #include <omni/core/input/syntax_element.hpp> #include <omni/core/input/syntax_template_element.hpp> #include <omni/core/input/regex_template_element.hpp> #include <omni/core/input/variable_template_element.hpp> #include <omni/core/input/fixed_template_element.hpp> #include <omni/core/input/repeater_template_element.hpp> #include <omni/core/input/template_visitor.hpp> #include <QLabel> omni::ui::syntax_input::syntax_input (QWidget * parent, omni::core::input::syntax_element & syntaxElement) : QWidget (parent), _syntaxElement (syntaxElement), _layout (this, 0, 0, 0), _widgets () { //setContentsMargins (QMargins (5, 5, 5, 5)); _layout.setMargin (0); //QPalette pal; //pal.setBrush (QPalette::Background, Qt::red); // fromRgb (0xE3, 0xE3, 0xE5) //setPalette (pal); //setAutoFillBackground (true); addRootTextEdit (); } void omni::ui::syntax_input::addRootTextEdit () { auto textEdit = std::make_shared <suggestion_text_edit> (this); connect ( textEdit.get (), SIGNAL (suggestionsRequested(QString const &, std::vector <omni::core::input::syntax_suggestion> &)), this, SLOT (provideSuggestions(QString const &, std::vector <omni::core::input::syntax_suggestion> &))); connect ( textEdit.get (), SIGNAL (suggestionAccepted (omni::core::input::syntax_suggestion)), this, SLOT (acceptSuggestion (omni::core::input::syntax_suggestion))); _layout.addWidget (textEdit.get ()); _widgets.push_back (textEdit); } void omni::ui::syntax_input::provideSuggestions (QString const & text, std::vector <omni::core::input::syntax_suggestion> & suggestions) { std::vector <omni::core::input::syntax_suggestion> newSuggestions = _syntaxElement.suggest (text.toStdString ()); suggestions.insert (suggestions.end (), newSuggestions.begin (), newSuggestions.end ()); } void omni::ui::syntax_input::clearWidgets () { for (auto widget : _widgets) { _layout.removeWidget (widget.get ()); widget->setParent (nullptr); } _widgets.clear (); } void omni::ui::syntax_input::acceptSuggestion (omni::core::input::syntax_suggestion suggestion) { clearWidgets (); using namespace omni::core::input; class template_create_widget_visitor : public template_visitor { public: template_create_widget_visitor ( QWidget & parent, QLayout & layout, std::list <std::shared_ptr <QWidget>> & widgets) : _parent (parent), _layout (layout), _widgets (widgets) { } void visitSyntaxTemplateElement (syntax_template_element & syntaxTemplateElement) override { auto textEdit = std::make_shared <syntax_input> (& _parent, * syntaxTemplateElement.getSyntaxElement ()); _layout.addWidget (textEdit.get ()); _widgets.push_back (textEdit); } void visitVariableTemplateElement (variable_template_element &) override { auto textEdit = std::make_shared <QLineEdit> (& _parent); textEdit->setPlaceholderText ("(variable)"); _layout.addWidget (textEdit.get ()); _widgets.push_back (textEdit); } void visitRegexTemplateElement (regex_template_element &) override { auto textEdit = std::make_shared <QLineEdit> (& _parent); textEdit->setPlaceholderText ("(regex)"); _layout.addWidget (textEdit.get ()); _widgets.push_back (textEdit); } void visitFixedTemplateElement (fixed_template_element & element) override { auto label = std::make_shared <QLabel> (& _parent); label->setText (QString::fromStdString (element.getText ())); _layout.addWidget (label.get ()); _widgets.push_back (label); } void visitRepeaterTemplateElement (repeater_template_element &) override { auto textEdit = std::make_shared <QLineEdit> (& _parent); textEdit->setPlaceholderText ("(repeater)"); _layout.addWidget (textEdit.get ()); _widgets.push_back (textEdit); } private: QWidget & _parent; QLayout & _layout; std::list <std::shared_ptr <QWidget>> & _widgets; } visitor (* this, _layout, _widgets); syntax_element & e = * suggestion.syntaxElement; for (std::size_t i = 0; i < e.templateElementCount (); ++i) { template_element & t = * e.templateElementAt (i); t.visit (visitor); } }
35.636364
136
0.642432
daniel-kun
8a91c300b8554e8e3e48df6b34e62e22089fea99
4,379
cpp
C++
src/datatypes/descriptor.cpp
SoerenHoffstedt/raster-time-series
b6b763c741fa8655e42ec38ae6c3fe1524bb5d28
[ "MIT" ]
null
null
null
src/datatypes/descriptor.cpp
SoerenHoffstedt/raster-time-series
b6b763c741fa8655e42ec38ae6c3fe1524bb5d28
[ "MIT" ]
null
null
null
src/datatypes/descriptor.cpp
SoerenHoffstedt/raster-time-series
b6b763c741fa8655e42ec38ae6c3fe1524bb5d28
[ "MIT" ]
null
null
null
#include <iostream> #include "datatypes/descriptor.h" #include "descriptor.h" #include <cmath> #include "util/raster_calculations.h" #include "datatypes/raster_operations.h" using namespace rts; // DescriptorInfo: DescriptorInfo::DescriptorInfo(const SpatialTemporalReference &totalInfo, const SpatialReference &tileSpatialInfo, const Resolution &tileResolution, Order order, uint32_t tileIndex, Resolution rasterTileCountDimensional, double nodata, GDALDataType dataType) : rasterInfo(totalInfo), tileSpatialInfo(tileSpatialInfo), tileResolution(tileResolution), order(order), tileIndex(tileIndex), rasterTileCountDimensional(rasterTileCountDimensional), rasterTileCount(rasterTileCountDimensional.resX * rasterTileCountDimensional.resY), nodata(nodata), dataType(dataType) { } DescriptorInfo::DescriptorInfo(const OptionalDescriptor &desc) : rasterInfo(desc->rasterInfo), order(desc->order), tileSpatialInfo(desc->tileSpatialInfo), tileResolution(desc->tileResolution), tileIndex(desc->tileIndex), rasterTileCountDimensional(desc->rasterTileCountDimensional), rasterTileCount(desc->rasterTileCount), nodata(desc->nodata), _isOnlyNodata(desc->_isOnlyNodata), dataType(desc->dataType) { } DescriptorInfo &DescriptorInfo::operator=(const boost::optional<Descriptor> &desc) { rasterInfo = desc->rasterInfo; order = desc->order; tileSpatialInfo = desc->tileSpatialInfo; tileResolution = desc->tileResolution; tileIndex = desc->tileIndex; rasterTileCountDimensional = desc->rasterTileCountDimensional; rasterTileCount = desc->rasterTileCount; nodata = desc->nodata; _isOnlyNodata = desc->_isOnlyNodata; dataType = desc->dataType; return *this; } bool DescriptorInfo::isOnlyNodata() const { return _isOnlyNodata; } // Descriptor: Descriptor::Descriptor(std::function<UniqueRaster(const Descriptor&)> &&getter, const SpatialTemporalReference &totalInfo, const SpatialReference &tileSpatialInfo, const Resolution &tileResolution, Order order, uint32_t tileIndex, Resolution rasterTileCountDimensional, double nodata, GDALDataType dataType) : getter(std::move(getter)), DescriptorInfo(totalInfo, tileSpatialInfo, tileResolution, order, tileIndex, rasterTileCountDimensional, nodata, dataType) { } std::unique_ptr<Raster> Descriptor::getRaster() const { return getter(*this); } boost::optional<Descriptor> Descriptor::createNodataDescriptor(SpatialTemporalReference &totalInfo, SpatialReference &tileSpatialInfo, Resolution &tileResolution, Order order, uint32_t tileIndex, Resolution rasterTileCountDimensional, double nodata, GDALDataType dataType) { auto getter = [](const Descriptor &self) -> UniqueRaster { UniqueRaster raster = Raster::createRaster(self.dataType, self.tileResolution); //set all values to nodata with the AllValuesSetter RasterOperations::callUnary<RasterOperations::AllValuesSetter>(raster.get(), self.nodata); return raster; }; auto ret = rts::make_optional<Descriptor>(std::move(getter), totalInfo, tileSpatialInfo, tileResolution, order, tileIndex, rasterTileCountDimensional, nodata, dataType); ret->_isOnlyNodata = true; return ret; } Descriptor::Descriptor(std::function<UniqueRaster(const Descriptor &)> &&getter, const DescriptorInfo &args) : getter(std::move(getter)), DescriptorInfo(args) { }
38.412281
173
0.59968
SoerenHoffstedt
8a94a09f7992b413ae1ba4fbd57b266d1c5ef1bc
1,559
hpp
C++
engine/graphics/geometry/mesh/builder/RMVertexBufferHeaderBuilder.hpp
vitali-kurlovich/RMPropeller
6b914957000dc5bd35319828b7e2608ceb2c92ca
[ "MIT" ]
null
null
null
engine/graphics/geometry/mesh/builder/RMVertexBufferHeaderBuilder.hpp
vitali-kurlovich/RMPropeller
6b914957000dc5bd35319828b7e2608ceb2c92ca
[ "MIT" ]
null
null
null
engine/graphics/geometry/mesh/builder/RMVertexBufferHeaderBuilder.hpp
vitali-kurlovich/RMPropeller
6b914957000dc5bd35319828b7e2608ceb2c92ca
[ "MIT" ]
null
null
null
// // Created by Vitali Kurlovich on 10/29/16. // #ifndef RMPROPELLER_RMVERTEXBUFFERHEADERBUILDER_HPP #define RMPROPELLER_RMVERTEXBUFFERHEADERBUILDER_HPP #include "graphics/geometry/geometry_common.hpp" #include <algorithm> #include "graphics/geometry/mesh/buffer/RMVertexAttribute.hpp" #include "graphics/geometry/mesh/buffer/RMVertexBufferHeader.hpp" namespace rmengine { namespace graphics { class RMVertexBufferHeaderBuilder final { std::vector<RMVertexAttributeItem> _attrsBuffer; uint16 _format{0}; uint8 _offset{0}; public: RMVertexBufferHeaderBuilder() { _attrsBuffer.reserve(16); } void clear() { _attrsBuffer.clear(); _format = 0; _offset = 0; } RMVertexBufferHeaderBuilder& append(RMVertexAttribute attr, RMAttributeElementSize size, RMType type) { #ifndef NDEBUG if (!_attrsBuffer.empty()) { assert(_attrsBuffer.back().attribute < attr); } #endif assert((_format & attr) == 0); _format |= attr; _attrsBuffer.push_back(RMVertexAttributeItem(attr, size, type, _offset)); _offset += sizeOfRMType(type)*size; return *this; } RMVertexBufferHeader build() { return RMVertexBufferHeader(_attrsBuffer); } }; } } #endif //RMPROPELLER_RMVERTEXBUFFERHEADERBUILDER_HPP
26.87931
115
0.597178
vitali-kurlovich
8a975c5f6590053d63bbe9faca4b9e2f2331f7ad
626
cpp
C++
src/tests/textbank/main.cpp
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/tests/textbank/main.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/tests/textbank/main.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
#include <gamebase/Gamebase.h> using namespace gamebase; using namespace std; class MyApp : public App { public: void load() { loadTextBank("textbank/Texts.json"); connect(button, setText); text << tr("text2"); } void setText() { text << tr(textBox.text()); } FromDesign(Button, button); FromDesign(TextBox, textBox); FromDesign(Label, text); }; int main(int argc, char** argv) { MyApp app; app.setConfig("config.json"); app.setDesign("textbank/Design.json"); if (!app.init(&argc, argv)) return 1; app.run(); return 0; }
17.388889
44
0.587859
TheMrButcher
8a9ba4c471ded164e560a6c1b2046cf2fdae94a7
6,347
cpp
C++
AtlStlStringSortPerf/AtlStlStringSortPerf.cpp
GiovanniDicanio/AtlStlStringSortPerf
ccec3b0b6acf5cea11a5ea9de3c5b7a648eb2422
[ "MIT" ]
4
2018-03-29T15:38:00.000Z
2020-12-24T18:55:32.000Z
AtlStlStringSortPerf/AtlStlStringSortPerf.cpp
GiovanniDicanio/AtlStlStringSortPerf
ccec3b0b6acf5cea11a5ea9de3c5b7a648eb2422
[ "MIT" ]
null
null
null
AtlStlStringSortPerf/AtlStlStringSortPerf.cpp
GiovanniDicanio/AtlStlStringSortPerf
ccec3b0b6acf5cea11a5ea9de3c5b7a648eb2422
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // *** ATL vs. STL String Sorting Performance Tests *** // // by Giovanni Dicanio // // Compares sorting times of vector<CStringW> vs. vector<wstring> // /////////////////////////////////////////////////////////////////////////////// // Define the following macro to enable custom std::wstring comparison // using wcscmp(), instead of the default wmemcmp() //#define TEST_STL_WCSCMP_COMPARE //============================================================================= // Includes //============================================================================= #include <string.h> // wcscmp #include <algorithm> // std::shuffle, std::sort #include <exception> // std::exception #include <iostream> // std::cout #include <random> // std::mt19937 #include <string> // std::wstring, std::string #include <vector> // std::vector #include <Windows.h> // Windows Platform SDK #include <atlexcept.h> // CAtlException #include <atlstr.h> // ATL CStringW using namespace std; using namespace ATL; //============================================================================= // Performance Counter Helpers //============================================================================= long long Counter() { LARGE_INTEGER li; ::QueryPerformanceCounter(&li); return li.QuadPart; } long long Frequency() { LARGE_INTEGER li; ::QueryPerformanceFrequency(&li); return li.QuadPart; } void PrintTime(const long long start, const long long finish, const char * const s) { cout << s << ": " << (finish - start) * 1000.0 / Frequency() << " ms \n"; } //============================================================================= // Performance Tests //============================================================================= #ifdef TEST_STL_WCSCMP_COMPARE bool CompareUsingWcscmp(const std::wstring& a, const std::wstring& b) { // a < b return (wcscmp(a.c_str(), b.c_str())) < 0; } #endif // TEST_STL_WCSCMP_COMPARE void RunTests() { cout << "\n*** String Sorting Performance Tests -- by Giovanni Dicanio *** \n\n"; #ifdef _WIN64 cout << "[64-bit build] \n\n"; #else cout << "[32-bit build] \n\n"; #endif // Build a vector of strings generated starting from "Lorem Ipsum" const auto shuffled = []() -> vector<wstring> { const wstring lorem[] = { L"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.", L"Maecenas porttitor congue massa. Fusce posuere, magna sed", L"pulvinar ultricies, purus lectus malesuada libero,", L"sit amet commodo magna eros quis urna.", L"Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.", L"Pellentesque habitant morbi tristique senectus et netus et", L"malesuada fames ac turpis egestas. Proin pharetra nonummy pede.", L"Mauris et orci. [*** add more chars to prevent SSO ***]" }; vector<wstring> v; #ifdef _DEBUG constexpr int kTestIterationCount = 1000; #else constexpr int kTestIterationCount = 200'000; #endif for (int i = 0; i < kTestIterationCount; ++i) { for (const auto & s : lorem) { v.push_back(s + L" (#" + to_wstring(i) + L")"); } } mt19937 prng(1980); shuffle(v.begin(), v.end(), prng); return v; }(); const auto shuffledPtrs = [&]() -> vector<const wchar_t *> { vector<const wchar_t *> v; for (const auto& s : shuffled) { v.push_back(s.c_str()); } return v; }(); cout << "Test string array contains " << (shuffled.size() / 1000) << "K strings. \n\n"; long long start = 0; long long finish = 0; vector<CStringW> atl1(shuffledPtrs.begin(), shuffledPtrs.end()); vector<wstring> stl1 = shuffled; vector<CStringW> atl2(shuffledPtrs.begin(), shuffledPtrs.end()); vector<wstring> stl2 = shuffled; vector<CStringW> atl3(shuffledPtrs.begin(), shuffledPtrs.end()); vector<wstring> stl3 = shuffled; //------------------------------------------------------------------------- cout << "=== String Sorting Test === \n"; #ifdef TEST_STL_WCSCMP_COMPARE cout << "*** Comparing std::wstrings using wcscmp ***\n"; #endif start = Counter(); sort(atl1.begin(), atl1.end()); finish = Counter(); PrintTime(start, finish, "ATL1"); start = Counter(); #ifdef TEST_STL_WCSCMP_COMPARE sort(stl1.begin(), stl1.end(), CompareUsingWcscmp); #else sort(stl1.begin(), stl1.end()); #endif finish = Counter(); PrintTime(start, finish, "STL1"); start = Counter(); sort(atl2.begin(), atl2.end()); finish = Counter(); PrintTime(start, finish, "ATL2"); start = Counter(); #ifdef TEST_STL_WCSCMP_COMPARE sort(stl2.begin(), stl2.end(), CompareUsingWcscmp); #else sort(stl2.begin(), stl2.end()); #endif finish = Counter(); PrintTime(start, finish, "STL2"); start = Counter(); sort(atl3.begin(), atl3.end()); finish = Counter(); PrintTime(start, finish, "ATL3"); start = Counter(); #ifdef TEST_STL_WCSCMP_COMPARE sort(stl3.begin(), stl3.end(), CompareUsingWcscmp); #else sort(stl3.begin(), stl3.end()); #endif finish = Counter(); PrintTime(start, finish, "STL3"); cout << '\n'; } int main() { constexpr int kExitOk = 0; constexpr int kExitError = 1; try { RunTests(); } catch (const CAtlException& e) { cerr << "\n*** ERROR: CAtlException thrown; HR=0x" << hex << e.m_hr << '\n'; return kExitError; } catch (const exception& e) { cerr << "\n*** ERROR: " << e.what() << '\n'; return kExitError; } return kExitOk; } ///////////////////////////////////////////////////////////////////////////////
28.85
92
0.49031
GiovanniDicanio
8a9f65a8419e580caf67c7d3dac35d62d66611ea
983
cxx
C++
ppdc/ppdc-font.cxx
nilakhan/cups
3859d70160010c61fd7a05ecbf23f3b4738e2b9d
[ "Apache-2.0" ]
463
2020-10-14T19:36:24.000Z
2022-03-30T18:35:47.000Z
ppdc/ppdc-font.cxx
nilakhan/cups
3859d70160010c61fd7a05ecbf23f3b4738e2b9d
[ "Apache-2.0" ]
373
2017-10-24T08:25:34.000Z
2022-03-30T20:34:06.000Z
ppdc/ppdc-font.cxx
nilakhan/cups
3859d70160010c61fd7a05ecbf23f3b4738e2b9d
[ "Apache-2.0" ]
124
2017-10-20T10:28:31.000Z
2022-03-22T21:07:18.000Z
// // Shared font class for the CUPS PPD Compiler. // // Copyright 2007-2009 by Apple Inc. // Copyright 2002-2005 by Easy Software Products. // // Licensed under Apache License v2.0. See the file "LICENSE" for more information. // // // Include necessary headers... // #include "ppdc-private.h" // // 'ppdcFont::ppdcFont()' - Create a shared font. // ppdcFont::ppdcFont(const char *n, // I - Name of font const char *e, // I - Font encoding const char *v, // I - Font version const char *c, // I - Font charset ppdcFontStatus s) // I - Font status : ppdcShared() { PPDC_NEW; name = new ppdcString(n); encoding = new ppdcString(e); version = new ppdcString(v); charset = new ppdcString(c); status = s; } // // 'ppdcFont::~ppdcFont()' - Destroy a shared font. // ppdcFont::~ppdcFont() { PPDC_DELETE; name->release(); encoding->release(); version->release(); charset->release(); }
19.27451
84
0.603255
nilakhan
8aa9e8aa0f61af883ee7e76c8484a8cc54c05b66
2,197
cpp
C++
Ackermann-function/Ackermann-function.cpp
esote/mathematical-functions
0bdf761583a49b6479a82d7e0668744d9bb75dad
[ "MIT" ]
null
null
null
Ackermann-function/Ackermann-function.cpp
esote/mathematical-functions
0bdf761583a49b6479a82d7e0668744d9bb75dad
[ "MIT" ]
null
null
null
Ackermann-function/Ackermann-function.cpp
esote/mathematical-functions
0bdf761583a49b6479a82d7e0668744d9bb75dad
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <limits> unsigned int ackermann(unsigned int m, unsigned int n){ if(m == 0) return n+1; if(n == 0) return ackermann(m-1,1); return ackermann(m-1,ackermann(m,n-1)); } enum var {M, N}; bool SOProtection; bool isInvalidCheck(double i, var name){ if(!std::cin){ std::cout << "Non-number (NaN)\n"; return true; } if(floor(i) != i){ std::cout << "Non-integer (\u2124)\n"; return true; } if(i < 0){ std::cout << "Non-natural (\u2115)\n"; return true; } if(name == M && i > 3 && SOProtection){ std::cout << "Out of Bounds (m > 3) with SO Protection\n"; return true; } if(name == N && i > 12 && SOProtection){ std::cout << "Out of Bounds (n > 12) with SO Protection\n"; return true; } return false; } bool isInvalid(double i, var name){ bool result = isInvalidCheck(i, name); std::cin.clear(); std::cin.ignore(); return result; } int main(){ double m, n; bool validM, validN; char checkSOProtection; std::cout << "Warning: If large values are entered, stack overflow and segmentation fault will occur!\n"; while(true){ std::cout << "Enable stack overflow protection? Y/N: "; std::cin >> checkSOProtection; if(checkSOProtection == 'Y' || checkSOProtection == 'y'){ SOProtection = true; break; } if(checkSOProtection == 'N' || checkSOProtection == 'n'){ SOProtection = false; break; } std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } do{ std::cout << "\nm = "; std::cin >> m; validM = isInvalid(m, M); } while(validM); do{ std::cout << "\nn = "; std::cin >> n; validN = isInvalid(n, N); } while(validN); std::cout << "\nCALCULATING" << std::endl; std::cout << "\nA(" << m << ',' << n << ") = " << ackermann(m,n) << std::endl; return 0; }
22.649485
109
0.497497
esote
8aac458883cfc4c12495f199526fe55e2247f48e
32,002
inl
C++
imgui/binding/src/lua_imgui_ImGui_DragX.inl
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
6
2022-02-26T09:21:40.000Z
2022-02-28T11:03:23.000Z
imgui/binding/src/lua_imgui_ImGui_DragX.inl
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
null
null
null
imgui/binding/src/lua_imgui_ImGui_DragX.inl
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
null
null
null
// ImGui::DragX static int lib_DragFloat(lua_State* L) { const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); float v = (float)luaL_checknumber(L, 2); bool ret = false; if (argc <= 2) { ret = ImGui::DragFloat(label, &v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = ImGui::DragFloat(label, &v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); ret = ImGui::DragFloat(label, &v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); ret = ImGui::DragFloat(label, &v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); ret = ImGui::DragFloat(label, &v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = ImGui::DragFloat(label, &v, v_speed, v_min, v_max, format, flags); } lua_pushboolean(L, ret); lua_pushnumber(L, (lua_Number)v); return 2; } static int lib_DragFloat2(lua_State* L) { #define N 2 #define F ImGui::DragFloat2 const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); float v[N] = {}; bool ret = false; for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_gettable(L, 2); v[idx] = (float)luaL_checknumber(L, argc + 1); lua_pop(L, 1); } if (argc <= 2) { ret = F(label, v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = F(label, v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); ret = F(label, v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); ret = F(label, v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); ret = F(label, v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = F(label, v, v_speed, v_min, v_max, format, flags); } for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_pushnumber(L, (lua_Number)v[idx]); lua_settable(L, 2); } lua_pushboolean(L, ret); lua_pushvalue(L, 2); return 2; #undef N #undef F } static int lib_DragFloat3(lua_State* L) { #define N 3 #define F ImGui::DragFloat3 const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); float v[N] = {}; bool ret = false; for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_gettable(L, 2); v[idx] = (float)luaL_checknumber(L, argc + 1); lua_pop(L, 1); } if (argc <= 2) { ret = F(label, v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = F(label, v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); ret = F(label, v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); ret = F(label, v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); ret = F(label, v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = F(label, v, v_speed, v_min, v_max, format, flags); } for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_pushnumber(L, (lua_Number)v[idx]); lua_settable(L, 2); } lua_pushboolean(L, ret); lua_pushvalue(L, 2); return 2; #undef N #undef F } static int lib_DragFloat4(lua_State* L) { #define N 4 #define F ImGui::DragFloat4 const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); float v[N] = {}; bool ret = false; for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_gettable(L, 2); v[idx] = (float)luaL_checknumber(L, argc + 1); lua_pop(L, 1); } if (argc <= 2) { ret = F(label, v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = F(label, v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); ret = F(label, v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); ret = F(label, v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); ret = F(label, v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const float v_min = (float)luaL_checknumber(L, 4); const float v_max = (float)luaL_checknumber(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = F(label, v, v_speed, v_min, v_max, format, flags); } for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_pushnumber(L, (lua_Number)v[idx]); lua_settable(L, 2); } lua_pushboolean(L, ret); lua_pushvalue(L, 2); return 2; #undef N #undef F } static int lib_DragFloatRange2(lua_State* L) { const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); float v_current_min = (float)luaL_checknumber(L, 2); float v_current_max = (float)luaL_checknumber(L, 3); bool ret = false; if (argc <= 3) { ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 4); ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max, v_speed); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 4); const float v_min = (float)luaL_checknumber(L, 5); ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max, v_speed, v_min); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 4); const float v_min = (float)luaL_checknumber(L, 5); const float v_max = (float)luaL_checknumber(L, 6); ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max); } else if (argc == 7) { const float v_speed = (float)luaL_checknumber(L, 4); const float v_min = (float)luaL_checknumber(L, 5); const float v_max = (float)luaL_checknumber(L, 6); const char* format = luaL_checkstring(L, 7); ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max, format); } else if (argc == 8) { const float v_speed = (float)luaL_checknumber(L, 4); const float v_min = (float)luaL_checknumber(L, 5); const float v_max = (float)luaL_checknumber(L, 6); const char* format = luaL_checkstring(L, 7); const char* format_max = luaL_checkstring(L, 8); ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max, format, format_max); } else { const float v_speed = (float)luaL_checknumber(L, 4); const float v_min = (float)luaL_checknumber(L, 5); const float v_max = (float)luaL_checknumber(L, 6); const char* format = luaL_checkstring(L, 7); const char* format_max = luaL_checkstring(L, 8); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 9); ret = ImGui::DragFloatRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max, format, format_max, flags); } lua_pushboolean(L, ret); lua_pushnumber(L, (lua_Number)v_current_min); lua_pushnumber(L, (lua_Number)v_current_max); return 3; } static int lib_DragInt(lua_State* L) { const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); int v = (int)luaL_checkinteger(L, 2); bool ret = false; if (argc <= 2) { ret = ImGui::DragInt(label, &v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = ImGui::DragInt(label, &v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); ret = ImGui::DragInt(label, &v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); ret = ImGui::DragInt(label, &v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); ret = ImGui::DragInt(label, &v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = ImGui::DragInt(label, &v, v_speed, v_min, v_max, format, flags); } lua_pushboolean(L, ret); lua_pushinteger(L, (lua_Integer)v); return 2; } static int lib_DragInt2(lua_State* L) { #define N 2 #define F ImGui::DragInt2 const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); int v[N] = {}; bool ret = false; for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_gettable(L, 2); v[idx] = (int)luaL_checkinteger(L, argc + 1); lua_pop(L, 1); } if (argc <= 2) { ret = F(label, v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = F(label, v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); ret = F(label, v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); ret = F(label, v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); ret = F(label, v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = F(label, v, v_speed, v_min, v_max, format, flags); } for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_pushinteger(L, (lua_Integer)v[idx]); lua_settable(L, 2); } lua_pushboolean(L, ret); lua_pushvalue(L, 2); return 2; #undef N #undef F } static int lib_DragInt3(lua_State* L) { #define N 3 #define F ImGui::DragInt3 const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); int v[N] = {}; bool ret = false; for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_gettable(L, 2); v[idx] = (int)luaL_checkinteger(L, argc + 1); lua_pop(L, 1); } if (argc <= 2) { ret = F(label, v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = F(label, v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); ret = F(label, v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); ret = F(label, v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); ret = F(label, v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = F(label, v, v_speed, v_min, v_max, format, flags); } for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_pushinteger(L, (lua_Integer)v[idx]); lua_settable(L, 2); } lua_pushboolean(L, ret); lua_pushvalue(L, 2); return 2; #undef N #undef F } static int lib_DragInt4(lua_State* L) { #define N 4 #define F ImGui::DragInt4 const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); int v[N] = {}; bool ret = false; for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_gettable(L, 2); v[idx] = (int)luaL_checkinteger(L, argc + 1); lua_pop(L, 1); } if (argc <= 2) { ret = F(label, v); } else if (argc == 3) { const float v_speed = (float)luaL_checknumber(L, 3); ret = F(label, v, v_speed); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); ret = F(label, v, v_speed, v_min); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); ret = F(label, v, v_speed, v_min, v_max); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); ret = F(label, v, v_speed, v_min, v_max, format); } else { const float v_speed = (float)luaL_checknumber(L, 3); const int v_min = (int)luaL_checkinteger(L, 4); const int v_max = (int)luaL_checkinteger(L, 5); const char* format = luaL_checkstring(L, 6); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 7); ret = F(label, v, v_speed, v_min, v_max, format, flags); } for (int idx = 0; idx < N; idx += 1) { lua_pushinteger(L, idx + 1); lua_pushinteger(L, (lua_Integer)v[idx]); lua_settable(L, 2); } lua_pushboolean(L, ret); lua_pushvalue(L, 2); return 2; #undef N #undef F } static int lib_DragIntRange2(lua_State* L) { const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); int v_current_min = (int)luaL_checkinteger(L, 2); int v_current_max = (int)luaL_checkinteger(L, 3); bool ret = false; if (argc <= 3) { ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 4); ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max, v_speed); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 4); const int v_min = (int)luaL_checkinteger(L, 5); ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max, v_speed, v_min); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 4); const int v_min = (int)luaL_checkinteger(L, 5); const int v_max = (int)luaL_checkinteger(L, 6); ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max); } else if (argc == 7) { const float v_speed = (float)luaL_checknumber(L, 4); const int v_min = (int)luaL_checkinteger(L, 5); const int v_max = (int)luaL_checkinteger(L, 6); const char* format = luaL_checkstring(L, 7); ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max, format); } else if (argc == 8) { const float v_speed = (float)luaL_checknumber(L, 4); const int v_min = (int)luaL_checkinteger(L, 5); const int v_max = (int)luaL_checkinteger(L, 6); const char* format = luaL_checkstring(L, 7); const char* format_max = luaL_checkstring(L, 8); ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max, format, format_max); } else { const float v_speed = (float)luaL_checknumber(L, 4); const int v_min = (int)luaL_checkinteger(L, 5); const int v_max = (int)luaL_checkinteger(L, 6); const char* format = luaL_checkstring(L, 7); const char* format_max = luaL_checkstring(L, 8); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 9); ret = ImGui::DragIntRange2(label, &v_current_min, &v_current_max, v_speed, v_min, v_max, format, format_max, flags); } lua_pushboolean(L, ret); lua_pushinteger(L, (lua_Integer)v_current_min); lua_pushinteger(L, (lua_Integer)v_current_max); return 3; } static int lib_DragScalar(lua_State* L) { const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); const ImGuiDataType data_type = (ImGuiDataType)luaL_checkinteger(L, 2); bool ret = false; if (data_type == ImGuiDataType_Integer) { lua_Integer data = luaL_checkinteger(L, 3); if (argc <= 3) { ret = ImGui::DragScalar(label, data_type, &data); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 4); ret = ImGui::DragScalar(label, data_type, &data, v_speed); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Integer min_ = luaL_checkinteger(L, 5); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Integer min_ = luaL_checkinteger(L, 5); const lua_Integer max_ = luaL_checkinteger(L, 6); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_, &max_); } else if (argc == 7) { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Integer min_ = luaL_checkinteger(L, 5); const lua_Integer max_ = luaL_checkinteger(L, 6); const char* format = luaL_checkstring(L, 7); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_, &max_, format); } else { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Integer min_ = luaL_checkinteger(L, 5); const lua_Integer max_ = luaL_checkinteger(L, 6); const char* format = luaL_checkstring(L, 7); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 8); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_, &max_, format, flags); } lua_pushboolean(L, ret); lua_pushinteger(L, data); return 2; } else if (data_type == ImGuiDataType_Number) { lua_Number data = luaL_checknumber(L, 3); if (argc <= 3) { ret = ImGui::DragScalar(label, data_type, &data, 1.0f); } else if (argc == 4) { const float v_speed = (float)luaL_checknumber(L, 4); ret = ImGui::DragScalar(label, data_type, &data, v_speed); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Number min_ = luaL_checknumber(L, 5); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Number min_ = luaL_checknumber(L, 5); const lua_Number max_ = luaL_checknumber(L, 6); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_, &max_); } else if (argc == 7) { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Number min_ = luaL_checknumber(L, 5); const lua_Number max_ = luaL_checknumber(L, 6); const char* format = luaL_checkstring(L, 7); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_, &max_, format); } else { const float v_speed = (float)luaL_checknumber(L, 4); const lua_Number min_ = luaL_checknumber(L, 5); const lua_Number max_ = luaL_checknumber(L, 6); const char* format = luaL_checkstring(L, 7); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 8); ret = ImGui::DragScalar(label, data_type, &data, v_speed, &min_, &max_, format, flags); } lua_pushboolean(L, ret); lua_pushnumber(L, data); return 2; } else { if (data_type >= 0 && data_type < (ImGuiDataType)ImGuiDataType_COUNT) { return luaL_error(L, R"(unsupported data type '%s')", ImGuiDataTypeName[data_type]); } return luaL_error(L, R"(unsupported data type '?')"); } } static int lib_DragScalarN(lua_State* L) { const int argc = lua_gettop(L); const char* label = luaL_checkstring(L, 1); const ImGuiDataType data_type = (ImGuiDataType)luaL_checkinteger(L, 2); bool ret = false; if (data_type == ImGuiDataType_Integer) { const int components = (argc >= 4) ? (int)luaL_checkinteger(L, 4) : _luaL_len(L, 3); integer_array data(components); for (int i = 0; i < components; i += 1) { lua_pushinteger(L, i + 1); lua_gettable(L, 3); data.data[i] = luaL_checkinteger(L, -1); lua_pop(L, 1); } if (argc <= 4) { ret = ImGui::DragScalarN(label, data_type, data.data, components); } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 5); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Integer min_ = luaL_checkinteger(L, 6); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_); } else if (argc == 7) { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Integer min_ = luaL_checkinteger(L, 6); const lua_Integer max_ = luaL_checkinteger(L, 7); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_, &max_); } else if (argc == 8) { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Integer min_ = luaL_checkinteger(L, 6); const lua_Integer max_ = luaL_checkinteger(L, 7); const char* format = luaL_checkstring(L, 8); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_, &max_, format); } else { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Integer min_ = luaL_checkinteger(L, 6); const lua_Integer max_ = luaL_checkinteger(L, 7); const char* format = luaL_checkstring(L, 8); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 9); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_, &max_, format, flags); } for (int i = 0; i < components; i += 1) { lua_pushinteger(L, i + 1); lua_pushinteger(L, data.data[i]); lua_settable(L, 3); } lua_pushboolean(L, ret); lua_pushvalue(L, 3); return 2; } else if (data_type == ImGuiDataType_Number) { const int components = (argc >= 4) ? (int)luaL_checkinteger(L, 4) : _luaL_len(L, 3); number_array data(components); for (int i = 0; i < components; i += 1) { lua_pushinteger(L, i + 1); lua_gettable(L, 3); data.data[i] = luaL_checknumber(L, -1); lua_pop(L, 1); } if (argc <= 3) { ret = ImGui::DragScalarN(label, data_type, data.data, components, 1.0f); // helper } else if (argc == 4) { ret = ImGui::DragScalarN(label, data_type, data.data, components, 1.0f); // helper } else if (argc == 5) { const float v_speed = (float)luaL_checknumber(L, 5); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed); } else if (argc == 6) { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Number min_ = luaL_checknumber(L, 6); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_); } else if (argc == 7) { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Number min_ = luaL_checknumber(L, 6); const lua_Number max_ = luaL_checknumber(L, 7); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_, &max_); } else if (argc == 8) { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Number min_ = luaL_checknumber(L, 6); const lua_Number max_ = luaL_checknumber(L, 7); const char* format = luaL_checkstring(L, 8); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_, &max_, format); } else { const float v_speed = (float)luaL_checknumber(L, 5); const lua_Number min_ = luaL_checknumber(L, 6); const lua_Number max_ = luaL_checknumber(L, 7); const char* format = luaL_checkstring(L, 8); const ImGuiSliderFlags flags = (ImGuiSliderFlags)luaL_checkinteger(L, 9); ret = ImGui::DragScalarN(label, data_type, data.data, components, v_speed, &min_, &max_, format, flags); } for (int i = 0; i < components; i += 1) { lua_pushinteger(L, i + 1); lua_pushnumber(L, data.data[i]); lua_settable(L, 3); } lua_pushboolean(L, ret); lua_pushvalue(L, 3); return 2; } else { if (data_type >= 0 && data_type < (ImGuiDataType)ImGuiDataType_COUNT) { return luaL_error(L, R"(unsupported data type '%s')", ImGuiDataTypeName[data_type]); } return luaL_error(L, R"(unsupported data type '?')"); } }
34.747014
97
0.556496
Legacy-LuaSTG-Engine
8aae16360798c8769bb5f79f6b35e30bf97901fb
392
cpp
C++
System/PixelShader.cpp
CrossProd/Aardbei_SouthsideExploration
cead610de95fb87b5aab60b4ec834a8c814a3c12
[ "MIT" ]
1
2018-11-20T03:50:35.000Z
2018-11-20T03:50:35.000Z
System/PixelShader.cpp
rbruinier/Aardbei_SouthsideExploration
cead610de95fb87b5aab60b4ec834a8c814a3c12
[ "MIT" ]
null
null
null
System/PixelShader.cpp
rbruinier/Aardbei_SouthsideExploration
cead610de95fb87b5aab60b4ec834a8c814a3c12
[ "MIT" ]
null
null
null
/* Pyramid System - Pixel Shader Class 2006, Robert Jan Bruinier (rob / aardbei) */ #include "PixelShader.h" PixelShader::PixelShader() { d3dPixelShader = NULL; } PixelShader::~PixelShader() { } int PixelShader::Destroy() { if (d3dPixelShader != NULL) { if (FAILED(d3dPixelShader->Release())) { return E_FAIL; } } return D3D_OK; }
11.529412
43
0.59949
CrossProd
8ab62bcc0ffa561dac2529f1cb902da77967b8bf
14,130
cpp
C++
of_dis/refine_variational.cpp
beaupreda/IMOT_OpticalFlow_Edges
633b8fec2c2a4525d1e62d385e553789d56f61f9
[ "MIT" ]
12
2018-01-31T13:32:49.000Z
2021-12-03T16:35:29.000Z
of_dis/refine_variational.cpp
beaupreda/IMOT_OpticalFlow_Edges
633b8fec2c2a4525d1e62d385e553789d56f61f9
[ "MIT" ]
2
2020-09-14T11:02:37.000Z
2021-04-29T23:28:48.000Z
of_dis/refine_variational.cpp
beaupreda/IMOT_OpticalFlow_Edges
633b8fec2c2a4525d1e62d385e553789d56f61f9
[ "MIT" ]
2
2019-04-01T12:20:48.000Z
2021-09-06T03:42:54.000Z
#include <iostream> #include <string> #include <vector> #include <valarray> #include <thread> #include <Eigen/Core> #include <Eigen/LU> #include <Eigen/Dense> #include <stdio.h> #include "refine_variational.h" using std::cout; using std::endl; using std::vector; namespace OFC { VarRefClass::VarRefClass(const float * im_ao_in, const float * im_ao_dx_in, const float * im_ao_dy_in, const float * im_bo_in, const float * im_bo_dx_in, const float * im_bo_dy_in, const camparam* cpt_in,const camparam* cpo_in,const optparam* op_in, float *flowout) : cpt(cpt_in), cpo(cpo_in), op(op_in) { // initialize parameters tvparams.alpha = op->tv_alpha; tvparams.beta = 0.0f; // for matching term, not needed for us tvparams.gamma = op->tv_gamma; tvparams.delta = op->tv_delta; tvparams.n_inner_iteration = op->tv_innerit * (cpt->curr_lv+1); tvparams.n_solver_iteration = op->tv_solverit;//5; tvparams.sor_omega = op->tv_sor; tvparams.tmp_quarter_alpha = 0.25f*tvparams.alpha; tvparams.tmp_half_gamma_over3 = tvparams.gamma*0.5f/3.0f; tvparams.tmp_half_delta_over3 = tvparams.delta*0.5f/3.0f; tvparams.tmp_half_beta = tvparams.beta*0.5f; float deriv_filter[3] = {0.0f, -8.0f/12.0f, 1.0f/12.0f}; deriv = convolution_new(2, deriv_filter, 0); float deriv_filter_flow[2] = {0.0f, -0.5f}; deriv_flow = convolution_new(1, deriv_filter_flow, 0); // copy flow initialization into FV structs #if (SELECTMODE==1) static int noparam = 2; // Optical flow #else static int noparam = 1; // Only horizontal displacements for stereo depth #endif std::vector<image_t*> flow_sep(noparam); for (int i = 0; i < noparam; ++i ) flow_sep[i] = image_new(cpt->width,cpt->height); for (int iy = 0; iy < cpt->height; ++iy) for (int ix = 0; ix < cpt->width; ++ix) { int i = iy * cpt->width + ix; int is = iy * flow_sep[0]->stride + ix; for (int j = 0; j < noparam; ++j) flow_sep[j]->c1[is] = flowout[i*noparam + j]; } // copy image data into FV structs #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) image_t * im_ao, *im_bo; im_ao = image_new(cpt->width,cpt->height); im_bo = image_new(cpt->width,cpt->height); #else color_image_t * im_ao, *im_bo; im_ao = color_image_new(cpt->width,cpt->height); im_bo = color_image_new(cpt->width,cpt->height); #endif copyimage(im_ao_in, im_ao); copyimage(im_bo_in, im_bo); // Call solver #if (SELECTMODE==1) RefLevelOF(flow_sep[0], flow_sep[1], im_ao, im_bo); #else RefLevelDE(flow_sep[0], im_ao, im_bo); #endif // Copy flow result back for (int iy = 0; iy < cpt->height; ++iy) for (int ix = 0; ix < cpt->width; ++ix) { int i = iy * cpt->width + ix; int is = iy * flow_sep[0]->stride + ix; for (int j = 0; j < noparam; ++j) flowout[i*noparam + j] = flow_sep[j]->c1[is]; } // free FV structs for (int i = 0; i < noparam; ++i ) image_delete(flow_sep[i]); convolution_delete(deriv); convolution_delete(deriv_flow); #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) image_delete(im_ao); image_delete(im_bo); #else color_image_delete(im_ao); color_image_delete(im_bo); #endif } #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) void VarRefClass::copyimage(const float* img, image_t * img_t) #else void VarRefClass::copyimage(const float* img, color_image_t * img_t) #endif { #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) const float * img_st = img + (cpt->tmp_w + 1 ) * (cpt->imgpadding); // remove image padding, start at first valid pixel #else const float * img_st = img + 3 * (cpt->tmp_w + 1 ) * (cpt->imgpadding); #endif for (int yi = 0; yi < cpt->height; ++yi) { for (int xi = 0; xi < cpt->width; ++xi, ++img_st) { int i = yi*img_t->stride+ xi; img_t->c1[i] = (*img_st); #if (SELECTCHANNEL==3) ++img_st; img_t->c2[i] = (*img_st); ++img_st; img_t->c3[i] = (*img_st); #endif } #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) img_st += 2 * cpt->imgpadding; #else img_st += 3 * 2 * cpt->imgpadding; #endif } } #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) void VarRefClass::RefLevelOF(image_t *wx, image_t *wy, const image_t *im1, const image_t *im2) #else void VarRefClass::RefLevelOF(image_t *wx, image_t *wy, const color_image_t *im1, const color_image_t *im2) #endif { int i_inner_iteration; int width = wx->width; int height = wx->height; int stride = wx->stride; image_t *du = image_new(width,height), *dv = image_new(width,height), // the flow increment *mask = image_new(width,height), // mask containing 0 if a point goes outside image boundary, 1 otherwise *smooth_horiz = image_new(width,height), *smooth_vert = image_new(width,height), // horiz: (i,j) contains the diffusivity coeff. from (i,j) to (i+1,j) *uu = image_new(width,height), *vv = image_new(width,height), // flow plus flow increment *a11 = image_new(width,height), *a12 = image_new(width,height), *a22 = image_new(width,height), // system matrix A of Ax=b for each pixel *b1 = image_new(width,height), *b2 = image_new(width,height); // system matrix b of Ax=b for each pixel #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) // use single band image image_t *w_im2 = image_new(width,height), // warped second image *Ix = image_new(width,height), *Iy = image_new(width,height), *Iz = image_new(width,height), // first order derivatives *Ixx = image_new(width,height), *Ixy = image_new(width,height), *Iyy = image_new(width,height), *Ixz = image_new(width,height), *Iyz = image_new(width,height); // second order derivatives #else // use RGB image color_image_t *w_im2 = color_image_new(width,height), // warped second image *Ix = color_image_new(width,height), *Iy = color_image_new(width,height), *Iz = color_image_new(width,height), // first order derivatives *Ixx = color_image_new(width,height), *Ixy = color_image_new(width,height), *Iyy = color_image_new(width,height), *Ixz = color_image_new(width,height), *Iyz = color_image_new(width,height); // second order derivatives #endif // warp second image image_warp(w_im2, mask, im2, wx, wy); // compute derivatives get_derivatives(im1, w_im2, deriv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz); // erase du and dv image_erase(du); image_erase(dv); // initialize uu and vv memcpy(uu->c1,wx->c1,wx->stride*wx->height*sizeof(float)); memcpy(vv->c1,wy->c1,wy->stride*wy->height*sizeof(float)); // inner fixed point iterations for(i_inner_iteration = 0 ; i_inner_iteration < tvparams.n_inner_iteration ; i_inner_iteration++) { // compute robust function and system compute_smoothness(smooth_horiz, smooth_vert, uu, vv, deriv_flow, tvparams.tmp_quarter_alpha ); //compute_data_and_match(a11, a12, a22, b1, b2, mask, wx, wy, du, dv, uu, vv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, desc_weight, desc_flow_x, desc_flow_y, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3); compute_data(a11, a12, a22, b1, b2, mask, wx, wy, du, dv, uu, vv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3); sub_laplacian(b1, wx, smooth_horiz, smooth_vert); sub_laplacian(b2, wy, smooth_horiz, smooth_vert); // solve system #ifdef WITH_OPENMP sor_coupled_slow_but_readable(du, dv, a11, a12, a22, b1, b2, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega); // slower but parallelized #else sor_coupled(du, dv, a11, a12, a22, b1, b2, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega); #endif // update flow plus flow increment int i; v4sf *uup = (v4sf*) uu->c1, *vvp = (v4sf*) vv->c1, *wxp = (v4sf*) wx->c1, *wyp = (v4sf*) wy->c1, *dup = (v4sf*) du->c1, *dvp = (v4sf*) dv->c1; for( i=0 ; i<height*stride/4 ; i++) { (*uup) = (*wxp) + (*dup); (*vvp) = (*wyp) + (*dvp); uup+=1; vvp+=1; wxp+=1; wyp+=1;dup+=1;dvp+=1; } } // add flow increment to current flow memcpy(wx->c1,uu->c1,uu->stride*uu->height*sizeof(float)); memcpy(wy->c1,vv->c1,vv->stride*vv->height*sizeof(float)); // free memory image_delete(du); image_delete(dv); image_delete(mask); image_delete(smooth_horiz); image_delete(smooth_vert); image_delete(uu); image_delete(vv); image_delete(a11); image_delete(a12); image_delete(a22); image_delete(b1); image_delete(b2); #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) // use single band image image_delete(w_im2); image_delete(Ix); image_delete(Iy); image_delete(Iz); image_delete(Ixx); image_delete(Ixy); image_delete(Iyy); image_delete(Ixz); image_delete(Iyz); #else color_image_delete(w_im2); color_image_delete(Ix); color_image_delete(Iy); color_image_delete(Iz); color_image_delete(Ixx); color_image_delete(Ixy); color_image_delete(Iyy); color_image_delete(Ixz); color_image_delete(Iyz); #endif } #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) void VarRefClass::RefLevelDE(image_t *wx, const image_t *im1, const image_t *im2) #else void VarRefClass::RefLevelDE(image_t *wx, const color_image_t *im1, const color_image_t *im2) #endif { int i_inner_iteration; int width = wx->width; int height = wx->height; int stride = wx->stride; image_t *du = image_new(width,height), *wy_dummy = image_new(width,height), // the flow increment *mask = image_new(width,height), // mask containing 0 if a point goes outside image boundary, 1 otherwise *smooth_horiz = image_new(width,height), *smooth_vert = image_new(width,height), // horiz: (i,j) contains the diffusivity coeff. from (i,j) to (i+1,j) *uu = image_new(width,height), // flow plus flow increment *a11 = image_new(width,height), // system matrix A of Ax=b for each pixel *b1 = image_new(width,height); // system matrix b of Ax=b for each pixel image_erase(wy_dummy); #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) // use single band image image_t *w_im2 = image_new(width,height), // warped second image *Ix = image_new(width,height), *Iy = image_new(width,height), *Iz = image_new(width,height), // first order derivatives *Ixx = image_new(width,height), *Ixy = image_new(width,height), *Iyy = image_new(width,height), *Ixz = image_new(width,height), *Iyz = image_new(width,height); // second order derivatives #else // use RGB image color_image_t *w_im2 = color_image_new(width,height), // warped second image *Ix = color_image_new(width,height), *Iy = color_image_new(width,height), *Iz = color_image_new(width,height), // first order derivatives *Ixx = color_image_new(width,height), *Ixy = color_image_new(width,height), *Iyy = color_image_new(width,height), *Ixz = color_image_new(width,height), *Iyz = color_image_new(width,height); // second order derivatives #endif // warp second image image_warp(w_im2, mask, im2, wx, wy_dummy); // compute derivatives get_derivatives(im1, w_im2, deriv, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz); // erase du and dv image_erase(du); // initialize uu and vv memcpy(uu->c1,wx->c1,wx->stride*wx->height*sizeof(float)); // inner fixed point iterations for(i_inner_iteration = 0 ; i_inner_iteration < tvparams.n_inner_iteration ; i_inner_iteration++) { // compute robust function and system compute_smoothness(smooth_horiz, smooth_vert, uu, wy_dummy, deriv_flow, tvparams.tmp_quarter_alpha ); compute_data_DE(a11, b1, mask, wx, du, uu, Ix, Iy, Iz, Ixx, Ixy, Iyy, Ixz, Iyz, tvparams.tmp_half_delta_over3, tvparams.tmp_half_beta, tvparams.tmp_half_gamma_over3); sub_laplacian(b1, wx, smooth_horiz, smooth_vert); // solve system sor_coupled_slow_but_readable_DE(du, a11, b1, smooth_horiz, smooth_vert, tvparams.n_solver_iteration, tvparams.sor_omega); // update flow plus flow increment int i; v4sf *uup = (v4sf*) uu->c1, *wxp = (v4sf*) wx->c1, *dup = (v4sf*) du->c1; if(cpt->camlr==0) // check if right or left camera, needed to truncate values above/below zero { for( i=0 ; i<height*stride/4 ; i++) { (*uup) = __builtin_ia32_minps( (*wxp) + (*dup) , op->zero); uup+=1; wxp+=1; dup+=1; } } else { for( i=0 ; i<height*stride/4 ; i++) { (*uup) = __builtin_ia32_maxps( (*wxp) + (*dup) , op->zero); uup+=1; wxp+=1; dup+=1; } } } // add flow increment to current flow memcpy(wx->c1,uu->c1,uu->stride*uu->height*sizeof(float)); // free memory image_delete(du); image_delete(wy_dummy); image_delete(mask); image_delete(smooth_horiz); image_delete(smooth_vert); image_delete(uu); image_delete(a11); image_delete(b1); #if (SELECTCHANNEL==1 | SELECTCHANNEL==2) image_delete(w_im2); image_delete(Ix); image_delete(Iy); image_delete(Iz); image_delete(Ixx); image_delete(Ixy); image_delete(Iyy); image_delete(Ixz); image_delete(Iyz); #else color_image_delete(w_im2); color_image_delete(Ix); color_image_delete(Iy); color_image_delete(Iz); color_image_delete(Ixx); color_image_delete(Ixy); color_image_delete(Iyy); color_image_delete(Ixz); color_image_delete(Iyz); #endif } VarRefClass::~VarRefClass() { } }
41.075581
248
0.635598
beaupreda
8ab64d5486081801d453ef1f87e7fca04e93fc32
8,510
tpp
C++
sequitur/baselist.tpp
lytnus/cpp-sequitur
a27a5d1ad85b78d6366f74d2be18d3727d5bce94
[ "MIT" ]
null
null
null
sequitur/baselist.tpp
lytnus/cpp-sequitur
a27a5d1ad85b78d6366f74d2be18d3727d5bce94
[ "MIT" ]
null
null
null
sequitur/baselist.tpp
lytnus/cpp-sequitur
a27a5d1ad85b78d6366f74d2be18d3727d5bce94
[ "MIT" ]
null
null
null
template<typename Child> template<typename Function> Child * BaseList<Child>::forUntil(const Function & f) { BaseList * item = this; BaseList * next; while(item) { next = item->next_ptr; if(!f(static_cast<Child*>(item))) break; item = next; } return static_cast<Child*>(item); } template<typename Child> template<typename Function> Child * BaseList<Child>::reverseForUntil(const Function & f) { BaseList * item = this; BaseList * prev; while(item) { prev = item->prev_ptr; if(!f(static_cast<Child*>(item))) break; item = prev; } return static_cast<Child*>(item); } template<typename Child> template<typename Function> const Child * BaseList<Child>::forUntil(const Function & f) const { const BaseList * item = this; const BaseList * next; while(item) { next = item->next_ptr; if(!f(static_cast<const Child*>(item))) break; item = next; } return static_cast<const Child*>(item); } template<typename Child> template<typename Function> const Child * BaseList<Child>::reverseForUntil(const Function & f) const { const BaseList * item = this; const BaseList * prev; while(item) { prev = item->prev_ptr; if(f(static_cast<const Child*>(item))) break; item = prev; } return static_cast<const Child*>(item); } template<typename Child> Child * BaseList<Child>::unlink(unsigned int number) { if(!number) throw std::range_error("Cannot unlick 0 items."); //find the required items: BaseList * this_prev = this->prev_ptr; //possibly nullptr BaseList * this_last = this->next(number-1); BaseList * this_after = this_last->next_ptr; //possibly nullptr //do the unlinking: this->prev_ptr = nullptr; this_last->next_ptr = nullptr; if(this_prev) this_prev->next_ptr = this_after; if(this_after) this_after->prev_ptr = this_prev; //return last item in unlinked chain: return static_cast<Child*>(this_last); } template<typename Child> Child * BaseList<Child>::reverseUnlink(unsigned int number) { if(!number) throw std::range_error("Cannot unlick 0 items."); //find the required items: BaseList * this_after = this->next_ptr; //possibly nullptr BaseList * this_first = this->prev(number-1); BaseList * this_before = this_first->prev_ptr; //possibly nullptr //do the unlinking: this_first->prev_ptr = nullptr; this->next_ptr = nullptr; if(this_before) this_before->next_ptr = this_after; if(this_after) this_after->prev_ptr = this_before; //return first item in unlinked chain: return static_cast<Child*>(this_first); } template<typename Child> Child * BaseList<Child>::splitBefore() { if(!this->prev_ptr) throw std::range_error("no items before to split from."); BaseList * prev = this->prev_ptr; prev->next_ptr = nullptr; this->prev_ptr = nullptr; return static_cast<Child*>(prev); } template<typename Child> Child * BaseList<Child>::splitAfter() { if(!this->next_ptr) throw std::range_error("no items after to split from."); BaseList * next = this->next_ptr; next->prev_ptr = nullptr; this->next_ptr = nullptr; return static_cast<Child*>(next); } template<typename Child> void BaseList<Child>::joinBefore(Child * other) { if(this->prev_ptr || other->next_ptr) throw std::runtime_error("joining must join ends of two lists."); this->prev_ptr = other; other->next_ptr = this; } template<typename Child> void BaseList<Child>::joinAfter(Child * other) { if(this->next_ptr || other->prev_ptr) throw std::runtime_error("joining must join ends of two lists."); this->next_ptr = other; other->prev_ptr = this; } template<typename Child> Child * BaseList<Child>::insertAfter(Child * list, unsigned int number) { if(!number) throw std::range_error("insertAfter: number items to add should be > 0"); //get a couple of pointers: BaseList * this_after = this->next_ptr; //potentially nullptr BaseList * list_prev = list->prev_ptr; //potentially nullptr //link first item in new list with current item: this->next_ptr = list; list->prev_ptr = this; //find last and one past last item in new list: BaseList * list_last = list->next(number-1); BaseList * list_after = list_last->next_ptr; //potentially nullptr //link last item in new list up: list_last->next_ptr = this_after; if(this_after) this_after->prev_ptr = list_last; //link input list together again (we've just cut a chunk out): if(list_prev) list_prev->next_ptr = list_after; if(list_after) list_after->prev_ptr = list_prev; return static_cast<Child*>(list_last); } template<typename Child> Child * BaseList<Child>::insertBefore(Child *list, unsigned int number) { //get a couple of pointers: BaseList * this_prev = this->prev_ptr; //potentialls nullptr BaseList * list_prev = list->prev_ptr; //potentially nullptr //link first item in new list with this_prev: if(this_prev) this_prev->next_ptr = list; list->prev_ptr = this_prev; //find last item in new list: BaseList * list_last = list->next(number-1); BaseList * list_after = list_last->next_ptr; //potentially nullptr //link last item in new list with this: list_last->next_ptr = this; this->prev_ptr = list_last; //link input list together again: if(list_prev) list_prev->next_ptr = list_after; if(list_after) list_after->prev_ptr = list_prev; return static_cast<Child*>(list); } template<typename Child> const Child * BaseList<Child>::next() const { return static_cast<const Child*>(this->next_ptr); } template<typename Child> const Child * BaseList<Child>::prev() const { return static_cast<const Child*>(this->prev_ptr); } template<typename Child> Child * BaseList<Child>::next() { return static_cast<Child*>(this->next_ptr); } template<typename Child> Child * BaseList<Child>::prev() { return static_cast<Child*>(this->prev_ptr); } template<typename Child> const Child * BaseList<Child>::next(unsigned int number) const { if(!number) return static_cast<const Child*>(this); const BaseList * output = this; while(number--) { if(!output) throw std::range_error("next: trying to access item which does not exist."); output = output->next_ptr; } return static_cast<const Child*>(output); } template<typename Child> const Child * BaseList<Child>::prev(unsigned int number) const { if(!number) return static_cast<const Child*>(this); const BaseList * output = this; while(number--) { if(!output) throw std::range_error("prev: trying to access item which does not exist."); output = output->prev_ptr; } return static_cast<const Child*>(output); } //non const versions of next and prev: template<typename Child> Child * BaseList<Child>::next(unsigned int number) { return (Child*)(const_cast<const BaseList*>(this)->next(number)); } template<typename Child> Child * BaseList<Child>::prev(unsigned int number) { return (Child*)(const_cast<const BaseList*>(this)->prev(number)); } template<typename Child> std::pair<const Child*,unsigned> BaseList<Child>::end() const { unsigned int count = 0; const BaseList * output = this; while(output->next_ptr) { ++count; output = output->next_ptr; } return std::make_pair(static_cast<const Child*>(output), count); } template<typename Child> std::pair<const Child*,unsigned> BaseList<Child>::begin() const { unsigned int count = 0; const BaseList * output = this; while(output->prev_ptr) { ++count; output = output->prev_ptr; } return std::make_pair(static_cast<const Child*>(output), count); } template<typename Child> std::pair<Child*,unsigned> BaseList<Child>::end() { auto output = const_cast<const BaseList*>(this)->end(); return std::make_pair((Child*)(output.first), output.second); } template<typename Child> std::pair<Child*,unsigned> BaseList<Child>::begin() { auto output = const_cast<const BaseList*>(this)->begin(); return std::make_pair((Child*)(output.first), output.second); }
28.945578
100
0.656287
lytnus
8ab88ddf7e6939fb526c63898c03de4a0c93e63c
4,381
hpp
C++
src/core/logic/RBAConstraintInfo.hpp
NaohiroNISHIGUCHI/RBA
ac86e4ffa643b8050b25161c951bb43f4e36235a
[ "Apache-2.0" ]
2
2020-07-17T11:13:48.000Z
2020-07-30T09:37:08.000Z
src/core/logic/RBAConstraintInfo.hpp
NaohiroNISHIGUCHI/RBA
ac86e4ffa643b8050b25161c951bb43f4e36235a
[ "Apache-2.0" ]
null
null
null
src/core/logic/RBAConstraintInfo.hpp
NaohiroNISHIGUCHI/RBA
ac86e4ffa643b8050b25161c951bb43f4e36235a
[ "Apache-2.0" ]
3
2020-06-25T07:19:19.000Z
2020-06-26T13:06:13.000Z
/** * Copyright (c) 2019 DENSO CORPORATION. * * 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. */ /// ConstraintInfo (Constraint expression Information) class header #ifndef RBACONSTRAINTINFO_HPP #define RBACONSTRAINTINFO_HPP #include <cstdint> #include <memory> #include <set> #include <vector> #include "RBAExecuteResult.hpp" #include "RBADllExport.hpp" namespace rba { class RBAAllocatable; class RBAExpression; class DLL_EXPORT RBAConstraintInfo { public: RBAConstraintInfo()=default; RBAConstraintInfo(const RBAConstraintInfo&)=delete; RBAConstraintInfo(const RBAConstraintInfo&&)=delete; RBAConstraintInfo& operator=(const RBAConstraintInfo&)=delete; RBAConstraintInfo& operator=(const RBAConstraintInfo&&)=delete; virtual ~RBAConstraintInfo()=default; public: void setExpression(const RBAExpression* const expression); const RBAExpression* getExpression() const; void addOperandAllocatable(const RBAAllocatable* const operandAllocatable); void setResult(const RBAExecuteResult result); RBAConstraintInfo* getChild(const std::uint32_t index) const; void setChild(const std::shared_ptr<RBAConstraintInfo> info); void addTrueAllocatable(const RBAAllocatable* const allocatable); void addFalseAllocatable(const RBAAllocatable* const allocatable); void addTrueAllocatableFromOperand(); void addFalseAllocatableFromOperand(); void clearFalseAllocatable(); const bool isImplies() const; void clear(); bool isExceptionBeforeArbitrate() const; void setExceptionBeforeArbitrate(const bool exceptionBeforeArbitrate); /// @brief Determine the need for re-arbitration /// @param [in] allocatable Allcatable druing arbitration /// @param [in] isImplies Whether the constraint expression contains /// implication syntax. /// @return Necessity of re-arbitration (true: need / false: No need) bool needsRearbitrationFor(const RBAAllocatable* const allocatable, bool isImplies = false) const; bool needsReRearbitrationFor(const RBAAllocatable* const allocatable) const; void collectRearbitrationTargetFor(const RBAAllocatable* const allocatable, std::set<const RBAAllocatable*>& targets, const bool isNot) const; void collectTrueAllocatables(std::set<const RBAAllocatable*>& allocatables) const; void collectFalseAllocatables(std::set<const RBAAllocatable*>& allocatables) const; bool contains(const RBAAllocatable* const allocatable) const; bool isTrue() const; bool isFalse() const; /// @brief Extraction of affected Area/Zone /// @param [in] isRevert Negative context (true: inside / false: outside) /// @param [out] affectAllocatables List of affected Allcatable /// @param [out] collecting Collection target context /// (true: inside / false: outside) /// @param [out] forObject ReferenceObject context /// (true: inside / false: outside) /// @return Necessity of re-arbitration (true: need / false: No need) void collectAffectedAllocatables( const bool isRevert, std::set<const RBAAllocatable*>& affectAllocatables, const bool collecting, const bool forObject); private: bool isRevert() const; bool isSizeOperator() const; private: bool exceptionBeforeArbitrate_ {false}; const RBAExpression* expression_ {nullptr}; RBAExecuteResult result_ {RBAExecuteResult::SKIP}; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4251) #endif std::set<const RBAAllocatable*> trueAllocatables_; std::set<const RBAAllocatable*> falseAllocatables_; std::set<const RBAAllocatable*> operandAllocatable_; // use to respond with an empty set const std::set<const RBAAllocatable*> emptyAllocatables_; mutable std::vector<std::shared_ptr<RBAConstraintInfo>> children_; #ifdef _MSC_VER #pragma warning(pop) #endif }; } #endif
36.508333
85
0.749372
NaohiroNISHIGUCHI
8ab8c4924a9f9cbbc1f408e8081c8f98694d7fcf
216
cpp
C++
test/startstop.cpp
davidmoreno/opp
16cfd074e132cdd0623eb013a16a891d80185dad
[ "Apache-2.0" ]
4
2018-11-09T19:50:56.000Z
2021-03-24T16:34:19.000Z
test/startstop.cpp
davidmoreno/opp
16cfd074e132cdd0623eb013a16a891d80185dad
[ "Apache-2.0" ]
null
null
null
test/startstop.cpp
davidmoreno/opp
16cfd074e132cdd0623eb013a16a891d80185dad
[ "Apache-2.0" ]
null
null
null
#include "opp.hpp" #include "vm.hpp" int main(){ fprintf(stderr, "Main Start\n"); opp::start(); opp::vm->print_stats(); opp::stop(); fprintf(stderr, "Main Stop, %ld uses of vm.\n", opp::vm.use_count()); }
19.636364
71
0.611111
davidmoreno
8abc6a8ce6b9b0fedda56fa8e936657f88c8a0d6
13,258
hh
C++
src/zone.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/zone.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/zone.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
1
2019-01-24T16:14:56.000Z
2019-01-24T16:14:56.000Z
// zone.hh #ifndef ZONE_HEADER #define ZONE_HEADER #include <clipper/clipper.h> #include "hkl_datatypes.hh" #include "range.hh" #include "globalcontrols.hh" #include "hkl_symmetry.hh" #include "score_datatypes.hh" namespace scala { //-------------------------------------------------------------- double IscoreVal(const IsigI& Isig); // Score function value from I,sig // = I/sigI //================================================================= class IndexIsigI { public: IndexIsigI(){} IndexIsigI(const int& j, const IsigI& Is) : index(j), Isig(Is) {} int index; IsigI Isig; }; //================================================================= class OneDFourier // One-dimensional Fourier, just a few grid points (eg 0, 1/2) { public: OneDFourier(){} OneDFourier(const std::vector<int>& Ngrid); OneDFourier(const std::vector<double>& Xgrid); // Add into totals void AddRef(const int& j, const double& Val); // Return number of contributions int Nobs() const; std::vector<double> FourierVal() const; private: std::vector<int> ngrid; // grid intervals are 1/ngrid std::vector<double> xgrid; std::vector<double> Sumx; int nobs; }; //================================================================= class Zone { public: Zone() {} // dummy constructor // Construct for screw axis // Axis == a,b,c // Nfold is order of axis // Nfold negated to test only the 1/Nfold point // (sets validpoint array) // this allows testing of 4(1) but not 4(2) // LGsym is Laue group symmetry Zone(const std::string& Axis, const int& Nfold, const hkl_symmetry& LGsym); // Construct for glide plane // GlidePlane == a,b,c,110,101,101 (normal to mirror) // Glide = a,b,c,n,d glide direction // LGsym is Laue group symmetry Zone(const std::string& GlidePlane, const std::string& Glide, const hkl_symmetry& LGsym); // return true if hkl is in defined zone bool InZone(const Hkl& hkl) const; // Return zone type, true if axis, false if glide bool Axis() const {return axis;} // Return angular order int Order() const {return order;} // Format zone, in "new" frame // RefToNew is reindex operator from "reference" (lattice) frame // (stored with StoreReindex function) to some new frame in // which to format the zone // if Sub > 1, the screw component is order/Sub std::string formatNewFrame(const ReindexOp& RefToNew, const int Sub=1) const; std::string formatRefFrame(const int Sub=1) const; // Format in Laue group frame std::string formatLGFrame(const int Sub=1) const; // Format condition, eg "0kl: h+k = 2n" // For axis, Sub is grid point std::string FormatConditionNewFrame(const ReindexOp& RefToNew, const int Sub=1) const; std::string FormatConditionRefFrame(const int Sub=1) const; std::string FormatConditionLGFrame(const int Sub=1) const; // Axis direction in reference frame std::string Direction() const; // Return true if two zones apply to the same hkl zone // Glides only, eg b(a), c(a), n(a) all apply to 0kl bool SameZone(const Zone& other) const; // Add into totals void AddRef(const Hkl& hkl, const IsigI& Isig, const float& sSqr); // Store SD of control reflections for Z-score // Adjust to avoid zeroes, but set flag to indicate this void StoreMeanSD(const std::vector<double>& Mean, const std::vector<double>& SD); // Store reindex from some standard reference frame, for comparison of zones void StoreReindex(const ReindexOp& reindexin); ReindexOp Reindex() const {return reindexmat;} // Store overall probability if valid, ie except for 4- & 6-fold screws // fail if invalid void StoreProb(const double& ProbYes); // Return Laue group symmetry hkl_symmetry LGsymm() const {return lgsymm;} // Return Fourier values at each grid point std::vector<double> FourierVal() const; // Return probability at each grid point std::vector<double> p() const; // Return overall probability if valid, ie except for 4- & 6-fold screws // fail if invalid double Prob() const; // Return grid points std::vector<int> Ngrid() const {return ngrid;} // Return number of grid points int NgridPoints() const {return npoint;} // Return number of contributions int Nobs() const; // Inverse resolution range Range InvResoRange() const {return InvResRange;} // Return minimum & maximum indices std::pair<int,int> IndexRange() const {return std::pair<int,int>(minIndx, maxIndx);} // Return list of indices std::vector<int> Indices() const; // Return valid flag bool Valid() const {return (valid);} // bool Valid() const {return (valid && active);} bool ValidPoint(const int& ig) const {return validpoint.at(ig);} // Return SD of control reflections for Z-score double GetSD(const int& i) const {return controlsd[i];} // Return true if data are systematically missing eg all odd indices bool PrunedData() const { // Return true if any are true for (int i=0;i<npoint;++i) { if (prunedData[i]) {return true;} } return false; } // Return true if data are systematically missing eg all odd indices bool PrunedData(const int& i) const {return prunedData[i];} // Return two test hkl which will be systematically absent // if in this zone, for glide planes // RefToNew is reindex operator from "reference" (lattice) frame // (stored with StoreReindex function) to some new frame in // which to return the indices std::vector<Hkl> GlideTestHkl(const ReindexOp& RefToNew) const; // Return test hkl's which will be systematically absent // if in this zone, for axes pricipal only, not 110) // One test hkl for each grid point, test in reverse order std::vector<Hkl> AxisTestHkl(const ReindexOp& RefToNew, std::vector<std::vector<int> >& screwabsence) const; std::vector<IndexIsigI> IndexedData() const {return IndxIsigI;} // weighted average I, sigma std::vector<IsigI> AverageIsigI() const { return averageIsigI;} // average I,sig after neighbour "correction" std::vector<IsigI> AdjustedIsigI() const {return adjustedIsigI;} // Fraction of intensity on screw axis to subtract from neighbouring reflection static void SetNeighbourFraction(const float& nf) {neighbourFraction = nf;} static float GetNeighbourFraction() {return neighbourFraction;} void dump() const; // For sorting, all glides after axes, then on order friend bool operator < (const Zone& a,const Zone& b) // true if a before b in sort order { if (a.axis) { if (!b.axis) return true; // b is glide, a is axis } else { if (b.axis) return false; // a is glide, b is axis } // Same, compare "order" return a.order > b.order; } // Compare two zones, return true if equivalent after allowing for reindexing bool Compare(const Zone& other) const; private: void init(const bool& disable); void TestValidIndices() const; void CalcResults() const; Hkl CondReference() const; std::vector<double> GetFourierValues() const; std::vector<IsigI> AverageI(const std::vector<IndexIsigI>& IdxIs) const; clipper::Vec3<double> DirectionRefFrame() const; // Get zone direction in reference frame // vector returned is axis direction or zone normal (for glide plane) // Permutation operator to convert input hkl to internal // standard h'T = hT [P] // Axis: 00l // Principle glide: hk0 // Diagonal glide: hhl ReindexOp permute; // Reindex from lattice frame to internal standard [P'] = [H] [P] ReindexOp permuteIndex; // Index along axis = [hc].qc // where hc is hkl in constructor frame & // cond = qc // cond is stored here permuted by [P] permutation // to convert external hkl clipper::Vec3<int> cond; // qcond = ql = [H] qc where [H] is the reindexing operator from // external reference (lattice) frame // Note that cond = qc is integral, while qcond = ql // may be half-integral if the lattice is centred clipper::Vec3<double> qcond; // Direction is axis direction or glide plane // "a", "b" "c", "110", "101", or "011" std::string direction; std::string glide; int order; bool axis; // true if axis, false if glideplane bool diagonal; // true if glide zone is diagonal ie 110 Range InvResRange; std::vector<IndexIsigI> IndxIsigI; int minIndx; int maxIndx; // next 2 vectors indexed by axial index 0 -> maxIndx mutable std::vector<IsigI> averageIsigI; // weighted average I, sigma mutable std::vector<IsigI> adjustedIsigI; // average I,sig after neighbour "correction" mutable std::vector<bool> validpoint; // Permanent flag for each point // this will set to false to avoid testing // this grid point, eg so as not to test // 4(2) axes in an I or F lattice // Totals for Fourier analysis std::vector<int> ngrid; // grid intervals are 1/ngrid // eg for 6-fold axis, ngrid = (1,2,3,6) mutable OneDFourier fsum; // 1D Fourier at grid intervals std::vector<double> controlsd; // Standard deviation of control score for each grid point std::vector<double> controlmean; // ... and its mean int npoint; // ngrid.size() bool ZeroControlSD; // at least one control SD was zero before resetting std::vector<bool> UnitControlMean; // at least one control Mean == 1.0 and control SD == 0.0 static double MinControlSD; // fraction of neighbouring reflection to subtract from intensity static float neighbourFraction; // Reindex operator from reference cell to constructor frame // for comparison of zones ReindexOp reindexmat; bool NonIdentityReindex; // true if reindexmat is not identity hkl_symmetry lgsymm; // Laue group symmetry bool singleprob; // true if only the last probability (Fourier) // point is useful. This is the case for all glides // and 2- & 3-fold screws // Things set in method CalcResults mutable bool valid; // true if we have enough data mutable bool results; mutable std::vector<double> Pfor; mutable double prob_yes; // unique probability values if singleprob = true mutable std::vector<bool> prunedData; // true if indices of reflection data are // systematically missing (eg only even orders) // so that the zone is indeterminate }; // Zone //================================================================ class SysAbsScore // Class to accumulate & calculate total "score" for systematic absences // in a putative spacegroup // Each condition (eg A) provide a probability p(A) which is // multiplied in either as p(A) or p(!A) = 1-p(A) depending on the // putative spacegroup // { public: SysAbsScore() : possible(true), TotalProb(1.0), n(0) {} SysAbsScore(const PossibleSpaceGroup& PSG) : possible(true), TotalProb(1.0), n(0), PossibleSG(PSG) {} // Add in contribution (only if non-zero) void ProbYes(const double& p) {if (p >= 0.0) {TotalProb *= p; n++;}} // Add in 1-contribution void ProbNo(const double& p) {if (p >= 0.0) {TotalProb *= 1.0-p; n++;}} // Set as impossible void Impossible() {possible=false;} // Set as possible void Possible() {possible=true;} // Set condition string void SetCondition(const std::string& cnd) {condition = cnd;} // Set condition string void SetConditionLG(const std::string& cnd) {conditionLG = cnd;} // Possible spacegroup void SetSGposs(const PossibleSpaceGroup& PSG) {PossibleSG = PSG;} // Normalise by multiplying factor void Normalise(const double& fac) {TotalProb *= fac;} // Add zone number to list void AddZone(const int& izone) {zonesingroup.push_back(izone);} // Return zone list std::vector<int> ZoneList() const {return zonesingroup;} // Return true if zone iz is in group bool IsZoneInGroup(const int& iz) const; // return total probability double TotalProbability() const {return TotalProb;} // Possible flag bool IsPossible() const {return possible;} // Condition string std::string Condition() const {return condition;} // Condition string Laue group frame std::string ConditionLG() const {return conditionLG;} PossibleSpaceGroup SGposs() const {return PossibleSG;} private: bool possible; double TotalProb; int n; std::string condition; std::string conditionLG; // Laue group frame PossibleSpaceGroup PossibleSG; std::vector<int> zonesingroup; // list of zone numbers in this group }; // SysAbsScore } #endif
37.88
106
0.634787
maciejwlodek
8abda83e0b68f1fff8e78a04114364a6df537726
442
cpp
C++
src/Command.cpp
Tosi/wadutil
2806999d8a3e9739236df858ec0268a9764c8a9f
[ "MIT" ]
null
null
null
src/Command.cpp
Tosi/wadutil
2806999d8a3e9739236df858ec0268a9764c8a9f
[ "MIT" ]
null
null
null
src/Command.cpp
Tosi/wadutil
2806999d8a3e9739236df858ec0268a9764c8a9f
[ "MIT" ]
null
null
null
#include "Command.h" #include <fstream> using std::string; using std::ifstream; using std::ofstream; using std::ios; Command::Command(const string& input_filename, const string& output_filename) : in_file(input_filename), out_file(output_filename) { has_input = false; has_output = false; if(in_file != "") { has_input = true; } if(out_file != "") { has_output = true; } } Command::~Command() { }
19.217391
77
0.642534
Tosi
8abe584c375958dc0d0480e530d3d42119dc147f
16,021
hpp
C++
external/boost_1_60_0/qsboost/proto/detail/deprecated.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/proto/detail/deprecated.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/proto/detail/deprecated.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// \file deprecated.hpp /// Definition of the deprecated BOOST_PROTO_DEFINE_FUCTION_TEMPLATE and /// BOOST_PROTO_DEFINE_VARARG_FUCTION_TEMPLATE macros // // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef QSBOOST_PROTO_DETAIL_DEPRECATED_HPP_EAN_11_25_2008 #define QSBOOST_PROTO_DETAIL_DEPRECATED_HPP_EAN_11_25_2008 #include <qsboost/preprocessor/cat.hpp> #include <qsboost/preprocessor/facilities/intercept.hpp> #include <qsboost/preprocessor/arithmetic/inc.hpp> #include <qsboost/preprocessor/arithmetic/dec.hpp> #include <qsboost/preprocessor/arithmetic/sub.hpp> #include <qsboost/preprocessor/punctuation/comma_if.hpp> #include <qsboost/preprocessor/control/if.hpp> #include <qsboost/preprocessor/control/expr_if.hpp> #include <qsboost/preprocessor/comparison/greater.hpp> #include <qsboost/preprocessor/tuple/elem.hpp> #include <qsboost/preprocessor/tuple/to_list.hpp> #include <qsboost/preprocessor/logical/and.hpp> #include <qsboost/preprocessor/seq/size.hpp> #include <qsboost/preprocessor/seq/enum.hpp> #include <qsboost/preprocessor/seq/seq.hpp> #include <qsboost/preprocessor/seq/to_tuple.hpp> #include <qsboost/preprocessor/seq/for_each_i.hpp> #include <qsboost/preprocessor/seq/pop_back.hpp> #include <qsboost/preprocessor/seq/push_back.hpp> #include <qsboost/preprocessor/seq/push_front.hpp> #include <qsboost/preprocessor/list/for_each_i.hpp> #include <qsboost/preprocessor/repetition/repeat.hpp> #include <qsboost/preprocessor/repetition/repeat_from_to.hpp> #include <qsboost/preprocessor/repetition/enum_binary_params.hpp> #include <qsboost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <qsboost/proto/proto_fwd.hpp> /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_TEMPLATE_AUX_(R, DATA, I, ELEM) \ (ELEM QSBOOST_PP_CAT(QSBOOST_PP_CAT(X, DATA), QSBOOST_PP_CAT(_, I))) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_TEMPLATE_YES_(R, DATA, I, ELEM) \ QSBOOST_PP_LIST_FOR_EACH_I_R( \ R \ , QSBOOST_PROTO_VARARG_TEMPLATE_AUX_ \ , I \ , QSBOOST_PP_TUPLE_TO_LIST( \ QSBOOST_PP_DEC(QSBOOST_PP_SEQ_SIZE(ELEM)) \ , QSBOOST_PP_SEQ_TO_TUPLE(QSBOOST_PP_SEQ_TAIL(ELEM)) \ ) \ ) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_TEMPLATE_NO_(R, DATA, I, ELEM) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_TEMPLATE_(R, DATA, I, ELEM) \ QSBOOST_PP_IF( \ QSBOOST_PP_DEC(QSBOOST_PP_SEQ_SIZE(ELEM)) \ , QSBOOST_PROTO_VARARG_TEMPLATE_YES_ \ , QSBOOST_PROTO_VARARG_TEMPLATE_NO_ \ )(R, DATA, I, ELEM) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_TYPE_AUX_(R, DATA, I, ELEM) \ (QSBOOST_PP_CAT(QSBOOST_PP_CAT(X, DATA), QSBOOST_PP_CAT(_, I))) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_TEMPLATE_PARAMS_YES_(R, DATA, I, ELEM) \ < \ QSBOOST_PP_SEQ_ENUM( \ QSBOOST_PP_LIST_FOR_EACH_I_R( \ R \ , QSBOOST_PROTO_VARARG_TYPE_AUX_ \ , I \ , QSBOOST_PP_TUPLE_TO_LIST( \ QSBOOST_PP_DEC(QSBOOST_PP_SEQ_SIZE(ELEM)) \ , QSBOOST_PP_SEQ_TO_TUPLE(QSBOOST_PP_SEQ_TAIL(ELEM)) \ ) \ ) \ ) \ > \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_TEMPLATE_PARAMS_NO_(R, DATA, I, ELEM) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_TYPE_(R, DATA, I, ELEM) \ QSBOOST_PP_COMMA_IF(I) \ QSBOOST_PP_SEQ_HEAD(ELEM) \ QSBOOST_PP_IF( \ QSBOOST_PP_DEC(QSBOOST_PP_SEQ_SIZE(ELEM)) \ , QSBOOST_PROTO_TEMPLATE_PARAMS_YES_ \ , QSBOOST_PROTO_TEMPLATE_PARAMS_NO_ \ )(R, DATA, I, ELEM) QSBOOST_PP_EXPR_IF(QSBOOST_PP_GREATER(I, 1), const) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_AS_EXPR_(R, DATA, I, ELEM) \ QSBOOST_PP_EXPR_IF( \ QSBOOST_PP_GREATER(I, 1) \ , (( \ QSBOOST_PP_SEQ_HEAD(ELEM) \ QSBOOST_PP_IF( \ QSBOOST_PP_DEC(QSBOOST_PP_SEQ_SIZE(ELEM)) \ , QSBOOST_PROTO_TEMPLATE_PARAMS_YES_ \ , QSBOOST_PROTO_TEMPLATE_PARAMS_NO_ \ )(R, DATA, I, ELEM)() \ )) \ ) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_AS_CHILD_(Z, N, DATA) \ (QSBOOST_PP_CAT(DATA, N)) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_SEQ_PUSH_FRONT(SEQ, ELEM) \ QSBOOST_PP_SEQ_POP_BACK(QSBOOST_PP_SEQ_PUSH_FRONT(QSBOOST_PP_SEQ_PUSH_BACK(SEQ, _dummy_), ELEM)) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_AS_PARAM_(Z, N, DATA) \ (QSBOOST_PP_CAT(DATA, N)) \ /**/ /// INTERNAL ONLY /// #define QSBOOST_PROTO_VARARG_FUN_(Z, N, DATA) \ template< \ QSBOOST_PP_SEQ_ENUM( \ QSBOOST_PP_SEQ_FOR_EACH_I( \ QSBOOST_PROTO_VARARG_TEMPLATE_, ~ \ , QSBOOST_PP_SEQ_PUSH_FRONT( \ QSBOOST_PROTO_SEQ_PUSH_FRONT( \ QSBOOST_PP_TUPLE_ELEM(4, 2, DATA) \ , (QSBOOST_PP_TUPLE_ELEM(4, 3, DATA)) \ ) \ , QSBOOST_PP_TUPLE_ELEM(4, 1, DATA) \ ) \ ) \ QSBOOST_PP_REPEAT_ ## Z(N, QSBOOST_PROTO_VARARG_AS_PARAM_, typename A) \ ) \ > \ typename qsboost::proto::result_of::make_expr< \ QSBOOST_PP_SEQ_FOR_EACH_I( \ QSBOOST_PROTO_VARARG_TYPE_, ~ \ , QSBOOST_PP_SEQ_PUSH_FRONT( \ QSBOOST_PROTO_SEQ_PUSH_FRONT( \ QSBOOST_PP_TUPLE_ELEM(4, 2, DATA) \ , (QSBOOST_PP_TUPLE_ELEM(4, 3, DATA)) \ ) \ , QSBOOST_PP_TUPLE_ELEM(4, 1, DATA) \ ) \ ) \ QSBOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(Z, N, A, const & QSBOOST_PP_INTERCEPT) \ >::type const \ QSBOOST_PP_TUPLE_ELEM(4, 0, DATA)(QSBOOST_PP_ENUM_BINARY_PARAMS_Z(Z, N, A, const &a)) \ { \ return qsboost::proto::detail::make_expr_< \ QSBOOST_PP_SEQ_FOR_EACH_I( \ QSBOOST_PROTO_VARARG_TYPE_, ~ \ , QSBOOST_PP_SEQ_PUSH_FRONT( \ QSBOOST_PROTO_SEQ_PUSH_FRONT( \ QSBOOST_PP_TUPLE_ELEM(4, 2, DATA) \ , (QSBOOST_PP_TUPLE_ELEM(4, 3, DATA)) \ ) \ , QSBOOST_PP_TUPLE_ELEM(4, 1, DATA) \ ) \ ) \ QSBOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(Z, N, A, const & QSBOOST_PP_INTERCEPT) \ >()( \ QSBOOST_PP_SEQ_ENUM( \ QSBOOST_PP_SEQ_FOR_EACH_I( \ QSBOOST_PROTO_VARARG_AS_EXPR_, ~ \ , QSBOOST_PP_SEQ_PUSH_FRONT( \ QSBOOST_PROTO_SEQ_PUSH_FRONT( \ QSBOOST_PP_TUPLE_ELEM(4, 2, DATA) \ , (QSBOOST_PP_TUPLE_ELEM(4, 3, DATA)) \ ) \ , QSBOOST_PP_TUPLE_ELEM(4, 1, DATA) \ ) \ ) \ QSBOOST_PP_REPEAT_ ## Z(N, QSBOOST_PROTO_VARARG_AS_CHILD_, a) \ ) \ ); \ } \ /**/ /// \code /// BOOST_PROTO_DEFINE_FUNCTION_TEMPLATE( /// 1 /// , construct /// , boost::proto::default_domain /// , (boost::proto::tag::function) /// , ((op::construct)(typename)(int)) /// ) /// \endcode #define QSBOOST_PROTO_DEFINE_FUNCTION_TEMPLATE(ARGCOUNT, NAME, DOMAIN, TAG, BOUNDARGS) \ QSBOOST_PP_REPEAT_FROM_TO( \ ARGCOUNT \ , QSBOOST_PP_INC(ARGCOUNT) \ , QSBOOST_PROTO_VARARG_FUN_ \ , (NAME, TAG, BOUNDARGS, DOMAIN) \ )\ /**/ /// \code /// BOOST_PROTO_DEFINE_VARARG_FUNCTION_TEMPLATE( /// construct /// , boost::proto::default_domain /// , (boost::proto::tag::function) /// , ((op::construct)(typename)(int)) /// ) /// \endcode #define QSBOOST_PROTO_DEFINE_VARARG_FUNCTION_TEMPLATE(NAME, DOMAIN, TAG, BOUNDARGS) \ QSBOOST_PP_REPEAT( \ QSBOOST_PP_SUB(QSBOOST_PP_INC(QSBOOST_PROTO_MAX_ARITY), QSBOOST_PP_SEQ_SIZE(BOUNDARGS)) \ , QSBOOST_PROTO_VARARG_FUN_ \ , (NAME, TAG, BOUNDARGS, DOMAIN) \ ) \ /**/ #endif
64.600806
105
0.32345
wouterboomsma
8abf9be37cb62461136fc2079cbf6a20c0c3323f
4,046
hpp
C++
src/util/math/Matrix.hpp
MeowyAsh/opengl-game
6704de98b396b96672c801f029d951267c3f5e24
[ "Unlicense" ]
6
2021-05-09T03:27:14.000Z
2021-06-21T05:59:17.000Z
src/util/math/Matrix.hpp
Meowy1227/opengl-game
6704de98b396b96672c801f029d951267c3f5e24
[ "Unlicense" ]
null
null
null
src/util/math/Matrix.hpp
Meowy1227/opengl-game
6704de98b396b96672c801f029d951267c3f5e24
[ "Unlicense" ]
1
2021-05-12T04:09:14.000Z
2021-05-12T04:09:14.000Z
#pragma once template <typename T> struct Matrix4 { T elems[16]; /** * 0 1 2 3 * 4 5 6 7 * 8 9 10 11 * 12 13 14 15 */ Matrix4<T> operator *(Matrix4<T> &that) const { return Matrix4<T>{ elems[0]*that[0] + elems[1]*that[4] + elems[2]*that[8] + elems[3]*that[12], /// r0*c0 elems[0]*that[1] + elems[1]*that[5] + elems[2]*that[9] + elems[3]*that[13], /// r0*c1 elems[0]*that[2] + elems[1]*that[6] + elems[2]*that[10] + elems[3]*that[14], /// r0*c2 elems[0]*that[3] + elems[1]*that[7] + elems[2]*that[11] + elems[3]*that[15], /// r0*c3 elems[4]*that[0] + elems[5]*that[4] + elems[6]*that[8] + elems[7]*that[12], /// r1*c0 elems[4]*that[1] + elems[5]*that[5] + elems[6]*that[9] + elems[7]*that[13], /// r1*c1 elems[4]*that[2] + elems[5]*that[6] + elems[6]*that[10] + elems[7]*that[14], /// r1*c2 elems[4]*that[3] + elems[5]*that[7] + elems[6]*that[11] + elems[7]*that[15], /// r1*c3 elems[8]*that[0] + elems[9]*that[4] + elems[10]*that[8] + elems[11]*that[12], /// r2*c0 elems[8]*that[1] + elems[9]*that[5] + elems[10]*that[9] + elems[11]*that[13], /// r2*c1 elems[8]*that[2] + elems[9]*that[6] + elems[10]*that[10] + elems[11]*that[14], /// r2*c2 elems[8]*that[3] + elems[9]*that[7] + elems[10]*that[11] + elems[11]*that[15], /// r2*c3 elems[12]*that[0] + elems[13]*that[4] + elems[14]*that[8] + elems[15]*that[12], /// r3*c0 elems[12]*that[1] + elems[13]*that[5] + elems[14]*that[9] + elems[15]*that[13], /// r3*c1 elems[12]*that[2] + elems[13]*that[6] + elems[14]*that[10] + elems[15]*that[14], /// r3*c2 elems[12]*that[3] + elems[13]*that[7] + elems[14]*that[11] + elems[15]*that[15], /// r3*c3 }; } Matrix4<T> operator *(T that) const { return Matrix4<T>{ elems[0]*that, elems[1]*that, elems[2]*that, elems[3]*that, elems[4]*that, elems[5]*that, elems[6]*that, elems[7]*that, elems[8]*that, elems[9]*that, elems[10]*that, elems[11]*that, elems[12]*that, elems[13]*that, elems[14]*that, elems[15]*that, }; } friend Matrix4<T> operator *(T scalar, Matrix4<T> &matrix) { return matrix * scalar; } Matrix4<T> operator +(Matrix4<T> &that) const { return Matrix4{ elems[0]+that[0], elems[1]+that[1], elems[2]+that[2], elems[3]+that[3], elems[4]+that[4], elems[5]+that[5], elems[6]+that[6], elems[7]+that[7], elems[8]+that[8], elems[9]+that[9], elems[10]+that[10], elems[11]+that[11], elems[12]+that[12], elems[13]+that[13], elems[14]+that[14], elems[15]+that[15], }; } Matrix4<T> operator -(Matrix4<T> &that) const { return Matrix4{ elems[0] -that[0], elems[1]-that[1], elems[2]-that[2], elems[3]-that[3], elems[4] -that[4], elems[5]-that[5], elems[6]-that[6], elems[7]-that[7], elems[8] -that[8], elems[9]-that[9], elems[10]-that[10], elems[11]-that[11], elems[12]-that[12], elems[13]-that[13], elems[14]-that[14], elems[15]-that[15], }; } T& operator [](uint_fast8_t i) { return elems[i]; } Matrix4<T> transpose() const { return Matrix4<T>{ elems[0], elems[4], elems[8], elems[12], elems[1], elems[5], elems[9], elems[13], elems[2], elems[6], elems[10], elems[14], elems[3], elems[7], elems[11], elems[15], }; } static Matrix4<T> identity() { return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; } operator T* () { return elems; } };
45.977273
106
0.470588
MeowyAsh
8ac08ad0d93c294a9df7ae151c0f382057e2163b
5,461
cpp
C++
SuSto-Engine-QT/Renderers/lightrenderer.cpp
SimonStoyanov/SuSto-Engine-QT
ab93bbad84902d0edce1a38cfba680bec5ae1f7f
[ "MIT" ]
null
null
null
SuSto-Engine-QT/Renderers/lightrenderer.cpp
SimonStoyanov/SuSto-Engine-QT
ab93bbad84902d0edce1a38cfba680bec5ae1f7f
[ "MIT" ]
null
null
null
SuSto-Engine-QT/Renderers/lightrenderer.cpp
SimonStoyanov/SuSto-Engine-QT
ab93bbad84902d0edce1a38cfba680bec5ae1f7f
[ "MIT" ]
null
null
null
#include "lightrenderer.h" #include "Managers/shadermanager.h" #include "Managers/rendermanager.h" #include "Renderers/rendertarget.h" #include "Managers/meshmanager.h" #include "Renderers/mesh.h" #include "Managers/scenerenderermanager.h" #include "Managers/entitymanager.h" #include "Entity/entity.h" #include "Entity/Components/c_light.h" #include "Entity/Components/c_transform.h" #include "Entity/Components/c_mesh_renderer.h" #include "Managers/cameramanager.h" LightRenderer::LightRenderer() { } void LightRenderer::Start() { plane_mesh = MeshManager::Instance()->vertical_plane_mesh; sphere_mesh = MeshManager::Instance()->sphere_mesh; std::string base_path = ShaderManager::Instance()->GetShadersBaseFolder(); std::string vert_path = base_path + "DirectionalLightVert.vert"; Shader* ver_sha = ShaderManager::Instance()->LoadShaderFromFile(vert_path, ShaderType::VERTEX); std::string frag_path = base_path + "DirectionalLightFrag.frag"; Shader* frag_sha = ShaderManager::Instance()->LoadShaderFromFile(frag_path, ShaderType::FRAGMENT); program = ShaderManager::Instance()->CreateShaderProgram(); program->AddShader(ver_sha); program->AddShader(frag_sha); program->LinkProgram(); } void LightRenderer::Render(Camera3D *camera, const float4x4 &view, const float4x4 &projection, RenderTarget *target) { RenderDirectionals(camera, view, projection, target); } void LightRenderer::CleanUp() { } void LightRenderer::RenderDirectionals(Camera3D *camera, const float4x4 &view, const float4x4 &projection, RenderTarget *target) { glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glDepthFunc(GL_LESS); program->UseProgram(); std::vector<Entity*> entities = EntityManager::Instance()->GetEntities(); for(std::vector<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it) { C_Transform* transform = (*it)->GetTransform(); C_Light* light = (C_Light*)(*it)->GetComponent(ComponentType::COMPONENT_LIGHT); if(light != nullptr) { if(1) { float3 light_colour = light->GetLightColour(); float light_intensity = light->GetLightIntensity(); Quat rotation = Quat::FromEulerXYZ(DEGTORAD(transform->GetRotationDegrees().x), DEGTORAD(transform->GetRotationDegrees().y), DEGTORAD(transform->GetRotationDegrees().z)); float3 rotation_degrees = transform->GetRotationDegrees(); float3 rotation_rads = float3(DEGTORAD(rotation_degrees.x), DEGTORAD(rotation_degrees.y), DEGTORAD(rotation_degrees.z)); float3 direction = float3::zero; direction.x = -cos(rotation_rads.z) * sin(rotation_rads.y) * sin(rotation_rads.x) * -sin(rotation_rads.z) * cos(rotation_rads.x); direction.y = -sin(rotation_rads.z) * sin(rotation_rads.y) * sin(rotation_rads.x)+cos(rotation_rads.z) * cos(rotation_rads.x); direction.z = cos(rotation_rads.y) * sin(rotation_rads.x); float4x4 transform_mat = float4x4::FromTRS(transform->GetPos(), rotation, transform->GetScale()); float4x4 world_transform = transform_mat; RenderManager::Instance()->BindVertexArrayBuffer(plane_mesh->GetVao()); RenderManager::Instance()->SetUniformMatrix(program->GetID(), "View", view.ptr()); RenderManager::Instance()->SetUniformMatrix(program->GetID(), "Projection", projection.ptr()); RenderManager::Instance()->SetUniformMatrix(program->GetID(), "Model", world_transform.Transposed().ptr()); RenderManager::Instance()->SetUniformVec3(program->GetID(), "CameraPos", camera->GetPosition()); RenderManager::Instance()->SetUniformVec3(program->GetID(), "LightDir", direction); RenderManager::Instance()->SetUniformVec3(program->GetID(), "LightColour", light_colour); RenderManager::Instance()->SetUniformFloat(program->GetID(), "LightIntensity", light_intensity); RenderManager::Instance()->SetUniformInt(program->GetID(), "gPosition", 0); RenderManager::Instance()->SetActiveTexture(GL_TEXTURE0); RenderManager::Instance()->BindTexture(target->GetPositionColorTextureId()); RenderManager::Instance()->SetUniformInt(program->GetID(), "gNormal", 1); RenderManager::Instance()->SetActiveTexture(GL_TEXTURE1); RenderManager::Instance()->BindTexture(target->GetNormalColorTextureId()); RenderManager::Instance()->SetUniformInt(program->GetID(), "gAlbedoSpec", 2); RenderManager::Instance()->SetActiveTexture(GL_TEXTURE2); RenderManager::Instance()->BindTexture(target->GetColorPlusSpecularColorTextureId()); RenderManager::Instance()->SetUniformInt(program->GetID(), "gAmbient", 3); RenderManager::Instance()->SetActiveTexture(GL_TEXTURE3); RenderManager::Instance()->BindTexture(target->GetAmbientLightTextureId()); RenderManager::Instance()->DrawElements(GL_TRIANGLES, plane_mesh->GetElementsCount()); RenderManager::Instance()->UnbindVertexArrayBuffer(); } } } program->StopUsingProgram(); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); }
43
145
0.668193
SimonStoyanov
8ac300809cb6f88f5c98898cfd57af5b7069f4b2
1,183
cpp
C++
src/tests/TestSingleFileStreams.cpp
sashamakarenko/slog
9764b8acc2d831aec11121e080a3331dc9e0dd62
[ "MIT" ]
null
null
null
src/tests/TestSingleFileStreams.cpp
sashamakarenko/slog
9764b8acc2d831aec11121e080a3331dc9e0dd62
[ "MIT" ]
null
null
null
src/tests/TestSingleFileStreams.cpp
sashamakarenko/slog
9764b8acc2d831aec11121e080a3331dc9e0dd62
[ "MIT" ]
null
null
null
#include <tests/Formats.h> #include <slog/impl/FileStreamChannelFactory.h> #include <iostream> #include <thread> #include <chrono> int main( int args, const char ** argv ) { slog::ChannelFactory::setInstance( new slog::impl::FileStreamChannelFactory( "out.log", { { slog::OPT_MULTIFILE, false } } ) ); slog::Channel & ch1 = slog::createChannel( "std1", { { slog::OPT_ASYNC, true }, { slog::OPT_LOG_CHANNEL_NAME, true }, { slog::OPT_LOG_THREAD_PID, true }, { slog::OPT_LOG_LEVEL, slog::Level::DEBUG } } ); slog::Channel & ch2 = slog::createChannel( "std2", { { slog::OPT_ASYNC, true }, { slog::OPT_LOG_CHANNEL_NAME, true }, { slog::OPT_LOG_THREAD_PID, true } } ); slog::Channel & ch3 = slog::createChannel( "std3", { { slog::OPT_ASYNC, true }, { slog::OPT_LOG_CHANNEL_NAME, true }, { slog::OPT_LOG_THREAD_PID, true }, { slog::OPT_INITIAL_RECORD_POOL_SIZE, 1 } } ); std::thread th1( [&]{ for( int i = 0; i < 100; ++i ) logAllMessages(ch1); } ); std::thread th2( [&]{ for( int i = 0; i < 100; ++i ) logAllMessages(ch2); } ); std::thread th3( [&]{ for( int i = 0; i < 100; ++i ) logAllMessages(ch3); } ); th1.join(); th2.join(); th3.join(); }
56.333333
207
0.633136
sashamakarenko
8ac68c95b5565017de66b9add1ba38a4d5458c50
454
cpp
C++
CsPlugin/Source/CsCore/Public/Managers/Time/CsTypes_Update.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlugin/Source/CsCore/Public/Managers/Time/CsTypes_Update.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlugin/Source/CsCore/Public/Managers/Time/CsTypes_Update.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Managers/Time/CsTypes_Update.h" // UpdateGroup #pragma region namespace NCsUpdateGroup { CSCORE_API CS_CREATE_ENUM_STRUCT_CUSTOM(EditorEngine, "Editor Engine"); CSCORE_API CS_CREATE_ENUM_STRUCT_CUSTOM(GameInstance, "Game Instance"); CSCORE_API CS_CREATE_ENUM_STRUCT_CUSTOM(GameState, "Game State"); CSCORE_API CS_CREATE_ENUM_STRUCT(Menu); } #pragma endregion UpdateGroup
30.266667
72
0.819383
closedsum
8acd83b30e9e73c0f9261c7f09e896a3154eaa9d
8,262
cpp
C++
src/ServiceListItem.cpp
Perelandra0x309/serviceswatcher
ec7a377b54dff4620758d38fef491ce2be0754c3
[ "BSD-3-Clause" ]
null
null
null
src/ServiceListItem.cpp
Perelandra0x309/serviceswatcher
ec7a377b54dff4620758d38fef491ce2be0754c3
[ "BSD-3-Clause" ]
1
2016-09-21T14:58:37.000Z
2016-10-23T01:46:32.000Z
src/ServiceListItem.cpp
Perelandra0x309/serviceswatcher
ec7a377b54dff4620758d38fef491ce2be0754c3
[ "BSD-3-Clause" ]
null
null
null
/* ServiceListItem.cpp * Copyright 2010 Brian Hill * All rights reserved. Distributed under the terms of the BSD License. */ #include "ServiceListItem.h" ServiceListItem::ServiceListItem(BEntry entry, const char * sig, AppOptions *options) : BListItem(), fCurrentState(STATE_NONE), fInitStatus(B_ERROR) { // Draw Options fDrawTwoLines = options->drawTwoLines; fIconSize = options->iconSize; fIcon = NULL; if(!entry.Exists()) return; BPath path; entry.GetPath(&path); fName.SetTo(path.Leaf()); fSignature.SetTo(sig); entry.GetRef(&fEntryRef); _GetIcon(); fInitStatus = B_OK; } ServiceListItem::~ServiceListItem() { delete fIcon; } void ServiceListItem::ProcessMessage(BMessage* msg) { switch(msg->what) { case B_SOME_APP_QUIT: { const char* sig; if (msg->FindString("be:signature", &sig) != B_OK) break; if(fSignature.Compare(sig)==0) { if(fCurrentState == STATE_OK_RESTARTING) // In the middle of a restart- send message to start the service { BMessage message(START_SERVICE); ProcessMessage(&message); } else // All other states { _SetState(STATE_OK_STOPPED); } } break; } case B_SOME_APP_LAUNCHED: { const char* sig; if (msg->FindString("be:signature", &sig) != B_OK) break; if(fSignature.Compare(sig)==0) { _SetState(STATE_OK_RUNNING); } break; } case RESTART_SERVICE: { _SetState(STATE_OK_RESTARTING); status_t rc = _StopService(); if(rc != B_OK) { if(be_roster->IsRunning(fSignature.String())) { _SetState(STATE_ERROR_STOPPING__IS_RUNNING); } else { _SetState(STATE_ERROR_STOPPING__IS_NOT_RUNNING); // Attempt to start the service BMessage message(START_SERVICE); ProcessMessage(&message); } } break; } case START_SERVICE: { _SetState(STATE_OK_STARTING); status_t rc = _StartService(); if(rc != B_OK) { if(be_roster->IsRunning(fSignature.String())) { _SetState(STATE_ERROR_STARTING__IS_RUNNING); } else { _SetState(STATE_ERROR_STARTING__IS_NOT_RUNNING); } } break; } case STOP_SERVICE: { _SetState(STATE_OK_STOPPING); status_t rc = _StopService(); if(rc != B_OK) { if(be_roster->IsRunning(fSignature.String())) { _SetState(STATE_ERROR_STOPPING__IS_RUNNING); } else { _SetState(STATE_ERROR_STOPPING__IS_NOT_RUNNING); } } break; } } } void ServiceListItem::SetDrawTwoLines(bool value) { fDrawTwoLines = value; } void ServiceListItem::SetIconSize(int value) { fIconSize = value; _GetIcon(); } void ServiceListItem::SetRunningState() { if(be_roster->IsRunning(fSignature.String())) { _SetState(STATE_OK_RUNNING); } else { _SetState(STATE_OK_STOPPED); } } void ServiceListItem::_GetIcon() { delete fIcon; if(fIconSize == 0) { fIcon = NULL; return; } BNode node; BNodeInfo nodeInfo; if (node.SetTo(&fEntryRef) == B_OK) { BRect iconRect(0, 0, fIconSize - 1, fIconSize - 1); fIcon = new BBitmap(iconRect, 0, B_RGBA32); status_t result = BIconUtils::GetVectorIcon(&node, "BEOS:ICON", fIcon); if(result != B_OK) { // attempt to get mini or large icon delete fIcon; if(nodeInfo.SetTo(&node) == B_OK) { if(fIconSize<32) { iconRect.Set(0, 0, 15, 15); fIcon = new BBitmap(iconRect, 0, B_RGBA32); result = nodeInfo.GetTrackerIcon(fIcon, B_MINI_ICON); } else { iconRect.Set(0, 0, 31, 31); fIcon = new BBitmap(iconRect, 0, B_RGBA32); result = nodeInfo.GetTrackerIcon(fIcon, B_LARGE_ICON); } if(result != B_OK) { delete fIcon; fIcon = NULL; } } else fIcon = NULL; } } else { fIcon = NULL; } } status_t ServiceListItem::_StartService() { status_t rc = be_roster->Launch(fSignature.String()); return rc; } status_t ServiceListItem::_StopService() { status_t rc = B_ERROR; BMessenger appMessenger(fSignature.String()); if(!appMessenger.IsValid()) { BString err("Error: Could not create messenger for service "); err.Append(fName); (new BAlert("", err.String(),"OK"))->Go(NULL); return rc; } rc = appMessenger.SendMessage(B_QUIT_REQUESTED); return rc; } void ServiceListItem::_SetStatusText(const char* text) { fStatusText.SetTo("Status: "); fStatusText.Append(text); } // TODO move this code to a state machine object void ServiceListItem::_SetState(int newstate) { switch(newstate) { case STATE_OK_RUNNING: { _SetStatusText("Running"); fCurrentState = STATE_OK_RUNNING; break; } case STATE_OK_STOPPING: { _SetStatusText("Stopping..."); fCurrentState = STATE_OK_STOPPING; break; } case STATE_ERROR_STOPPING__IS_NOT_RUNNING: { _SetStatusText("There was an error stopping the service"); fCurrentState = STATE_ERROR_STOPPING__IS_NOT_RUNNING; break; } case STATE_ERROR_STOPPING__IS_RUNNING: { _SetStatusText("There was an error stopping the service"); fCurrentState = STATE_ERROR_STOPPING__IS_RUNNING; break; } case STATE_OK_STOPPED: { _SetStatusText("Stopped"); fCurrentState = STATE_OK_STOPPED; break; } case STATE_OK_STARTING: { _SetStatusText("Starting..."); fCurrentState = STATE_OK_STARTING; break; } case STATE_ERROR_STARTING__IS_RUNNING: { _SetStatusText("There was an error starting the service"); fCurrentState = STATE_ERROR_STARTING__IS_RUNNING; } case STATE_ERROR_STARTING__IS_NOT_RUNNING: { _SetStatusText("There was an error starting the service"); fCurrentState = STATE_ERROR_STARTING__IS_NOT_RUNNING; break; } case STATE_OK_RESTARTING: { _SetStatusText("Restarting..."); fCurrentState = STATE_OK_RESTARTING; break; } default: { _SetStatusText("Unknown"); fCurrentState = STATE_NONE; } } } void ServiceListItem::DrawItem(BView *owner, BRect item_rect, bool complete = false) { float offset_width = 0, offset_height = fFontAscent; float listItemHeight = Height(); rgb_color backgroundColor; //background if(IsSelected()) { backgroundColor = ui_color(B_LIST_SELECTED_BACKGROUND_COLOR); } else { // alternate the unselected background color // int listIndex = ((BListView*)owner)->IndexOf(this); backgroundColor = ui_color(B_LIST_BACKGROUND_COLOR); // if(fmod(listIndex, 2)) // backgroundColor = tint_color(backgroundColor, B_DARKEN_1_TINT); } owner->SetHighColor(backgroundColor); owner->SetLowColor(backgroundColor); owner->FillRect(item_rect); //icon if (fIcon) { float offsetMarginHeight = floor( (listItemHeight - fIcon->Bounds().Height())/2); float offsetMarginWidth = floor( (fIconSize - fIcon->Bounds().Width())/2 ) + kIconMargin; owner->SetDrawingMode(B_OP_OVER); owner->DrawBitmap(fIcon, BPoint(item_rect.left + offsetMarginWidth, item_rect.top + offsetMarginHeight)); owner->SetDrawingMode(B_OP_COPY); offset_width += fIconSize + 2*kIconMargin; } // no icon, give the text some margin space else { offset_width += kTextMargin; } //text if(listItemHeight > fTextOnlyHeight) offset_height += floor( (listItemHeight - fTextOnlyHeight)/2 ); // center the text vertically BPoint cursor(item_rect.left + offset_width, item_rect.top + offset_height + kTextMargin); if(IsSelected()) owner->SetHighColor(ui_color(B_LIST_SELECTED_ITEM_TEXT_COLOR)); else owner->SetHighColor(ui_color(B_LIST_ITEM_TEXT_COLOR)); owner->MovePenTo(cursor.x, cursor.y); owner->DrawString(fName); if(fDrawTwoLines) owner->MovePenTo(cursor.x, cursor.y + fFontHeight + kTextMargin); else owner->DrawString(" "); owner->DrawString(fStatusText); } void ServiceListItem::Update(BView *owner, const BFont *font) { BListItem::Update(owner, font); _UpdateHeight(font); } void ServiceListItem::_UpdateHeight(const BFont *font) { font_height fontHeight; font->GetHeight(&fontHeight); fFontHeight = fontHeight.ascent + fontHeight.descent + fontHeight.leading; fFontAscent = fontHeight.ascent; if(fDrawTwoLines) fTextOnlyHeight = 2*fFontHeight + 3*kTextMargin; else fTextOnlyHeight = fFontHeight + 2*kTextMargin; if(fIcon) { float iconSpacing = fIconSize + 2*kIconMargin; if(iconSpacing > fTextOnlyHeight) SetHeight(iconSpacing); else SetHeight(fTextOnlyHeight); } else SetHeight(fTextOnlyHeight); }
21.404145
91
0.701525
Perelandra0x309
8ace48b9222db88651f7cb019a8547c9c9782b2c
3,235
hpp
C++
include/cryptcpp/impl/openssl/openssl_digital_signature.hpp
santanusen/cryptcpp
33d95904c44ba97de65517930fedc7d877d55c84
[ "Apache-2.0" ]
null
null
null
include/cryptcpp/impl/openssl/openssl_digital_signature.hpp
santanusen/cryptcpp
33d95904c44ba97de65517930fedc7d877d55c84
[ "Apache-2.0" ]
null
null
null
include/cryptcpp/impl/openssl/openssl_digital_signature.hpp
santanusen/cryptcpp
33d95904c44ba97de65517930fedc7d877d55c84
[ "Apache-2.0" ]
null
null
null
// // Copyright 2021 Santanu Sen. All Rights Reserved. // // Licensed under the Apache License 2.0 (the "License"). You may not use // this file except in compliance with the License. You can obtain a copy // in the file LICENSE in the source distribution. // #ifndef __CRYPTCPP_OPENSSL_DSA_HPP__ #define __CRYPTCPP_OPENSSL_DSA_HPP__ #include <cryptcpp/digital_signature.hpp> #include <openssl/ossl_typ.h> namespace cryptcpp { //@{ // @class openssl_digital_signature // @brief Implements the digital_signature interface // using opnssl Digital Signature Algorithm routines. //@} class openssl_digital_signature : public digital_signature { public: //@{ // @brief Constructor. // //@} openssl_digital_signature(); //@{ // @brief Destructor. //@} virtual ~openssl_digital_signature(); //@{ // @brief Loads keys from a file. // // @param file file containing the input key. // @param _key_type input key type. // @param password password input key is protected with. // @param pass_len password length. // @exception throw if invalid or non-DSA key is passed. //@} virtual bool set_key(const char *file, key_type _key_type, const char *password, size_t pass_len) OVERRIDE; //@{ // @brief Digitally signs a digest with DSA private key. // // @param digest the digest to be digitally signed. // @param digest_len length of the digest. // @param sign_buf output buffer where the signature is written. // @param sign_buf_len maximum length of the output buffer. // @return length of the digital signature. // @exception throw on openssl library call error. //@} virtual size_t sign(const unsigned char *digest, size_t digest_len, unsigned char *sign_buf, size_t sign_buf_len) OVERRIDE; //@{ // @brief Verifies a digital signature against a digest // using the DSA public key. // // @param digest the digest the signature to verify against. // @param digest_len length of the digest. // @param signature the digital signature. // @param sign_len length of the digital signature. // @return true if signature verification passed, else false. // @exception throw on openssl library call error. //@} virtual bool verify(const unsigned char *digest, size_t digest_len, const unsigned char *signature, size_t sign_len) OVERRIDE; //@{ // @brief Set digest algorithm if valid. // // @param digest_algo to use in sign or verify. // @return true if successful. // @exception throw on openssl library call error. //@} virtual bool set_digest_algo(digest::digest_algorithm digest_algo) OVERRIDE; private: //@{ // @brief Update _M_Key to pkey if valid. // // @param pkey key to update to. // @return true if successful. // @exception throw on openssl library call error. //@} bool update_key(EVP_PKEY *pkey); //@{ // @brief Common context initializer. // // @return pointer to new context. // @exception throw on openssl library call error. //@} EVP_MD_CTX *common_ctx_init(void); //@{ // The digest algorithm. //@} const EVP_MD *_M_md; //@{ // The openssl DSA key. //@} EVP_PKEY *_M_key; }; } // namespace cryptcpp #endif
27.887931
80
0.686244
santanusen
8acf5ba06fc08543f2263fa983678e0bb5de6653
1,384
hpp
C++
src/Sites/LoginHtml.hpp
JSydll/enlighting-letters
24a5b45002466d05291476977fd4ee8bef03d61b
[ "MIT" ]
null
null
null
src/Sites/LoginHtml.hpp
JSydll/enlighting-letters
24a5b45002466d05291476977fd4ee8bef03d61b
[ "MIT" ]
null
null
null
src/Sites/LoginHtml.hpp
JSydll/enlighting-letters
24a5b45002466d05291476977fd4ee8bef03d61b
[ "MIT" ]
null
null
null
/** * @file LoginHtml.hpp * @author your name (you@domain.com) * @brief * @version 0.1 * @date 2019-05-13 * * @copyright Copyright (c) 2019 * */ #ifndef UPDATE__LOGIN_HPP #define UPDATE__LOGIN_HPP #include <string> namespace EnlightingLetters { const std::string kUser = "updater"; const std::string kPassword = "ljwedding19"; // clang-format off const std::string kLoginPage = "<form name='loginForm'>" "<table width='20%' bgcolor='A09F9F' align='center'>" "<tr>" "<td colspan=2>" "<center><font size=4><b>L&J Login</b></font></center><br>" "</td><br><br>" "</tr>" "<tr>" "<td>User:</td>" "<td><input type='text' size=25 name='usr'><br></td><br><br>" "</tr>" "<tr>" "<td>Password:</td>" "<td><input type='Password' size=25 name='pwd'><br></td><br><br>" "</tr>" "<tr>" "<td><input type='submit' onclick='check(this.form)' value='Login'></td>" "</tr>" "</table>" "</form>" "<script>" "function check(f){ " "if(f.usr.value=='" + kUser + "' && form.pwd.value=='" + kPassword + "'){" "window.open('/upload')" "} else { " "alert('Invalid password or username')" "}" "}" "</script>"; // clang-format on } // namespace EnlightingLetters #endif
23.862069
83
0.510116
JSydll
8acfcbda208e8048354e596eff7c17d16b3785f0
407
cpp
C++
src/asset/prefab/prefab_inc.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
src/asset/prefab/prefab_inc.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
src/asset/prefab/prefab_inc.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#include "prefab_inc.hpp" CE_BEGIN_NAMESPACE namespace PrefabState { _Prefab::_Sig2Prb sig2PrbFn = nullptr; _Prefab::_Sig2Ass sig2AssFn = nullptr; std::vector<pPrefab> prefabStack = {}; std::stack<SceneObject> activeBaseObjs = {}; std::stack<std::unordered_set<ChokoEngine::objectid>> ids_indirect = {}; std::stack<std::vector<std::function<void()>>> refresolvers = {}; } CE_END_NAMESPACE
22.611111
73
0.724816
chokomancarr
8ad320945a1542a9205876a469c59bbf2a5bd1b8
19,375
cpp
C++
minsubsystem/minimgio/src/pack.cpp
dketterer/colorsegmentation
58440fc4eb9aeb7e025a91b521e56c87c154b176
[ "MIT" ]
6
2020-05-27T07:04:11.000Z
2022-02-21T16:27:01.000Z
minsubsystem/minimgio/src/pack.cpp
Visillect/segmentation
07cb7ec960a7f8461aedcf8f8d08a1abc79f297f
[ "MIT" ]
null
null
null
minsubsystem/minimgio/src/pack.cpp
Visillect/segmentation
07cb7ec960a7f8461aedcf8f8d08a1abc79f297f
[ "MIT" ]
null
null
null
/* Copyright (c) 2011, Smart Engines Limited. All rights reserved. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS "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 COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of copyright holders. */ #include <cstring> #include "pack.h" #include <minbase/minresult.h> #include <minbase/mintyp.h> #define GETBIT(pLine, x) (((pLine)[(x) >> 3]) & (128 >> ((x) & 7))) #define SETBIT(pLine, x) (((pLine)[(x) >> 3]) |= (128 >> ((x) & 7))) #define CLRBIT(pLine, x) (((pLine)[(x) >> 3]) &= (65407 >> ((x) & 7))) #define INVBIT(pLine, x) (((pLine)[(x) >> 3]) ^= (128 >> ((x) & 7))) static const uint64_t UNPACK_LUT[] = { UINT64_C(0x0000000000000000), UINT64_C(0xFF00000000000000), UINT64_C(0x00FF000000000000), UINT64_C(0xFFFF000000000000), UINT64_C(0x0000FF0000000000), UINT64_C(0xFF00FF0000000000), UINT64_C(0x00FFFF0000000000), UINT64_C(0xFFFFFF0000000000), UINT64_C(0x000000FF00000000), UINT64_C(0xFF0000FF00000000), UINT64_C(0x00FF00FF00000000), UINT64_C(0xFFFF00FF00000000), UINT64_C(0x0000FFFF00000000), UINT64_C(0xFF00FFFF00000000), UINT64_C(0x00FFFFFF00000000), UINT64_C(0xFFFFFFFF00000000), UINT64_C(0x00000000FF000000), UINT64_C(0xFF000000FF000000), UINT64_C(0x00FF0000FF000000), UINT64_C(0xFFFF0000FF000000), UINT64_C(0x0000FF00FF000000), UINT64_C(0xFF00FF00FF000000), UINT64_C(0x00FFFF00FF000000), UINT64_C(0xFFFFFF00FF000000), UINT64_C(0x000000FFFF000000), UINT64_C(0xFF0000FFFF000000), UINT64_C(0x00FF00FFFF000000), UINT64_C(0xFFFF00FFFF000000), UINT64_C(0x0000FFFFFF000000), UINT64_C(0xFF00FFFFFF000000), UINT64_C(0x00FFFFFFFF000000), UINT64_C(0xFFFFFFFFFF000000), UINT64_C(0x0000000000FF0000), UINT64_C(0xFF00000000FF0000), UINT64_C(0x00FF000000FF0000), UINT64_C(0xFFFF000000FF0000), UINT64_C(0x0000FF0000FF0000), UINT64_C(0xFF00FF0000FF0000), UINT64_C(0x00FFFF0000FF0000), UINT64_C(0xFFFFFF0000FF0000), UINT64_C(0x000000FF00FF0000), UINT64_C(0xFF0000FF00FF0000), UINT64_C(0x00FF00FF00FF0000), UINT64_C(0xFFFF00FF00FF0000), UINT64_C(0x0000FFFF00FF0000), UINT64_C(0xFF00FFFF00FF0000), UINT64_C(0x00FFFFFF00FF0000), UINT64_C(0xFFFFFFFF00FF0000), UINT64_C(0x00000000FFFF0000), UINT64_C(0xFF000000FFFF0000), UINT64_C(0x00FF0000FFFF0000), UINT64_C(0xFFFF0000FFFF0000), UINT64_C(0x0000FF00FFFF0000), UINT64_C(0xFF00FF00FFFF0000), UINT64_C(0x00FFFF00FFFF0000), UINT64_C(0xFFFFFF00FFFF0000), UINT64_C(0x000000FFFFFF0000), UINT64_C(0xFF0000FFFFFF0000), UINT64_C(0x00FF00FFFFFF0000), UINT64_C(0xFFFF00FFFFFF0000), UINT64_C(0x0000FFFFFFFF0000), UINT64_C(0xFF00FFFFFFFF0000), UINT64_C(0x00FFFFFFFFFF0000), UINT64_C(0xFFFFFFFFFFFF0000), UINT64_C(0x000000000000FF00), UINT64_C(0xFF0000000000FF00), UINT64_C(0x00FF00000000FF00), UINT64_C(0xFFFF00000000FF00), UINT64_C(0x0000FF000000FF00), UINT64_C(0xFF00FF000000FF00), UINT64_C(0x00FFFF000000FF00), UINT64_C(0xFFFFFF000000FF00), UINT64_C(0x000000FF0000FF00), UINT64_C(0xFF0000FF0000FF00), UINT64_C(0x00FF00FF0000FF00), UINT64_C(0xFFFF00FF0000FF00), UINT64_C(0x0000FFFF0000FF00), UINT64_C(0xFF00FFFF0000FF00), UINT64_C(0x00FFFFFF0000FF00), UINT64_C(0xFFFFFFFF0000FF00), UINT64_C(0x00000000FF00FF00), UINT64_C(0xFF000000FF00FF00), UINT64_C(0x00FF0000FF00FF00), UINT64_C(0xFFFF0000FF00FF00), UINT64_C(0x0000FF00FF00FF00), UINT64_C(0xFF00FF00FF00FF00), UINT64_C(0x00FFFF00FF00FF00), UINT64_C(0xFFFFFF00FF00FF00), UINT64_C(0x000000FFFF00FF00), UINT64_C(0xFF0000FFFF00FF00), UINT64_C(0x00FF00FFFF00FF00), UINT64_C(0xFFFF00FFFF00FF00), UINT64_C(0x0000FFFFFF00FF00), UINT64_C(0xFF00FFFFFF00FF00), UINT64_C(0x00FFFFFFFF00FF00), UINT64_C(0xFFFFFFFFFF00FF00), UINT64_C(0x0000000000FFFF00), UINT64_C(0xFF00000000FFFF00), UINT64_C(0x00FF000000FFFF00), UINT64_C(0xFFFF000000FFFF00), UINT64_C(0x0000FF0000FFFF00), UINT64_C(0xFF00FF0000FFFF00), UINT64_C(0x00FFFF0000FFFF00), UINT64_C(0xFFFFFF0000FFFF00), UINT64_C(0x000000FF00FFFF00), UINT64_C(0xFF0000FF00FFFF00), UINT64_C(0x00FF00FF00FFFF00), UINT64_C(0xFFFF00FF00FFFF00), UINT64_C(0x0000FFFF00FFFF00), UINT64_C(0xFF00FFFF00FFFF00), UINT64_C(0x00FFFFFF00FFFF00), UINT64_C(0xFFFFFFFF00FFFF00), UINT64_C(0x00000000FFFFFF00), UINT64_C(0xFF000000FFFFFF00), UINT64_C(0x00FF0000FFFFFF00), UINT64_C(0xFFFF0000FFFFFF00), UINT64_C(0x0000FF00FFFFFF00), UINT64_C(0xFF00FF00FFFFFF00), UINT64_C(0x00FFFF00FFFFFF00), UINT64_C(0xFFFFFF00FFFFFF00), UINT64_C(0x000000FFFFFFFF00), UINT64_C(0xFF0000FFFFFFFF00), UINT64_C(0x00FF00FFFFFFFF00), UINT64_C(0xFFFF00FFFFFFFF00), UINT64_C(0x0000FFFFFFFFFF00), UINT64_C(0xFF00FFFFFFFFFF00), UINT64_C(0x00FFFFFFFFFFFF00), UINT64_C(0xFFFFFFFFFFFFFF00), UINT64_C(0x00000000000000FF), UINT64_C(0xFF000000000000FF), UINT64_C(0x00FF0000000000FF), UINT64_C(0xFFFF0000000000FF), UINT64_C(0x0000FF00000000FF), UINT64_C(0xFF00FF00000000FF), UINT64_C(0x00FFFF00000000FF), UINT64_C(0xFFFFFF00000000FF), UINT64_C(0x000000FF000000FF), UINT64_C(0xFF0000FF000000FF), UINT64_C(0x00FF00FF000000FF), UINT64_C(0xFFFF00FF000000FF), UINT64_C(0x0000FFFF000000FF), UINT64_C(0xFF00FFFF000000FF), UINT64_C(0x00FFFFFF000000FF), UINT64_C(0xFFFFFFFF000000FF), UINT64_C(0x00000000FF0000FF), UINT64_C(0xFF000000FF0000FF), UINT64_C(0x00FF0000FF0000FF), UINT64_C(0xFFFF0000FF0000FF), UINT64_C(0x0000FF00FF0000FF), UINT64_C(0xFF00FF00FF0000FF), UINT64_C(0x00FFFF00FF0000FF), UINT64_C(0xFFFFFF00FF0000FF), UINT64_C(0x000000FFFF0000FF), UINT64_C(0xFF0000FFFF0000FF), UINT64_C(0x00FF00FFFF0000FF), UINT64_C(0xFFFF00FFFF0000FF), UINT64_C(0x0000FFFFFF0000FF), UINT64_C(0xFF00FFFFFF0000FF), UINT64_C(0x00FFFFFFFF0000FF), UINT64_C(0xFFFFFFFFFF0000FF), UINT64_C(0x0000000000FF00FF), UINT64_C(0xFF00000000FF00FF), UINT64_C(0x00FF000000FF00FF), UINT64_C(0xFFFF000000FF00FF), UINT64_C(0x0000FF0000FF00FF), UINT64_C(0xFF00FF0000FF00FF), UINT64_C(0x00FFFF0000FF00FF), UINT64_C(0xFFFFFF0000FF00FF), UINT64_C(0x000000FF00FF00FF), UINT64_C(0xFF0000FF00FF00FF), UINT64_C(0x00FF00FF00FF00FF), UINT64_C(0xFFFF00FF00FF00FF), UINT64_C(0x0000FFFF00FF00FF), UINT64_C(0xFF00FFFF00FF00FF), UINT64_C(0x00FFFFFF00FF00FF), UINT64_C(0xFFFFFFFF00FF00FF), UINT64_C(0x00000000FFFF00FF), UINT64_C(0xFF000000FFFF00FF), UINT64_C(0x00FF0000FFFF00FF), UINT64_C(0xFFFF0000FFFF00FF), UINT64_C(0x0000FF00FFFF00FF), UINT64_C(0xFF00FF00FFFF00FF), UINT64_C(0x00FFFF00FFFF00FF), UINT64_C(0xFFFFFF00FFFF00FF), UINT64_C(0x000000FFFFFF00FF), UINT64_C(0xFF0000FFFFFF00FF), UINT64_C(0x00FF00FFFFFF00FF), UINT64_C(0xFFFF00FFFFFF00FF), UINT64_C(0x0000FFFFFFFF00FF), UINT64_C(0xFF00FFFFFFFF00FF), UINT64_C(0x00FFFFFFFFFF00FF), UINT64_C(0xFFFFFFFFFFFF00FF), UINT64_C(0x000000000000FFFF), UINT64_C(0xFF0000000000FFFF), UINT64_C(0x00FF00000000FFFF), UINT64_C(0xFFFF00000000FFFF), UINT64_C(0x0000FF000000FFFF), UINT64_C(0xFF00FF000000FFFF), UINT64_C(0x00FFFF000000FFFF), UINT64_C(0xFFFFFF000000FFFF), UINT64_C(0x000000FF0000FFFF), UINT64_C(0xFF0000FF0000FFFF), UINT64_C(0x00FF00FF0000FFFF), UINT64_C(0xFFFF00FF0000FFFF), UINT64_C(0x0000FFFF0000FFFF), UINT64_C(0xFF00FFFF0000FFFF), UINT64_C(0x00FFFFFF0000FFFF), UINT64_C(0xFFFFFFFF0000FFFF), UINT64_C(0x00000000FF00FFFF), UINT64_C(0xFF000000FF00FFFF), UINT64_C(0x00FF0000FF00FFFF), UINT64_C(0xFFFF0000FF00FFFF), UINT64_C(0x0000FF00FF00FFFF), UINT64_C(0xFF00FF00FF00FFFF), UINT64_C(0x00FFFF00FF00FFFF), UINT64_C(0xFFFFFF00FF00FFFF), UINT64_C(0x000000FFFF00FFFF), UINT64_C(0xFF0000FFFF00FFFF), UINT64_C(0x00FF00FFFF00FFFF), UINT64_C(0xFFFF00FFFF00FFFF), UINT64_C(0x0000FFFFFF00FFFF), UINT64_C(0xFF00FFFFFF00FFFF), UINT64_C(0x00FFFFFFFF00FFFF), UINT64_C(0xFFFFFFFFFF00FFFF), UINT64_C(0x0000000000FFFFFF), UINT64_C(0xFF00000000FFFFFF), UINT64_C(0x00FF000000FFFFFF), UINT64_C(0xFFFF000000FFFFFF), UINT64_C(0x0000FF0000FFFFFF), UINT64_C(0xFF00FF0000FFFFFF), UINT64_C(0x00FFFF0000FFFFFF), UINT64_C(0xFFFFFF0000FFFFFF), UINT64_C(0x000000FF00FFFFFF), UINT64_C(0xFF0000FF00FFFFFF), UINT64_C(0x00FF00FF00FFFFFF), UINT64_C(0xFFFF00FF00FFFFFF), UINT64_C(0x0000FFFF00FFFFFF), UINT64_C(0xFF00FFFF00FFFFFF), UINT64_C(0x00FFFFFF00FFFFFF), UINT64_C(0xFFFFFFFF00FFFFFF), UINT64_C(0x00000000FFFFFFFF), UINT64_C(0xFF000000FFFFFFFF), UINT64_C(0x00FF0000FFFFFFFF), UINT64_C(0xFFFF0000FFFFFFFF), UINT64_C(0x0000FF00FFFFFFFF), UINT64_C(0xFF00FF00FFFFFFFF), UINT64_C(0x00FFFF00FFFFFFFF), UINT64_C(0xFFFFFF00FFFFFFFF), UINT64_C(0x000000FFFFFFFFFF), UINT64_C(0xFF0000FFFFFFFFFF), UINT64_C(0x00FF00FFFFFFFFFF), UINT64_C(0xFFFF00FFFFFFFFFF), UINT64_C(0x0000FFFFFFFFFFFF), UINT64_C(0xFF00FFFFFFFFFFFF), UINT64_C(0x00FFFFFFFFFFFFFF), UINT64_C(0xFFFFFFFFFFFFFFFF) }; static const uint64_t UNPACK_LUT_INV[] = { UINT64_C(0xFFFFFFFFFFFFFFFF), UINT64_C(0x00FFFFFFFFFFFFFF), UINT64_C(0xFF00FFFFFFFFFFFF), UINT64_C(0x0000FFFFFFFFFFFF), UINT64_C(0xFFFF00FFFFFFFFFF), UINT64_C(0x00FF00FFFFFFFFFF), UINT64_C(0xFF0000FFFFFFFFFF), UINT64_C(0x000000FFFFFFFFFF), UINT64_C(0xFFFFFF00FFFFFFFF), UINT64_C(0x00FFFF00FFFFFFFF), UINT64_C(0xFF00FF00FFFFFFFF), UINT64_C(0x0000FF00FFFFFFFF), UINT64_C(0xFFFF0000FFFFFFFF), UINT64_C(0x00FF0000FFFFFFFF), UINT64_C(0xFF000000FFFFFFFF), UINT64_C(0x00000000FFFFFFFF), UINT64_C(0xFFFFFFFF00FFFFFF), UINT64_C(0x00FFFFFF00FFFFFF), UINT64_C(0xFF00FFFF00FFFFFF), UINT64_C(0x0000FFFF00FFFFFF), UINT64_C(0xFFFF00FF00FFFFFF), UINT64_C(0x00FF00FF00FFFFFF), UINT64_C(0xFF0000FF00FFFFFF), UINT64_C(0x000000FF00FFFFFF), UINT64_C(0xFFFFFF0000FFFFFF), UINT64_C(0x00FFFF0000FFFFFF), UINT64_C(0xFF00FF0000FFFFFF), UINT64_C(0x0000FF0000FFFFFF), UINT64_C(0xFFFF000000FFFFFF), UINT64_C(0x00FF000000FFFFFF), UINT64_C(0xFF00000000FFFFFF), UINT64_C(0x0000000000FFFFFF), UINT64_C(0xFFFFFFFFFF00FFFF), UINT64_C(0x00FFFFFFFF00FFFF), UINT64_C(0xFF00FFFFFF00FFFF), UINT64_C(0x0000FFFFFF00FFFF), UINT64_C(0xFFFF00FFFF00FFFF), UINT64_C(0x00FF00FFFF00FFFF), UINT64_C(0xFF0000FFFF00FFFF), UINT64_C(0x000000FFFF00FFFF), UINT64_C(0xFFFFFF00FF00FFFF), UINT64_C(0x00FFFF00FF00FFFF), UINT64_C(0xFF00FF00FF00FFFF), UINT64_C(0x0000FF00FF00FFFF), UINT64_C(0xFFFF0000FF00FFFF), UINT64_C(0x00FF0000FF00FFFF), UINT64_C(0xFF000000FF00FFFF), UINT64_C(0x00000000FF00FFFF), UINT64_C(0xFFFFFFFF0000FFFF), UINT64_C(0x00FFFFFF0000FFFF), UINT64_C(0xFF00FFFF0000FFFF), UINT64_C(0x0000FFFF0000FFFF), UINT64_C(0xFFFF00FF0000FFFF), UINT64_C(0x00FF00FF0000FFFF), UINT64_C(0xFF0000FF0000FFFF), UINT64_C(0x000000FF0000FFFF), UINT64_C(0xFFFFFF000000FFFF), UINT64_C(0x00FFFF000000FFFF), UINT64_C(0xFF00FF000000FFFF), UINT64_C(0x0000FF000000FFFF), UINT64_C(0xFFFF00000000FFFF), UINT64_C(0x00FF00000000FFFF), UINT64_C(0xFF0000000000FFFF), UINT64_C(0x000000000000FFFF), UINT64_C(0xFFFFFFFFFFFF00FF), UINT64_C(0x00FFFFFFFFFF00FF), UINT64_C(0xFF00FFFFFFFF00FF), UINT64_C(0x0000FFFFFFFF00FF), UINT64_C(0xFFFF00FFFFFF00FF), UINT64_C(0x00FF00FFFFFF00FF), UINT64_C(0xFF0000FFFFFF00FF), UINT64_C(0x000000FFFFFF00FF), UINT64_C(0xFFFFFF00FFFF00FF), UINT64_C(0x00FFFF00FFFF00FF), UINT64_C(0xFF00FF00FFFF00FF), UINT64_C(0x0000FF00FFFF00FF), UINT64_C(0xFFFF0000FFFF00FF), UINT64_C(0x00FF0000FFFF00FF), UINT64_C(0xFF000000FFFF00FF), UINT64_C(0x00000000FFFF00FF), UINT64_C(0xFFFFFFFF00FF00FF), UINT64_C(0x00FFFFFF00FF00FF), UINT64_C(0xFF00FFFF00FF00FF), UINT64_C(0x0000FFFF00FF00FF), UINT64_C(0xFFFF00FF00FF00FF), UINT64_C(0x00FF00FF00FF00FF), UINT64_C(0xFF0000FF00FF00FF), UINT64_C(0x000000FF00FF00FF), UINT64_C(0xFFFFFF0000FF00FF), UINT64_C(0x00FFFF0000FF00FF), UINT64_C(0xFF00FF0000FF00FF), UINT64_C(0x0000FF0000FF00FF), UINT64_C(0xFFFF000000FF00FF), UINT64_C(0x00FF000000FF00FF), UINT64_C(0xFF00000000FF00FF), UINT64_C(0x0000000000FF00FF), UINT64_C(0xFFFFFFFFFF0000FF), UINT64_C(0x00FFFFFFFF0000FF), UINT64_C(0xFF00FFFFFF0000FF), UINT64_C(0x0000FFFFFF0000FF), UINT64_C(0xFFFF00FFFF0000FF), UINT64_C(0x00FF00FFFF0000FF), UINT64_C(0xFF0000FFFF0000FF), UINT64_C(0x000000FFFF0000FF), UINT64_C(0xFFFFFF00FF0000FF), UINT64_C(0x00FFFF00FF0000FF), UINT64_C(0xFF00FF00FF0000FF), UINT64_C(0x0000FF00FF0000FF), UINT64_C(0xFFFF0000FF0000FF), UINT64_C(0x00FF0000FF0000FF), UINT64_C(0xFF000000FF0000FF), UINT64_C(0x00000000FF0000FF), UINT64_C(0xFFFFFFFF000000FF), UINT64_C(0x00FFFFFF000000FF), UINT64_C(0xFF00FFFF000000FF), UINT64_C(0x0000FFFF000000FF), UINT64_C(0xFFFF00FF000000FF), UINT64_C(0x00FF00FF000000FF), UINT64_C(0xFF0000FF000000FF), UINT64_C(0x000000FF000000FF), UINT64_C(0xFFFFFF00000000FF), UINT64_C(0x00FFFF00000000FF), UINT64_C(0xFF00FF00000000FF), UINT64_C(0x0000FF00000000FF), UINT64_C(0xFFFF0000000000FF), UINT64_C(0x00FF0000000000FF), UINT64_C(0xFF000000000000FF), UINT64_C(0x00000000000000FF), UINT64_C(0xFFFFFFFFFFFFFF00), UINT64_C(0x00FFFFFFFFFFFF00), UINT64_C(0xFF00FFFFFFFFFF00), UINT64_C(0x0000FFFFFFFFFF00), UINT64_C(0xFFFF00FFFFFFFF00), UINT64_C(0x00FF00FFFFFFFF00), UINT64_C(0xFF0000FFFFFFFF00), UINT64_C(0x000000FFFFFFFF00), UINT64_C(0xFFFFFF00FFFFFF00), UINT64_C(0x00FFFF00FFFFFF00), UINT64_C(0xFF00FF00FFFFFF00), UINT64_C(0x0000FF00FFFFFF00), UINT64_C(0xFFFF0000FFFFFF00), UINT64_C(0x00FF0000FFFFFF00), UINT64_C(0xFF000000FFFFFF00), UINT64_C(0x00000000FFFFFF00), UINT64_C(0xFFFFFFFF00FFFF00), UINT64_C(0x00FFFFFF00FFFF00), UINT64_C(0xFF00FFFF00FFFF00), UINT64_C(0x0000FFFF00FFFF00), UINT64_C(0xFFFF00FF00FFFF00), UINT64_C(0x00FF00FF00FFFF00), UINT64_C(0xFF0000FF00FFFF00), UINT64_C(0x000000FF00FFFF00), UINT64_C(0xFFFFFF0000FFFF00), UINT64_C(0x00FFFF0000FFFF00), UINT64_C(0xFF00FF0000FFFF00), UINT64_C(0x0000FF0000FFFF00), UINT64_C(0xFFFF000000FFFF00), UINT64_C(0x00FF000000FFFF00), UINT64_C(0xFF00000000FFFF00), UINT64_C(0x0000000000FFFF00), UINT64_C(0xFFFFFFFFFF00FF00), UINT64_C(0x00FFFFFFFF00FF00), UINT64_C(0xFF00FFFFFF00FF00), UINT64_C(0x0000FFFFFF00FF00), UINT64_C(0xFFFF00FFFF00FF00), UINT64_C(0x00FF00FFFF00FF00), UINT64_C(0xFF0000FFFF00FF00), UINT64_C(0x000000FFFF00FF00), UINT64_C(0xFFFFFF00FF00FF00), UINT64_C(0x00FFFF00FF00FF00), UINT64_C(0xFF00FF00FF00FF00), UINT64_C(0x0000FF00FF00FF00), UINT64_C(0xFFFF0000FF00FF00), UINT64_C(0x00FF0000FF00FF00), UINT64_C(0xFF000000FF00FF00), UINT64_C(0x00000000FF00FF00), UINT64_C(0xFFFFFFFF0000FF00), UINT64_C(0x00FFFFFF0000FF00), UINT64_C(0xFF00FFFF0000FF00), UINT64_C(0x0000FFFF0000FF00), UINT64_C(0xFFFF00FF0000FF00), UINT64_C(0x00FF00FF0000FF00), UINT64_C(0xFF0000FF0000FF00), UINT64_C(0x000000FF0000FF00), UINT64_C(0xFFFFFF000000FF00), UINT64_C(0x00FFFF000000FF00), UINT64_C(0xFF00FF000000FF00), UINT64_C(0x0000FF000000FF00), UINT64_C(0xFFFF00000000FF00), UINT64_C(0x00FF00000000FF00), UINT64_C(0xFF0000000000FF00), UINT64_C(0x000000000000FF00), UINT64_C(0xFFFFFFFFFFFF0000), UINT64_C(0x00FFFFFFFFFF0000), UINT64_C(0xFF00FFFFFFFF0000), UINT64_C(0x0000FFFFFFFF0000), UINT64_C(0xFFFF00FFFFFF0000), UINT64_C(0x00FF00FFFFFF0000), UINT64_C(0xFF0000FFFFFF0000), UINT64_C(0x000000FFFFFF0000), UINT64_C(0xFFFFFF00FFFF0000), UINT64_C(0x00FFFF00FFFF0000), UINT64_C(0xFF00FF00FFFF0000), UINT64_C(0x0000FF00FFFF0000), UINT64_C(0xFFFF0000FFFF0000), UINT64_C(0x00FF0000FFFF0000), UINT64_C(0xFF000000FFFF0000), UINT64_C(0x00000000FFFF0000), UINT64_C(0xFFFFFFFF00FF0000), UINT64_C(0x00FFFFFF00FF0000), UINT64_C(0xFF00FFFF00FF0000), UINT64_C(0x0000FFFF00FF0000), UINT64_C(0xFFFF00FF00FF0000), UINT64_C(0x00FF00FF00FF0000), UINT64_C(0xFF0000FF00FF0000), UINT64_C(0x000000FF00FF0000), UINT64_C(0xFFFFFF0000FF0000), UINT64_C(0x00FFFF0000FF0000), UINT64_C(0xFF00FF0000FF0000), UINT64_C(0x0000FF0000FF0000), UINT64_C(0xFFFF000000FF0000), UINT64_C(0x00FF000000FF0000), UINT64_C(0xFF00000000FF0000), UINT64_C(0x0000000000FF0000), UINT64_C(0xFFFFFFFFFF000000), UINT64_C(0x00FFFFFFFF000000), UINT64_C(0xFF00FFFFFF000000), UINT64_C(0x0000FFFFFF000000), UINT64_C(0xFFFF00FFFF000000), UINT64_C(0x00FF00FFFF000000), UINT64_C(0xFF0000FFFF000000), UINT64_C(0x000000FFFF000000), UINT64_C(0xFFFFFF00FF000000), UINT64_C(0x00FFFF00FF000000), UINT64_C(0xFF00FF00FF000000), UINT64_C(0x0000FF00FF000000), UINT64_C(0xFFFF0000FF000000), UINT64_C(0x00FF0000FF000000), UINT64_C(0xFF000000FF000000), UINT64_C(0x00000000FF000000), UINT64_C(0xFFFFFFFF00000000), UINT64_C(0x00FFFFFF00000000), UINT64_C(0xFF00FFFF00000000), UINT64_C(0x0000FFFF00000000), UINT64_C(0xFFFF00FF00000000), UINT64_C(0x00FF00FF00000000), UINT64_C(0xFF0000FF00000000), UINT64_C(0x000000FF00000000), UINT64_C(0xFFFFFF0000000000), UINT64_C(0x00FFFF0000000000), UINT64_C(0xFF00FF0000000000), UINT64_C(0x0000FF0000000000), UINT64_C(0xFFFF000000000000), UINT64_C(0x00FF000000000000), UINT64_C(0xFF00000000000000), UINT64_C(0x0000000000000000) }; int PackLine(uint8_t *pDstLine, const uint8_t *pSrcLine, uint8_t level, size_t count, bool invert) { if (pDstLine == NULL || pSrcLine == NULL) return BAD_ARGS; if (invert) { for (size_t x = 0; x < count; x++) { if (pSrcLine[x] < level) SETBIT(pDstLine, x); else CLRBIT(pDstLine, x); } } else { for (size_t x = 0; x < count; x++) { if (pSrcLine[x] < level) CLRBIT(pDstLine, x); else SETBIT(pDstLine, x); } } return NO_ERRORS; } int UnpackLine(uint8_t *pDstLine, const uint8_t *pSrcLine, size_t count, bool invert) { if (pDstLine == NULL || pSrcLine == NULL) return BAD_ARGS; size_t nBytes = count >> 3; size_t tail = count & 7; const uint64_t *pLUT = invert ? UNPACK_LUT_INV : UNPACK_LUT; for (size_t x = 0; x < nBytes; x++) ::memcpy(pDstLine + x * 8, &pLUT[pSrcLine[x]], 8); if (tail > 0) ::memcpy(pDstLine + nBytes * 8, &pLUT[pSrcLine[nBytes]], tail); return NO_ERRORS; } int CopyBits(uint8_t *pDstLine, const uint8_t *pSrcLine, size_t count, bool invert) { if (pDstLine == NULL || pSrcLine == 0) return BAD_ARGS; size_t nBytes = count >> 3; size_t tail = count & 7; if (invert) { for (size_t x = 0; x < nBytes; x++) pDstLine[x] = ~pSrcLine[x]; for (size_t x = (nBytes << 3); x < count; x++) { if (GETBIT(pSrcLine, x)) CLRBIT(pDstLine, x); else SETBIT(pDstLine, x); } } else { for (size_t x = 0; x < nBytes; x++) pDstLine[x] = pSrcLine[x]; for (size_t x = (nBytes << 3); x < count; x++) { if (GETBIT(pSrcLine, x)) SETBIT(pDstLine, x); else CLRBIT(pDstLine, x); } } return NO_ERRORS; }
72.565543
121
0.814348
dketterer
8ad34b379e1a3fbcc8ebe5ab86479da6d0c2f4a3
3,724
cpp
C++
srcs/Shader.cpp
paribro/hydrodynamic-simulator
63f16099a4b60bd6240d2c7a6950009637197382
[ "MIT" ]
2
2020-08-12T11:41:04.000Z
2021-02-20T20:02:44.000Z
srcs/Shader.cpp
prdbrg/hydrodynamic-simulator
63f16099a4b60bd6240d2c7a6950009637197382
[ "MIT" ]
null
null
null
srcs/Shader.cpp
prdbrg/hydrodynamic-simulator
63f16099a4b60bd6240d2c7a6950009637197382
[ "MIT" ]
null
null
null
#include <iostream> #include <Exceptions.hpp> #include <Shader.hpp> /******************************************* Constructors *******************************************/ Shader::Shader(void) : _vertex(glCreateShader(GL_VERTEX_SHADER)), _fragment(glCreateShader(GL_FRAGMENT_SHADER)) { this->compile(); this->link(); this->checkStatus(); this->setVertexAttributes(); this->setFragmentAttributes(); return; } /******************************************* Destructor *******************************************/ Shader::~Shader(void) { return ; } /******************************************* Accessors *******************************************/ GLint Shader::getAPosition(void) const { return this->_aPosition; } GLint Shader::getAInstance(void) const { return this->_aInstance; } GLint Shader::getAColors(void) const { return this->_aColors; } GLint Shader::getANormals(void) const { return this->_aNormals; } GLint Shader::getUProjection(void) const { return this->_uProjection; } GLint Shader::getULight(void) const { return this->_uLight; } GLint Shader::getUModel(void) const { return this->_uModel; } GLint Shader::getUView(void) const { return this->_uView; } /******************************************* Member functions *******************************************/ void Shader::freeResources(void) { glDeleteProgram(this->_id); glDeleteShader(this->_vertex); glDeleteShader(this->_fragment); } void Shader::compile(void) { glShaderSource(this->_vertex, 1, &Shader::_vertexSource, nullptr); glShaderSource(this->_fragment, 1, &Shader::_fragmentSource, nullptr); glCompileShader(this->_vertex); glCompileShader(this->_fragment); } void Shader::link(void) { this->_id = glCreateProgram(); glAttachShader(this->_id, this->_vertex); glAttachShader(this->_id, this->_fragment); glLinkProgram(this->_id); glUseProgram(this->_id); } void Shader::checkStatus(void) { glGetShaderiv(this->_vertex, GL_COMPILE_STATUS, &this->_vertex_status); glGetShaderiv(this->_fragment, GL_COMPILE_STATUS, &this->_fragment_status); if (this->_vertex_status != GL_TRUE || this->_fragment_status != GL_TRUE) { char buffer[512]; glGetShaderInfoLog(this->_vertex, 512, NULL, buffer); std::cout << buffer << std::endl; throw invalidShadersException(); } } void Shader::setVertexAttributes(void) { this->_aPosition = glGetAttribLocation(this->_id, "position"); this->_aColors = glGetAttribLocation(this->_id, "vertexColor"); this->_aNormals = glGetAttribLocation(this->_id, "normal"); this->_aInstance = glGetAttribLocation(this->_id, "instance"); this->_uView = glGetUniformLocation(this->_id, "view"); this->_uProjection = glGetUniformLocation(this->_id, "projection"); this->_uModel = glGetUniformLocation(this->_id, "model"); this->_uLight = glGetUniformLocation(this->_id, "light"); } void Shader::setFragmentAttributes(void) { glBindFragDataLocation(this->_id, 0, "outColor"); } GLchar const * Shader::_vertexSource = "#version 410 core\n" "in vec3 position;" "in vec3 instance;" "in vec3 normal;" "in vec4 vertexColor;" "out vec4 fragmentColor;" "uniform vec3 light;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 projection;" "void main() {" " gl_Position = projection * view * model * vec4(position + instance, 1.0);" " vec3 lightRay = light - position;" " float brightness = 0.6 + dot(normal, lightRay) / (length(normal) * length(lightRay));" " brightness = clamp(brightness, 0, 1) + 0.25;" " fragmentColor = vertexColor * brightness;" "}"; GLchar const * Shader::_fragmentSource = "#version 410 core\n" "in vec4 fragmentColor;" "out vec4 outColor;" "void main() {" " outColor = fragmentColor;" "}";
23.871795
111
0.647959
paribro
e9d1cad8bd94ee9fa25718b7263fd099681deead
257
cpp
C++
Src/Base/WindowBase.cpp
cdoty/SuperPlayExtended
0a9717c44b8e3820afeaf0673f86b152daf88cd7
[ "MIT" ]
null
null
null
Src/Base/WindowBase.cpp
cdoty/SuperPlayExtended
0a9717c44b8e3820afeaf0673f86b152daf88cd7
[ "MIT" ]
null
null
null
Src/Base/WindowBase.cpp
cdoty/SuperPlayExtended
0a9717c44b8e3820afeaf0673f86b152daf88cd7
[ "MIT" ]
null
null
null
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "WindowBase.h" WindowBase::WindowBase() : m_iWidth(0), m_iHeight(0) { }
23.363636
95
0.715953
cdoty
e9d346c1ff7b7726f317facbdeae1b0ea36f0785
824
cc
C++
structural_patterns/flyweight/source/clothes_factory.cc
HelenXR/design_patterns_HelenXR-Dev-
083ebc3d724329bbdf71c16c4b25566d4bf860cf
[ "MIT" ]
1
2018-10-10T17:17:27.000Z
2018-10-10T17:17:27.000Z
structural_patterns/flyweight/source/clothes_factory.cc
HelenXR/design_patterns_HelenXR-Dev-
083ebc3d724329bbdf71c16c4b25566d4bf860cf
[ "MIT" ]
null
null
null
structural_patterns/flyweight/source/clothes_factory.cc
HelenXR/design_patterns_HelenXR-Dev-
083ebc3d724329bbdf71c16c4b25566d4bf860cf
[ "MIT" ]
1
2019-07-01T04:06:38.000Z
2019-07-01T04:06:38.000Z
#include "clothes_factory.h" #include "runner_clothes.h" #include <iostream> using namespace std; ClothesFactory::ClothesFactory(){ } ClothesFactory::~ClothesFactory(){ map<int,Clothes*>::iterator iterator; iterator = map_clothes_.begin(); while(iterator != map_clothes_.end()){ delete iterator->second; printf("%s:[%c] delete!\n",__func__,iterator->first); iterator++; } } Clothes *ClothesFactory::GetClothes(int key){ map<int,Clothes*>::iterator iterator = map_clothes_.find(key); if(iterator == map_clothes_.end()){ Clothes *clothes = new RunnerClothes(); map_clothes_.insert(make_pair(key,clothes)); cout << "key (" << key << ")" << " is not exist,insert." << endl; return clothes; } else{ cout << "key (" << key << ")" << " is exist,return object." << endl; return iterator->second; } }
24.969697
70
0.674757
HelenXR
e9d92c581be451c9aedc86ff54c167f8914152ce
403
cpp
C++
SpaghettiDungeonGen/Coord.cpp
RedBreadcat/SpaghettiDungeonGenerator
1153dd8f26dfd835ca70c520e735f199f50ef858
[ "MIT" ]
39
2019-11-23T14:52:46.000Z
2022-01-04T08:57:04.000Z
SpaghettiDungeonGen/Coord.cpp
RedBreadcat/SpaghettiDungeonGenerator
1153dd8f26dfd835ca70c520e735f199f50ef858
[ "MIT" ]
null
null
null
SpaghettiDungeonGen/Coord.cpp
RedBreadcat/SpaghettiDungeonGenerator
1153dd8f26dfd835ca70c520e735f199f50ef858
[ "MIT" ]
5
2019-11-24T00:35:04.000Z
2019-12-09T11:08:16.000Z
#include "Coord.h" bool operator==(Coord const& lhs, Coord const& rhs) { return (lhs.x == rhs.x) && (lhs.y == rhs.y); } Coord operator+(Coord const& lhs, Coord const& rhs) { return {lhs.x + rhs.x, lhs.y + rhs.y}; } Coord operator-(Coord const& lhs, Coord const& rhs) { return { lhs.x - rhs.x, lhs.y - rhs.y }; } Coord operator*(Coord const& lhs, int rhs) { return { lhs.x * rhs, lhs.y * rhs }; }
19.190476
51
0.612903
RedBreadcat
e9d96706e3de26cd7efd7bd8823ca90f2379ed67
1,913
cpp
C++
merge_sort/merge_sort.cpp
cutlas62/Sorting-Algorithms
3ae816b4d286899ffa9fc0918e17dbba47017671
[ "MIT" ]
7
2020-05-28T04:10:47.000Z
2021-02-25T13:34:56.000Z
merge_sort/merge_sort.cpp
cutlas62/Sorting-Algorithms
3ae816b4d286899ffa9fc0918e17dbba47017671
[ "MIT" ]
null
null
null
merge_sort/merge_sort.cpp
cutlas62/Sorting-Algorithms
3ae816b4d286899ffa9fc0918e17dbba47017671
[ "MIT" ]
1
2020-06-02T15:06:24.000Z
2020-06-02T15:06:24.000Z
#include "../utils.h" void _merge_sort(int *arr, int l, int r, statistics_t * ret); void _merge(int *arr, int l, int m, int r, statistics_t * ret); statistics_t merge_sort(int *arr, int n) { printf("Sorting array with merge sort...\n\n"); statistics_t ret = {0}; uint64_t start_t = microsSinceEpoch(); _merge_sort(arr, 0, n - 1, &ret); ret.time = microsSinceEpoch() - start_t; return ret; } void _merge_sort( int *arr, int l, int r, statistics_t * ret) { if (r > l) { int m = (l + r) / 2; // Divide and conquer! _merge_sort(arr, l, m, ret); _merge_sort(arr, m + 1, r, ret); _merge(arr, l, m, r, ret); } } void _merge(int *arr, int l, int m, int r, statistics_t * ret) { // Create temporary arrays int left_arr [m + 1 - l] = {0}; int right_arr [r - m] = {0}; // Fill them for (int i = 0; i < m + 1 - l; i++) { left_arr[i] = *(arr + l + i); ret->array_accesses++; } for (int i = 0; i < r - m; i++) { right_arr[i] = *(arr + m + 1 + i); ret->array_accesses++; } // Merge the two arrays sorted from low to high int i = 0; int j = 0; int k = l; while((i < m + 1 - l) && (j < r - m)) { ret->comparisons++; if(left_arr[i] < right_arr[j]) { *(arr + k) = left_arr[i]; i++; ret->array_accesses++; } else { *(arr + k) = right_arr[j]; j++; ret->array_accesses++; } k++; } // There is usually one number hanging, place it into the merged array as well while(i < m + 1 - l) { *(arr + k) = left_arr[i]; i++; k++; ret->array_accesses++; } while(j < r - m) { *(arr + k) = right_arr[j]; j++; k++; ret->array_accesses++; } }
21.988506
82
0.468374
cutlas62
e9dc1498ffee6fc4a21c1e7ac92b802ce46cd579
1,987
cpp
C++
sort/mergesort_4_linkedlist.cpp
yyuze/study-algorithm
1169638a4386b7c3d04261cce698f2b14bd0ba5b
[ "Apache-2.0" ]
null
null
null
sort/mergesort_4_linkedlist.cpp
yyuze/study-algorithm
1169638a4386b7c3d04261cce698f2b14bd0ba5b
[ "Apache-2.0" ]
null
null
null
sort/mergesort_4_linkedlist.cpp
yyuze/study-algorithm
1169638a4386b7c3d04261cce698f2b14bd0ba5b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include<list> using namespace std; class node { public: int value; node * next; node() { next = nullptr; } node(int i) { value = i; next = nullptr; } }; class linked_list { public: int num_nodes; node * head; linked_list() { num_nodes = 0; head = nullptr; } void make_list(int m, int n) { for (int i = 0; i < m; i++) { node * p = new node(rand() % n); p->next = head; head = p; } num_nodes = m; } void append(node* p) { p->next = this->head; this->head = p; ++this->num_nodes; } }; void sort(linked_list & L, node * p, int n) { if (n == 1) { L.head = nullptr; L.num_nodes = 0; L.append(p); } else { list<thread::id> thread_records; int boundary = n / 2; for (int i = 0; i < boundary; ++i) { p = p->next; } linked_list result1; linked_list result2; result1.head = L.head; result2.head = p; result1.num_nodes = boundary; result2.num_nodes = n - boundary; sort(result1, result1.head, result1.num_nodes); sort(result2, result2.head, result2.num_nodes); merge(L, result1.head, result1.num_nodes, result2.head, result2.num_nodes); } } void reverse(linked_list& link) { if (link.num_nodes < 2) { return; } node* index = link.head->next; node* previous = link.head; link.head->next = nullptr; node* next; while (index->next != nullptr) { next = index->next; index->next = previous; previous = index; index = next; } link.head = index; index->next = previous; } void merge(linked_list & L, node * p1, int n1, node * p2, int n2) { L.head = nullptr; L.num_nodes = 0; int count = n1 + n2; for (int i = 0; i < count; ++i) { node* a_node; if (p1 != nullptr && p2 != nullptr) { if (p1->value < p2->value) { a_node = p1; p1 = p1->next; } else { a_node = p2; p2 = p2->next; } } else { if (p1 != nullptr) { a_node = p1; p1 = p1->next; } else { a_node = p2; p2 = p2->next; } } L.append(a_node); } reverse(L); }
18.398148
77
0.582285
yyuze
e9dd9a46848f0f3f47fc70bc85efc6d2d997722e
1,340
cpp
C++
Creational/FactoryMethod/factory_method.cpp
AhmedShaban94/design_patterns_cpp
1b630afd5130bc2b0a34b03c0e10870e727c5028
[ "MIT" ]
null
null
null
Creational/FactoryMethod/factory_method.cpp
AhmedShaban94/design_patterns_cpp
1b630afd5130bc2b0a34b03c0e10870e727c5028
[ "MIT" ]
null
null
null
Creational/FactoryMethod/factory_method.cpp
AhmedShaban94/design_patterns_cpp
1b630afd5130bc2b0a34b03c0e10870e727c5028
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> struct Product { Product() = default; virtual ~Product() = default; virtual void operation() = 0; }; struct ConcreteProduct1 : public Product { ConcreteProduct1() = default; ~ConcreteProduct1() = default; void operation() override { std::cout << "Creating ConcreteProduct1\n"; } }; struct ConcreteProduct2 : public Product { ConcreteProduct2() = default; ~ConcreteProduct2() = default; void operation() override { std::cout << "Creating ConcreteProduct2\n"; } }; struct Factory { public: Factory() = default; virtual ~Factory() = default; virtual std::unique_ptr<Product> createProduct() = 0; }; struct ConcreteFactory1 : public Factory { std::unique_ptr<Product> createProduct() override { return std::make_unique<ConcreteProduct1>(); } }; struct ConcreteFactory2 : public Factory { std::unique_ptr<Product> createProduct() override { return std::make_unique<ConcreteProduct2>(); } }; int main() { ConcreteFactory1 factory1{}; ConcreteFactory2 factory2{}; const auto product1 = factory1.createProduct(); const auto product2 = factory2.createProduct(); product1->operation(); product2->operation(); return EXIT_SUCCESS; }
19.142857
57
0.647015
AhmedShaban94
e9dfd9721911c42e5cdd1e0920017bcd76d8743c
31,774
cpp
C++
co-op/Sidetrack.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/Sidetrack.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/Sidetrack.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//----------------------------------- // (c) Reliable Software, 2004 - 2008 //----------------------------------- #include "precompiled.h" #undef DBG_LOGGING #define DBG_LOGGING false #include "Sidetrack.h" #include "ProjectDb.h" #include "PathFind.h" #include "ScriptCommands.h" #include "ScriptList.h" #include "ScriptHeader.h" #include "ScriptCommandList.h" #include "ScriptName.h" #include "Chunker.h" #include "TransportHeader.h" #include "ScriptCmd.h" #include "Registry.h" #include "ScriptBasket.h" #include <Dbg/Out.h> #include <StringOp.h> Sidetrack::Sidetrack (Project::Db & projectDb, PathFinder const & pathFinder) : _projectDb (projectDb), _pathFinder (pathFinder), _isNewMissing (false) { AddTransactableMember (_missing); AddTransactableMember (_missingChunks); AddTransactableMember (_resendRequests); } // Return true if new missing script has been detected bool Sidetrack::IsNewMissing_Reset () { bool isNewMissing = _isNewMissing; _isNewMissing = false; return isNewMissing; } // Returns the # of chunks stored for this script (including this one) // Invariant: Every script on the _missingChunk list is absent from the _missing list unsigned Sidetrack::XAddChunk (ScriptHeader const & inHdr, std::string const & fileName) { GlobalId scriptId; if (inHdr.IsFullSynch ()) scriptId = inHdr.GetLineage ().GetReferenceId (); else scriptId = inHdr.ScriptId (); unsigned count = _missingChunks.XCount (); unsigned idx; for (idx = 0; idx < count; ++idx) { Sidetrack::MissingChunk const * missing = _missingChunks.XGet (idx); if (missing != 0 && missing->ScriptId () == scriptId) { // Another chunk of the same script, sent independently of our request if (missing->GetMaxChunkSize () != inHdr.GetMaxChunkSize ()) { // New script chunk has different size than the chunks already recorded. // We will ignore the new script chunk. return missing->GetStoredCount (); } break; } } if (idx == count) // never seen before { _isNewMissing = true; std::unique_ptr<MissingChunk> missing (new MissingChunk (inHdr, _projectDb)); missing->StoreChunk (inHdr.GetPartNumber (), fileName, _pathFinder); _missingChunks.XAppend (std::move(missing)); // make sure it's not on the list of whole missing scripts unsigned scriptCount = _missing.XCount (); for (unsigned i = 0; i < scriptCount; ++i) { Sidetrack::Missing const * missing = _missing.XGet (i); if (missing != 0 && missing->ScriptId () == scriptId) { _missing.XMarkDeleted (i); break; } } return 1; } // We know about this script MissingChunk * missing = _missingChunks.XGetEdit (idx); missing->StoreChunk (inHdr.GetPartNumber (), fileName, _pathFinder); unsigned countSoFar = missing->GetStoredCount (); if (countSoFar != missing->GetPartCount ()) return countSoFar; Assert (countSoFar == missing->GetPartCount ()); // This is the last chunk: reconstruct the whole script and deposit it in the inbox missing->Reconstruct (_pathFinder); missing->ResetRecipients (); // Leave the missing chunk entry--it will be cleaned or reused by next update return countSoFar; } // Returns false if corruption discovered bool Sidetrack::XRememberResendRequest (ScriptHeader const & inHdr, CommandList const & cmdList) { Assert (cmdList.size () == 1); CommandList::Sequencer seq (cmdList); ResendFullSynchRequestCmd const & cmd = seq.GetFsResendCmd (); GlobalId scriptId = cmd.GetSetScripts ().GetReferenceId (); unsigned count = _resendRequests.XCount (); unsigned idx; for (idx = 0; idx < count; ++idx) { Sidetrack::ResendRequest const * req = _resendRequests.XGet (idx); if (req != 0 && req->ScriptId () == scriptId) break; } if (idx == count) // never seen before { if (cmd.GetSetScripts ().Count () == 0 && cmd.GetMembershipScripts ().size () == 0) return false; GlobalIdPack packedId (scriptId); std::string fileName (packedId.ToString ()); fileName += "-FullSynchResendRequest.cmd"; char const * dstPath = _pathFinder.GetSysFilePath (fileName.c_str ()); FileSerializer out (dstPath); cmd.Serialize (out); std::unique_ptr<ResendRequest> req ( new ResendRequest (scriptId, inHdr.GetPartCount (), inHdr.GetMaxChunkSize (), dstPath)); req->AddChunkNo (inHdr.GetPartNumber ()); _resendRequests.XAppend (std::move(req)); } else { // We know about this script ResendRequest * req = _resendRequests.XGetEdit (idx); req->AddChunkNo (inHdr.GetPartNumber ()); } return true; } bool Sidetrack::HasFullSynchRequests () const { return _resendRequests.Count () != 0; } bool Sidetrack::GetFullSynchRequest (FullSynchData & fullSynchData, std::vector<unsigned> & chunkNumbers, unsigned & maxChunkSize, unsigned & chunkCount) { Sidetrack::ResendRequestIter it = _resendRequests.begin (); if (it == _resendRequests.end ()) return false; ResendRequest const * req = *it; maxChunkSize = req->GetMaxChunkSize (); chunkCount = req->GetPartCount (); std::vector<unsigned> const & numbers = req->GetChunkNumbers (); chunkNumbers.insert (chunkNumbers.begin (), numbers.begin (), numbers.end ()); std::string const & path = req->GetPath (); FileDeserializer in (path); ResendFullSynchRequestCmd cmd; ScriptCmdType type = static_cast<ScriptCmdType> (in.GetLong ()); if (type != typeResendFullSynchRequest) { Win::ClearError (); throw Win::Exception ("Corrupted Full Synch resend request command"); } cmd.Deserialize (in, scriptVersion); fullSynchData.SwapLineages (cmd.GetSetScripts (), cmd.GetMembershipScripts ()); return true; } void Sidetrack::XRemoveFullSynchChunkRequest (GlobalId scriptId) { unsigned count = _resendRequests.XCount (); for (unsigned idx = 0; idx < count; ++idx) { Sidetrack::ResendRequest const * req = _resendRequests.XGet (idx); if (req != 0 && (scriptId == gidInvalid || req->ScriptId () == scriptId)) { File::DeleteNoEx (req->GetPath ().c_str ()); _resendRequests.XMarkDeleted (idx); break; } } } void Sidetrack::XRemoveMissingChunk (unsigned idx) { // remove this entry for missing chunks MissingChunk * missEdit = _missingChunks.XGetEdit (idx); // delete all already received chunks MissingChunk::PartMap & partMap = missEdit->GetPartMap (); for (MissingChunk::PartMap::iterator it = partMap.begin (); it != partMap.end (); ) { char const * chunkPath = _pathFinder.GetSysFilePath (it->second.c_str ()); File::DeleteNoEx (chunkPath); it = partMap.erase (it); } _missingChunks.XMarkDeleted (idx); } void Sidetrack::GetMissingScripts (Unit::Type unitType, GidSet & gids) const { for (MissingIter it = _missing.begin (); it != _missing.end (); ++it) { Missing * missing = *it; if (missing->UnitType () == unitType) gids.insert (missing->ScriptId ()); } // Currently only Unit::Set script are chunked. for (MissingChunkIter it = _missingChunks.begin (); it != _missingChunks.end (); ++it) { gids.insert ((*it)->ScriptId ()); } } Sidetrack::Missing const * Sidetrack::GetMissing (GlobalId scriptId) const { Assert (IsMissing (scriptId)); MissingIter mit = std::find_if (_missing.begin (), _missing.end (), IsEqualId (scriptId)); if (mit != _missing.end ()) { return *mit; } MissingChunkIter cit = std::find_if (_missingChunks.begin (), _missingChunks.end (), IsEqualId (scriptId)); if (cit != _missingChunks.end ()) { return *cit; } return 0; // Never happens } bool Sidetrack::IsMissing (GlobalId gid) const { MissingIter mit = std::find_if (_missing.begin (), _missing.end (), IsEqualId (gid)); if (mit != _missing.end ()) { return true; } MissingChunkIter cit = std::find_if (_missingChunks.begin (), _missingChunks.end (), IsEqualId (gid)); if (cit != _missingChunks.end ()) { return true; } return false; } bool Sidetrack::IsMissingChunked (GlobalId gid, unsigned & received, unsigned & total) const { MissingChunkIter cit = std::find_if (_missingChunks.begin (), _missingChunks.end (), IsEqualId (gid)); if (cit != _missingChunks.end ()) { total = (*cit)->GetPartCount (); received = (*cit)->GetStoredCount (); return true; } return false; } UserId Sidetrack::SentTo (GlobalId gid) const { MissingIter mit = std::find_if (_missing.begin (), _missing.end (), IsEqualId (gid)); if (mit != _missing.end ()) return (*mit)->SentTo (); MissingChunkIter cit = std::find_if (_missingChunks.begin (), _missingChunks.end (), IsEqualId (gid)); if (cit != _missingChunks.end ()) return (*cit)->SentTo (); return gidInvalid; } UserId Sidetrack::NextRecipientId (GlobalId gid) const { MissingIter mit = std::find_if (_missing.begin (), _missing.end (), IsEqualId (gid)); if (mit != _missing.end ()) return (*mit)->NextRecipientId (); MissingChunkIter cit = std::find_if (_missingChunks.begin (), _missingChunks.end (), IsEqualId (gid)); if (cit != _missingChunks.end ()) return (*cit)->NextRecipientId (); return gidInvalid; } // Returns true when sidetrack needs to be updated bool Sidetrack::NeedsUpdating (Unit::ScriptList const & historyMissingScripts) const { GidSet historyMissingSet; Unit::ScriptList::const_iterator it = historyMissingScripts.begin (); for (; it != historyMissingScripts.end (); ++it) { GlobalId gid = it->Gid (); if (NeedsUpdate (gid)) // checks all lists { // We have to request this script re-send -- sidetrack needs to be updated dbg << "Sidetrack in project: " << _projectDb.ProjectName () << ", User id: " << std::hex << _projectDb.GetMyId () << std::endl; return true; } historyMissingSet.insert (gid); } for (MissingIter it = _missing.begin (); it != _missing.end (); ++it) { if (historyMissingSet.find ((*it)->ScriptId ()) == historyMissingSet.end ()) return true; // History missing script set has changed -- sidetrack needs to be updated } for (MissingChunkIter it = _missingChunks.begin (); it != _missingChunks.end (); ++it) { if (historyMissingSet.find ((*it)->ScriptId ()) == historyMissingSet.end ()) return true; // History missing script set has changed -- sidetrack needs to be updated } // If we have the full sync re-send requests then sidetrack needs updating return _resendRequests.Count () != 0; } // Return true if there is an entry with this scriptId needing immediate action on either list bool Sidetrack::NeedsUpdate (GlobalId scriptId) const { for (MissingIter it = _missing.begin (); it != _missing.end (); ++it) { if ((*it)->ScriptId () == scriptId) { PackedTimeStr str ((*it)->NextTime ()); dbg << "Sidetrack script entry: " << GlobalIdPack (scriptId) << " Time: " << str.c_str () << std::endl; return (*it)->NextTime () < CurrentPackedTime (); } } for (MissingChunkIter it = _missingChunks.begin (); it != _missingChunks.end (); ++it) { if ((*it)->ScriptId () == scriptId) { PackedTimeStr str ((*it)->NextTime ()); dbg << "Sidetrack chunk entry: " << GlobalIdPack (scriptId) << " Time: " << str.c_str () << std::endl; return (*it)->NextTime () < CurrentPackedTime (); } } return true; // not found } // Call only if no chunk entry was found for scriptId Sidetrack::Missing * Sidetrack::XNeedsScriptResend (GlobalId scriptId, Unit::Type unitType) { unsigned i = XFindScriptEntry(scriptId); if (i != npos) { Assert(_missing.XGet(i) != 0); if (_missing.XGet(i)->NextTime () < CurrentPackedTime()) return _missing.XGetEdit(i); else return 0; } // Not found: create new entry _isNewMissing = true; std::unique_ptr<Missing> missing (new Missing (scriptId, unitType, _projectDb)); _missing.XAppend (std::move(missing)); return 0; } unsigned Sidetrack::XFindScriptEntry(GlobalId scriptId) { unsigned count = _missing.XCount (); for (unsigned i = 0; i != count; ++i) { Missing const * missing = _missing.XGet (i); if (missing != 0 && missing->ScriptId () == scriptId) { return i; } } return npos; } Sidetrack::MissingChunk * Sidetrack::XNeedsChunkResend (GlobalId scriptId, bool & isFound) { isFound = false; unsigned i = XFindChunkEntry(scriptId); if (i == npos) return 0; isFound = true; Assert(_missingChunks.XGet(i) != 0); if (_missingChunks.XGet(i)->NextTime () < CurrentPackedTime ()) return _missingChunks.XGetEdit (i); else return 0; } unsigned Sidetrack::XFindChunkEntry(GlobalId scriptId) { unsigned count = _missingChunks.XCount (); for (unsigned i = 0; i != count; ++i) { MissingChunk const * missing = _missingChunks.XGet (i); if (missing != 0 && missing->ScriptId () == scriptId) { return i; } } return npos; } bool Sidetrack::XProcessMissingScripts (Unit::ScriptList const & missingScripts, ScriptBasket & scriptBasket) { GidSet missingChunkSet; GidSet missingScriptSet; Unit::ScriptList::const_iterator it = missingScripts.begin (); for (; it != missingScripts.end (); ++it) { // Search missing chunk list first! bool isChunkFound; // will be set Sidetrack::MissingChunk * chunkEntry = XNeedsChunkResend (it->Gid (), isChunkFound); if (chunkEntry != 0) { if (chunkEntry->IsFullSynch ()) XSendFullSynchChunkRequest (chunkEntry, scriptBasket); else if (!chunkEntry->IsExhausted ()) XSendChunkRequest (chunkEntry, scriptBasket); chunkEntry->Update (_projectDb); } if (isChunkFound) { missingChunkSet.insert (it->Gid ()); continue; } Assert (!isChunkFound); // Search missing script list (add if not present) Sidetrack::Missing * resendEntry = XNeedsScriptResend (it->Gid (), it->Type ()); missingScriptSet.insert (it->Gid ()); if (resendEntry != 0) { if (!resendEntry->IsExhausted ()) XSendScriptRequest (resendEntry, scriptBasket); resendEntry->Update (_projectDb); } // Revisit: full sync chunk? } // remove entries that are not in the set unsigned count = _missing.XCount (); for (unsigned i = 0; i != count; ++i) { Missing const * missing = _missing.XGet (i); if (missing != 0 && missingScriptSet.find (missing->ScriptId ()) == missingScriptSet.end ()) { _missing.XMarkDeleted (i); } } count = _missingChunks.XCount (); for (unsigned i = 0; i != count; ++i) { MissingChunk const * missing = _missingChunks.XGet (i); if (missing != 0 && missingChunkSet.find (missing->ScriptId ()) == missingChunkSet.end ()) { XRemoveMissingChunk (i); } } // Postcondition: every script on the _missingChunk list is absent from the _missing list return IsNewMissing_Reset (); } void Sidetrack::XRequestResend(GlobalId scriptId, UserIdList const & addresseeList, ScriptBasket & scriptBasket) { unsigned i = XFindChunkEntry(scriptId); if (i != npos) { Sidetrack::MissingChunk const * chunkEntry = _missingChunks.XGet(i); Assert(chunkEntry != 0); Assume(!chunkEntry->IsFullSynch (), "Cannot ask for resend of full sync script"); XMakeChunkRequest (chunkEntry, addresseeList, scriptBasket); return; } i = XFindScriptEntry(scriptId); if (i != npos) { Sidetrack::Missing const * scriptEntry = _missing.XGet(i); Assert(scriptEntry != 0); XMakeScriptRequest (scriptEntry, addresseeList, scriptBasket); } } void Sidetrack::XRemoveMissingScript (GlobalId gid) { unsigned count = _missing.XCount (); for (unsigned i = 0; i != count; ++i) { Missing const * missing = _missing.XGet (i); if (missing != 0 && missing->ScriptId () == gid) { _missing.XMarkDeleted (i); return; } } count = _missingChunks.XCount (); for (unsigned i = 0; i != count; ++i) { MissingChunk const * missing = _missingChunks.XGet (i); if (missing != 0 && missing->ScriptId () == gid) { XRemoveMissingChunk (i); return; } } } void Sidetrack::XSendScriptRequest (Sidetrack::Missing * resendEntry, ScriptBasket & scriptBasket) { UserId nextRecipientId = resendEntry->NextRecipientId (); Assert (nextRecipientId >= 0); if (!_projectDb.XIsProjectMember (nextRecipientId) || _projectDb.XGetMemberState (nextRecipientId).IsDead ()) return; UserIdList userIds; userIds.push_back(nextRecipientId); XMakeScriptRequest(resendEntry, userIds, scriptBasket); } void Sidetrack::XMakeScriptRequest(Sidetrack::Missing const * resendEntry, UserIdList const & userIds, ScriptBasket & scriptBasket) { std::unique_ptr<ScriptHeader> hdr(new ScriptHeader ( ScriptKindResendRequest (), gidInvalid, _projectDb.XProjectName ())); hdr->SetScriptId (_projectDb.XMakeScriptId ()); std::string comment ("Requesting script re-send: "); comment += GlobalIdPack (resendEntry->ScriptId ()).ToString (); hdr->AddComment (comment); hdr->SetUnitType (resendEntry->UnitType ()); dbg << "Sidetrack: Send script request: " << GlobalIdPack (resendEntry->ScriptId ()) << std::endl; CommandList cmdList; std::unique_ptr<ScriptCmd> cmd (new ResendRequestCmd (resendEntry->ScriptId ())); cmdList.push_back (std::move(cmd)); scriptBasket.Put(std::move(hdr), cmdList, userIds); } void Sidetrack::XSendChunkRequest (Sidetrack::MissingChunk * resendEntry, ScriptBasket & scriptBasket) { UserId nextRecipientId = resendEntry->NextRecipientId (); Assert (nextRecipientId >= 0); if (!_projectDb.XIsProjectMember (nextRecipientId) || _projectDb.XGetMemberState (nextRecipientId).IsDead ()) return; UserIdList userIds; userIds.push_back(nextRecipientId); XMakeChunkRequest(resendEntry, userIds, scriptBasket); } void Sidetrack::XMakeChunkRequest(Sidetrack::MissingChunk const * resendEntry, UserIdList const & userIds, ScriptBasket & scriptBasket) { dbg << "Sidetrack: Send chunk requests: " << GlobalIdPack (resendEntry->ScriptId ()) << std::endl; // iterate over missing chunks and send a request for each unsigned partCount = resendEntry->GetPartCount (); unsigned maxChunkSize = resendEntry->GetMaxChunkSize (); MissingChunk::PartMap const & partMap = resendEntry->GetPartMap (); for (unsigned partNo = 1; partNo <= partCount; ++partNo) { if (partMap.find (partNo) != partMap.end ()) continue; // we already have this chunk std::unique_ptr<ScriptHeader> hdr(new ScriptHeader ( ScriptKindResendRequest (), gidInvalid, _projectDb.XProjectName ())); hdr->SetScriptId (_projectDb.XMakeScriptId ()); std::string comment ("Requesting script chunk re-send: "); comment += GlobalIdPack (resendEntry->ScriptId ()).ToString (); comment += " ("; comment += ToString (partNo); comment += " of "; comment += ToString (partCount); comment += "); max chunk size = "; comment + ToString (maxChunkSize); hdr->AddComment (comment); hdr->SetUnitType (resendEntry->UnitType ()); hdr->SetChunkInfo (partNo, partCount, maxChunkSize); CommandList cmdList; std::unique_ptr<ScriptCmd> cmd (new ResendRequestCmd (resendEntry->ScriptId ())); cmdList.push_back (std::move(cmd)); scriptBasket.Put(std::move(hdr), cmdList, userIds); } } void Sidetrack::XSendFullSynchChunkRequest (Sidetrack::MissingChunk * resendEntry, ScriptBasket & scriptBasket) { dbg << "Sidetrack: Send FS chunk request: " << GlobalIdPack (resendEntry->ScriptId ()) << std::endl; // iterate over missing chunks and send a request for each unsigned partCount = resendEntry->GetPartCount (); unsigned maxChunkSize = resendEntry->GetMaxChunkSize (); MissingChunk::PartMap const & partMap = resendEntry->GetPartMap (); if (partMap.begin () == partMap.end ()) { throw Win::InternalException ("Corrupted or invalid full sync script.\n" "You must defect and re-join the following project:", _projectDb.XProjectName ().c_str ()); } for (unsigned partNo = 1; partNo <= partCount; ++partNo) { if (partMap.find (partNo) != partMap.end ()) continue; // we already have this chunk std::unique_ptr<ScriptHeader> hdr(new ScriptHeader ( ScriptKindFullSynchResendRequest (), gidInvalid, _projectDb.XProjectName ())); hdr->SetScriptId (_projectDb.XMakeScriptId ()); std::string comment ("Requesting Full Synch chunk re-send: "); comment += GlobalIdPack (resendEntry->ScriptId ()).ToString (); comment += " ("; comment += ToString (partNo); comment += " of "; comment += ToString (partCount); comment += "); max chunk size = "; comment += FormatFileSize (maxChunkSize); hdr->AddComment (comment); hdr->SetUnitType (resendEntry->UnitType ()); hdr->SetChunkInfo (partNo, partCount, maxChunkSize); // Get script inventory from existing chunk Assume (partMap.begin () != partMap.end (), GlobalIdPack (resendEntry->ScriptId ()).ToBracketedString ().c_str ()); char const * firstChunkPath = _pathFinder.GetSysFilePath (partMap.begin ()->second.c_str ()); FileDeserializer in (firstChunkPath); ScriptHeader origHeader (in); Lineage setScripts; origHeader.SwapMainLineage (setScripts); auto_vector<UnitLineage> membershipScripts; origHeader.SwapSideLineages (membershipScripts); std::unique_ptr<ScriptCmd> cmd ( new ResendFullSynchRequestCmd (resendEntry->ScriptId (), setScripts, membershipScripts)); CommandList cmdList; cmdList.push_back (std::move(cmd)); UserId adminId = _projectDb.XGetAdminId (); if (adminId == gidInvalid) { throw Win::InternalException ( "Cannot ask for a full sync re-send\n" "because there is no admin in the project:", _projectDb.XProjectName ().c_str ()); } scriptBasket.Put(std::move(hdr), cmdList, adminId); } } void Sidetrack::Dump (std::ostream & out) const { if (_missing.Count () != 0) { out << std::endl << "===Missing scripts:" << std::endl; for (MissingIter it = _missing.begin (); it != _missing.end (); ++it) { Missing const * missingScript = *it; out << *missingScript << std::endl; } } if (_missingChunks.Count () != 0) { out << std::endl << "===Missing script chunks:" << std::endl; for (MissingChunkIter it = _missingChunks.begin (); it != _missingChunks.end (); ++it) { MissingChunk const * missingChunk = *it; out << *missingChunk << std::endl; } } } // // Sidetrack::MissingChunk // Sidetrack::MissingChunk::MissingChunk (ScriptHeader const & inHdr, Project::Db & projectDb) : Missing (inHdr.ScriptId (), inHdr.GetUnitType (), projectDb), _partCount (inHdr.GetPartCount ()), _maxChunkSize (inHdr.GetMaxChunkSize ()) { if (inHdr.IsFullSynch ()) { _flags.set (bitFullSynch, true); _scriptId = inHdr.GetLineage ().GetReferenceId (); _unitType = Unit::Set; } // delay resend requests for chunks // add 1 hour delay for every 5 chunks // with the maximum delay of 6 hours (for 30 and more chunks) unsigned int hoursDelayed = 6; if (_partCount < 30) { hoursDelayed = _partCount / 5; } _nextTime += PackedTimeInterval (0, hoursDelayed * 60); } void Sidetrack::MissingChunk::Serialize (Serializer& out) const { Missing::Serialize (out); out.PutLong (_partCount); out.PutLong (_maxChunkSize); out.PutLong (_received.size ()); for (PartMap::const_iterator it = _received.begin (); it != _received.end (); ++it) { out.PutLong (it->first); out.PutLong (it->second.size ()); out.PutBytes (it->second.data (), it->second.size ()); } out.PutLong (_flags.to_ulong ()); } void Sidetrack::MissingChunk::Deserialize (Deserializer& in, int version) { Missing::Deserialize (in, version); _partCount = in.GetLong (); _maxChunkSize = in.GetLong (); unsigned count = in.GetLong (); for (unsigned i = 0; i < count; ++i) { unsigned partNo = in.GetLong (); unsigned size = in.GetLong (); std::string fileName; fileName.resize (size); in.GetBytes (&fileName [0], size); _received [partNo] = fileName; } unsigned long long value = in.GetLong (); _flags = value; } void Sidetrack::MissingChunk::Update (Project::Db & projectDb) { if (IsFullSynch ()) { _nextTime.Now (); PackedTimeInterval day (1); _nextTime += day; } else Sidetrack::Missing::Update (projectDb); } void Sidetrack::MissingChunk::StoreChunk (unsigned partNumber, std::string const & fileName, PathFinder const & pathFinder) { char const * srcPath = pathFinder.InBoxDir ().GetFilePath (fileName); char const * dstPath = pathFinder.GetSysFilePath (fileName.c_str ()); File::Copy (srcPath, dstPath); PartMap::const_iterator it = _received.find (partNumber); if (it != _received.end ()) { // we've already had it if (!IsFileNameEqual (fileName, it->second)) { // delete previous one, if names different dstPath = pathFinder.GetSysFilePath (it->second.c_str ()); File::DeleteNoEx (dstPath); } } _received [partNumber] = fileName; } class SafeChunks { public: typedef std::vector<std::string>::const_iterator Iterator; SafeChunks (PathFinder const & pathFinder, Sidetrack::MissingChunk::PartMap & chunks) { for (unsigned i = 1; i <= chunks.size (); ++i) { char const * chunkPath = pathFinder.GetSysFilePath (chunks [i].c_str ()); _paths.push_back (chunkPath); } chunks.clear (); } ~SafeChunks () { for (std::vector<std::string>::iterator it = _paths.begin (); it != _paths.end (); ++it) File::DeleteNoEx (*it); } Iterator begin () const { return _paths.begin (); } Iterator end () const { return _paths.end (); } private: std::vector<std::string> _paths; }; void Sidetrack::MissingChunk::Reconstruct (PathFinder const & pathFinder) { SafeChunks chunks (pathFinder, _received); // Reconstruct headers Assert (chunks.begin () != chunks.end ()); std::string const & firstChunkPath = *chunks.begin (); FileDeserializer in (firstChunkPath); TransportHeader transHdr (in); ScriptHeader hdr (in); in.Close (); hdr.SetChunkInfo (1, 1, _maxChunkSize); // Assemble new script file in the database directory ScriptFileName fileName (ScriptId (), "local user", hdr.GetProjectName ()); std::string scriptName (fileName.Get ()); std::string srcPath (pathFinder.GetSysFilePath (scriptName.c_str ())); FileSerializer out (srcPath); transHdr.Save (out); hdr.Save (out); for (SafeChunks::Iterator it = chunks.begin (); it != chunks.end (); ++it) { FileDeserializer in (*it); ScriptChunk chunk (in); out.PutBytes (chunk.GetCargo (), chunk.GetSize ()); } out.Close (); char const * dstPath = pathFinder.InBoxDir ().GetFilePath (scriptName); File::Copy (srcPath.c_str (), dstPath); File::DeleteNoEx (srcPath.c_str ()); // chunks are deleted automatically } // // Sidetrack::Missing // Sidetrack::Missing::Missing (GlobalId scriptId, Unit::Type unitType, Project::Db & projectDb) : _scriptId (scriptId), _unitType (unitType) { _nextTime.Now (); Registry::UserDispatcherPrefs dispatcherPrefs; unsigned long delayMinutes; dispatcherPrefs.GetResendDelay (delayMinutes); PackedTimeInterval delay (0, delayMinutes); _nextTime += delay; // first resend request goes to the script creator // if this is not my script and we know script author GlobalIdPack pack (scriptId); UserId scriptAuthorId = pack.GetUserId (); if (scriptAuthorId != projectDb.XGetMyId () && projectDb.XIsProjectMember (scriptAuthorId)) _recipients.push_back (scriptAuthorId); else SelectRecipient (projectDb); } void Sidetrack::Missing::Update (Project::Db & projectDb) { _nextTime.Now (); Registry::UserDispatcherPrefs dispatcherPrefs; unsigned long repeatMinutes; dispatcherPrefs.GetRepeatInterval (repeatMinutes); PackedTimeInterval repeatInterval (0, repeatMinutes); _nextTime += repeatInterval; SelectRecipient (projectDb); } void Sidetrack::Missing::SelectRecipient (Project::Db & projectDb) { if (IsFullSynch ()) return; // full sync resend request always goes to administrator if (_recipients.empty () || _recipients.back () == gidInvalid) { dbg << "Restart asking for " << GlobalIdPack (_scriptId) << std::endl; _recipients.clear (); } GidList memberIds; projectDb.XGetResendCandidates (memberIds); UserId myId = projectDb.XGetMyId (); GidList::const_iterator it; dbg << "Missing::XUpdate: Sorted list of potential recipients" << std::endl; for (it = memberIds.begin (); it != memberIds.end (); ++it) { dbg << *it << std::endl; if (*it == myId) { dbg << " my own id" << std::endl; continue; } GidList::const_iterator itr; for (itr = _recipients.begin (); itr != _recipients.end (); ++itr) { if (*it == *itr) { dbg << " already sent" << std::endl; break; // has been sent to that one } } if (itr == _recipients.end ()) break; } if (it != memberIds.end ()) { dbg << "Next to ask: " << *it << std::endl; _recipients.push_back (*it); } else { dbg << "No more candidates to ask for resend\n" << std::endl; _recipients.push_back (gidInvalid); // gone through all users } } UserId Sidetrack::Missing::SentTo () const { Assert (!_recipients.empty ()); return _recipients.size () == 1 ? _recipients [0] : _recipients [_recipients.size () - 2]; } void Sidetrack::Missing::ResetRecipients () { // Leave only the first one (the original sender) while (_recipients.size () > 1) _recipients.pop_back (); } void Sidetrack::Missing::Serialize (Serializer& out) const { out.PutLong (_scriptId); out.PutLong (_unitType); _nextTime.Serialize (out); _recipients.Serialize (out); } void Sidetrack::Missing::Deserialize (Deserializer& in, int version) { _scriptId = in.GetLong (); _unitType = static_cast<Unit::Type> (in.GetLong ()); _nextTime.Deserialize (in, version); _recipients.Deserialize (in, version); } // Sidetrack::ResendRequest void Sidetrack::ResendRequest::Serialize (Serializer& out) const { out.PutLong (_scriptId); out.PutLong (_flags.to_ulong ()); _path.Serialize (out); out.PutLong (_partCount); out.PutLong (_maxChunkSize); _chunkNumbers.Serialize (out); } void Sidetrack::ResendRequest::Deserialize (Deserializer& in, int version) { _scriptId = in.GetLong (); unsigned long long value = in.GetLong (); _flags = value; _path.Deserialize (in, version); _partCount = in.GetLong (); _maxChunkSize = in.GetLong (); _chunkNumbers.Deserialize (in, version); } void Sidetrack::ResendRequest::AddChunkNo (unsigned chunkNo) { if (std::find (_chunkNumbers.begin (), _chunkNumbers.end (), chunkNo) == _chunkNumbers.end ()) _chunkNumbers.push_back (chunkNo); } std::ostream & operator<<(std::ostream & os, Sidetrack::Missing const & missingScript) { if (missingScript.IsFullSynch ()) { os << " " << GlobalIdPack (missingScript.ScriptId ()).ToSquaredString () << "; Full Sync Script; "; os << "next re-send request goes on " << PackedTimeStr (missingScript.NextTime ()).c_str () << " to project administrator."; } else { os << " " << GlobalIdPack (missingScript.ScriptId ()).ToSquaredString () << "; unit id: " << missingScript.UnitType (); if (missingScript.IsExhausted ()) os << "; re-send list exhausted"; else os << "; next re-send request goes on " << PackedTimeStr (missingScript.NextTime ()).c_str () << "; to user " << std::hex << missingScript.NextRecipientId (); os << std::endl; std::vector<UserId> const & recipients = missingScript.GetRequestRecipients (); if (recipients.size () > 1) { os << " Re-send request have been sent to the following project members: "; for (unsigned i = 0; i < recipients.size () - 1; ++i) os << std::hex << recipients [i] << ' '; os << std::endl; } } return os; } std::ostream & operator<<(std::ostream & os, Sidetrack::MissingChunk const & missingChunk) { os << reinterpret_cast<Sidetrack::Missing const &>(missingChunk); os << std::endl; os << " Part count: " << std::dec << missingChunk.GetPartCount () << "; max chunk size: " << std::dec << missingChunk.GetMaxChunkSize () << std::endl; Sidetrack::MissingChunk::PartMap const & parts = missingChunk.GetPartMap (); if (parts.size () != 0) { os << "Received parts:" << std::endl; for (Sidetrack::MissingChunk::PartMap::const_iterator iter = parts.begin (); iter != parts.end (); ++iter) { std::pair<unsigned, std::string> const & part = *iter; os << " " << std::dec << part.first << ": " << part.second << std::endl; } } return os; }
31.64741
151
0.689117
BartoszMilewski
e9e1202b0943872d66e821932e6d72e5f341754c
413
hpp
C++
src/cameras/PinHoleCamera.hpp
sophia-x/RayTracing
1092971b08ff17e8642e408e2cb0c518d6591e2b
[ "MIT" ]
1
2016-05-05T10:20:45.000Z
2016-05-05T10:20:45.000Z
src/cameras/PinHoleCamera.hpp
sophia-x/RayTracing
1092971b08ff17e8642e408e2cb0c518d6591e2b
[ "MIT" ]
null
null
null
src/cameras/PinHoleCamera.hpp
sophia-x/RayTracing
1092971b08ff17e8642e408e2cb0c518d6591e2b
[ "MIT" ]
null
null
null
#ifndef PIN_HOLE_CAMERA #define PIN_HOLE_CAMERA #include "basic_camera.hpp" #include "../common.hpp" class PinHoleCamera: public BasicCamera { public: PinHoleCamera(const vec3 &position, const vec3 &direction, const vec3 &up, float fov, float radio): BasicCamera(position, direction, up, fov, radio) {}; void render(Mat &result, unsigned short anti_t, size_t thread_num = 16) const; }; #endif
27.533333
92
0.731235
sophia-x
e9eb7a6f38cb01349538022420abb825929240c3
4,277
cpp
C++
tests/ysfx_test_serialization.cpp
nlaroche/ysfx
abf4d54aa70031d6d57af949aa6f1919997b5ab9
[ "Apache-2.0" ]
41
2021-11-10T18:03:58.000Z
2022-03-24T08:33:40.000Z
tests/ysfx_test_serialization.cpp
nlaroche/ysfx
abf4d54aa70031d6d57af949aa6f1919997b5ab9
[ "Apache-2.0" ]
38
2021-11-12T01:58:06.000Z
2022-03-21T15:24:34.000Z
tests/ysfx_test_serialization.cpp
nlaroche/ysfx
abf4d54aa70031d6d57af949aa6f1919997b5ab9
[ "Apache-2.0" ]
5
2021-11-16T20:29:20.000Z
2021-12-31T16:39:21.000Z
// Copyright 2021 Jean Pierre Cimalando // // 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. // // SPDX-License-Identifier: Apache-2.0 // #include "ysfx.h" #include "ysfx_utils.hpp" #include "ysfx_test_utils.hpp" #include <catch.hpp> TEST_CASE("save and load", "[serialization]") { SECTION("sliders only") { const char *text = "desc:example" "\n" "out_pin:output" "\n" "slider1:1<1,3,0.1>the slider 1" "\n" "slider2:2<1,3,0.1>the slider 2" "\n" "@sample" "\n" "spl0=0.0;" "\n"; scoped_new_dir dir_fx("${root}/Effects"); scoped_new_txt file_main("${root}/Effects/example.jsfx", text); ysfx_config_u config{ysfx_config_new()}; ysfx_u fx{ysfx_new(config.get())}; REQUIRE(ysfx_load_file(fx.get(), file_main.m_path.c_str(), 0)); REQUIRE(ysfx_compile(fx.get(), 0)); ysfx_state_u state{ysfx_save_state(fx.get())}; REQUIRE(state); REQUIRE(state->data_size == 0); REQUIRE(state->slider_count == 2); REQUIRE(state->sliders[0].index == 0); REQUIRE(state->sliders[1].index == 1); REQUIRE(state->sliders[0].value == 1); REQUIRE(state->sliders[1].value == 2); state->sliders[0].value = 2; state->sliders[1].value = 3; ysfx_load_state(fx.get(), state.get()); REQUIRE(ysfx_slider_get_value(fx.get(), 0) == 2); REQUIRE(ysfx_slider_get_value(fx.get(), 1) == 3); }; SECTION("serialization only") { const char *text = "desc:example" "\n" "out_pin:output" "\n" "@init" "\n" "myvar1=1;" "\n" "myvar2=2;" "\n" "myarray=777;" "\n" "myarray[0]=100;" "\n" "myarray[1]=200;" "\n" "myarray[2]=300;" "\n" "@serialize" "\n" "file_var(0, myvar1);" "\n" "file_var(0, myvar2);" "\n" "file_mem(0, myarray, 3);" "\n" "@sample" "\n" "spl0=0.0;" "\n"; scoped_new_dir dir_fx("${root}/Effects"); scoped_new_txt file_main("${root}/Effects/example.jsfx", text); ysfx_config_u config{ysfx_config_new()}; ysfx_u fx{ysfx_new(config.get())}; REQUIRE(ysfx_load_file(fx.get(), file_main.m_path.c_str(), 0)); REQUIRE(ysfx_compile(fx.get(), 0)); ysfx_state_u state{ysfx_save_state(fx.get())}; REQUIRE(state); REQUIRE(state->data_size == 5 * sizeof(float)); REQUIRE(ysfx::unpack_f32le(&state->data[0 * sizeof(float)]) == 1); REQUIRE(ysfx::unpack_f32le(&state->data[1 * sizeof(float)]) == 2); REQUIRE(ysfx::unpack_f32le(&state->data[2 * sizeof(float)]) == 100); REQUIRE(ysfx::unpack_f32le(&state->data[3 * sizeof(float)]) == 200); REQUIRE(ysfx::unpack_f32le(&state->data[4 * sizeof(float)]) == 300); ysfx::pack_f32le(2, &state->data[0 * sizeof(float)]); ysfx::pack_f32le(3, &state->data[1 * sizeof(float)]); ysfx::pack_f32le(200, &state->data[2 * sizeof(float)]); ysfx::pack_f32le(300, &state->data[3 * sizeof(float)]); ysfx::pack_f32le(400, &state->data[4 * sizeof(float)]); ysfx_load_state(fx.get(), state.get()); state.reset(ysfx_save_state(fx.get())); REQUIRE(state->data_size == 5 * sizeof(float)); REQUIRE(ysfx::unpack_f32le(&state->data[0 * sizeof(float)]) == 2); REQUIRE(ysfx::unpack_f32le(&state->data[1 * sizeof(float)]) == 3); REQUIRE(ysfx::unpack_f32le(&state->data[2 * sizeof(float)]) == 200); REQUIRE(ysfx::unpack_f32le(&state->data[3 * sizeof(float)]) == 300); REQUIRE(ysfx::unpack_f32le(&state->data[4 * sizeof(float)]) == 400); }; }
38.1875
76
0.580547
nlaroche
e9f4979a606d95d5b83907bd3a8cf11139661426
1,227
hpp
C++
MLPP/Regularization/Reg.hpp
KangLin/MLPP
abd2dba6076c98aa2e1c29fb3198b74a3f28f8fe
[ "MIT" ]
927
2021-12-03T07:02:25.000Z
2022-03-30T07:37:23.000Z
MLPP/Regularization/Reg.hpp
DJofOUC/MLPP
6940fc1fbcb1bc16fe910c90a32d9e4db52e264f
[ "MIT" ]
7
2022-02-13T22:38:08.000Z
2022-03-07T01:00:32.000Z
MLPP/Regularization/Reg.hpp
DJofOUC/MLPP
6940fc1fbcb1bc16fe910c90a32d9e4db52e264f
[ "MIT" ]
132
2022-01-13T02:19:04.000Z
2022-03-23T19:23:56.000Z
// // Reg.hpp // // Created by Marc Melikyan on 1/16/21. // #ifndef Reg_hpp #define Reg_hpp #include <vector> namespace MLPP{ class Reg{ public: double regTerm(std::vector<double> weights, double lambda, double alpha, std::string reg); double regTerm(std::vector<std::vector<double>> weights, double lambda, double alpha, std::string reg); std::vector<double> regWeights(std::vector<double> weights, double lambda, double alpha, std::string reg); std::vector<std::vector<double>> regWeights(std::vector<std::vector<double>> weights, double lambda, double alpha, std::string reg); std::vector<double> regDerivTerm(std::vector<double> weights, double lambda, double alpha, std::string reg); std::vector<std::vector<double>> regDerivTerm(std::vector<std::vector<double>>, double lambda, double alpha, std::string reg); private: double regDerivTerm(std::vector<double> weights, double lambda, double alpha, std::string reg, int j); double regDerivTerm(std::vector<std::vector<double>> weights, double lambda, double alpha, std::string reg, int i, int j); }; } #endif /* Reg_hpp */
38.34375
144
0.651997
KangLin
e9f5c083456cabba514de474e3fcfdbd1dcd8dbc
7,197
cpp
C++
libs/geometry/example_extensions/gis/latlong/distance_example.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
1
2016-07-03T22:12:18.000Z
2016-07-03T22:12:18.000Z
libs/geometry/extensions/example/gis/latlong/distance_example.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
null
null
null
libs/geometry/extensions/example/gis/latlong/distance_example.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
null
null
null
// Boost.Geometry (aka GGL, Generic Geometry Library) // // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Distance Example // This sample demonstrates the use of latlong-points, xy-points, // calculate distances between latlong points using different formulas, // calculate distance between points using pythagoras #include <iostream> #include <boost/geometry/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/strategies/spherical/distance_cross_track.hpp> #include <boost/geometry/extensions/gis/latlong/latlong.hpp> #include <boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp> #include <boost/geometry/extensions/gis/projections/proj/sterea.hpp> #include <boost/geometry/extensions/gis/projections/proj/laea.hpp> #include <boost/geometry/extensions/gis/projections/parameters.hpp> // BSG 28-10-2010 // TODO: clear up this test // it is more a test than an example // the results are sometimes WRONG int main() { using namespace boost::geometry; typedef model::ll::point<degree> latlon_point; typedef model::d2::point_xy<double> xy_point; latlon_point city1; // Amsterdam 52 22'23"N 4 53'32"E std::string const city1_name = "Amsterdam"; city1.lat(dms<north>(52, 22, 23)); city1.lon(dms<east>(4, 53, 32)); // Rotterdam 51 55'51"N 4 28'45"E // latlon_point city2(latitude<>(dms<north>(51, 55, 51)), longitude<>(dms<east>(4, 28, 45))); // Paris 48 52' 0" N, 2 19' 59" E std::string const city2_name = "Paris"; latlon_point city2(latitude<>(dms<north>(48, 52, 0)), longitude<>(dms<east>(2, 19, 59))); // The Hague: 52 4' 48" N, 4 18' 0" E //latlon_point city3(longitude<>(dms<east>(4, 18, 0)), latitude<>(dms<north>(52, 4, 48))); // Barcelona std::string const city3_name = "Barcelona"; latlon_point city3(longitude<>(dms<east>(2, 11, 0)), latitude<>(dms<north>(41, 23, 0))); model::ll::point<radian> city1_rad, city2_rad, city3_rad; transform(city1, city1_rad); transform(city2, city2_rad); transform(city3, city3_rad); /* projections::sterea_ellipsoid<model::ll::point<radian>, xy_point> proj (projections::init( "+lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m")); */ projections::laea_ellipsoid<model::ll::point<radian>, xy_point> proj (projections::init( " +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m")); xy_point city1_prj, city2_prj, city3_prj; proj.forward(city1_rad, city1_prj); proj.forward(city3_rad, city3_prj); proj.forward(city2_rad, city2_prj); // ------------------------------------------------------------------------------------------ // Distances // ------------------------------------------------------------------------------------------ std::cout << "Distance " << city1_name << "-" << city2_name << ": " << std::endl; std::cout << "haversine: " << 0.001 * distance(city1, city2) << " km" << std::endl; std::cout << "haversine rad: " << 0.001 * distance(city1_rad, city2_rad) << " km" << std::endl; std::cout << "haversine other radius: " << distance(city1, city2, strategy::distance::haversine<latlon_point>(6371.0) ) << " km" << std::endl; std::cout << "andoyer: " << 0.001 * distance(city1, city2, strategy::distance::andoyer<latlon_point>() ) << " km" << std::endl; std::cout << "vincenty: " << 0.001 * distance(city1, city2, strategy::distance::vincenty<latlon_point>() ) << " km" << std::endl; std::cout << "vincenty rad: " << 0.001 * distance(city1_rad, city2_rad, strategy::distance::vincenty<model::ll::point<radian> >() ) << " km" << std::endl; std::cout << "Projected, pythagoras: " << 0.001 * distance(city1_prj, city2_prj) << " km" << std::endl; std::cout << std::endl; std::cout << "Distance " << city1_name << "-" << city3_name << ": " << std::endl; std::cout << "andoyer: " << 0.001 * distance(city1, city3, strategy::distance::andoyer<latlon_point>()) << " km" << std::endl; std::cout << "Distance " << city2_name << "-" << city3_name << ": " << std::endl; std::cout << "andoyer: " << 0.001 * distance(city2, city3, strategy::distance::andoyer<latlon_point>()) << " km" << std::endl; // ------------------------------------------------------------------------------------------ // Distances to segments // ------------------------------------------------------------------------------------------ std::cout << std::endl << city3_name << " - line " << city1_name << "," << city2_name << std::endl; model::segment<xy_point> ar_xy(city1_prj, city2_prj); double dr = distance(city3_prj, ar_xy); std::cout << "projected: " << 0.001 * dr << std::endl; dr = distance(city3, model::segment<latlon_point>(city1, city2)); std::cout << "in LL: " << 0.001 * dr << std::endl; std::cout << std::endl << city2_name << " - line " << city1_name << "," << city3_name << std::endl; dr = distance(city2_prj, model::segment<xy_point>(city1_prj, city3_prj)); std::cout << "projected: " << 0.001 * dr << std::endl; dr = distance(city2, model::segment<latlon_point>(city1, city3)); std::cout << "in LL: " << 0.001 * dr << std::endl; std::cout << std::endl; // ------------------------------------------------------------------------------------------ // Compilation // ------------------------------------------------------------------------------------------ // Next line does not compile because Vincenty cannot work on xy-points //std::cout << "vincenty on xy: " << 0.001 * distance(city1_prj, city2_prj, formulae::distance::vincenty<>() ) << " km" << std::endl; // Next line does not compile because you cannot (yet) assign degree to radian directly //ll::point<radian> a_rad2 = city1; // Next line does not compile because you cannot assign latlong to xy // d2::point axy = city1; // ------------------------------------------------------------------------------------------ // Length // ------------------------------------------------------------------------------------------ // Length calculations use distances internally. The lines below take automatically the default // formulae for distance. However, you can also specify city1 formula explicitly. model::linestring<latlon_point> line1; append(line1, city1); append(line1, city2); std::cout << "length: " << length(line1) << std::endl; std::cout << "length using Vincenty: " << length(line1, strategy::distance::vincenty<latlon_point>()) << std::endl; model::linestring<xy_point> line2; append(line2, city1_prj); append(line2, city2_prj); std::cout << "length: " << length(line2) << std::endl; return 0; }
48.302013
168
0.572461
juslee
e9fb5634c93b4da28a887ebed0579a4950745d6e
82,500
hpp
C++
src/tree_for_force_utils2.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
src/tree_for_force_utils2.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
src/tree_for_force_utils2.hpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
namespace ParticleSimulator{ /////////////////////////////// // small functions for dispatch template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchLong, const ReallocatableArray<Ttc> & tc_first){ return F64ort(-1234.5, -9876.5); } template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchLongCutoff, const ReallocatableArray<Ttc> & tc_first){ return tc_first[0].mom_.getVertexOut(); } template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchLongScatter, const ReallocatableArray<Ttc> & tc_first){ return tc_first[0].mom_.getVertexOut(); } template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchLongSymmetry, const ReallocatableArray<Ttc> & tc_first){ return tc_first[0].mom_.getVertexOut(); } template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchShortGather, const ReallocatableArray<Ttc> & tc_first){ return tc_first[0].mom_.getVertexOut(); } template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchShortSymmetry, const ReallocatableArray<Ttc> & tc_first){ return tc_first[0].mom_.getVertexOut(); } template<class Ttc> inline F64ort GetOuterBoundaryOfMyTree(TagSearchShortScatter, const ReallocatableArray<Ttc> & tc_first){ return tc_first[0].mom_.getVertexOut(); } inline void ExchangeOuterBoundary(TagSearchLong, F64ort * my_outer, ReallocatableArray<F64ort> & outer){/* do nothing */ } inline void ExchangeOuterBoundary(TagSearchLongCutoff, F64ort * my_outer, ReallocatableArray<F64ort> & outer){/* do nothing */ } inline void ExchangeOuterBoundary(TagSearchLongScatter, F64ort * my_outer, ReallocatableArray<F64ort> & outer){/* do nothing */ } inline void ExchangeOuterBoundary(TagSearchLongSymmetry, F64ort * my_outer, ReallocatableArray<F64ort> & outer){ Comm::allGather(my_outer, 1, outer.getPointer()); } inline void ExchangeOuterBoundary(TagSearchShortScatter, F64ort * my_outer, ReallocatableArray<F64ort> & outer){/* do nothing */ } inline void ExchangeOuterBoundary(TagSearchShortGather, F64ort * my_outer, ReallocatableArray<F64ort> & outer){/* do nothing */ } inline void ExchangeOuterBoundary(TagSearchShortSymmetry, F64ort * my_outer, ReallocatableArray<F64ort> & outer){/* do nothing */ } //////////////////// // for exchange LET template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchLongCutoff, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; ptcl_send[n_ptcl_offset+j].setPos(ptcl[adr].getPos() - shift); } } template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchLong, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; } } template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchLongScatter, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; } } template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchLongSymmetry, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; } } template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchShortScatter, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; ptcl_send[n_ptcl_offset+j].setPos(ptcl[adr].getPos() - shift); } } template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchShortGather, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; ptcl_send[n_ptcl_offset+j].setPos(ptcl[adr].getPos() - shift); } } template<class Tptcl> inline void CopyPtclToSendBuf(TagSearchShortSymmetry, ReallocatableArray<Tptcl> & ptcl_send, const ReallocatableArray<Tptcl> & ptcl, const ReallocatableArray<S32> & adr_ptcl_send, const S32 n_ptcl, const S32 n_ptcl_offset, const F64vec & shift){ for(S32 j=0; j<n_ptcl; j++){ S32 adr = adr_ptcl_send[n_ptcl_offset+j]; ptcl_send[n_ptcl_offset+j] = ptcl[adr]; ptcl_send[n_ptcl_offset+j].setPos(ptcl[adr].getPos() - shift); } } // for exchange LET //////////////////// // small functions for dispatch /////////////////////////////// // for long mode template<class TSM, class Ttc, class Ttp, class Tep, class Tsp, class Twalkmode> inline void FindScatterParticle(const ReallocatableArray<Ttc> & tc_first, const ReallocatableArray<Ttp> & tp_first, const ReallocatableArray<Tep> & ep_first, ReallocatableArray<S32> & n_ep_send, ReallocatableArray<S32> & adr_ep_send, const DomainInfo & dinfo, const S32 n_leaf_limit, const ReallocatableArray<Tsp> & sp_first, ReallocatableArray<S32> & n_sp_send, ReallocatableArray<S32> & adr_sp_send, ReallocatableArray<F64vec> & shift_per_image, ReallocatableArray<S32> & n_image_per_proc, ReallocatableArray<S32> & n_ep_per_image, ReallocatableArray<S32> & n_sp_per_image, const F64 r_crit_sq){ const S32 n_thread = Comm::getNumberOfThread(); const S32 n_proc = Comm::getNumberOfProc(); const S32 my_rank = Comm::getRank(); static bool first = true; static ReallocatableArray<S32> * rank_tmp; static ReallocatableArray<F64vec> * shift_per_image_tmp; static ReallocatableArray<S32> * adr_ep_send_tmp; static ReallocatableArray<S32> * n_ep_per_image_tmp; static ReallocatableArray<S32> * adr_sp_send_tmp; static ReallocatableArray<S32> * n_sp_per_image_tmp; static ReallocatableArray<F64ort> outer_boundary_of_tree; if(first){ rank_tmp = new ReallocatableArray<S32>[n_thread]; shift_per_image_tmp = new ReallocatableArray<F64vec>[n_thread]; adr_ep_send_tmp = new ReallocatableArray<S32>[n_thread]; n_ep_per_image_tmp = new ReallocatableArray<S32>[n_thread]; adr_sp_send_tmp = new ReallocatableArray<S32>[n_thread]; n_sp_per_image_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } outer_boundary_of_tree.resizeNoInitialize(n_proc); n_ep_send.resizeNoInitialize(n_proc); n_sp_send.resizeNoInitialize(n_proc); n_image_per_proc.resizeNoInitialize(n_proc); bool pa[DIMENSION]; dinfo.getPeriodicAxis(pa); F64ort pos_root_domain = dinfo.getPosRootDomain(); F64vec len_peri = pos_root_domain.getFullLength(); for(S32 i=0; i<DIMENSION; i++){ if(pa[i]==false) len_peri[i] = 0.0; } F64ort outer_boundary_of_my_tree = GetOuterBoundaryOfMyTree(typename TSM::search_type(), tc_first); S32 adr_tc = 0; S32 adr_tree_sp_first = 0; ExchangeOuterBoundary(typename TSM::search_type(), &outer_boundary_of_my_tree, outer_boundary_of_tree); // for long symmetry #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { S32 ith = Comm::getThreadNum(); rank_tmp[ith].clearSize(); shift_per_image_tmp[ith].clearSize(); adr_ep_send_tmp[ith].clearSize(); n_ep_per_image_tmp[ith].clearSize(); adr_sp_send_tmp[ith].clearSize(); n_sp_per_image_tmp[ith].clearSize(); //ReallocatableArray<S32> adr_sp_send_tmp; ReallocatableArray<Tsp> sp_first; //F64 r_crit_sq = 1.0; // dummy #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(S32 i=0; i<n_proc; i++){ const S32 n_image_tmp_prev = shift_per_image_tmp[ith].size(); rank_tmp[ith].push_back(i); CalcNumberAndShiftOfImageDomain (shift_per_image_tmp[ith], dinfo.getPosRootDomain().getFullLength(), outer_boundary_of_my_tree, dinfo.getPosDomain(i), pa, false); /* if(my_rank==0){ std::cerr<<"i= "<<i <<" shift_per_image_tmp[ith].size()= "<<shift_per_image_tmp[ith].size()<<std::endl; for(S32 j=0; j<shift_per_image_tmp[ith].size(); j++){ std::cerr<<"shift_per_image_tmp[ith][j]= "<<shift_per_image_tmp[ith][j]<<std::endl; } } */ const S32 n_image_tmp = shift_per_image_tmp[ith].size(); n_image_per_proc[i] = n_image_tmp - n_image_tmp_prev; S32 n_ep_prev = adr_ep_send_tmp[ith].size(); S32 n_sp_prev = adr_sp_send_tmp[ith].size(); for(S32 j=n_image_tmp_prev; j<n_image_tmp; j++){ S32 n_ep_prev_2 = adr_ep_send_tmp[ith].size(); S32 n_sp_prev_2 = adr_sp_send_tmp[ith].size(); if(my_rank==i && j==n_image_tmp_prev){ n_ep_per_image_tmp[ith].push_back(adr_ep_send_tmp[ith].size() - n_ep_prev_2); // is 0 n_sp_per_image_tmp[ith].push_back(adr_sp_send_tmp[ith].size() - n_sp_prev_2); // is 0 continue; } F64ort pos_target_domain = dinfo.getPosDomain(i).shift(shift_per_image_tmp[ith][j]); /* if(my_rank==0){ std::cerr<<"i= "<<i<<" j= "<<j<<std::endl; std::cerr<<"r_crit_sq= "<<r_crit_sq<<std::endl; std::cerr<<"dinfo.getPosDomain(i)= "<<dinfo.getPosDomain(i)<<std::endl; std::cerr<<"pos_target_domain= "<<pos_target_domain<<std::endl; } */ TargetBox<TSM> target_box; //target_box.vertex_ = pos_target_domain; SetTargetBoxExLet(target_box, pos_target_domain, outer_boundary_of_tree[i].shift(shift_per_image_tmp[ith][j])); /* if(my_rank==1){ std::cout<<"i= "<<i <<" vertex_out= "<<target_box.vertex_out_ <<" vertex_in= "<<target_box.vertex_in_ <<std::endl; } */ MakeListUsingTreeRecursiveTop <TSM, Ttc, TreeParticle, Tep, Tsp, Twalkmode, TagChopLeafFalse> (tc_first, adr_tc, tp_first, ep_first, adr_ep_send_tmp[ith], sp_first, adr_sp_send_tmp[ith], target_box, r_crit_sq, n_leaf_limit, adr_tree_sp_first, F64vec(0.0)); n_ep_per_image_tmp[ith].push_back(adr_ep_send_tmp[ith].size() - n_ep_prev_2); n_sp_per_image_tmp[ith].push_back(adr_sp_send_tmp[ith].size() - n_sp_prev_2); /* if(my_rank == 0){ std::cerr<<"n_ep_per_image_tmp[ith].back()= "<<n_ep_per_image_tmp[ith].back()<<std::endl; std::cerr<<"pos_target_domain= "<<pos_target_domain<<std::endl; } */ } n_ep_send[i] = adr_ep_send_tmp[ith].size() - n_ep_prev; n_sp_send[i] = adr_sp_send_tmp[ith].size() - n_sp_prev; } } // end of OMP scope ReallocatableArray<S32> n_disp_image_per_proc; n_disp_image_per_proc.resizeNoInitialize(n_proc+1); n_disp_image_per_proc[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_image_per_proc[i+1] = n_disp_image_per_proc[i] + n_image_per_proc[i]; } /* if(my_rank == 0){ for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<shift_per_image_tmp[i].size(); j++){ std::cerr<<"i= "<<i <<" j= "<<j <<" shift_per_image_tmp[i][j]= "<<shift_per_image_tmp[i][j] <<std::endl; } for(S32 j=0; j<rank_tmp[i].size(); j++){ std::cerr<<"i= "<<i <<" j= "<<j <<" rank_tmp[i][j]= "<<rank_tmp[i][j] <<std::endl; } } } */ const S32 n_image_tot = n_disp_image_per_proc[n_proc]; shift_per_image.resizeNoInitialize( n_image_tot ); n_ep_per_image.resizeNoInitialize( n_image_tot); n_sp_per_image.resizeNoInitialize( n_image_tot); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ S32 n_cnt = 0; //S32 n_cnt_ep = 0; //S32 n_cnt_sp = 0; for(S32 j=0; j<rank_tmp[i].size(); j++){ S32 rank = rank_tmp[i][j]; S32 offset = n_disp_image_per_proc[rank]; for(S32 k=0; k<n_image_per_proc[rank]; k++){ shift_per_image[offset+k] = shift_per_image_tmp[i][n_cnt]; n_ep_per_image[offset+k] = n_ep_per_image_tmp[i][n_cnt]; n_sp_per_image[offset+k] = n_sp_per_image_tmp[i][n_cnt]; n_cnt++; } } } /* if(my_rank == 0){ std::cerr<<"n_disp_image_per_proc.size()= "<<n_disp_image_per_proc.size()<<std::endl; for(S32 i=0; i<n_proc; i++){ std::cerr<<"i(rank)= "<<i<<std::endl; std::cerr<<"n_image_per_proc[i]= "<<n_image_per_proc[i]<<std::endl; S32 adr_image = n_disp_image_per_proc[i]; for(S32 j=0; j<n_image_per_proc[i]; j++, adr_image++){ std::cerr<<"shift_per_image[adr_image]= "<<shift_per_image[adr_image]<<std::endl; } } } */ // OK //Comm::barrier(); //exit(1); ReallocatableArray<S32> n_disp_ep_per_image(n_image_tot+1); ReallocatableArray<S32> n_disp_sp_per_image(n_image_tot+1); n_disp_ep_per_image[0] = 0; n_disp_sp_per_image[0] = 0; for(S32 i=0; i<n_image_tot; i++){ n_disp_ep_per_image[i+1] = n_disp_ep_per_image[i] + n_ep_per_image[i]; n_disp_sp_per_image[i+1] = n_disp_sp_per_image[i] + n_sp_per_image[i]; } const S32 n_ep_send_tot = n_disp_ep_per_image[ n_image_tot ]; const S32 n_sp_send_tot = n_disp_sp_per_image[ n_image_tot ]; adr_ep_send.resizeNoInitialize( n_ep_send_tot ); adr_sp_send.resizeNoInitialize( n_sp_send_tot ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ S32 n_cnt_ep = 0; S32 n_cnt_sp = 0; for(S32 j=0; j<rank_tmp[i].size(); j++){ S32 rank = rank_tmp[i][j]; const S32 adr_image_head = n_disp_image_per_proc[rank]; const S32 adr_image_end = n_disp_image_per_proc[rank+1]; for(S32 k=adr_image_head; k<adr_image_end; k++){ const S32 adr_ep_head = n_disp_ep_per_image[k]; const S32 adr_ep_end = n_disp_ep_per_image[k+1]; for(S32 l=adr_ep_head; l<adr_ep_end; l++){ adr_ep_send[l] = adr_ep_send_tmp[i][n_cnt_ep++]; } const S32 adr_sp_head = n_disp_sp_per_image[k]; const S32 adr_sp_end = n_disp_sp_per_image[k+1]; for(S32 l=adr_sp_head; l<adr_sp_end; l++){ adr_sp_send[l] = adr_sp_send_tmp[i][n_cnt_sp++]; } } } } /* if(my_rank == 0){ for(S32 i=0; i<n_proc; i++){ std::cout<<"i(rank)= "<<i<<std::endl; for(S32 j=n_disp_image_per_proc[i]; j<n_disp_image_per_proc[i+1]; j++){ std::cout<<" j(image)= "<<j <<" shift_per_image[j]= "<<shift_per_image[j]<<std::endl; for(S32 k=n_disp_ep_per_image[j]; k<n_disp_ep_per_image[j+1]; k++){ std::cout<<" adr_ep_send[k]= "<<adr_ep_send[k] <<" ep_first[adr_ep_send[k]].pos= "<<ep_first[adr_ep_send[k]].pos<<std::endl; } } } } Comm::barrier(); exit(1); */ } // for short mode template<class Ttc, class Ttp, class Tep, class Tsp, class Twalkmode> inline void FindScatterParticle(const ReallocatableArray<Ttc> & tc_first, const ReallocatableArray<Ttp> & tp_first, const ReallocatableArray<Tep> & ep_first, ReallocatableArray<S32> & n_ep_send, ReallocatableArray<S32> & adr_ep_send, const DomainInfo & dinfo, const S32 n_leaf_limit, ReallocatableArray<F64vec> & shift_per_image, ReallocatableArray<S32> & n_image_per_proc, ReallocatableArray<S32> & n_ep_per_image){ static bool first = true; static const S32 n_thread = Comm::getNumberOfThread(); static ReallocatableArray<S32> * rank_tmp; static ReallocatableArray<F64vec> * shift_per_image_tmp; static ReallocatableArray<S32> * adr_ep_send_tmp; static ReallocatableArray<S32> * n_ep_per_image_tmp; if(first){ rank_tmp = new ReallocatableArray<S32>[n_thread]; shift_per_image_tmp = new ReallocatableArray<F64vec>[n_thread]; adr_ep_send_tmp = new ReallocatableArray<S32>[n_thread]; n_ep_per_image_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } const S32 n_proc = Comm::getNumberOfProc(); const S32 my_rank = Comm::getRank(); n_ep_send.resizeNoInitialize(n_proc); n_image_per_proc.resizeNoInitialize(n_proc); bool pa[DIMENSION]; dinfo.getPeriodicAxis(pa); F64ort pos_root_domain = dinfo.getPosRootDomain(); F64vec len_peri = pos_root_domain.getFullLength(); for(S32 i=0; i<DIMENSION; i++){ if(pa[i]==false) len_peri[i] = 0.0; } const F64ort outer_boundary_of_my_tree = tc_first[0].mom_.vertex_out_; S32 adr_tc = 0; S32 adr_tree_sp_first = 0; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { S32 ith = Comm::getThreadNum(); rank_tmp[ith].clearSize(); shift_per_image_tmp[ith].clearSize(); adr_ep_send_tmp[ith].clearSize(); n_ep_per_image_tmp[ith].clearSize(); ReallocatableArray<S32> adr_sp_send_tmp; ReallocatableArray<Tsp> sp_first; F64 r_crit_sq = 1.0; // dummy #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 4) #endif for(S32 i=0; i<n_proc; i++){ const S32 n_image_tmp_prev = shift_per_image_tmp[ith].size(); rank_tmp[ith].push_back(i); /* if(my_rank==0 && i==0){ std::cerr<<"dinfo.getPosDomain(i)= "<<dinfo.getPosDomain(i)<<std::endl; std::cerr<<"outer_boundary_of_my_tree= "<<outer_boundary_of_my_tree<<std::endl; } */ CalcNumberAndShiftOfImageDomain (shift_per_image_tmp[ith], dinfo.getPosRootDomain().getFullLength(), outer_boundary_of_my_tree, dinfo.getPosDomain(i), pa, false); /* if(my_rank==0 && i==0){ std::cerr<<"shift_per_image_tmp[ith].size()= "<<shift_per_image_tmp[ith].size()<<std::endl; for(S32 j=0; j<shift_per_image_tmp[ith].size(); j++){ std::cerr<<"shift_per_image_tmp[ith][j]= "<<shift_per_image_tmp[ith][j]<<std::endl; } } */ const S32 n_image_tmp = shift_per_image_tmp[ith].size(); n_image_per_proc[i] = n_image_tmp - n_image_tmp_prev; S32 n_ep_prev = adr_ep_send_tmp[ith].size(); for(S32 j=n_image_tmp_prev; j<n_image_tmp; j++){ S32 n_ep_prev_2 = adr_ep_send_tmp[ith].size(); //if(my_rank==i && j==0){ if(my_rank==i && j==n_image_tmp_prev){ n_ep_per_image_tmp[ith].push_back(adr_ep_send_tmp[ith].size() - n_ep_prev_2); // is 0 continue; } F64ort pos_target_domain = dinfo.getPosDomain(i).shift(shift_per_image_tmp[ith][j]); /* if(my_rank==0){ std::cerr<<"i= "<<i<<" j= "<<j<<std::endl; std::cerr<<"dinfo.getPosDomain(i)= "<<dinfo.getPosDomain(i)<<std::endl; std::cerr<<"pos_target_domain= "<<pos_target_domain<<std::endl; } */ TargetBox<SEARCH_MODE_SCATTER> target_box; target_box.vertex_in_ = pos_target_domain; MakeListUsingTreeRecursiveTop <SEARCH_MODE_SCATTER, Ttc, TreeParticle, Tep, Tsp, Twalkmode, TagChopLeafFalse> (tc_first, adr_tc, tp_first, ep_first, adr_ep_send_tmp[ith], sp_first, adr_sp_send_tmp, //pos_target_domain, target_box, r_crit_sq, n_leaf_limit, adr_tree_sp_first, F64vec(0.0)); n_ep_per_image_tmp[ith].push_back(adr_ep_send_tmp[ith].size() - n_ep_prev_2); /* if(my_rank == 0){ std::cerr<<"n_ep_per_image_tmp[ith].back()= "<<n_ep_per_image_tmp[ith].back()<<std::endl; std::cerr<<"pos_target_domain= "<<pos_target_domain<<std::endl; } */ } n_ep_send[i] = adr_ep_send_tmp[ith].size() - n_ep_prev; } } // end of OMP scope ReallocatableArray<S32> n_disp_image_per_proc; n_disp_image_per_proc.resizeNoInitialize(n_proc+1); n_disp_image_per_proc[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_image_per_proc[i+1] = n_disp_image_per_proc[i] + n_image_per_proc[i]; } /* if(my_rank == 0){ for(S32 i=0; i<n_thread; i++){ for(S32 j=0; j<shift_image_domain_tmp[i].size(); j++){ std::cerr<<"i= "<<i <<" j= "<<j <<" shift_image_domain_tmp[i][j]= "<<shift_image_domain_tmp[i][j] <<std::endl; } for(S32 j=0; j<rank_tmp[i].size(); j++){ std::cerr<<"i= "<<i <<" j= "<<j <<" rank_tmp[i][j]= "<<rank_tmp[i][j] <<std::endl; } } } */ const S32 n_image_tot = n_disp_image_per_proc[n_proc]; shift_per_image.resizeNoInitialize( n_image_tot ); n_ep_per_image.resizeNoInitialize( n_image_tot); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ S32 n_cnt = 0; //S32 n_cnt_ep = 0; for(S32 j=0; j<rank_tmp[i].size(); j++){ S32 rank = rank_tmp[i][j]; S32 offset = n_disp_image_per_proc[rank]; for(S32 k=0; k<n_image_per_proc[rank]; k++){ shift_per_image[offset+k] = shift_per_image_tmp[i][n_cnt]; n_ep_per_image[offset+k] = n_ep_per_image_tmp[i][n_cnt]; n_cnt++; } } } /* if(my_rank == 0){ std::cerr<<"n_disp_image_per_proc.size()= "<<n_disp_image_per_proc.size()<<std::endl; for(S32 i=0; i<n_proc; i++){ std::cerr<<"i(rank)= "<<i<<std::endl; std::cerr<<"n_image_per_proc[i]= "<<n_image_per_proc[i]<<std::endl; S32 adr_image = n_disp_image_per_proc[i]; for(S32 j=0; j<n_image_per_proc[i]; j++, adr_image++){ std::cerr<<"shift_per_image[adr_image]= "<<shift_per_image[adr_image]<<std::endl; } } } */ // OK //Comm::barrier(); //exit(1); ReallocatableArray<S32> n_disp_ep_per_image(n_image_tot+1); n_disp_ep_per_image[0] = 0; for(S32 i=0; i<n_image_tot; i++){ n_disp_ep_per_image[i+1] = n_disp_ep_per_image[i] + n_ep_per_image[i]; } const S32 n_ep_send_tot = n_disp_ep_per_image[ n_image_tot ]; adr_ep_send.resizeNoInitialize( n_ep_send_tot ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ S32 n_cnt_ep = 0; for(S32 j=0; j<rank_tmp[i].size(); j++){ S32 rank = rank_tmp[i][j]; const S32 adr_image_head = n_disp_image_per_proc[rank]; const S32 adr_image_end = n_disp_image_per_proc[rank+1]; for(S32 k=adr_image_head; k<adr_image_end; k++){ const S32 adr_ep_head = n_disp_ep_per_image[k]; const S32 adr_ep_end = n_disp_ep_per_image[k+1]; for(S32 l=adr_ep_head; l<adr_ep_end; l++){ adr_ep_send[l] = adr_ep_send_tmp[i][n_cnt_ep++]; } } } } /* if(my_rank == 3){ for(S32 i=0; i<n_proc; i++){ std::cout<<"i(rank)= "<<i<<std::endl; for(S32 j=n_disp_image_per_proc[i]; j<n_disp_image_per_proc[i+1]; j++){ std::cout<<" j(image)= "<<j <<" shift_per_image[j]= "<<shift_per_image[j]<<std::endl; for(S32 k=n_disp_ep_per_image[j]; k<n_disp_ep_per_image[j+1]; k++){ std::cout<<" adr_ep_send[k]= "<<adr_ep_send[k] <<" ep_first[adr_ep_send[k]].pos= "<<ep_first[adr_ep_send[k]].pos<<std::endl; } } } } Comm::barrier(); exit(1); */ } ////////////// // exchange # of LET inline void ExchangeNumber(const ReallocatableArray<S32> & n_ep_send, ReallocatableArray<S32> & n_ep_recv, const ReallocatableArray<S32> & n_sp_send, ReallocatableArray<S32> & n_sp_recv){ const S32 n_proc = Comm::getNumberOfProc(); static ReallocatableArray<S32> n_ep_sp_send(n_proc*2); static ReallocatableArray<S32> n_ep_sp_recv(n_proc*2); for(S32 i=0; i<n_proc; i++){ n_ep_sp_send[i*2] = n_ep_send[i]; n_ep_sp_send[i*2+1] = n_sp_send[i]; } Comm::allToAll(n_ep_sp_send.getPointer(), 2, n_ep_sp_recv.getPointer()); n_ep_recv.resizeNoInitialize(n_proc); n_sp_recv.resizeNoInitialize(n_proc); for(S32 i=0; i<n_proc; i++){ n_ep_recv[i] = n_ep_sp_recv[i*2]; n_sp_recv[i] = n_ep_sp_recv[i*2+1]; } } inline void ExchangeNumber(const ReallocatableArray<S32> & n_ep_send, ReallocatableArray<S32> & n_ep_recv){ const S32 n_proc = Comm::getNumberOfProc(); n_ep_recv.resizeNoInitialize(n_proc); Comm::allToAll(n_ep_send.getPointer(), 1, n_ep_recv.getPointer()); } // exchange # of LET ////////////// /////////////// // exchange LET template<class TSM, class Tep, class Tsp> inline void ExchangeLet(const ReallocatableArray<Tep> & ep, const ReallocatableArray<S32> & n_ep_send, const ReallocatableArray<S32> & n_ep_recv, const ReallocatableArray<S32> & n_ep_per_image, const ReallocatableArray<S32> & adr_ep_send, ReallocatableArray<Tep> & ep_recv, const ReallocatableArray<Tsp> & sp, const ReallocatableArray<S32> & n_sp_send, const ReallocatableArray<S32> & n_sp_recv, const ReallocatableArray<S32> & n_sp_per_image, const ReallocatableArray<S32> & adr_sp_send, ReallocatableArray<Tsp> & sp_recv, const ReallocatableArray<F64vec> & shift_image_domain, const ReallocatableArray<S32> & n_image_per_proc){ const S32 n_proc = Comm::getNumberOfProc(); //const S32 my_rank = Comm::getRank(); ReallocatableArray<S32> n_disp_ep_send(n_proc+1); ReallocatableArray<S32> n_disp_sp_send(n_proc+1); ReallocatableArray<S32> n_disp_ep_recv(n_proc+1); ReallocatableArray<S32> n_disp_sp_recv(n_proc+1); n_disp_ep_send[0] = n_disp_sp_send[0] = n_disp_ep_recv[0] = n_disp_sp_recv[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_ep_send[i+1] = n_ep_send[i] + n_disp_ep_send[i]; n_disp_sp_send[i+1] = n_sp_send[i] + n_disp_sp_send[i]; n_disp_ep_recv[i+1] = n_ep_recv[i] + n_disp_ep_recv[i]; n_disp_sp_recv[i+1] = n_sp_recv[i] + n_disp_sp_recv[i]; } const S32 n_image_tot = n_ep_per_image.size(); //if(my_rank==0) std::cerr<<"n_image_tot= "<<n_image_tot<<std::endl; ReallocatableArray<S32> n_disp_ep_per_image(n_image_tot+1); ReallocatableArray<S32> n_disp_sp_per_image(n_image_tot+1); n_disp_ep_per_image[0] = n_disp_sp_per_image[0] = 0; for(S32 i=0; i<n_image_tot; i++){ n_disp_ep_per_image[i+1] = n_disp_ep_per_image[i] + n_ep_per_image[i]; n_disp_sp_per_image[i+1] = n_disp_sp_per_image[i] + n_sp_per_image[i]; } ReallocatableArray<Tep> ep_send( n_disp_ep_send[n_proc] ); ReallocatableArray<Tsp> sp_send( n_disp_sp_send[n_proc] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(S32 i=0; i<n_image_tot; i++){ F64vec shift = shift_image_domain[i]; S32 n_ep = n_ep_per_image[i]; S32 n_ep_offset = n_disp_ep_per_image[i]; CopyPtclToSendBuf(typename TSM::search_type(), ep_send, ep, adr_ep_send, n_ep, n_ep_offset, shift); /* for(S32 j=0; j<n_ep; j++){ S32 adr = adr_ep_send[n_ep_offset+j]; ep_send[n_ep_offset+j] = ep[adr]; ep_send[n_ep_offset+j].setPos(ep[adr].getPos() - shift); } */ S32 n_sp = n_sp_per_image[i]; S32 n_sp_offset = n_disp_sp_per_image[i]; CopyPtclToSendBuf(typename TSM::search_type(), sp_send, sp, adr_sp_send, n_sp, n_sp_offset, shift); /* for(S32 j=0; j<n_sp; j++){ S32 adr = adr_sp_send[n_sp_offset+j]; sp_send[n_sp_offset+j] = sp[adr]; sp_send[n_sp_offset+j].setPos(sp[adr].getPos() - shift); } */ } ep_recv.resizeNoInitialize( n_disp_ep_recv[n_proc] ); sp_recv.resizeNoInitialize( n_disp_sp_recv[n_proc] ); Comm::allToAllV(ep_send.getPointer(), n_ep_send.getPointer(), n_disp_ep_send.getPointer(), ep_recv.getPointer(), n_ep_recv.getPointer(), n_disp_ep_recv.getPointer()); Comm::allToAllV(sp_send.getPointer(), n_sp_send.getPointer(), n_disp_sp_send.getPointer(), sp_recv.getPointer(), n_sp_recv.getPointer(), n_disp_sp_recv.getPointer()); } template<class Tep> inline void ExchangeLet(const ReallocatableArray<Tep> & ep, const ReallocatableArray<S32> & n_ep_send, const ReallocatableArray<S32> & n_ep_recv, const ReallocatableArray<S32> & n_ep_per_image, const ReallocatableArray<S32> & adr_ep_send, ReallocatableArray<Tep> & ep_recv, const ReallocatableArray<F64vec> & shift_image_domain, const ReallocatableArray<S32> & n_image_per_proc){ const S32 n_proc = Comm::getNumberOfProc(); //const S32 my_rank = Comm::getRank(); ReallocatableArray<S32> n_disp_ep_send(n_proc+1); ReallocatableArray<S32> n_disp_ep_recv(n_proc+1); n_disp_ep_send[0] = n_disp_ep_recv[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_ep_send[i+1] = n_ep_send[i] + n_disp_ep_send[i]; n_disp_ep_recv[i+1] = n_ep_recv[i] + n_disp_ep_recv[i]; } const S32 n_image_tot = n_ep_per_image.size(); ReallocatableArray<S32> n_disp_ep_per_image(n_image_tot+1); n_disp_ep_per_image[0] = 0; for(S32 i=0; i<n_image_tot; i++){ n_disp_ep_per_image[i+1] = n_disp_ep_per_image[i] + n_ep_per_image[i]; } ReallocatableArray<Tep> ep_send( n_disp_ep_send[n_proc] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(S32 i=0; i<n_image_tot; i++){ F64vec shift = shift_image_domain[i]; S32 n_ep = n_ep_per_image[i]; S32 n_ep_offset = n_disp_ep_per_image[i]; for(S32 j=0; j<n_ep; j++){ S32 adr = adr_ep_send[n_ep_offset+j]; ep_send[n_ep_offset+j] = ep[adr]; ep_send[n_ep_offset+j].setPos(ep[adr].getPos() - shift); } } ep_recv.resizeNoInitialize( n_disp_ep_recv[n_proc] ); Comm::allToAllV(ep_send.getPointer(), n_ep_send.getPointer(), n_disp_ep_send.getPointer(), ep_recv.getPointer(), n_ep_recv.getPointer(), n_disp_ep_recv.getPointer()); /* if(my_rank == 0){ for(S32 i=0; i<n_disp_ep_recv[n_proc]; i++){ std::cerr<<"ep_recv[i].pos= "<<ep_recv[i].pos<<std::endl; } } */ } // exchange LET ////////////// template<class Tep> inline void ExchangeParticle(const ReallocatableArray<Tep> & ep, const ReallocatableArray<S32> & n_ep_send, const ReallocatableArray<S32> & n_ep_recv, const ReallocatableArray<S32> & n_ep_per_image, const ReallocatableArray<S32> & adr_ep_send, ReallocatableArray<Tep> & ep_recv, const ReallocatableArray<F64vec> & shift_image_domain, const ReallocatableArray<S32> & n_image_per_proc){ const S32 n_proc = Comm::getNumberOfProc(); ReallocatableArray<S32> n_disp_ep_send(n_proc+1); ReallocatableArray<S32> n_disp_ep_recv(n_proc+1); n_disp_ep_send[0] = n_disp_ep_recv[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_ep_send[i+1] = n_ep_send[i] + n_disp_ep_send[i]; n_disp_ep_recv[i+1] = n_ep_recv[i] + n_disp_ep_recv[i]; } const S32 n_image_tot = n_ep_per_image.size(); ReallocatableArray<S32> n_disp_ep_per_image(n_image_tot+1); n_disp_ep_per_image[0] = 0; for(S32 i=0; i<n_image_tot; i++){ n_disp_ep_per_image[i+1] = n_disp_ep_per_image[i] + n_ep_per_image[i]; } ReallocatableArray<Tep> ep_send( n_disp_ep_send[n_proc] ); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for schedule(dynamic, 4) #endif for(S32 i=0; i<n_image_tot; i++){ F64vec shift = shift_image_domain[i]; S32 n_ep = n_ep_per_image[i]; S32 n_ep_offset = n_disp_ep_per_image[i]; for(S32 j=0; j<n_ep; j++){ S32 adr = adr_ep_send[n_ep_offset+j]; ep_send[n_ep_offset+j] = ep[adr]; ep_send[n_ep_offset+j].setPos(ep[adr].getPos() - shift); } } ep_recv.resizeNoInitialize( n_disp_ep_recv[n_proc] ); Comm::allToAllV(ep_send.getPointer(), n_ep_send.getPointer(), n_disp_ep_send.getPointer(), ep_recv.getPointer(), n_ep_recv.getPointer(), n_disp_ep_recv.getPointer()); } template<class Ttc, class Ttp, class Tepj> inline void FindExchangeParticleDoubleWalk(const ReallocatableArray<Tepj> & epj_A, // received particles const ReallocatableArray<Ttc> & tc_first_B, const ReallocatableArray<S32> & n_epj_src_per_proc, const ReallocatableArray<S32> & n_image_send_per_proc_irnai, // not needed const DomainInfo & dinfo, const S32 n_leaf_limit_B, ReallocatableArray<S32> & n_epj_send_per_proc, ReallocatableArray<S32> & n_epj_send_per_image, ReallocatableArray<S32> & n_image_send_per_proc, ReallocatableArray<S32> & adr_ep_send, ReallocatableArray<F64vec> & shift_per_image, const ReallocatableArray<Tepj> & epj_B, // assigned const F64vec & center_tree, const F64 & full_len_tree ){ const S32 n_proc = Comm::getNumberOfProc(); //const S32 my_rank = Comm::getRank(); /* if(my_rank==0){ std::cerr<<"epj_A.size()= "<<epj_A.size() <<" tc_first_B.size()= "<<tc_first_B.size() <<std::endl; for(S32 i=0; i<n_proc; i++){ std::cerr<<"n_epj_src_per_proc[i]= "<<n_epj_src_per_proc[i]<<std::endl; } } */ const S32 n_thread = Comm::getNumberOfThread(); const F64ort pos_root_domain = dinfo.getPosRootDomain(); const F64vec len_root_domain = pos_root_domain.getFullLength(); n_image_send_per_proc.resizeNoInitialize(n_proc); n_epj_send_per_proc.resizeNoInitialize(n_proc); ReallocatableArray<S32> n_disp_epj_per_proc; n_disp_epj_per_proc.resizeNoInitialize(n_proc+1); n_disp_epj_per_proc[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_epj_per_proc[i+1] = n_disp_epj_per_proc[i] + n_epj_src_per_proc[i]; } for(S32 i=0; i<n_proc; i++){ n_epj_send_per_proc[i] = 0; } static ReallocatableArray<Tepj> * epj_sorted_tmp; static ReallocatableArray<F64vec> * shift_per_image_tmp; static ReallocatableArray<Ttp> * tp_tmp; static ReallocatableArray<Ttc> * tc_tmp; static ReallocatableArray<S32> * adr_tc_level_partition_tmp; static ReallocatableArray<S32> * adr_ptcl_send_tmp; static ReallocatableArray<S32> * rank_dst_tmp; static ReallocatableArray<S32> * adr_epj_src_per_image_tmp; static ReallocatableArray<S32> * n_epj_src_per_image_tmp; static ReallocatableArray<S32> * n_epj_send_per_image_tmp; static bool first = true; if(first){ epj_sorted_tmp = new ReallocatableArray<Tepj>[n_thread]; shift_per_image_tmp = new ReallocatableArray<F64vec>[n_thread]; tp_tmp = new ReallocatableArray<Ttp>[n_thread]; tc_tmp = new ReallocatableArray<Ttc>[n_thread]; adr_tc_level_partition_tmp = new ReallocatableArray<S32>[n_thread]; adr_ptcl_send_tmp = new ReallocatableArray<S32>[n_thread]; for(S32 i=0; i<n_thread; i++){ adr_tc_level_partition_tmp[i].resizeNoInitialize(TREE_LEVEL_LIMIT+2); } rank_dst_tmp = new ReallocatableArray<S32>[n_thread]; adr_epj_src_per_image_tmp = new ReallocatableArray<S32>[n_thread]; n_epj_src_per_image_tmp = new ReallocatableArray<S32>[n_thread]; n_epj_send_per_image_tmp = new ReallocatableArray<S32>[n_thread]; first = false; } ReallocatableArray<S32> rank_src(n_proc); for(S32 i=0; i<n_proc; i++){ n_image_send_per_proc[i] = 0; if(n_epj_src_per_proc[i] > 0) rank_src.push_back(i); } ReallocatableArray<F64> len_peri(DIMENSION); bool pa[DIMENSION]; dinfo.getPeriodicAxis(pa); for(S32 i=0; i<DIMENSION; i++){ if(pa[i]==false) len_peri[i] = 0.0; } #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { const S32 ith = Comm::getThreadNum(); epj_sorted_tmp[ith].clearSize(); shift_per_image_tmp[ith].clearSize(); adr_ptcl_send_tmp[ith].clearSize(); rank_dst_tmp[ith].clearSize(); tc_tmp[ith].clearSize(); tp_tmp[ith].clearSize(); adr_epj_src_per_image_tmp[ith].clearSize(); n_epj_src_per_image_tmp[ith].clearSize(); n_epj_send_per_image_tmp[ith].clearSize(); //S32 n_ep_send_cum_old = 0; //bool first_loop = true; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for schedule(dynamic, 1) //#pragma omp for schedule(static) #endif for(S32 ib=0; ib<rank_src.size(); ib++){ const S32 rank_tmp = rank_src[ib]; rank_dst_tmp[ith].push_back(rank_tmp); /* if(Comm::getRank() == 0){ std::cerr<<"rank_tmp= "<<rank_tmp <<" n_epj_per_proc[rank_tmp]= " <<n_epj_per_proc[rank_tmp] <<std::endl; } */ if( n_epj_src_per_proc[rank_tmp] <= 0) continue; const S32 adr_ptcl_head = n_disp_epj_per_proc[rank_tmp]; const S32 adr_ptcl_end = n_disp_epj_per_proc[rank_tmp+1]; S32vec id_image_old = -9999; S32 n_image = 0; for(S32 ip=adr_ptcl_head; ip<adr_ptcl_end; ip++){ const F64vec pos_target = epj_A[ip].getPos(); const S32vec id_image_new = CalcIDOfImageDomain(pos_root_domain, pos_target, pa); if(id_image_old != id_image_new){ adr_epj_src_per_image_tmp[ith].push_back(ip); n_epj_src_per_image_tmp[ith].push_back(0); #ifdef PARTICLE_SIMULATOR_TWO_DIMENSION shift_per_image_tmp[ith].push_back(F64vec(id_image_new.x*len_root_domain.x, id_image_new.y*len_root_domain.y)); #else shift_per_image_tmp[ith].push_back(F64vec(id_image_new.x*len_root_domain.x, id_image_new.y*len_root_domain.y, id_image_new.z*len_root_domain.z)); #endif id_image_old = id_image_new; n_image++; } n_epj_src_per_image_tmp[ith].back()++; } /* if(Comm::getRank()==0 && rank_tmp==1){ std::cerr<<"adr_ptcl_head= "<<adr_ptcl_head <<" adr_ptcl_end= "<<adr_ptcl_end <<std::endl; } */ /* if(Comm::getRank()==0){ std::cerr<<"rank_tmp= "<<rank_tmp <<" n_image= "<<n_image <<" n_disp_epj_per_image_tmp[ith].size()= "<<n_disp_epj_per_image_tmp[ith].size() <<std::endl; for(S32 ip=adr_ptcl_head; ip<adr_ptcl_end; ip++){ std::cerr<<"ip, pos= "<<ip<<", "<<epj_A[ip].getPos()<<std::endl; } } */ n_image_send_per_proc[rank_tmp] = n_image; const S32 adr_image_end = n_epj_src_per_image_tmp[ith].size(); const S32 adr_image_head = adr_image_end - n_image; const S32 n_epj_send_cum_prev = adr_ptcl_send_tmp[ith].size(); for(S32 ii=adr_image_head; ii<adr_image_end; ii++){ const F64vec shift = shift_per_image_tmp[ith][ii]; /* if(Comm::getRank()==0){ std::cerr<<"rank_tmp= "<<rank_tmp <<" ii= "<<ii <<" shift= "<<shift <<" n_epj_src_per_image_tmp[ith][ii]= "<<n_epj_src_per_image_tmp[ith][ii] <<std::endl; } */ const F64ort pos_domain = dinfo.getPosDomain(rank_tmp).shift(shift); //const F64ort pos_domain = dinfo.getPosDomain(rank_tmp).shift(-shift); /* if(Comm::getRank() == 0 && rank_tmp==1){ std::cerr<<"rank_tmp= "<<rank_tmp <<" shift= "<<shift <<" pos_domain= "<<pos_domain <<" n_disp_epj_per_image_tmp[ith][ii]= " <<n_disp_epj_per_image_tmp[ith][ii] <<" n_disp_epj_per_image_tmp[ith][ii+1]= " <<n_disp_epj_per_image_tmp[ith][ii+1] <<std::endl; } */ /////////////// // MAKE TREE A S32 n_cnt = 0; tp_tmp[ith].resizeNoInitialize(n_epj_src_per_image_tmp[ith][ii]); for(S32 ip=adr_epj_src_per_image_tmp[ith][ii]; ip<adr_epj_src_per_image_tmp[ith][ii]+n_epj_src_per_image_tmp[ith][ii]; ip++, n_cnt++){ tp_tmp[ith][n_cnt].setFromEP(epj_A[ip], ip); //if(Comm::getRank()==0) std::cerr<<"epj_A[ip].pos= "<<epj_A[ip].pos<<std::endl; } std::sort(tp_tmp[ith].getPointer(), tp_tmp[ith].getPointer()+n_cnt, LessOPKEY()); epj_sorted_tmp[ith].resizeNoInitialize(n_cnt); for(S32 ip=0; ip<n_cnt; ip++){ const S32 adr = tp_tmp[ith][ip].adr_ptcl_; epj_sorted_tmp[ith][ip] = epj_A[adr]; tp_tmp[ith][ip].adr_ptcl_ = ip; /* if(Comm::getRank()==0 && rank_tmp == 1){ std::cout<<"ip= "<<ip<<" epj_A[adr].pos= "<<epj_A[adr].pos<<std::endl; } */ } /* if(Comm::getRank() == 0){ for(S32 ip=0; ip<n_cnt; ip++){ std::cerr<<"epj_sorted_tmp[ith][ip].pos= "<<epj_sorted_tmp[ith][ip].pos<<std::endl; } } */ const S32 n_leaf_limit_A = 1; S32 lev_max_A = 0; LinkCellST(tc_tmp[ith], adr_tc_level_partition_tmp[ith].getPointer(), tp_tmp[ith].getPointer(), lev_max_A, n_cnt, n_leaf_limit_A); CalcMomentST(adr_tc_level_partition_tmp[ith].getPointer(), tc_tmp[ith].getPointer(), epj_sorted_tmp[ith].getPointer(), lev_max_A, n_leaf_limit_A); /* if(Comm::getRank() == 0 && rank_tmp == 1){ std::cerr<<"tc_tmp[ith][0].mom_.getVertexOut()= "<<tc_tmp[ith][0].mom_.getVertexOut() <<"tc_tmp[ith][0].mom_.getVertexIn()= "<<tc_tmp[ith][0].mom_.getVertexIn() <<" epj_sorted_tmp[ith][0].pos= "<<epj_sorted_tmp[ith][0].pos <<std::endl; } */ /* if(Comm::getRank() == 0){ S32 err = 0; tc_tmp[ith].getPointer()->checkTree(epj_sorted_tmp[ith].getPointer(), tc_tmp[ith].getPointer(), center_tree, full_len_tree*0.5, n_leaf_limit_A, 1e-4, err); tc_tmp[ith].getPointer()->dumpTree(epj_sorted_tmp[ith].getPointer(), tc_tmp[ith].getPointer(), center_tree, full_len_tree*0.5, n_leaf_limit_A); } */ const S32 n_epj_send_per_image_prev = adr_ptcl_send_tmp[ith].size(); MakeListDoubleWalkTop(tc_tmp[ith], tc_first_B, epj_A, pos_domain, n_leaf_limit_A, n_leaf_limit_B, adr_ptcl_send_tmp[ith]); n_epj_send_per_image_tmp[ith].push_back(adr_ptcl_send_tmp[ith].size() - n_epj_send_per_image_prev); if(Comm::getRank() == 0 && rank_tmp == 1){ /* std::cout<<"rank_tmp= "<<rank_tmp <<" shift= "<<shift <<" pos_domain= "<<pos_domain <<" tc_tmp[ith].size()= "<<tc_tmp[ith].size() <<" tc_first_B.size()= "<<tc_first_B.size() <<" n_epj_send_per_image_tmp[ith].back()= "<<n_epj_send_per_image_tmp[ith].back() <<" adr_ptcl_send_tmp[ith].size()= "<<adr_ptcl_send_tmp[ith].size() <<std::endl; */ /* for(S32 iii=n_epj_send_per_image_prev; iii<adr_ptcl_send_tmp[ith].size(); iii++){ std::cerr<<"adr_ptcl_send_tmp[ith][iii]= "<<adr_ptcl_send_tmp[ith][iii] <<" epj_B[adr_ptcl_send_tmp[ith][iii]].id= "<<epj_B[adr_ptcl_send_tmp[ith][iii]].id <<" pos= "<<epj_B[adr_ptcl_send_tmp[ith][iii]].pos <<std::endl; } */ } /* const S32 n_ep_per_image = adr_ptcl_send_tmp[ith].size(); n_ep_per_image_tmp[ith].push_back(n_ep_per_image); for(S32 jp=0; jp<n_ep_per_image; jp++){ const S32 adr = adr_ptcl_send_tmp[ith][jp]; //const F64vec pos_j = epj[adr].getPos(); //if( pos_root_cell_.notOverlapped(pos_j-shift) ) continue; } */ } // end of for ii=0 to n_image n_epj_send_per_proc[rank_tmp] = adr_ptcl_send_tmp[ith].size() - n_epj_send_cum_prev; } // end of OMP for } // end of OMP scope /* if(Comm::getRank()==0){ for(S32 i=0; i<n_proc; i++){ std::cerr<<"n_image_send_per_proc[i]= "<<n_image_send_per_proc[i] <<" n_epj_send_per_proc[i]= "<<n_epj_send_per_proc[i] <<std::endl; } } */ /* if(Comm::getRank()==0){ for(S32 i=0; i<n_thread; i++){ std::cerr<<"rank_send_tmp[i].size()= "<<rank_send_tmp[i].size()<<std::endl; for(S32 j=0; j<rank_send_tmp[i].size(); j++){ std::cerr<<"rank_send_tmp[i][j]= "<<rank_send_tmp[i][j]<<std::endl; } } } */ ReallocatableArray<S32> n_disp_image_send_per_proc; n_disp_image_send_per_proc.resizeNoInitialize(n_proc+1); n_disp_image_send_per_proc[0] = 0; for(S32 i=0; i<n_proc; i++){ n_disp_image_send_per_proc[i+1] = n_disp_image_send_per_proc[i] + n_image_send_per_proc[i]; } /* if(Comm::getRank()==0){ for(S32 i=0; i<n_proc; i++){ std::cerr<<"n_image_send_per_proc[i]= "<<n_image_send_per_proc[i] <<" n_disp_image_send_per_proc[i]= "<<n_disp_image_send_per_proc[i] <<std::endl; } } */ /* S32 n_image_send_tot = 0; for(S32 i=0; i<n_thread; i++){ n_image_send_tot += shift_per_image_tmp[i].size(); } if(Comm::getRank()==0){ std::cerr<<"n_image_send_tot= "<<n_image_send_tot<<std::endl; } */ const S32 n_image_send_tot = n_disp_image_send_per_proc[n_proc]; n_epj_send_per_image.resizeNoInitialize(n_image_send_tot); shift_per_image.resizeNoInitialize(n_image_send_tot); for(S32 i=0; i<n_thread; i++){ S32 n_cnt_image = 0; //S32 n_cnt_ep = 0; for(S32 j=0; j<rank_dst_tmp[i].size(); j++){ const S32 rank = rank_dst_tmp[i][j]; const S32 adr_image_head = n_disp_image_send_per_proc[rank]; const S32 adr_image_end = n_disp_image_send_per_proc[rank+1]; /* if(Comm::getRank()==0){ std::cerr<<"rank= "<<rank <<" adr_image_head= "<<adr_image_head <<" adr_image_end= "<<adr_image_end <<std::endl; } */ for(S32 k=adr_image_head; k<adr_image_end; k++, n_cnt_image++){ n_epj_send_per_image[k] = n_epj_send_per_image_tmp[i][n_cnt_image]; shift_per_image[k] = shift_per_image_tmp[i][n_cnt_image]; /* if(Comm::getRank()==0){ std::cerr<<"k= "<<k <<" n_epj_send_per_image[k]= "<<n_epj_send_per_image[k] <<std::endl; } */ } } } ReallocatableArray<S32> n_disp_epj_send_per_image; n_disp_epj_send_per_image.resizeNoInitialize(n_image_send_tot+1); n_disp_epj_send_per_image[0] = 0; for(S32 i=0; i<n_image_send_tot; i++){ n_disp_epj_send_per_image[i+1] = n_disp_epj_send_per_image[i] + n_epj_send_per_image[i]; } S32 n_epj_send_tot = 0; for(S32 i=0; i<n_proc; i++) n_epj_send_tot += n_epj_send_per_proc[i]; adr_ep_send.resizeNoInitialize(n_epj_send_tot); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_thread; i++){ S32 n_cnt_image = 0; S32 n_cnt_ep = 0; for(S32 j=0; j<rank_dst_tmp[i].size(); j++){ const S32 rank = rank_dst_tmp[i][j]; const S32 adr_image_head = n_disp_image_send_per_proc[rank]; const S32 adr_image_end = n_disp_image_send_per_proc[rank+1]; for(S32 k=adr_image_head; k<adr_image_end; k++, n_cnt_image++){ n_epj_send_per_image[k] = n_epj_send_per_image_tmp[i][n_cnt_image]; shift_per_image[k] = shift_per_image_tmp[i][n_cnt_image]; const S32 adr_epj_head = n_disp_epj_send_per_image[k]; const S32 adr_epj_end = n_disp_epj_send_per_image[k+1]; for(S32 l=adr_epj_head; l<adr_epj_end; l++, n_cnt_ep++){ adr_ep_send[l] = adr_ptcl_send_tmp[i][n_cnt_ep]; /* if(Comm::getRank()==0){ std::cerr<<"l= "<<l <<" adr_ep_send[l]= "<<adr_ep_send[l] <<std::endl; } */ } } } } /* if(Comm::getRank()==0){ for(S32 i=0; i<n_proc; i++){ std::cout<<"rank= "<<i<<std::endl; const S32 adr_image_head = n_disp_image_send_per_proc[i]; const S32 adr_image_end = n_disp_image_send_per_proc[i+1]; for(S32 j=adr_image_head; j<adr_image_end; j++){ std::cout<<"image= "<<j <<" shift_per_image[j]= "<<shift_per_image[j] <<std::endl; const S32 adr_epj_head = n_disp_epj_send_per_image[j]; const S32 adr_epj_end = n_disp_epj_send_per_image[j+1]; for(S32 k=adr_epj_head; k<adr_epj_end; k++){ std::cout<<"k= "<<k <<" adr_ep_send[k]= "<<adr_ep_send[k] <<std::endl; } } } } */ //Comm::barrier(); //exit(1); } ////////////////// // add moment as sp #if 1 template<class Ttreecell, class Tspj> inline void AddMomentAsSpImpl(TagForceLong, const ReallocatableArray<Ttreecell> & _tc, const S32 offset, ReallocatableArray<Tspj> & _spj){ /* S32 n_spj_prev = _spj.size(); if(Comm::getRank() == 0){ std::cerr<<"_tc.size()= "<<_tc.size() <<" _spj.size()= "<<_spj.size() <<std::endl; } */ /* if(Comm::getRank() == 0){ std::cerr<<"_tc.size()= "<<_tc.size() <<" offset= "<<offset <<" _spj.size()= "<<_spj.size() <<std::endl; } */ _spj.resizeNoInitialize(offset+_tc.size()); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif //PARTICLE_SIMULATOR_THREAD_PARALLEL for(S32 i=0; i<_tc.size(); i++){ _spj[offset+i].copyFromMoment(_tc[i].mom_); } } #else template<class Ttreecell, class Tspj> inline void AddMomentAsSpImpl(TagForceLong, const ReallocatableArray<Ttreecell> & _tc, ReallocatableArray<Tspj> & _spj){ S32 n_spj_prev = _spj.size(); /* if(Comm::getRank() == 0){ std::cerr<<"_tc.size()= "<<_tc.size() <<" _spj.size()= "<<_spj.size() <<std::endl; } */ _spj.resizeNoInitialize(n_spj_prev+_tc.size()); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif //PARTICLE_SIMULATOR_THREAD_PARALLEL for(S32 i=0; i<_tc.size(); i++){ _spj[n_spj_prev+i].copyFromMoment(_tc[i].mom_); } } #endif template<class Ttreecell, class Tspj> inline void AddMomentAsSpImpl(TagForceShort, const ReallocatableArray<Ttreecell> & _tc, const S32 offset, ReallocatableArray<Tspj> & _spj){ // do nothing } // for long force template<class Ttp, class Tepj0, class Tepj1, class Tspj0, class Tspj1> inline void SetLocalEssentialTreeToGlobalTreeImpl(const ReallocatableArray<Tepj0> & epj_recv, const ReallocatableArray<Tspj0> & spj_recv, const ReallocatableArray<Ttp> & tp_loc, ReallocatableArray<Tepj1> & epj_org, ReallocatableArray<Tspj1> & spj_org, ReallocatableArray<Ttp> & tp_glb, const bool flag_reuse = false){ //const S32 n_proc = Comm::getNumberOfProc(); const S32 n_loc = tp_loc.size(); const S32 n_ep_add = epj_recv.size(); const S32 n_sp_add = spj_recv.size(); const S32 offset_sp = n_loc + n_ep_add; const S32 n_glb_tot = n_loc + n_ep_add + n_sp_add; //std::cerr<<"n_loc= "<<n_loc // <<" offset_sp= "<<offset_sp // <<" n_glb_tot= "<<n_glb_tot // <<std::endl; tp_glb.resizeNoInitialize( n_glb_tot ); epj_org.resizeNoInitialize( offset_sp ); spj_org.resizeNoInitialize( n_glb_tot ); if(!flag_reuse){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for #endif for(S32 i=0; i<n_loc; i++){ tp_glb[i] = tp_loc[i]; // NOTE: need to keep tp_loc_[]? } #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for #endif for(S32 i=0; i<n_ep_add; i++){ epj_org[n_loc+i] = epj_recv[i]; tp_glb[n_loc+i].setFromEP(epj_recv[i], n_loc+i); } #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for #endif for(S32 i=0; i<n_sp_add; i++){ spj_org[offset_sp+i] = spj_recv[i]; tp_glb[offset_sp+i].setFromSP(spj_recv[i], offset_sp+i); } } } else{ /* if(Comm::getRank()==0){ std::cerr<<"n_loc= "<<n_loc<<std::endl; std::cerr<<"offset_sp= "<<offset_sp<<std::endl; std::cerr<<"n_ep_add= "<<n_ep_add<<std::endl; std::cerr<<"n_sp_add= "<<n_sp_add<<std::endl; } */ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_ep_add; i++){ epj_org[n_loc+i] = epj_recv[i]; /* if(Comm::getRank()==0){ std::cerr<<"i= "<<i<<" epj_recv[i].mass= "<<epj_recv[i].mass<<std::endl; std::cerr<<"n_loc+i= "<<n_loc+i<<" epj_org[n_loc+i].mass= "<<epj_org[n_loc+i].mass<<std::endl; } */ } #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_sp_add; i++){ spj_org[offset_sp+i] = spj_recv[i]; } } } template<class Ttp, class Tepj0, class Tepj1> inline void SetLocalEssentialTreeToGlobalTreeImpl(const ReallocatableArray<Tepj0> & epj_recv, const ReallocatableArray<Ttp> & tp_loc, ReallocatableArray<Tepj1> & epj_org, ReallocatableArray<Ttp> & tp_glb, const bool flag_reuse = false){ //const S32 n_proc = Comm::getNumberOfProc(); const S32 n_ep_add = epj_recv.size(); const S32 n_loc = tp_loc.size(); const S32 n_glb_tot = n_loc + n_ep_add; tp_glb.resizeNoInitialize( n_glb_tot ); epj_org.resizeNoInitialize( n_glb_tot ); if(!flag_reuse){ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel #endif { #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for #endif for(S32 i=0; i<n_loc; i++){ tp_glb[i] = tp_loc[i]; } #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp for #endif for(S32 i=0; i<n_ep_add; i++){ epj_org[n_loc+i] = epj_recv[i]; tp_glb[n_loc+i].setFromEP(epj_recv[i], n_loc+i); } } } else{ #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_ep_add; i++){ epj_org[n_loc+i] = epj_recv[i]; } } } #if 0 template<class Ttc, class Tepj, class Tspj> inline void SetOuterBoxGlobalTreeForLongCutoff(TagSearchLongCutoff, S32 adr_tc_level_partition[], Ttc tc[], TreeParticle tp[], Tepj epj[], Tspj spj[], const S32 lev_max, const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ F64 r_cut = epj[0].getRSearch(); /* if(Comm::getRank()==0){ std::cerr<<"r_cut= "<<r_cut <<" tc_hlen= "<<tc_hlen <<" tc_cen= "<<tc_cen <<std::endl; } */ for(S32 i=lev_max; i>=0; --i){ const S32 head = adr_tc_level_partition[i]; const S32 next = adr_tc_level_partition[i+1]; #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 j=head; j<next; j++){ Ttc * tc_tmp = tc + j; const int n_tmp = tc_tmp->n_ptcl_; tc_tmp->mom_.vertex_out_.init(); if( n_tmp == 0) continue; else if(tc_tmp->isLeaf(n_leaf_limit)){ // leaf const S32 adr = tc_tmp->adr_ptcl_; F64vec cen = tc_cen; F64 hlen = tc_hlen; U64 mkey = tp[adr].key_; for(S32 k=0; k<=i; k++){ U64 id = MortonKey::getCellID(k, mkey); cen = cen + SHIFT_CENTER[id]*hlen; hlen *= 0.5; } hlen *= 2.0; tc_tmp->mom_.vertex_out_.high_ = cen + (hlen+r_cut); tc_tmp->mom_.vertex_out_.low_ = cen - (hlen+r_cut); /* if(Comm::getRank()==0){ std::cerr<<"tc_tmp->mom_.vertex_out_= "<<tc_tmp->mom_.vertex_out_<<std::endl; for(S32 k=adr; k<adr+n_tmp; k++){ if( GetMSB(tp[k].adr_ptcl_) == 0 ){ std::cerr<<"epj[k].pos= "<<epj[k].pos<<std::endl; } else{ std::cerr<<"spj[k].pos= "<<spj[k].pos<<std::endl; } } } */ /* if(Comm::getRank()==0){ std::cerr<<"n_tmp= "<<n_tmp<<std::endl;} for(S32 iii=0; iii<n_tmp; iii++){ U64 mkey = tp[adr+iii].key_; for(S32 k=0; k<=i; k++){ U64 id = MortonKey::getCellID(k, mkey); cen = cen + SHIFT_CENTER[id]*hlen; hlen *= 0.5; if(Comm::getRank()==0){ std::cerr<<" id= "<<id <<" cen= "<<cen; } } if(Comm::getRank()==0){ std::cerr<<std::endl; } } U64 mkey = tp[adr].key_; */ #if 0 if(Comm::getRank()==0){ /* std::cerr<<"tc_tmp->mom_.vertex_out_= " <<tc_tmp->mom_.vertex_out_ <<std::endl; */ /* std::cerr<<" tc_tmp->level_= "<<tc_tmp->level_ <<" i= "<<i <<" mkey= "<<mkey <<std::endl; */ /* std::cerr<<"tc_tmp->mom_.vertex_out_= " <<tc_tmp->mom_.vertex_out_ <<" tc_tmp->level_= "<<tc_tmp->level_ <<" i= "<<i <<" mkey= "<<mkey <<std::endl; */ } #endif } else{ // not leaf for(S32 k=0; k<N_CHILDREN; k++){ Ttc * tc_tmp_tmp = tc + ((tc_tmp->adr_tc_)+k); if(tc_tmp_tmp->n_ptcl_ == 0) continue; tc_tmp->mom_.vertex_out_.merge(tc_tmp_tmp->mom_.vertex_out_); } } } } /* if(Comm::getRank()==0){ std::cerr<<"tc[0].mom_.vertex_out_= "<<tc[0].mom_.vertex_out_<<std::endl; } */ } #endif template<class Ttc> inline void SetOuterBoxGlobalTreeForLongCutoffRecursive(Ttc tc[], const S32 n_leaf_limit, const F64 r_cut, const S32 adr_tc, const F64 tc_hlen, const F64vec tc_cen){ F64 child_hlen = tc_hlen*0.5; for(S32 i=0; i<N_CHILDREN; i++){ F64vec child_cen = tc_cen + SHIFT_CENTER[i]*tc_hlen; tc[adr_tc+i].mom_.vertex_out_.high_ = child_cen + (child_hlen+r_cut); tc[adr_tc+i].mom_.vertex_out_.low_ = child_cen - (child_hlen+r_cut); S32 child_adr_tc = tc[adr_tc+i].adr_tc_; if(tc[adr_tc+i].n_ptcl_ <= 0) continue; else if(tc[adr_tc+i].isLeaf(n_leaf_limit)) continue; else{ SetOuterBoxGlobalTreeForLongCutoffRecursive(tc, n_leaf_limit, r_cut, child_adr_tc, child_hlen, child_cen); } } } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchLongCutoff, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ F64 r_cut = epj[0].getRSearch(); tc[0].mom_.vertex_out_.high_ = tc_cen + (tc_hlen+r_cut); tc[0].mom_.vertex_out_.low_ = tc_cen - (tc_hlen+r_cut); for(S32 i=1; i<N_CHILDREN; i++) tc[i].mom_.vertex_out_.init(); if( tc[0].n_ptcl_ < 0 || tc[0].isLeaf(n_leaf_limit) ) return; S32 adr_tc = N_CHILDREN; SetOuterBoxGlobalTreeForLongCutoffRecursive(tc, n_leaf_limit, r_cut, adr_tc, tc_hlen, tc_cen); } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchLong, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ // do nothing } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchLongScatter, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ // do nothing } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchLongSymmetry, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ // do nothing } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchShortGather, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ // do nothing } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchShortScatter, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ // do nothing } template<class Ttc, class Tepj> inline void SetOuterBoxGlobalTreeForLongCutoffTop(TagSearchShortSymmetry, Ttc tc[], Tepj epj[], const S32 n_leaf_limit, const F64 tc_hlen, const F64vec tc_cen){ // do nothing } // it may works only if tp has one component. template<class Tsys, class Ttp, class Tepi, class Tepj> inline void CopyFpToEpSortedLocalTree(const Tsys & sys, const ReallocatableArray<Ttp> & tp, ReallocatableArray<Tepi> &epi_sorted, ReallocatableArray<Tepj> &epj_sorted){ const S32 n_loc = sys.getNumberOfParticleLocal(); for(S32 i=0; i<n_loc; i++){ const S32 adr = tp[i].adr_ptcl_; epi_sorted[i].copyFromFP(sys[adr]); epj_sorted[i].copyFromFP(sys[adr]); } } /* // under construction template<class Ttp, class Tepj, class Tspj> void CopyPtclLocPtclRecvToPtclSortedGlobalTree(TagForceLong, const ReallocatableArray<Tepj> & epj_recv, const ReallocatableArray<Tspj> & spj_recv, const ReallocatableArray<Ttp> & tp_glb, ReallocatableArray<Tepj> &epj_sorted, ReallocatableArray<Tspj> &epj_sorted){ const S32 n_loc; const S32 n_epj_recv = epj_recv.size(); const S32 n_spj_recv = epj_recv.size(); for(S32 i=0; i<n_epj_recv; i++){ S32 adr = tp_glb_[n_loc+i].adr_ptcl_; } const S32 n_glb = ; for(S32 i=0; i<n_glb; i++){ const U32 adr = tp[i].adr_ptcl_; if( GetMSB(adr) == 0){ epj_sorted_[i] = epj_org_[adr]; } else{ spj_sorted_[i] = spj_org_[ClearMSB(adr)]; } } } */ /* template<class Tfp, class Ttp> void MortonSortFP(ParticleSystem<Tfp> & sys, const ReallocatableArray<Ttp> tp_loc){ const S32 n_loc_tot = tp_loc.size(); ReallocatableArray<Tfp> fp_org(n_loc_tot); #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot; i++){ fp_org[i] = sys[i]; } #ifdef PARTICLE_SIMULATOR_THREAD_PARALLEL #pragma omp parallel for #endif for(S32 i=0; i<n_loc_tot; i++){ const S32 adr = tp_loc[i].adr_ptcl_; sys[i] = fp_org[adr]; } } */ }
47.632794
169
0.487164
Guo-astro
e9fd7bfd82928bd139c42b4c05ae96b8ec947960
6,591
hh
C++
kenlm/util/sized_iterator.hh
cmedlock/deepspeech.pytorch
7f0dbcdb3bcc41992136ebedfcd3e7d6fdb256d1
[ "MIT" ]
111
2020-08-31T04:58:54.000Z
2022-03-29T15:44:18.000Z
Part 02/001_LM/ngram_lm_lab/kenlm/util/sized_iterator.hh
Kabongosalomon/AMMI-NLP
00a0e47399926ad1951b84a11cd936598a9c7c3b
[ "MIT" ]
14
2020-12-16T07:27:22.000Z
2022-03-15T17:39:01.000Z
Part 02/001_LM/ngram_lm_lab/kenlm/util/sized_iterator.hh
Kabongosalomon/AMMI-NLP
00a0e47399926ad1951b84a11cd936598a9c7c3b
[ "MIT" ]
29
2021-02-09T08:57:15.000Z
2022-03-12T14:09:19.000Z
#ifndef UTIL_SIZED_ITERATOR_H #define UTIL_SIZED_ITERATOR_H #include "util/pool.hh" #include "util/proxy_iterator.hh" #include <algorithm> #include <functional> #include <string> #include <stdint.h> #include <cstring> #include <stdlib.h> namespace util { class SizedInnerIterator { public: SizedInnerIterator() {} SizedInnerIterator(void *ptr, std::size_t size) : ptr_(static_cast<uint8_t*>(ptr)), size_(size) {} bool operator==(const SizedInnerIterator &other) const { return ptr_ == other.ptr_; } bool operator<(const SizedInnerIterator &other) const { return ptr_ < other.ptr_; } SizedInnerIterator &operator+=(std::ptrdiff_t amount) { ptr_ += amount * size_; return *this; } std::ptrdiff_t operator-(const SizedInnerIterator &other) const { return (ptr_ - other.ptr_) / size_; } const void *Data() const { return ptr_; } void *Data() { return ptr_; } std::size_t EntrySize() const { return size_; } friend void swap(SizedInnerIterator &first, SizedInnerIterator &second); private: uint8_t *ptr_; std::size_t size_; }; inline void swap(SizedInnerIterator &first, SizedInnerIterator &second) { using std::swap; swap(first.ptr_, second.ptr_); swap(first.size_, second.size_); } class ValueBlock { public: explicit ValueBlock(const void *from, FreePool &pool) : ptr_(std::memcpy(pool.Allocate(), from, pool.ElementSize())), pool_(pool) {} ValueBlock(const ValueBlock &from) : ptr_(std::memcpy(from.pool_.Allocate(), from.ptr_, from.pool_.ElementSize())), pool_(from.pool_) {} ValueBlock &operator=(const ValueBlock &from) { std::memcpy(ptr_, from.ptr_, pool_.ElementSize()); return *this; } ~ValueBlock() { pool_.Free(ptr_); } const void *Data() const { return ptr_; } void *Data() { return ptr_; } private: void *ptr_; FreePool &pool_; }; class SizedProxy { public: SizedProxy() {} SizedProxy(void *ptr, FreePool &pool) : inner_(ptr, pool.ElementSize()), pool_(&pool) {} operator ValueBlock() const { return ValueBlock(inner_.Data(), *pool_); } SizedProxy &operator=(const SizedProxy &from) { memcpy(inner_.Data(), from.inner_.Data(), inner_.EntrySize()); return *this; } SizedProxy &operator=(const ValueBlock &from) { memcpy(inner_.Data(), from.Data(), inner_.EntrySize()); return *this; } const void *Data() const { return inner_.Data(); } void *Data() { return inner_.Data(); } friend void swap(SizedProxy first, SizedProxy second); private: friend class util::ProxyIterator<SizedProxy>; typedef ValueBlock value_type; typedef SizedInnerIterator InnerIterator; InnerIterator &Inner() { return inner_; } const InnerIterator &Inner() const { return inner_; } InnerIterator inner_; FreePool *pool_; }; inline void swap(SizedProxy first, SizedProxy second) { std::swap_ranges( static_cast<char*>(first.inner_.Data()), static_cast<char*>(first.inner_.Data()) + first.inner_.EntrySize(), static_cast<char*>(second.inner_.Data())); } typedef ProxyIterator<SizedProxy> SizedIterator; // Useful wrapper for a comparison function i.e. sort. template <class Delegate, class Proxy = SizedProxy> class SizedCompare : public std::binary_function<const Proxy &, const Proxy &, bool> { public: explicit SizedCompare(const Delegate &delegate = Delegate()) : delegate_(delegate) {} bool operator()(const Proxy &first, const Proxy &second) const { return delegate_(first.Data(), second.Data()); } bool operator()(const Proxy &first, const ValueBlock &second) const { return delegate_(first.Data(), second.Data()); } bool operator()(const ValueBlock &first, const Proxy &second) const { return delegate_(first.Data(), second.Data()); } bool operator()(const ValueBlock &first, const ValueBlock &second) const { return delegate_(first.Data(), second.Data()); } const Delegate &GetDelegate() const { return delegate_; } private: const Delegate delegate_; }; template <unsigned Size> class JustPOD { unsigned char data[Size]; }; template <class Delegate, unsigned Size> class JustPODDelegate : std::binary_function<const JustPOD<Size> &, const JustPOD<Size> &, bool> { public: explicit JustPODDelegate(const Delegate &compare) : delegate_(compare) {} bool operator()(const JustPOD<Size> &first, const JustPOD<Size> &second) const { return delegate_(&first, &second); } private: Delegate delegate_; }; #define UTIL_SORT_SPECIALIZE(Size) \ case Size: \ std::sort(static_cast<JustPOD<Size>*>(start), static_cast<JustPOD<Size>*>(end), JustPODDelegate<Compare, Size>(compare)); \ break; template <class Compare> void SizedSort(void *start, void *end, std::size_t element_size, const Compare &compare) { switch (element_size) { // Benchmarking sort found it's about 2x faster with an explicitly sized type. So here goes :-(. UTIL_SORT_SPECIALIZE(4); UTIL_SORT_SPECIALIZE(8); UTIL_SORT_SPECIALIZE(12); UTIL_SORT_SPECIALIZE(16); UTIL_SORT_SPECIALIZE(17); // This is used by interpolation. UTIL_SORT_SPECIALIZE(20); UTIL_SORT_SPECIALIZE(24); UTIL_SORT_SPECIALIZE(28); UTIL_SORT_SPECIALIZE(32); default: // Recent g++ versions create a temporary value_type then compare with it. // Problem is that value_type in this case needs to be a runtime-sized array. // Previously I had std::string serve this role. However, there were a lot // of string new and delete calls. // // The temporary value is on the stack, so there will typically only be one // at a time. But we can't guarantee that. So here is a pool optimized for // the case where one element is allocated at any given time. It can // allocate more, should the underlying C++ sort code change. { FreePool pool(element_size); // TODO is this necessary anymore? #if defined(_WIN32) || defined(_WIN64) std::stable_sort #else std::sort #endif (SizedIterator(SizedProxy(start, pool)), SizedIterator(SizedProxy(end, pool)), SizedCompare<Compare>(compare)); } } } } // namespace util // Dirty hack because g++ 4.6 at least wants to do a bunch of copy operations. namespace std { inline void iter_swap(util::SizedIterator first, util::SizedIterator second) { util::swap(*first, *second); } } // namespace std #endif // UTIL_SIZED_ITERATOR_H
30.513889
139
0.676984
cmedlock
18006c47b751a8c47ef3b39add71b44b8cf6c960
1,012
cpp
C++
src/dev/java_helper/java_helper_tools.cpp
rDSN-Projects/rDSN.Java
c6eacde9aa0ecaecba428f207bcfff8ae7d9ae40
[ "MIT" ]
null
null
null
src/dev/java_helper/java_helper_tools.cpp
rDSN-Projects/rDSN.Java
c6eacde9aa0ecaecba428f207bcfff8ae7d9ae40
[ "MIT" ]
null
null
null
src/dev/java_helper/java_helper_tools.cpp
rDSN-Projects/rDSN.Java
c6eacde9aa0ecaecba428f207bcfff8ae7d9ae40
[ "MIT" ]
null
null
null
# include "java_helper_header.h" JavaVM *g_vm; jstring chartojstring(JNIEnv* env, const char* str) { jclass clazz = env->FindClass("Ljava/lang/String;"); jmethodID method = env->GetMethodID(clazz, "<init>", "([BLjava/lang/String;)V"); jbyteArray bytes = env->NewByteArray(strlen(str)); env->SetByteArrayRegion(bytes, 0, strlen(str), (jbyte*)str); jstring encoding = env->NewStringUTF("utf-8"); return (jstring)env->NewObject(clazz, method, bytes, encoding); } // //jbyteArray Address_To_Jbyte(JNIEnv* env, dsn_address_t addr) //{ // int len = sizeof(addr); // jbyteArray addrbyte = env->NewByteArray(len + 1); // env->SetByteArrayRegion(addrbyte, 0, len, (jbyte*)&addr); // return addrbyte; //} // //dsn_address_t* Jbyte_To_Address(JNIEnv* env, jbyteArray addrbyte) //{ // return (dsn_address_t*)env->GetByteArrayElements(addrbyte, false); //} /*void Get_JavaVM(JNIEnv* env) { if (jvm.magic != 0xdeadbeef) { env->GetJavaVM(&jvm.vm); } return; }*/
28.914286
84
0.666008
rDSN-Projects
18046dc82f6eee1f946f1f072883d35beecb53eb
16,987
cc
C++
wrappers/8.1.1/vtkRIBExporterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkRIBExporterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkRIBExporterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkExporterWrap.h" #include "vtkRIBExporterWrap.h" #include "vtkObjectBaseWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkRIBExporterWrap::ptpl; VtkRIBExporterWrap::VtkRIBExporterWrap() { } VtkRIBExporterWrap::VtkRIBExporterWrap(vtkSmartPointer<vtkRIBExporter> _native) { native = _native; } VtkRIBExporterWrap::~VtkRIBExporterWrap() { } void VtkRIBExporterWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkRIBExporter").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("RIBExporter").ToLocalChecked(), ConstructorGetter); } void VtkRIBExporterWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkRIBExporterWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkExporterWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkExporterWrap::ptpl)); tpl->SetClassName(Nan::New("VtkRIBExporterWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "BackgroundOff", BackgroundOff); Nan::SetPrototypeMethod(tpl, "backgroundOff", BackgroundOff); Nan::SetPrototypeMethod(tpl, "BackgroundOn", BackgroundOn); Nan::SetPrototypeMethod(tpl, "backgroundOn", BackgroundOn); Nan::SetPrototypeMethod(tpl, "ExportArraysOff", ExportArraysOff); Nan::SetPrototypeMethod(tpl, "exportArraysOff", ExportArraysOff); Nan::SetPrototypeMethod(tpl, "ExportArraysOn", ExportArraysOn); Nan::SetPrototypeMethod(tpl, "exportArraysOn", ExportArraysOn); Nan::SetPrototypeMethod(tpl, "GetBackground", GetBackground); Nan::SetPrototypeMethod(tpl, "getBackground", GetBackground); Nan::SetPrototypeMethod(tpl, "GetExportArrays", GetExportArrays); Nan::SetPrototypeMethod(tpl, "getExportArrays", GetExportArrays); Nan::SetPrototypeMethod(tpl, "GetExportArraysMaxValue", GetExportArraysMaxValue); Nan::SetPrototypeMethod(tpl, "getExportArraysMaxValue", GetExportArraysMaxValue); Nan::SetPrototypeMethod(tpl, "GetExportArraysMinValue", GetExportArraysMinValue); Nan::SetPrototypeMethod(tpl, "getExportArraysMinValue", GetExportArraysMinValue); Nan::SetPrototypeMethod(tpl, "GetFilePrefix", GetFilePrefix); Nan::SetPrototypeMethod(tpl, "getFilePrefix", GetFilePrefix); Nan::SetPrototypeMethod(tpl, "GetPixelSamples", GetPixelSamples); Nan::SetPrototypeMethod(tpl, "getPixelSamples", GetPixelSamples); Nan::SetPrototypeMethod(tpl, "GetSize", GetSize); Nan::SetPrototypeMethod(tpl, "getSize", GetSize); Nan::SetPrototypeMethod(tpl, "GetTexturePrefix", GetTexturePrefix); Nan::SetPrototypeMethod(tpl, "getTexturePrefix", GetTexturePrefix); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetBackground", SetBackground); Nan::SetPrototypeMethod(tpl, "setBackground", SetBackground); Nan::SetPrototypeMethod(tpl, "SetExportArrays", SetExportArrays); Nan::SetPrototypeMethod(tpl, "setExportArrays", SetExportArrays); Nan::SetPrototypeMethod(tpl, "SetFilePrefix", SetFilePrefix); Nan::SetPrototypeMethod(tpl, "setFilePrefix", SetFilePrefix); Nan::SetPrototypeMethod(tpl, "SetPixelSamples", SetPixelSamples); Nan::SetPrototypeMethod(tpl, "setPixelSamples", SetPixelSamples); Nan::SetPrototypeMethod(tpl, "SetSize", SetSize); Nan::SetPrototypeMethod(tpl, "setSize", SetSize); Nan::SetPrototypeMethod(tpl, "SetTexturePrefix", SetTexturePrefix); Nan::SetPrototypeMethod(tpl, "setTexturePrefix", SetTexturePrefix); #ifdef VTK_NODE_PLUS_VTKRIBEXPORTERWRAP_INITPTPL VTK_NODE_PLUS_VTKRIBEXPORTERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkRIBExporterWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkRIBExporter> native = vtkSmartPointer<vtkRIBExporter>::New(); VtkRIBExporterWrap* obj = new VtkRIBExporterWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkRIBExporterWrap::BackgroundOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->BackgroundOff(); } void VtkRIBExporterWrap::BackgroundOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->BackgroundOn(); } void VtkRIBExporterWrap::ExportArraysOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ExportArraysOff(); } void VtkRIBExporterWrap::ExportArraysOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ExportArraysOn(); } void VtkRIBExporterWrap::GetBackground(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetBackground(); info.GetReturnValue().Set(Nan::New(r)); } void VtkRIBExporterWrap::GetExportArrays(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetExportArrays(); info.GetReturnValue().Set(Nan::New(r)); } void VtkRIBExporterWrap::GetExportArraysMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetExportArraysMaxValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkRIBExporterWrap::GetExportArraysMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetExportArraysMinValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkRIBExporterWrap::GetFilePrefix(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetFilePrefix(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkRIBExporterWrap::GetPixelSamples(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); int const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetPixelSamples(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 2 * sizeof(int)); Local<v8::Int32Array> at = v8::Int32Array::New(ab, 0, 2); memcpy(ab->GetContents().Data(), r, 2 * sizeof(int)); info.GetReturnValue().Set(at); } void VtkRIBExporterWrap::GetSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); int const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetSize(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 2 * sizeof(int)); Local<v8::Int32Array> at = v8::Int32Array::New(ab, 0, 2); memcpy(ab->GetContents().Data(), r, 2 * sizeof(int)); info.GetReturnValue().Set(at); } void VtkRIBExporterWrap::GetTexturePrefix(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTexturePrefix(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkRIBExporterWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); vtkRIBExporter * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkRIBExporterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkRIBExporterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkRIBExporterWrap *w = new VtkRIBExporterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkRIBExporterWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkRIBExporter * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkRIBExporterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkRIBExporterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkRIBExporterWrap *w = new VtkRIBExporterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkRIBExporterWrap::SetBackground(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetBackground( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkRIBExporterWrap::SetExportArrays(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetExportArrays( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkRIBExporterWrap::SetFilePrefix(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetFilePrefix( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkRIBExporterWrap::SetPixelSamples(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsInt32Array()) { v8::Local<v8::Int32Array>a0(v8::Local<v8::Int32Array>::Cast(info[0]->ToObject())); if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPixelSamples( (int *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); int b0[2]; if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 2; i++ ) { if( !a0->Get(i)->IsInt32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Int32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPixelSamples( b0 ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsInt32()) { if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetPixelSamples( info[0]->Int32Value(), info[1]->Int32Value() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkRIBExporterWrap::SetSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsInt32Array()) { v8::Local<v8::Int32Array>a0(v8::Local<v8::Int32Array>::Cast(info[0]->ToObject())); if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetSize( (int *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); int b0[2]; if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 2; i++ ) { if( !a0->Get(i)->IsInt32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Int32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetSize( b0 ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsInt32()) { if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetSize( info[0]->Int32Value(), info[1]->Int32Value() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkRIBExporterWrap::SetTexturePrefix(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkRIBExporterWrap *wrapper = ObjectWrap::Unwrap<VtkRIBExporterWrap>(info.Holder()); vtkRIBExporter *native = (vtkRIBExporter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTexturePrefix( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); }
29.087329
106
0.705657
axkibe
180d6898b409dbd7c4d2c69a68f523dc8df16e68
1,391
cpp
C++
src/buffer/lru_replacer.cpp
Laotan0926/cmu14445
48216418bbf0d38836a619530c5eca29cde31f32
[ "MIT" ]
6
2022-01-07T05:23:54.000Z
2022-03-07T10:50:13.000Z
src/buffer/lru_replacer.cpp
Laotan0926/cmu14445
48216418bbf0d38836a619530c5eca29cde31f32
[ "MIT" ]
null
null
null
src/buffer/lru_replacer.cpp
Laotan0926/cmu14445
48216418bbf0d38836a619530c5eca29cde31f32
[ "MIT" ]
1
2022-02-15T17:16:54.000Z
2022-02-15T17:16:54.000Z
//===----------------------------------------------------------------------===// // // BusTub // // lru_replacer.cpp // // Identification: src/buffer/lru_replacer.cpp // // Copyright (c) 2015-2019, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "buffer/lru_replacer.h" namespace bustub { LRUReplacer::LRUReplacer(size_t num_pages) {} LRUReplacer::~LRUReplacer() = default; bool LRUReplacer::Victim(frame_id_t *frame_id) { std::lock_guard<std::mutex> lock(mutex_); if(lru_list_.empty()){ *frame_id = INVALID_PAGE_ID; return false; } *frame_id = lru_list_.back(); lru_list_.pop_back(); lru_map_.erase(*frame_id); return true; } void LRUReplacer::Pin(frame_id_t frame_id) { std::lock_guard<std::mutex> lock(mutex_); auto iterator = lru_map_.find(frame_id); if(iterator!=lru_map_.end()){ lru_list_.erase(iterator->second); lru_map_.erase(frame_id); } } void LRUReplacer::Unpin(frame_id_t frame_id) { std::lock_guard<std::mutex> lock(mutex_); auto iterator = lru_map_.find(frame_id); if(iterator==lru_map_.end()){ lru_list_.push_front(frame_id); lru_map_.emplace(frame_id,lru_list_.begin()); } } size_t LRUReplacer::Size() { std::lock_guard<std::mutex> lock(mutex_); return lru_list_.size(); } } // namespace bustub
24.403509
80
0.61179
Laotan0926
180fb61fa18a04a51e84b6a537362f6a2172e660
846
tcc
C++
src/scope.tcc
unbornchikken/reflect-cpp
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
[ "BSD-2-Clause" ]
45
2015-03-24T09:35:46.000Z
2021-05-06T11:50:34.000Z
src/scope.tcc
unbornchikken/reflect-cpp
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
[ "BSD-2-Clause" ]
null
null
null
src/scope.tcc
unbornchikken/reflect-cpp
1a9a3d107c952406d3b7cae4bc5a6a23d566ea4f
[ "BSD-2-Clause" ]
11
2015-01-27T12:08:21.000Z
2020-08-29T16:34:13.000Z
/* scope.tcc -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 17 Apr 2014 FreeBSD-style copyright and disclaimer apply Template implementation of Scope */ #include "reflect.h" #pragma once namespace reflect { /******************************************************************************/ /* NAMESPACE */ /******************************************************************************/ template<typename Fn> void Scope:: addFunction(const std::string& name, Fn&& rawFn) { addFunction(name, Function(tail(name).first, std::forward<Fn>(rawFn))); } template<typename Ret, typename... Args> Ret Scope:: call(const std::string& fn, Args&&... args) const { return function(fn).call<Ret>(std::forward<Args>(args)...); } } // reflect
24.882353
80
0.470449
unbornchikken
181039bdcdc4ddaa1aa456f388257407d896b3d3
54
cpp
C++
conan/freeimage/test_package/example.cpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
null
null
null
conan/freeimage/test_package/example.cpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
null
null
null
conan/freeimage/test_package/example.cpp
icebreakersentertainment/ice_engine
52a8313bc266c053366bdf554b5dc27a54ddcb25
[ "MIT" ]
1
2019-06-11T03:41:48.000Z
2019-06-11T03:41:48.000Z
#include <FreeImage.h> int main() { // hello(); }
9
22
0.537037
icebreakersentertainment
18185a59d238c48ce052e29c49f27dadbec7c7a0
7,265
cpp
C++
src/Residue.cpp
gjoni/iPot
9af44ed4fe1121933f5c936b2608ace0d293ad87
[ "MIT" ]
4
2018-09-20T18:14:16.000Z
2022-01-13T06:11:20.000Z
src/Residue.cpp
gjoni/iPot
9af44ed4fe1121933f5c936b2608ace0d293ad87
[ "MIT" ]
null
null
null
src/Residue.cpp
gjoni/iPot
9af44ed4fe1121933f5c936b2608ace0d293ad87
[ "MIT" ]
1
2022-02-15T12:53:44.000Z
2022-02-15T12:53:44.000Z
/* * Residue.cpp * * Created on: Jun 3, 2014 * Author: ivan */ #include "Residue.h" #include "Info.h" #include <cstring> #include <cstdio> #include <cstdlib> #include <cassert> #include <new> #include <map> Residue::Residue() : type(23), seqNum(-1), insCode(' '), atom(NULL), nAtoms(0), chainId(' '), ntFlag( false), ctFlag(false), N(NULL), CA(NULL), C(NULL), O(NULL), CB( NULL) { strcpy(name, "UNK"); centroid[0] = centroid[1] = centroid[2] = 0; } Residue::Residue(const Residue &source) : type(source.type), seqNum(source.seqNum), insCode(source.insCode), atom( NULL), nAtoms(source.nAtoms), chainId(source.chainId), ntFlag( source.ntFlag), ctFlag(source.ctFlag), N(NULL), CA(NULL), O( NULL), CB(NULL) { assert(nAtoms > 0); /* pedantic check */ strcpy(name, source.name); atom = new Atom[nAtoms]; for (int i = 0; i < nAtoms; i++) { atom[i] = source.atom[i]; atom[i].residue = this; } SetBBAtoms(); /* N, CA, C, O, CB are pointers - they need to be reinitialized */ memcpy(centroid, source.centroid, 3 * sizeof(double)); } Residue::Residue(const std::vector<AtomRecord>& source) : seqNum(source[0].resNum), insCode(source[0].insCode), atom(NULL), nAtoms( source.size()), chainId(source[0].chainId), ntFlag(false), ctFlag( false), N(NULL), CA(NULL), C( NULL), O(NULL), CB(NULL) { assert(nAtoms > 0); /* pedantic check */ strcpy(name, source[0].resName); /* first atom is used to name the residue*/ atom = new Atom[nAtoms]; int idx = 0; for (int i = 0; i < nAtoms; i++) { atom[i] = Atom(source[i]); atom[i].residue = this; idx++; } SetBBAtoms(); /* N, CA, C, O, CB are pointers - they need to be reinitialized */ type = SetType(name); SetCentroid(); } Residue::Residue(std::vector<AtomRecord>::iterator begin_it, std::vector<AtomRecord>::iterator end_it) : seqNum(begin_it->resNum), insCode(begin_it->insCode), atom(NULL), nAtoms( end_it - begin_it + 1), chainId(begin_it->chainId), ntFlag( false), ctFlag(false), N(NULL), CA( NULL), C(NULL), O(NULL), CB(NULL) { assert(nAtoms > 0); /* pedantic check */ strcpy(name, begin_it->resName); /* residue name is read from the 1st atom */ /* check for alternative conformations */ std::vector<AtomRecord>::iterator it; bool fl = false; for (it = begin_it; it <= end_it; it++) { if (it->altLoc != ' ') { fl = true; break; } } if (!fl) { /* no alternative conformations */ /* use all atoms */ atom = new Atom[nAtoms]; int idx = 0; for (it = begin_it; it <= end_it; it++) { atom[idx] = Atom(*it); atom[idx].residue = this; idx++; } } else { /* there are alternative conformations */ /* save top-populated conformation for each atom */ std::map<std::string, std::vector<AtomRecord>::iterator> atoms_map; std::map<std::string, std::vector<AtomRecord>::iterator>::iterator itmap; atoms_map[begin_it->atomName] = begin_it; for (it = begin_it + 1; it <= end_it; it++) { /* save only atoms with the same residue name as the first atom */ if (strcmp(begin_it->resName, it->resName) == 0) { itmap = atoms_map.find(it->atomName); if (itmap == atoms_map.end()) { atoms_map[it->atomName] = it; } else { if (itmap->second->occup < it->occup) { itmap->second = it; } } } } /* save marked atoms */ atom = new Atom[atoms_map.size()]; nAtoms = 0; for (itmap = atoms_map.begin(); itmap != atoms_map.end(); itmap++) { atom[nAtoms] = Atom(*(itmap->second)); atom[nAtoms].residue = this; nAtoms++; } } SetBBAtoms(); /* N, CA, C, O, CB are pointers - they need to be reinitialized */ type = SetType(name); SetCentroid(); } Residue::~Residue() { delete[] atom; atom = NULL; } Residue & Residue::operator =(const Residue & source) { assert(this != &source); /* an attempt to assign Residue to itself */ type = source.type; strcpy(name, source.name); seqNum = source.seqNum; insCode = source.insCode; nAtoms = source.nAtoms; chainId = source.chainId; delete[] atom; atom = new Atom[nAtoms]; for (int i = 0; i < nAtoms; i++) { atom[i] = source.atom[i]; atom[i].residue = this; } SetBBAtoms(); memcpy(centroid, source.centroid, 3 * sizeof(double)); return *this; } int Residue::SetBBAtoms() { bool flN = false, flCA = false, flC = false, flO = false, flCB = false; for (int i = 0; i < nAtoms; i++) { if (strcmp(atom[i].name, "N") == 0) { N = &(atom[i]); flN = true; } else if (strcmp(atom[i].name, "CA") == 0) { CA = &(atom[i]); flCA = true; } else if (strcmp(atom[i].name, "CB") == 0) { CB = &(atom[i]); flCB = true; } else if (strcmp(atom[i].name, "C") == 0) { C = &(atom[i]); flC = true; } else if (strcmp(atom[i].name, "O") == 0 || strcmp(atom[i].name, "OXT") == 0) { O = &(atom[i]); flO = true; } else if (strcmp(atom[i].name, "H1") == 0) { ntFlag = true; } else if (strcmp(atom[i].name, "H2") == 0) { ntFlag = true; } else if (strcmp(atom[i].name, "H3") == 0) { ntFlag = true; } else if (strcmp(atom[i].name, "OXT") == 0) { ctFlag = true; } } int n = flN + flCA + flC + flO + flCB; return n; } char Residue::SetType(const char* name) { for (int i = 0; i < 24; i++) { if (strcmp(name, AAA3[i]) == 0) { return i; } } return 23; } void Residue::SetCentroid() { centroid[0] = centroid[1] = centroid[2] = 0.0; if (type == 7 /* GLY */) { centroid[0] = CA->x; centroid[1] = CA->y; centroid[2] = CA->z; } else /* other residues */{ for (int j = 0; j < nAtoms; j++) { centroid[0] += atom[j].x; centroid[1] += atom[j].y; centroid[2] += atom[j].z; } centroid[0] /= nAtoms; centroid[1] /= nAtoms; centroid[2] /= nAtoms; } } double Residue::MinDist(const Residue &R1, const Residue &R2, int mode) { double dmin = 9999.99; switch (mode) { case 0: /* SC + BB */ for (int i = 0; i < R1.nAtoms; i++) { if (R1.atom[i].type == 'H') { continue; } for (int j = 0; j < R2.nAtoms; j++) { if (R2.atom[j].type == 'H') { continue; } double d = Atom::Dist(R1.atom[i], R2.atom[j]); dmin = d < dmin ? d : dmin; } } break; case 1: /* SC */ for (int i = 0; i < R1.nAtoms; i++) { Atom *A = &(R1.atom[i]); if (A == R1.C || A == R1.CA || A == R1.N || A == R1.O) { continue; } if (R1.atom[i].type == 'H') { continue; } for (int j = 0; j < R2.nAtoms; j++) { Atom *B = &(R2.atom[j]); if (B == R2.C || B == R2.CA || B == R2.N || B == R2.O) { continue; } if (R2.atom[j].type == 'H') { continue; } double d = Atom::Dist(R1.atom[i], R2.atom[j]); dmin = d < dmin ? d : dmin; } } break; case 2: /* BB */ for (int i = 0; i < R1.nAtoms; i++) { Atom *A = &(R1.atom[i]); if (A != R1.C && A != R1.CA && A != R1.N && A != R1.O) { continue; } if (R1.atom[i].type == 'H') { continue; } for (int j = 0; j < R2.nAtoms; j++) { Atom *B = &(R2.atom[j]); if (B != R2.C && B != R2.CA && B != R2.N && B != R2.O) { continue; } if (R2.atom[j].type == 'H') { continue; } double d = Atom::Dist(R1.atom[i], R2.atom[j]); dmin = d < dmin ? d : dmin; } } break; default: return dmin; break; } return dmin; }
22.082067
82
0.560496
gjoni
1818fc9d14259654e79785c99a237a4ae283249c
1,595
hpp
C++
src/hackflight.hpp
sujanabasnet/Hackflight
98d0f0dee07dbddd81c63bd1997e845ca244106f
[ "MIT" ]
null
null
null
src/hackflight.hpp
sujanabasnet/Hackflight
98d0f0dee07dbddd81c63bd1997e845ca244106f
[ "MIT" ]
null
null
null
src/hackflight.hpp
sujanabasnet/Hackflight
98d0f0dee07dbddd81c63bd1997e845ca244106f
[ "MIT" ]
2
2021-05-17T21:12:24.000Z
2021-05-17T21:18:11.000Z
/* Hackflight core algorithm Copyright (c) 2020 Simon D. Levy MIT License */ #pragma once #include <RFT_board.hpp> #include "receiver.hpp" #include "state.hpp" #include "serialtask.hpp" #include "actuators/mixer.hpp" #include <RFT_sensor.hpp> #include <RFT_filters.hpp> #include <RoboFirmwareToolkit.hpp> namespace hf { class Hackflight : public rft::RFT { private: // Passed to Hackflight constructor Receiver * _receiver = NULL; // Serial timer task for GCS SerialTask _serialTask; // Vehicle state State _state; protected: virtual bool safeStateForArming(void) override { return _state.safeToArm(); } public: Hackflight(rft::Board * board, Receiver * receiver, rft::Actuator * actuator) : rft::RFT(&_state, board, receiver, actuator) { // Store the essentials _receiver = receiver; } void begin(bool armed=false) { // Initialize state memset(&_state, 0, sizeof(State)); RFT::begin(armed); // Initialize serial timer task _serialTask.begin(_board, &_state, _receiver, _actuator); } // init void update(void) { RFT::update(); // Update serial comms task _serialTask.update(); } }; // class Hackflight } // namespace
20.448718
89
0.521003
sujanabasnet
1819bef4fb090957ea798650c259890669cff1cf
12,483
cpp
C++
aztec/src/ResourceManager.cpp
viccsneto/aztec
a49e269c53f19d2de22f0d297908c917f36c658d
[ "MIT" ]
null
null
null
aztec/src/ResourceManager.cpp
viccsneto/aztec
a49e269c53f19d2de22f0d297908c917f36c658d
[ "MIT" ]
null
null
null
aztec/src/ResourceManager.cpp
viccsneto/aztec
a49e269c53f19d2de22f0d297908c917f36c658d
[ "MIT" ]
null
null
null
#include "ResourceManager.h" #include "EventDispatcher.h" #include "GameEngine.h" #include <SFML/Graphics.hpp> #include <math.h> #include "Keyboard.h" #define CHARACTERS_PER_LINE 16 #define CHARACTER_BORDER_WIDTH 8 #define FONT_DEFINITION_FORMAT_STRING "%s_%d" namespace Aztec { list<RESFont *> ResourceManager::_Fonts; list<RESTexture *> ResourceManager::_Surfaces; list<RESShader *> ResourceManager::_Shaders; list<RESMusic *> ResourceManager::_Musics; list<RESChunk *> ResourceManager::_Chunks; multimap<GameObject *, list<GameObject *> *> ResourceManager::_toDestroy; multimap<GameObject *, list<GameObject *> *> ResourceManager::_toRemove; RESTexture *ResourceManager::createTexture(int width, int height, void *data) { GameEngine::getInstance()->getGameCanvas()->activateContext(); GLenum texture_format = GL_RGBA; GLint nOfColors = 4; GLint originalWidth; GLint originalHeight; originalWidth = width; originalHeight = height; RESTexture *rsurface = new RESTexture(); for (GLuint i = 0; width < originalWidth; i++) { width = static_cast<int>(powl(2, i)); } for (GLuint i = 0; height < originalHeight; i++) { height = static_cast<int>(powl(2, i)); } GLuint texture; // Have OpenGL generate a texture object handle for us glGenTextures(1, &texture); // Bind the texture object glBindTexture(GL_TEXTURE_2D, texture); // Set the texture's stretching properties glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D(GL_TEXTURE_2D, 0, texture_format, width, height, 0, texture_format, GL_UNSIGNED_BYTE, data); rsurface->texture_id = texture; rsurface->originalWidth = static_cast<float>(originalWidth); rsurface->originalHeight = static_cast<float>(originalHeight); rsurface->width = width; rsurface->height = height; return rsurface; } RESTexture *ResourceManager::loadImage(const char *path) { RESTexture *rsurface; GLint originalWidth; GLint originalHeight; GLint channels; GLint width = 0; GLint height = 0; for (list<RESTexture *>::iterator i = _Surfaces.begin(); i != _Surfaces.end(); ++i) { if ((*i)->path.compare(path) == 0) { (*i)->ref_count++; return (*i); } } auto image = new sf::Image(); if (!image->loadFromFile(std::string(path))) { GameEngine::getInstance()->registerError("Image could not be loaded: %s -<%s [%d]>", path, __FILE__, __LINE__); return NULL; } originalWidth = image->getSize().x; originalHeight = image->getSize().y; channels = 4; width = originalWidth; height = originalHeight; for (GLuint i = 0; width < originalWidth; i++) { width = static_cast<int>(powl(2, i)); } for (GLuint i = 0; height < originalHeight; i++) { height = static_cast<int>(powl(2, i)); } if (image) { rsurface = putImage(path, image->getPixelsPtr(), width, height, originalWidth, originalHeight, channels); return rsurface; } } RESTexture *ResourceManager::putImage(const char *path, const sf::Uint8 *data, int width, int height, int originalWidth, int originalHeight, int channels) { GameEngine::getInstance()->getGameCanvas()->activateContext(); RESTexture *rsurface; GLenum texture_format = GL_RGBA; GLint nOfColors = 4; GLuint texture = 0; for (list<RESTexture *>::iterator i = _Surfaces.begin(); i != _Surfaces.end(); ++i) { if ((*i)->path.compare(path) == 0) { (*i)->ref_count++; return (*i); } } rsurface = new RESTexture(); rsurface->originalWidth = originalWidth; rsurface->originalHeight = originalHeight; rsurface->width = width; rsurface->height = height; // get the number of channels in the SDL surface if (channels == 4) // contains an alpha channel { texture_format = GL_RGBA; } else if (channels == 3) // no alpha channel { texture_format = GL_RGB; } else { GameEngine::getInstance()->registerWarning("warning: the image %s is not truecolor.. this will probably break\n", path); } if (data != NULL) { glEnable(GL_TEXTURE_2D); // Have OpenGL generate a texture object handle for us glGenTextures(1, &texture); if (texture == 0) { GLenum err = glGetError(); throw err; } // Bind the texture object glBindTexture(GL_TEXTURE_2D, texture); // Set the texture's stretching properties glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Edit the texture object's image data using the information SDL_Surface gives us glTexImage2D(GL_TEXTURE_2D, 0, texture_format, originalWidth, originalHeight, 0, texture_format, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); rsurface->texture_id = texture; if (rsurface->texture_id == 0) { delete rsurface; return NULL; } } rsurface->path.assign(path); rsurface->ref_count = 1; _Surfaces.push_front(rsurface); rsurface->originalWidth = static_cast<float>(originalWidth); rsurface->originalHeight = static_cast<float>(originalHeight); return rsurface; } void ResourceManager::releaseImage(const char *path) { for (list<RESTexture *>::iterator i = _Surfaces.begin(); i != _Surfaces.end(); ++i) { if ((*i)->path.compare(path) == 0) { (*i)->ref_count--; if ((*i)->ref_count == 0) { glDeleteTextures(1, &(*i)->texture_id); delete ((*i)); _Surfaces.remove((*i)); } return; } } } void ResourceManager::releaseImage(RESTexture *surface) { for (list<RESTexture *>::iterator i = _Surfaces.begin(); i != _Surfaces.end(); ++i) { if ((*i) == surface) { (*i)->ref_count--; if ((*i)->ref_count == 0) { glDeleteTextures(1, &(*i)->texture_id); delete ((*i)); _Surfaces.remove((*i)); } return; } } } sf::Music *ResourceManager::loadMusic(const char *path) { for (list<RESMusic *>::iterator i = _Musics.begin(); i != _Musics.end(); ++i) { if ((*i)->path.compare(path) == 0) { (*i)->ref_count++; return (*i)->music; } } RESMusic *rmusic = new RESMusic(); rmusic->music = new sf::Music(); rmusic->music->openFromFile(std::string(path)); if (rmusic->music == NULL) { delete rmusic; return NULL; } rmusic->path.assign(path); rmusic->ref_count = 1; _Musics.push_front(rmusic); return rmusic->music; } sf::Sound *ResourceManager::loadChunk(const char *path) { for (list<RESChunk *>::iterator i = _Chunks.begin(); i != _Chunks.end(); ++i) { if ((*i)->path.compare(path) == 0) { (*i)->ref_count++; return (*i)->chunk; } } RESChunk *rchunk = new RESChunk(); rchunk->chunk = new sf::Sound(); sf::SoundBuffer *sound_buffer = new sf::SoundBuffer(); sound_buffer->loadFromFile(std::string(path)); rchunk->chunk->setBuffer(*sound_buffer); rchunk->chunk_buffer = sound_buffer; if (rchunk->chunk == NULL) { delete rchunk; return NULL; } rchunk->path.assign(path); rchunk->ref_count = 1; _Chunks.push_front(rchunk); return rchunk->chunk; } RESFont *ResourceManager::loadFont(const char *path, glm::vec4 color, int size) { size_t font_definition_size = snprintf(nullptr, 0, FONT_DEFINITION_FORMAT_STRING, path, size); char * fontDefinition = new char[font_definition_size]; sprintf(fontDefinition, FONT_DEFINITION_FORMAT_STRING, path, size); for (list<RESFont *>::iterator it = _Fonts.begin(); it != _Fonts.end(); ++it) { if ((*it)->path.compare(fontDefinition) == 0) { (*it)->ref_count++; return (*it); } } RESFont *resFont = new RESFont(); resFont->ref_count = 1; sf::Font *ttfFont = new sf::Font(); if (!ttfFont->loadFromFile(path)) { GameEngine::getInstance()->registerError("Font could not be loaded: %s -<%s [%d]>", path, __FILE__, __LINE__); exit(1); } int width, height, powerWidth, powerHeight; int lineWidth = 0; int lineHeight = 0; int totalWidth = 0; int totalHeight = 0; for (int i = 0; i < 255; i++) { ttfFont->getGlyph(getWideChar((char)i), size, false); } for (int i = 0; i < 255; i++) { sf::Glyph glyph = ttfFont->getGlyph(getWideChar((char)i), size, false); resFont->charPositions[i] = glyph; if (glyph.textureRect.height > lineHeight) { lineHeight = glyph.textureRect.height; resFont->charHeight = static_cast<float>(lineHeight); } if (glyph.textureRect.width > resFont->charWidth) { resFont->charWidth = static_cast<float>(glyph.textureRect.width); } } resFont->path = fontDefinition; sf::Image fontMap = ttfFont->getTexture(size).copyToImage(); resFont->texture = ResourceManager::putImage(fontDefinition, fontMap.getPixelsPtr(), fontMap.getSize().x, fontMap.getSize().y, fontMap.getSize().x, fontMap.getSize().y, 4); _Fonts.push_front(resFont); return resFont; } void ResourceManager::releaseFont(RESFont *font) { for (list<RESFont *>::iterator i = _Fonts.begin(); i != _Fonts.end(); ++i) { if ((*i) == font) { (*i)->ref_count--; if ((*i)->ref_count == 0) { releaseImage(font->path.c_str()); delete ((*i)); _Fonts.remove((*i)); } return; } } } void ResourceManager::releaseMusic(sf::Music *music) { for (list<RESMusic *>::iterator i = _Musics.begin(); i != _Musics.end(); ++i) { if ((*i)->music == music) { (*i)->ref_count--; if ((*i)->ref_count == 0) { delete ((*i)); _Musics.remove((*i)); } return; } } } void ResourceManager::releaseChunk(const char *path) { for (list<RESChunk *>::iterator i = _Chunks.begin(); i != _Chunks.end(); ++i) { if ((*i)->path.compare(path) == 0) { (*i)->ref_count--; if ((*i)->ref_count == 0) { delete ((*i)); _Chunks.remove((*i)); } return; } } } void ResourceManager::releaseChunk(sf::Sound *chunk) { for (list<RESChunk *>::iterator i = _Chunks.begin(); i != _Chunks.end(); ++i) { if ((*i)->chunk == chunk) { (*i)->ref_count--; if ((*i)->ref_count == 0) { delete ((*i)); _Chunks.remove((*i)); } return; } } } void ResourceManager::registerForDestruction(GameObject *obj) { _toDestroy.insert(pair<GameObject *, list<GameObject *> *>(obj, obj->getOwnerList())); } void ResourceManager::registerForRemove(GameObject *obj) { _toRemove.insert(pair<GameObject *, list<GameObject *> *>(obj, obj->getOwnerList())); } void ResourceManager::destroyObjects() { for (multimap<GameObject *, list<GameObject *> *>::iterator i = _toDestroy.begin(); i != _toDestroy.end(); ++i) { (*i).second->remove((*i).first); delete (*i).first; } _toDestroy.clear(); } void ResourceManager::removeObjects() { for (multimap<GameObject *, list<GameObject *> *>::iterator i = _toRemove.begin(); i != _toRemove.end(); ++i) { if ((*i).first->getOwnerList() != (*i).second) { (*i).second->remove((*i).first); } } _toRemove.clear(); } void ResourceManager::freeAll() { for (RESChunk *chunk : _Chunks) delete chunk; _Chunks.clear(); for (RESMusic *music : _Musics) delete music; _Musics.clear(); for (RESFont *resfont : _Fonts) delete resfont; _Fonts.clear(); for (RESTexture *ressurface : _Surfaces) delete ressurface; _Surfaces.clear(); } wchar_t ResourceManager::getWideChar(char c) { std::string aux = " "; aux[0] = c; std::wstring s(aux.begin(), aux.end()); return s[0]; } } // namespace Aztec
26.787554
176
0.601538
viccsneto
1821350eb94cef954c4cc114b543fd285b1ef04d
754
cpp
C++
src/engine/mem.cpp
DeadZoneLuna/csso-src
6c978ea304ee2df3796bc9c0d2916bac550050d5
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/engine/mem.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/engine/mem.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// // mem.c #include <stdlib.h> #include <memory.h> #include <string.h> #include "mem.h" void *Mem_Malloc( size_t size ) { return malloc( size ); } void *Mem_ZeroMalloc( size_t size ) { void *p; p = malloc( size ); memset( (unsigned char *)p, 0, size ); return p; } void *Mem_Realloc( void *memblock, size_t size ) { return realloc( memblock, size ); } void *Mem_Calloc( int num, size_t size ) { return calloc( num, size ); } char *Mem_Strdup( const char *strSource ) { return strdup( strSource ); } void Mem_Free( void *p ) { free( p ); }
15.708333
81
0.55305
DeadZoneLuna
1825fffe81a62a55f6e3b103fce4995bec44f1b9
7,458
cpp
C++
lib/src/Listbox.cpp
JPGygax68/libCppGUI
9484b6b4e544a522019276fcd49eb8495b04e60d
[ "Apache-2.0" ]
2
2017-03-28T14:11:47.000Z
2021-05-31T07:31:43.000Z
lib/src/Listbox.cpp
JPGygax68/libCppGUI
9484b6b4e544a522019276fcd49eb8495b04e60d
[ "Apache-2.0" ]
null
null
null
lib/src/Listbox.cpp
JPGygax68/libCppGUI
9484b6b4e544a522019276fcd49eb8495b04e60d
[ "Apache-2.0" ]
1
2021-05-31T07:31:44.000Z
2021-05-31T07:31:44.000Z
#include <cassert> #include <layouting.hpp> #include <Listbox.hpp> #include <iostream> namespace cppgui { // Private implementation of Content_pane contract ------------------------ class Listbox_content_pane: public Content_pane { public: void render(Canvas *, const Point &offs) override; void set_focus_on_child(Widget *) override; private: using Super = Content_pane; auto separator_width() const { return 1; } auto separator_color(Widget_states) const -> RGBA { return { 0.6f, 0.6f, 0.6f, 1 }; } #ifndef CPPGUI_EXCLUDE_LAYOUTING public: auto get_minimal_bounds() -> Bbox override; void compute_layout(Bbox_cref b) override; auto get_minimal_window() -> Extents override; #endif // !CPPGUI_EXCLUDE_LAYOUTING }; void Listbox_content_pane::render(Canvas *c, const Point &offs) { // TODO: optimize implementation to only draw visible items auto p = offs + position(); for (auto child: children()) { // List item child->render(c, p); // Separator auto r = child->rectangle(); r.pos.y += r.ext.h; r.ext.h = separator_width(); c->fill_rect(r + p, separator_color(visual_states())); } } void Listbox_content_pane::set_focus_on_child(Widget *c) { Super::set_focus_on_child(c); if (c) container()->bring_item_into_view(c); } #ifndef CPPGUI_EXCLUDE_LAYOUTING auto Listbox_content_pane::get_minimal_bounds() -> Bbox { auto bb_min = Bbox::empty(); if (child_count() > 0) { for (auto child: children()) { //bb_min.merge(child->get_minimal_bounds()); bb_min.append_at_bottom(child->get_minimal_bounds(), horizontal_origin); // TODO: margin } bb_min.y_min -= child_count() * separator_width(); } // TODO: minimal bounds if there are no children ? return bb_min; } void Listbox_content_pane::compute_layout(Bbox_cref b) { if (child_count() > 0) { auto p = Point{0, 0}; // Layout vertically into the provided bounding box (can exceed at bottom) for (auto child: children()) { auto bc = child->get_minimal_bounds().expand_to({b.width(), 0}, left, baseline); child->set_bounds(p - b.origin(), bc, left, top); p.y += child->height(); p.y += separator_width(); } } } auto Listbox_content_pane::get_minimal_window() -> Extents { Extents ext; for (auto child: children()) { ext |= Extents{child->get_minimal_bounds()}; } // TODO: support a dummy item bounding box in case the list can be initially empty return ext; } #endif !CPPGUI_EXCLUDE_LAYOUTING // Listbox_base implementation -------------------------------------------- Listbox_base::Listbox_base(): Scrolling_container(new Listbox_content_pane()) { } void Listbox_base::add_item(Widget *item) const { content_pane()->add_child(item); } void Listbox_base::navigate(Navigation_unit unit, const Fraction<int> &delta) { if (items().empty()) return; if (unit == element) { assert(delta.den == 1); scroll_by_items(delta.num); } else if (unit == fraction) { //std::cout << "delta (fraction): " << delta.num << "/" << delta.den << std::endl; auto d = delta.num * item_count() / delta.den; if (d != 0) { scroll_by_items(d); } } else if (unit == page) { assert(delta.den == 1); scroll_by_items(delta.num * visible_item_count()); } } void Listbox_base::scroll_by_items(int d) { while (d != 0) { if (d < 0) { scroll_up(); // content pane moves down relative to window d ++; } else { scroll_down(); // content pane moves up relative to window d --; } } } bool Listbox_base::item_fully_visible(Index index) const { return content_window().contains_full_height_of( item_rectangle(item(index)) ); } bool Listbox_base::first_item_fully_visible() const { assert(!items().empty()); return item_fully_visible(0); } bool Listbox_base::last_item_fully_visible() const { assert(!items().empty()); return item_fully_visible(item_count() - 1); } auto Listbox_base::first_partially_visible_item_index() const -> Index { auto r_win = content_window(); for (Index i = 0; i < static_cast<Index>(items().size()); i ++) { auto r_item = item_rectangle(item(i)); if (r_win.intersects_vertically_with(r_item)) return i; } return -1; } auto Listbox_base::first_partially_visible_item() const -> Widget * { return item( first_partially_visible_item_index() ); } auto Listbox_base::last_partially_visible_item_index() const -> Index { auto r_win = content_window(); for (Index i = item_count(); i-- > 0; ) { auto r_item = item_rectangle(item(i)); if (r_win.intersects_vertically_with(r_item)) return i; } return -1; } auto Listbox_base::hidden_height_of_first_visible_item() const -> Length { auto r_item = item_rectangle(first_partially_visible_item()); return content_window().y1() - r_item.y1(); } auto Listbox_base::visible_item_count() const -> Count { auto i = first_partially_visible_item_index(); if (!item_fully_visible(i)) i ++; auto j = i; while (j < item_count() && item_fully_visible(j)) j ++; return j - i; } /* void Listbox_base::bring_item_into_view(Index index) { // Find relative position of item to bring into full view auto r = item_rectangle( item(index) ); // TODO: limit to try and prevent uncovering empty space at the bottom auto dy = r.y1() - content_window().y1(); // Shift shift_content_by({ 0, -dy }); } */ void Listbox_base::scroll_down() { // "scroll down" = content pane moves up relative to content window, uncovering items at bottom if (!last_item_fully_visible()) { // Find first item that is not fully visible auto i = last_partially_visible_item_index(); while (i < (item_count()-1) && item_fully_visible(i)) i ++; bring_item_into_view(i); } } void Listbox_base::scroll_up() { // "scroll up" = content pane moves down relative to content window, uncovering predecessor items // Find the item that we need to uncover auto i = first_partially_visible_item_index(); while (i > 0 && item_fully_visible(i)) i --; if (i >= 0) { bring_item_into_view(i); } } } // ns cppgui
26.260563
105
0.550684
JPGygax68
1827c1c2317b427b2ccb1c8cf5e7b8a5f2520754
966
cc
C++
below2.1/semafori.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/semafori.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/semafori.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <utility> using namespace std; int main(){ int tl,roadln; cin>>tl>>roadln; pair <int, pair <int, int > > arr[tl]; for (int i = 0; i < tl; i++) { cin>>arr[i].first>>arr[i].second.first>>arr[i].second.second; } int pos = 0; int time = 0; int lightth = 0; bool isgreen; while (true) { isgreen = true; if(lightth<tl){if(arr[lightth].first == pos){ if((time%(arr[lightth].second.first + arr[lightth].second.second)) <= arr[lightth].second.first &&(time%(arr[lightth].second.first + arr[lightth].second.second)) != 0){ isgreen = false; } else{ lightth++; } }} if(isgreen){ pos++; time++; }else{ time++; } if(pos == roadln){ break; } } cout<<time-1; return 0; }
22.465116
107
0.452381
danzel-py
1829603fce04e00450459529dc7964ebda915dac
1,081
cpp
C++
Sid's Contests/LeetCode contests/May Challenge/Maximum Points You Can Obtain From Cards.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Contests/LeetCode contests/May Challenge/Maximum Points You Can Obtain From Cards.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Contests/LeetCode contests/May Challenge/Maximum Points You Can Obtain From Cards.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: int maxScore(vector<int>& cardPoints, int k) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA int l = 0, r = 0; int left = 0, right = cardPoints.size() - 1; int leftSum[100000], rightSum[100000]; leftSum[0] = 0; rightSum[0] = 0; for(int i = 1; i <= k; i++) { leftSum[i] = leftSum[i-1] + cardPoints[i-1]; } // for(int i = 0; i <= k; i++) // cout << leftSum[i] << " "; for(int i = 1; i <= k; i++) { rightSum[i] = rightSum[i-1] + cardPoints[right]; right--; } // for(int i = 0; i <= k; i++) // { // cout << rightSum[i] << " "; // } reverse(rightSum, rightSum + k + 1); int maxScore = 0; for(int i = 0; i <= k; i++) { maxScore = max(maxScore, leftSum[i] + rightSum[i]); } return maxScore; } };
29.216216
73
0.438483
Tiger-Team-01
18323bea91dff0987af7867a5f2e06f8622d5e26
20,325
cpp
C++
ee21/marker/marker_07_real.cpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/marker/marker_07_real.cpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/marker/marker_07_real.cpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
/*! \file marker_07_real.cpp \brief Expression Evaluator marking application. \author Garth Santor \date 2021-11-07 \copyright Garth Santor ============================================================= Revision History ------------------------------------------------------------- Version 2021.11.07 Alpha release. ============================================================= Copyright Garth Santor / Trinh Han The copyright to the computer program(s) herein is the property of Garth Santor / Trinh Han, Canada. The program(s) may be used and /or copied only with the written permission of Garth Santor / Trinh Han or in accordance with the terms and conditions stipulated in the agreement / contract under which the program(s) have been supplied. ============================================================= */ #include <gats/TestApp.hpp> #include "ut_test_phases.hpp" #include "test_parser.hpp" #include <ee/RPNEvaluator.hpp> #include <ee/expression_evaluator.hpp> #include <ee/real.hpp> #include <ee/operator.hpp> #include <ee/function.hpp> #include <ee/pseudo_operation.hpp> #include "round_real.hpp" constexpr unsigned GROUP_COUNT = 60; constexpr double GROUP_WEIGHT = 10.0 / GROUP_COUNT; GATS_TEST_CASE_WEIGHTED(07aa_Real_3_14, GROUP_WEIGHT){ #if TEST_RPN && TEST_REAL auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("3.14")) }); GATS_CHECK(value_of<Real>(result) == Real::value_type("3.14")); #endif } GATS_TEST_CASE_WEIGHTED(07ab_constant_Pi, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL auto result = RPNEvaluator().evaluate({ make<Pi>() }); GATS_CHECK(value_of<Real>(result) == boost::math::constants::pi<Real::value_type>()); #endif } GATS_TEST_CASE_WEIGHTED(07ac_constant_E, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL auto result = RPNEvaluator().evaluate({ make<E>() }); GATS_CHECK(value_of<Real>(result) == boost::math::constants::e<Real::value_type>()); #endif } GATS_TEST_CASE_WEIGHTED(07ad_negation_test_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_UNARY_OPERATOR auto result = RPNEvaluator().evaluate({ make<Real>(3), make<Negation>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("-3.0")); #endif } GATS_TEST_CASE_WEIGHTED(07ae_parser_function_1_arg_sin, GROUP_WEIGHT) { #if TEST_PARSER && TEST_REAL && TEST_SINGLE_ARG_FUNCTION && TEST_PARENTHESIS GATS_CHECK(parse_test( // Test: sin(2.0) TokenList({ make<Sin>(), make<LeftParenthesis>(), make<Real>(2.0), make<RightParenthesis>() }), TokenList({ make<Real>(2.0), make<Sin>() }) )); #endif } GATS_TEST_CASE_WEIGHTED(07af_parser_function_1_arg_cos, GROUP_WEIGHT) { #if TEST_PARSER && TEST_REAL && TEST_SINGLE_ARG_FUNCTION && TEST_PARENTHESIS GATS_CHECK(parse_test( // Test: cos(2.0) TokenList({ make<Cos>(), make<LeftParenthesis>(), make<Real>(2.0), make<RightParenthesis>() }), TokenList({ make<Real>(2.0), make<Cos>() }) )); #endif } GATS_TEST_CASE_WEIGHTED(07ag_parser_function_1_arg_tan, GROUP_WEIGHT) { #if TEST_PARSER && TEST_REAL && TEST_SINGLE_ARG_FUNCTION && TEST_PARENTHESIS GATS_CHECK(parse_test( // Test: tan(2.0) TokenList({ make<Tan>(), make<LeftParenthesis>(), make<Real>(2.0), make<RightParenthesis>() }), TokenList({ make<Real>(2.0), make<Tan>() }) )); #endif } GATS_TEST_CASE_WEIGHTED(07ah_parser_function_2_arg_pow, GROUP_WEIGHT) { #if TEST_PARSER && TEST_REAL && TEST_MULTI_ARG_FUNCTION && TEST_PARENTHESIS GATS_CHECK(parse_test( // Test: pow(2.3,3.4) TokenList({ make<Pow>(), make<LeftParenthesis>(), make<Real>(2.3), make<ArgumentSeparator>(), make<Real>(3.4), make<RightParenthesis>() }), TokenList({ make<Real>(2.3), make<Real>(3.4), make<Pow>() }) )); #endif } GATS_TEST_CASE_WEIGHTED(07ai_parser_function_expression, GROUP_WEIGHT) { #if TEST_PARSER && TEST_REAL && TEST_MULTI_ARG_FUNCTION && TEST_PARENTHESIS GATS_CHECK(parse_test( // Test: atan2(2.1,4.2)-10.3 TokenList({ make<Arctan2>(), make<LeftParenthesis>(), make<Real>(2.1), make<ArgumentSeparator>(), make<Real>(4.2), make<RightParenthesis>(), make<Subtraction>(), make<Real>(10.3) }), TokenList({ make<Real>(2.1), make<Real>(4.2), make<Arctan2>(), make<Real>(10.3), make<Subtraction>() }) )); #endif } GATS_TEST_CASE_WEIGHTED(07aj_parser_function_argument_expression, GROUP_WEIGHT) { #if TEST_PARSER && TEST_REAL && TEST_MULTI_ARG_FUNCTION && TEST_PARENTHESIS GATS_CHECK(parse_test( // Test: atan2(2.1,4.2-10.3) TokenList({ make<Arctan2>(), make<LeftParenthesis>(), make<Real>(2.1), make<ArgumentSeparator>(), make<Real>(4.2), make<Subtraction>(), make<Real>(10.3), make<RightParenthesis>() }), TokenList({ make<Real>(2.1), make<Real>(4.2), make<Real>(10.3), make<Subtraction>(), make<Arctan2>() }) )); #endif } GATS_TEST_CASE_WEIGHTED(07ak_test_multiply_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_BINARY_OPERATOR auto result = RPNEvaluator().evaluate({ make<Real>(3.0), make<Real>(4.0), make<Multiplication>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("12.0")); #endif } GATS_TEST_CASE_WEIGHTED(07al_test_divide_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_BINARY_OPERATOR auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("45.0")), make<Real>(Real::value_type("3.0")), make<Division>() }); GATS_CHECK(round(result) == round(Real::value_type("15.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07am_test_addition_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_BINARY_OPERATOR auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("3.0")), make<Real>(Real::value_type("4.0")), make<Addition>() }); GATS_CHECK(round(result) == round(Real::value_type("7.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07an_test_subtraction_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_BINARY_OPERATOR auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("3.0")), make<Real>(Real::value_type("4.0")), make<Subtraction>() }); GATS_CHECK(round(result) == round(Real::value_type("-1.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07ao_test_power_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_BINARY_OPERATOR auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("3.0")), make<Real>(Real::value_type("4.0")), make<Power>() }); GATS_CHECK(round(result) == round(Real::value_type("81"))); #endif } GATS_TEST_CASE_WEIGHTED(07ap_test_abs_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("4.0")), make<Abs>() }); GATS_CHECK(round(result) == round(Real::value_type("4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07aq_test_abs_Real_neg, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("-4.0")), make<Abs>() }); GATS_CHECK(round(result) == round(Real::value_type("4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07ar_test_acos_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Arccos>() }); GATS_CHECK(round(result) == Real::value_type("0.0")); #endif } GATS_TEST_CASE_WEIGHTED(07as_test_asin_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Arcsin>() }); GATS_CHECK(value_of<Real>(result) == boost::math::constants::half_pi<Real::value_type>()); #endif } GATS_TEST_CASE_WEIGHTED(07at_test_atan_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("0.0")), make<Arctan>() }); GATS_CHECK(round(result) == Real::value_type("0.0")); #endif } GATS_TEST_CASE_WEIGHTED(07au_test_ceil_high_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("4.3")), make<Ceil>() }); GATS_CHECK(round(result) == round(Real::value_type("5.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07av_test_ceil_low_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("-4.3")), make<Ceil>() }); GATS_CHECK(round(result) == round(Real::value_type("-4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07aw_test_cos_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("0.0")), make<Cos>() }); GATS_CHECK(round(result) == round(Real::value_type("1.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07ax_test_exp, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Exp>() }); GATS_CHECK(round(result) == round(boost::math::constants::e<Real::value_type>())); #endif } GATS_TEST_CASE_WEIGHTED(07ay_test_floor_positive_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("4.3")), make<Floor>() }); GATS_CHECK(round(result) == round(Real::value_type("4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07az_test_floor__negative_Real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("-4.3")), make<Floor>() }); GATS_CHECK(round(result) == round(Real::value_type("-5.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07ba_test_lb, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("8.0")), make<Lb>() }); GATS_CHECK(round(value_of<Real>(result)) == round(Real::value_type("3.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07bb_test_ln, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Ln>() }); GATS_CHECK(round(value_of<Real>(result)) == boost::multiprecision::log(Real::value_type("1.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07bc_test_sin, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("0.0")), make<Sin>() }); GATS_CHECK(round(value_of<Real>(result)) == Real::value_type("0.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bd_test_sqrt, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("16.0")), make<Sqrt>() }); GATS_CHECK(round(value_of<Real>(result)) == round(Real::value_type("4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07be_test_tan, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Tan>() }); GATS_CHECK(value_of<Real>(result) == tan(Real::value_type("1.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07bf_test_arctan2, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Real>(Real::value_type("2.0")), make<Arctan2>() }); GATS_CHECK(value_of<Real>(result) == atan2(Real::value_type("1.0"), Real::value_type("2.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07bg_test_max_real_real_rhs, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Real>(Real::value_type("2.0")), make<Max>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("2.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bh_test_max_real_real_lhs, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("2.0")), make<Real>(Real::value_type("1.0")), make<Max>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("2.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bi_test_max_real_real_same, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("2.0")), make<Real>(Real::value_type("2.0")), make<Max>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("2.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bj_test_min_real_real_rhs, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("1.0")), make<Real>(Real::value_type("2.0")), make<Min>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("1.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bk_test_min_real_real_lhs, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("2.0")), make<Real>(Real::value_type("1.0")), make<Min>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("1.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bl_test_min_real_real_same, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("2.0")), make<Real>(Real::value_type("2.0")), make<Min>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("2.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bm_test_pow_real, GROUP_WEIGHT) { #if TEST_RPN && TEST_REAL && TEST_MULTI_ARG_FUNCTION auto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type("2.0")), make<Real>(Real::value_type("3.0")), make<Pow>() }); GATS_CHECK(value_of<Real>(result) == Real::value_type("8.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bn_EE_real_small, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL auto result = ExpressionEvaluator().evaluate("1234.5678"); GATS_CHECK(value_of<Real>(result) == Real::value_type("1234.5678")); #endif } GATS_TEST_CASE_WEIGHTED(07bo_EE_real_large, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL auto result = ExpressionEvaluator().evaluate("123456789012345678901234567890123456789012345678901234567890.123456789012345678901234567890123456789012345678901234567890"); GATS_CHECK(value_of<Real>(result) == Real::value_type("123456789012345678901234567890123456789012345678901234567890.123456789012345678901234567890123456789012345678901234567890")); #endif } GATS_TEST_CASE_WEIGHTED(07bp_EE_real_e, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL auto result = ExpressionEvaluator().evaluate("e"); GATS_CHECK(value_of<Real>(result) == boost::math::constants::e<Real::value_type>()); result = ExpressionEvaluator().evaluate("E"); GATS_CHECK(value_of<Real>(result) == boost::math::constants::e<Real::value_type>()); #endif } GATS_TEST_CASE_WEIGHTED(07bq_EE_real_pi, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL auto result = ExpressionEvaluator().evaluate("pi"); GATS_CHECK(value_of<Real>(result) == boost::math::constants::pi<Real::value_type>()); result = ExpressionEvaluator().evaluate("Pi"); GATS_CHECK(value_of<Real>(result) == boost::math::constants::pi<Real::value_type>()); result = ExpressionEvaluator().evaluate("PI"); GATS_CHECK(value_of<Real>(result) == boost::math::constants::pi<Real::value_type>()); #endif } GATS_TEST_CASE_WEIGHTED(07br_EE_identity_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_UNARY_OPERATOR auto result = ExpressionEvaluator().evaluate("+42.3"); GATS_CHECK(value_of<Real>(result) == Real::value_type("42.3")); #endif } GATS_TEST_CASE_WEIGHTED(07bs_EE_negation_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_UNARY_OPERATOR auto result = ExpressionEvaluator().evaluate("-42.3"); GATS_CHECK(value_of<Real>(result) == Real::value_type("-42.3")); #endif } GATS_TEST_CASE_WEIGHTED(07bt_EE_addition_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR auto result = ExpressionEvaluator().evaluate("2.2+3.3"); GATS_CHECK(value_of<Real>(result) == Real::value_type("5.5")); #endif } GATS_TEST_CASE_WEIGHTED(07bu_EE_subtraction_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR auto result = ExpressionEvaluator().evaluate("2.2-3.3"); GATS_CHECK(value_of<Real>(result) == Real::value_type("-1.1")); #endif } GATS_TEST_CASE_WEIGHTED(07bv_EE_multiplication_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR auto result = ExpressionEvaluator().evaluate("2.5*3.5"); GATS_CHECK(value_of<Real>(result) == Real::value_type("8.75")); #endif } GATS_TEST_CASE_WEIGHTED(07bw_EE_division_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR auto result = ExpressionEvaluator().evaluate("5.5/1.1"); GATS_CHECK(round(result) == round(Real::value_type("5.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07bx_EE_power_operator_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR auto result = ExpressionEvaluator().evaluate("4.0 ** 0.5"); GATS_CHECK(round(result) == round(Real::value_type("2.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07by_EE_real_trig, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("cos(0.0)"); GATS_CHECK(value_of<Real>(result) == Real::value_type("1.0")); result = ExpressionEvaluator().evaluate("arccos(1.0)"); GATS_CHECK(value_of<Real>(result) == Real::value_type("0.0")); result = ExpressionEvaluator().evaluate("sin(0.0)"); GATS_CHECK(value_of<Real>(result) == Real::value_type("0.0")); result = ExpressionEvaluator().evaluate("arcsin(1.0)"); GATS_CHECK(value_of<Real>(result) == boost::math::constants::half_pi<Real::value_type>()); result = ExpressionEvaluator().evaluate("tan(0.0)"); GATS_CHECK(value_of<Real>(result) == Real::value_type("0.0")); result = ExpressionEvaluator().evaluate("arctan(0.0)"); GATS_CHECK(value_of<Real>(result) == Real::value_type("0.0")); #endif } GATS_TEST_CASE_WEIGHTED(07bz_EE_abs, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("abs(4.0)"); GATS_CHECK(round(result) == round(Real::value_type("4.0"))); result = ExpressionEvaluator().evaluate("abs(-4.0)"); GATS_CHECK(round(result) == round(Real::value_type("4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07ca_EE_ceil, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("ceil(4.3)"); GATS_CHECK(round(result) == round(Real::value_type("5.0"))); result = ExpressionEvaluator().evaluate("ceil(-4.3)"); GATS_CHECK(round(result) == round(Real::value_type("-4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07cb_EE_exp, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("exp(1.0)"); GATS_CHECK(value_of<Real>(result) == exp(Real::value_type("1.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07cc_EE_floor, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("floor(4.3)"); GATS_CHECK(round(result) == round(Real::value_type("4.0"))); result = ExpressionEvaluator().evaluate("floor(-4.3)"); GATS_CHECK(round(result) == round(Real::value_type("-5.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07cd_EE_lb, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("lb(8.0)"); GATS_CHECK(round(value_of<Real>(result)) == round(Real::value_type("3.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07ced_EE_ln, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("ln(1.0)"); GATS_CHECK(round(value_of<Real>(result)) == boost::multiprecision::log(Real::value_type("1.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07cf_EE_sqrt, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("sqrt(16.0)"); GATS_CHECK(round(value_of<Real>(result)) == round(Real::value_type("4.0"))); #endif } GATS_TEST_CASE_WEIGHTED(07cg_EE_order_real, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR auto result = ExpressionEvaluator().evaluate("1.0/(1.0/32.0+1.0/48.0)"); auto x = round(result); GATS_CHECK(x == round(Real::value_type("19.2"))); #endif } GATS_TEST_CASE_WEIGHTED(07ch_EE_order_real_function, GROUP_WEIGHT) { #if TEST_EE && TEST_REAL && TEST_BINARY_OPERATOR && TEST_SINGLE_ARG_FUNCTION auto result = ExpressionEvaluator().evaluate("sin(1.0)**2+cos(1.0)**2"); GATS_CHECK(round(result) == round(Real::value_type("1.0"))); #endif }
41.060606
184
0.72674
ygor-rezende
1833a34afcf9a1da8872337affe638e9884a25f5
2,819
cpp
C++
ext/common/Logging.cpp
bf4/passenger
0369eb329ea587d2a662cadd169f196081e81c7a
[ "MIT" ]
null
null
null
ext/common/Logging.cpp
bf4/passenger
0369eb329ea587d2a662cadd169f196081e81c7a
[ "MIT" ]
null
null
null
ext/common/Logging.cpp
bf4/passenger
0369eb329ea587d2a662cadd169f196081e81c7a
[ "MIT" ]
null
null
null
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2010-2013 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <iomanip> #include <cstdlib> #include <fcntl.h> #include <unistd.h> #include <Logging.h> #include <Utils/StrIntUtils.h> namespace Passenger { int _logLevel = 0; int _logOutput = STDERR_FILENO; int getLogLevel() { return _logLevel; } void setLogLevel(int value) { _logLevel = value; } bool setDebugFile(const char *logFile) { int fd = open(logFile, O_WRONLY | O_CREAT | O_APPEND, 0644); if (fd != -1) { _logOutput = fd; return true; } else { return false; } } void _prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) { time_t the_time; struct tm the_tm; char datetime_buf[60]; struct timeval tv; if (startsWith(file, "ext/")) { file += sizeof("ext/") - 1; if (startsWith(file, "common/")) { file += sizeof("common/") - 1; if (startsWith(file, "ApplicationPool2/")) { file += sizeof("Application") - 1; } } } the_time = time(NULL); localtime_r(&the_time, &the_tm); strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm); gettimeofday(&tv, NULL); sstream << "[ " << datetime_buf << "." << std::setfill('0') << std::setw(4) << (unsigned long) (tv.tv_usec / 100) << " " << std::dec << getpid() << "/" << std::hex << pthread_self() << std::dec << " " << file << ":" << line << " ]: "; } void _writeLogEntry(const std::string &str) { size_t written = 0; do { ssize_t ret = write(_logOutput, str.data() + written, str.size() - written); if (ret != -1) { written += ret; } } while (written < str.size()); } } // namespace Passenger
27.910891
83
0.674707
bf4
1836389bbd6371175d9ce813221b55602f9ef73e
151
cpp
C++
src/av2/p22.cpp
finki-mk/SP
da1fffce9ba1096283f54ffa6a175b01900c335c
[ "MIT" ]
15
2017-02-09T11:50:08.000Z
2022-03-20T13:26:26.000Z
src/av2/p22.cpp
finki-mk/SP
da1fffce9ba1096283f54ffa6a175b01900c335c
[ "MIT" ]
3
2016-10-13T18:46:05.000Z
2020-10-13T16:29:16.000Z
src/av2/p22.cpp
finki-mk/SP
da1fffce9ba1096283f54ffa6a175b01900c335c
[ "MIT" ]
6
2016-11-20T22:04:24.000Z
2021-02-01T15:56:22.000Z
#include <iostream> using namespace std; int main() { int x = 7; cout << "Brojot " << x << " na kvadrat e " << x * x << endl; return 0; }
16.777778
64
0.516556
finki-mk
183a1c46b287179b3ca7ce1a827fb839dccbda0f
4,750
cpp
C++
2018/cpp/src/day07.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
1
2021-12-04T20:55:02.000Z
2021-12-04T20:55:02.000Z
2018/cpp/src/day07.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
null
null
null
2018/cpp/src/day07.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <list> #include <algorithm> #include <numeric> #include <regex> #include <get_input.hpp> struct Step { char prereq; char step_token; }; std::ostream& operator<<(std::ostream& os, const Step& s) { return os << "Do " << s.prereq << " before " << s.step_token; } auto parse_steps(const std::vector<std::string>& input) { std::vector<Step> vsteps (input.size()); const std::regex pat {R"(^Step\s(\w).*(\w)\scan\sbegin\.$)"}; std::transform(std::begin(input), std::end(input), std::begin(vsteps), [&pat](auto line) { //std::cmatch match; std::smatch match; std::regex_search(line, match, pat); //Step step {match[1], match[2]}; Step step {match[1].str()[0], match[2].str()[0]}; return step; }); return vsteps; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * struct Worker { char task = '\0'; int time_left = 0; void dec_time() { --time_left; } }; class Task_mgr { public: Task_mgr(size_t max_w, size_t num_s, int base_t = 0); std::string get_order_string() const; int run(const std::vector<Step>& steps); private: int get_task_time(char t) const; bool tasks_complete() const { return done.size() == num_steps; } void assign_task(char t); void advance_time(); bool check_workers(); void review_tasks(const std::vector<Step>& steps); const char first_token = 'A'; const size_t max_workers; // max workers const size_t num_steps; // number of tasks const int base_tt; // base task time std::vector<char> done; std::vector<char> ready; std::vector<char> pool; std::list<Worker> workers; }; Task_mgr::Task_mgr(size_t max_w, size_t num_s, int base_t) : max_workers{max_w}, num_steps{num_s}, base_tt{base_t}, pool{std::vector<char>(num_s)} { std::iota(std::begin(pool), std::end(pool), first_token); } int Task_mgr::get_task_time(char task) const { return base_tt + 1 + task - first_token; } void Task_mgr::assign_task(char t) { workers.push_back(Worker{t, get_task_time(t)}); } void Task_mgr::advance_time() { std::for_each(std::begin(workers), std::end(workers), [](auto& w) { w.dec_time(); }); } bool Task_mgr::check_workers() { if (workers.size() == 0) return true; bool change = false; for (auto it = std::begin(workers); it != std::end(workers); ) if (it->time_left <= 0) { done.push_back(it->task); change = true; it = workers.erase(it); } else { ++it; } return change; } void Task_mgr::review_tasks(const std::vector<Step>& steps) { ready.resize(pool.size()); std::copy(std::begin(pool), std::end(pool), std::begin(ready)); pool.clear(); for (const auto& s : steps) { auto dit = std::find(std::begin(done), std::end(done), s.prereq); if (dit == std::end(done)) { auto rit = std::find(std::begin(ready), std::end(ready), s.step_token); if (rit != std::end(ready)) { ready.erase(rit); pool.push_back(s.step_token); } } } std::sort(std::rbegin(ready), std::rend(ready)); for (auto it = std::rbegin(ready); it != std::rend(ready) && workers.size() < max_workers; ) { assign_task(*it); ++it; ready.pop_back(); } for (const auto c : ready) pool.push_back(c); ready.clear(); } int Task_mgr::run(const std::vector<Step>& steps) { int total_time = 0; while (!tasks_complete()) { if (check_workers()) review_tasks(steps); if (!tasks_complete()) { advance_time(); ++total_time; } } return total_time; } std::string Task_mgr::get_order_string() const { return std::string{std::begin(done), std::end(done)}; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * int main(int argc, char* argv[]) { std::cout << "AoC 2018 Day 7 - The Sum of Its Parts\n"; auto input = utils::get_input_lines(argc, argv, "07"); auto steps = parse_steps(input); Task_mgr solo_mgr {1, 26}; auto time1 = solo_mgr.run(steps); auto order1 = solo_mgr.get_order_string(); std::cout << "Part 1: " << time1 << "s " << order1 << '\n'; Task_mgr group_mgr {5, 26, 60}; auto time2 = group_mgr.run(steps); auto order2 = group_mgr.get_order_string(); std::cout << "Part 2: " << time2 << "s " << order2 << '\n'; }
25.132275
79
0.547579
Chrinkus
183d0fcdf8aeb559d88283843a6e3ad892d7f213
5,290
cpp
C++
Modules/MitkExt/DataManagement/mitkSphereLandmarkProjector.cpp
rfloca/MITK
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
[ "BSD-3-Clause" ]
null
null
null
Modules/MitkExt/DataManagement/mitkSphereLandmarkProjector.cpp
rfloca/MITK
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
[ "BSD-3-Clause" ]
null
null
null
Modules/MitkExt/DataManagement/mitkSphereLandmarkProjector.cpp
rfloca/MITK
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
[ "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSphereLandmarkProjector.h" #include <vtkThinPlateSplineTransform.h> #include <vtkTransform.h> #include <vtkSphericalTransform.h> #include <vtkGeneralTransform.h> mitk::SphereLandmarkProjector::SphereLandmarkProjector() { m_SphericalTransform = vtkSphericalTransform::New(); m_SphereRotation = vtkTransform::New(); m_SpatialPlacementTransform = vtkTransform::New(); m_PlaneToSphericalTransform = vtkGeneralTransform::New(); m_SphereRotation->RotateX(90); //setup parameter-plane of the sphere: x is phi, y is theta; the radius is always 1 mitk::ScalarType origin[3] = {1, 0, 2*vnl_math::pi}; // (1, 0, 6.28) (1, 0, 0) mitk::ScalarType right[3] = {0, 0, -2*vnl_math::pi}; // (0,3.14, 0) (0, 0, 6.28) mitk::ScalarType bottom[3] = {0, vnl_math::pi, 0}; // (0, 0,-6.28) (0,3.14, 0) m_SphereParameterPlane = mitk::PlaneGeometry::New(); m_SphereParameterPlane->InitializeStandardPlane(right, bottom); m_SphereParameterPlane->SetOrigin(origin); m_SphereParameterPlane->SetSizeInUnits(100, 50); m_ParameterPlane = m_SphereParameterPlane; } mitk::SphereLandmarkProjector::~SphereLandmarkProjector() { m_SphericalTransform->Delete(); m_SphereRotation->Delete(); m_SpatialPlacementTransform->Delete(); m_PlaneToSphericalTransform->Delete(); } void mitk::SphereLandmarkProjector::ComputeCompleteAbstractTransform() { m_PlaneToSphericalTransform->Identity(); m_PlaneToSphericalTransform->PostMultiply(); m_PlaneToSphericalTransform->Concatenate(m_SphericalTransform); m_PlaneToSphericalTransform->Concatenate(m_SphereRotation); m_PlaneToSphericalTransform->Concatenate(m_InterpolatingAbstractTransform);//GetInterpolatingAbstractTransform()); m_PlaneToSphericalTransform->Concatenate(m_SpatialPlacementTransform); m_CompleteAbstractTransform = m_PlaneToSphericalTransform; } void mitk::SphereLandmarkProjector::ProjectLandmarks( const mitk::PointSet::DataType::PointsContainer* targetLandmarks) { unsigned int size=targetLandmarks->Size(); mitk::PointSet::DataType::PointsContainer::ConstIterator pointiterator, start = targetLandmarks->Begin(); mitk::PointSet::DataType::PointsContainer::ElementIdentifier id; //Part I: Calculate center of sphere mitk::Point3D center; center.Fill(0); mitk::ScalarType radius; mitk::PointSet::PointType point; //determine center for(id=0, pointiterator=start;id<size;++id, ++pointiterator) { point = pointiterator->Value(); center[0]+=point[0]; center[1]+=point[1]; center[2]+=point[2]; } center[0]/=(mitk::ScalarType)size; center[1]/=(mitk::ScalarType)size; center[2]/=(mitk::ScalarType)size; //determine radius switch(0) { case 0/*MIN*/: radius = mitk::ScalarTypeNumericTraits::max(); for(id=0, pointiterator=start;id<size;++id, ++pointiterator) { point = pointiterator->Value(); mitk::Vector3D v; v[0]=point[0]-center[0]; v[1]=point[1]-center[1]; v[2]=point[2]-center[2]; if (v.GetNorm() < radius) radius = v.GetNorm(); } break; case 1/*MAX*/: radius = 0; for(id=0, pointiterator=start;id<size;++id, ++pointiterator) { point = pointiterator->Value(); mitk::Vector3D v; v[0]=point[0]-center[0]; v[1]=point[1]-center[1]; v[2]=point[2]-center[2]; if (v.GetNorm() > radius) radius = v.GetNorm(); } break; case 2/*AVERAGE*/: radius = 0; for(id=0, pointiterator=start;id<size;++id, ++pointiterator) { point = pointiterator->Value(); mitk::Vector3D v; v[0]=point[0]-center[0]; v[1]=point[1]-center[1]; v[2]=point[2]-center[2]; radius += v.GetNorm(); } radius*=1.0/size; break; } mitk::Point3D origin = m_SphereParameterPlane->GetOrigin(); origin[0]=radius; m_SphereParameterPlane->SetOrigin(origin); m_SpatialPlacementTransform->GetMatrix()->SetElement(0, 3, center[0]); m_SpatialPlacementTransform->GetMatrix()->SetElement(1, 3, center[1]); m_SpatialPlacementTransform->GetMatrix()->SetElement(2, 3, center[2]); //Part II: Project points on sphere mitk::Point3D projectedPoint; m_WritableFinalTargetLandmarks->Initialize(); m_ProjectedLandmarks->Initialize(); m_WritableFinalTargetLandmarks->Reserve(size); m_ProjectedLandmarks->Reserve(size); for(id=0, pointiterator=start;id<size;++id, ++pointiterator) { point = pointiterator->Value(); mitk::Vector3D v; v=point-center; mitk::FillVector3D(point, v[0], v[1], v[2]); v.Normalize(); v*=radius; mitk::FillVector3D(projectedPoint, v[0], v[1], v[2]); m_WritableFinalTargetLandmarks->InsertElement(id, point); m_ProjectedLandmarks->InsertElement(id, projectedPoint); } }
33.27044
122
0.680529
rfloca
1848098486ffd236fa484d6711b5f1ca9e350b61
2,503
cpp
C++
src-qt5/core-utils/lumina-search/ConfigUI.cpp
q5sys/lumina
d3654eb6a83d7f8aad5530ba10816a245c9f55b3
[ "BSD-3-Clause" ]
246
2018-04-13T20:07:34.000Z
2022-03-29T01:33:37.000Z
src-qt5/core-utils/lumina-search/ConfigUI.cpp
q5sys/lumina
d3654eb6a83d7f8aad5530ba10816a245c9f55b3
[ "BSD-3-Clause" ]
332
2016-06-21T13:37:10.000Z
2018-04-06T13:06:41.000Z
src-qt5/core-utils/lumina-search/ConfigUI.cpp
q5sys/lumina
d3654eb6a83d7f8aad5530ba10816a245c9f55b3
[ "BSD-3-Clause" ]
69
2018-04-12T15:46:09.000Z
2022-03-20T21:21:45.000Z
// Copyright (c) 2015, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "ConfigUI.h" #include "ui_ConfigUI.h" #include <QFileDialog> #include <QListWidget> #include <QListWidgetItem> #include <QListView> #include <QTreeView> #include <QPoint> #include <LuminaXDG.h> ConfigUI::ConfigUI(QWidget *parent) : QDialog(parent), ui(new Ui::ConfigUI){ ui->setupUi(this); //Make sure this dialog is centered on the parent if(parent!=0){ QPoint ctr = parent->geometry().center(); this->move( ctr.x()-(this->width()/2), ctr.y()-(this->height()/2) ); } ui->tool_getStartDir->setIcon( LXDG::findIcon("folder","") ); ui->tool_adddirs->setIcon( LXDG::findIcon("list-add","") ); ui->tool_rmdir->setIcon( LXDG::findIcon("list-remove","") ); newDefaults = false; } ConfigUI::~ConfigUI(){ } void ConfigUI::loadInitialValues(QString startdir, QStringList skipdirs){ ui->label_start->setText(startdir); ui->list_excludes->clear(); ui->list_excludes->addItems(skipdirs); } void ConfigUI::on_tool_getStartDir_clicked(){ QString dir = QFileDialog::getExistingDirectory(this, tr("Select Search Directory"), QDir::homePath() ); if(dir.isEmpty()){ return; } ui->label_start->setText(dir); } void ConfigUI::on_tool_adddirs_clicked(){ QFileDialog dlg(this); dlg.setFileMode(QFileDialog::DirectoryOnly); QListView *l = dlg.findChild<QListView*>("listView"); if(l){ l->setSelectionMode(QAbstractItemView::MultiSelection); } QTreeView *t = dlg.findChild<QTreeView*>(); if(t){ t->setSelectionMode(QAbstractItemView::MultiSelection); } dlg.setDirectory(QDir::homePath()); dlg.setWindowTitle( tr("Exclude Directories") ); if(dlg.exec()){ //Directories selected QStringList paths = dlg.selectedFiles(); ui->list_excludes->addItems(paths); } } void ConfigUI::on_tool_rmdir_clicked(){ qDeleteAll(ui->list_excludes->selectedItems()); } void ConfigUI::on_list_excludes_itemSelectionChanged(){ ui->tool_rmdir->setEnabled( !ui->list_excludes->selectedItems().isEmpty() ); } void ConfigUI::on_buttonBox_accepted(){ newStartDir = ui->label_start->text(); QStringList dirs; for(int i=0; i<ui->list_excludes->count(); i++){ dirs << ui->list_excludes->item(i)->text(); } dirs.removeDuplicates(); newSkipDirs = dirs; newDefaults = ui->check_setDefaults->isChecked(); this->close(); } void ConfigUI::on_buttonBox_rejected(){ this->close(); }
29.447059
106
0.693168
q5sys
184ba034c9ba55d92a0d8e452d79a92ec6ccc340
9,629
cpp
C++
src/src/touchpad.cpp
JyeSmith/rx5808-pro-diversity
7d29ef47afccbe674dac49744b397f5c1c913757
[ "MIT" ]
63
2018-09-05T11:57:29.000Z
2022-02-18T06:59:41.000Z
src/src/touchpad.cpp
JyeSmith/rx5808-pro-diversity
7d29ef47afccbe674dac49744b397f5c1c913757
[ "MIT" ]
2
2022-01-04T22:28:27.000Z
2022-03-20T03:46:40.000Z
src/src/touchpad.cpp
JyeSmith/rx5808-pro-diversity
7d29ef47afccbe674dac49744b397f5c1c913757
[ "MIT" ]
5
2018-11-06T00:56:32.000Z
2021-01-24T13:00:48.000Z
#include <Arduino.h> #include "ui.h" #include "channels.h" #include "receiver.h" #include "settings.h" #include "settings_eeprom.h" #include "touchpad.h" //// Cirque's 7-bit I2C Slave Address //#define TOUCHPAD_SLAVE_ADDR 0x2A // Masks for Cirque Register Access Protocol (RAP) #define TOUCHPAD_WRITE_MASK 0x80 #define TOUCHPAD_READ_MASK 0xA0 namespace TouchPad { const int sizeOfGestureArray = 8; int xGestureArray[sizeOfGestureArray] = {0}; int yGestureArray[sizeOfGestureArray] = {0}; int xSwipeThreshold = 130; int ySwipeThreshold = 200; relData_t touchData; void setup() { Pinnacle_Init(); touchData.cursorX = 200; touchData.cursorY = 100; touchData.timeLastButtonPress = 0; touchData.switchButtonOrder = false; touchData.switchButtonOrder = false; } void update() { if(isDataAvailable()) { Pinnacle_getRelative(&touchData); if (Ui::isTvOn) { touchData.cursorX += touchData.xDelta; touchData.cursorY -= touchData.yDelta; // touchData.cursorX -= touchData.xDelta; // touchData.cursorY += touchData.yDelta; if (touchData.cursorX < 1) { touchData.cursorX = 1; } if (touchData.cursorX > SCREEN_WIDTH - 1) { touchData.cursorX = SCREEN_WIDTH - 1; } if (touchData.cursorY < 1) { touchData.cursorY = 1; } if (touchData.cursorY > SCREEN_HEIGHT - 1) { touchData.cursorY = SCREEN_HEIGHT - 1; } } else { Gesture currentGesture = isGesture(); if (currentGesture != Gesture::Nope) { doGesture(currentGesture); } } // if (touchData.buttonPrimary) { //// Ui::beep(); // } // Serial.print(touchData.buttonPrimary); // Serial.print('\t'); // Serial.print(touchData.buttonSecondary); // Serial.print('\t'); // Serial.print(touchData.buttonAuxiliary); // Serial.print('\t'); // Serial.print(touchData.xDelta); // Serial.print('\t'); // Serial.print(touchData.yDelta); // Serial.print('\t'); // Serial.print(touchData.xSign); // Serial.print('\t'); // Serial.println(touchData.ySign); } } void clearTouchData() { touchData.isActive = false; touchData.buttonPrimary = 0; touchData.buttonSecondary = 0; touchData.buttonAuxiliary = 0; touchData.xDelta = 0; touchData.yDelta = 0; touchData.xSign = 0; touchData.ySign = 0; } /* Pinnacle-based TM0XX0XX Functions */ void Pinnacle_Init() { SPI.begin(); // Host clears SW_CC flag Pinnacle_ClearFlags(); // Feed Enable RAP_Write(0x04, 0b00000001); } // Reads X, Y, and Scroll-Wheel deltas from Pinnacle, as well as button states // NOTE: this function should be called immediately after DR is asserted (HIGH) void Pinnacle_getRelative(relData_t * result) { uint8_t data[3] = { 0,0,0 }; RAP_ReadBytes(0x12, data, 3); Pinnacle_ClearFlags(); result->isActive = true; bool buttonOrderChecked; bool switchButtonOrder; result->buttonPrimary = data[0] & 0b00000001; result->buttonSecondary = data[0] & 0b00000010; // // Some touch pads reverse the primary/secondard order. // // Hacky fix to detect rapis button pressing and reverse order. // if(!switchButtonOrder && (millis() - result->timeLastButtonPress < 10)) // { // switchButtonOrder = true; // result->timeLastButtonPress = millis(); // } // if(switchButtonOrder) // { // result->buttonPrimary = data[0] & 0b00000010; // result->buttonSecondary = data[0] & 0b00000001; // } // /////////////////////////////////////////////////////////////// result->buttonAuxiliary = data[0] & 0b00000100; result->xDelta = (int8_t)data[2]; result->yDelta = (int8_t)data[1]; result->xSign = data[0] & 0b00010000; result->ySign = data[0] & 0b00100000; } // Clears Status1 register flags (SW_CC and SW_DR) void Pinnacle_ClearFlags() { RAP_Write(0x02, 0x00); delayMicroseconds(50); } /* RAP Functions */ // Reads <count> Pinnacle registers starting at <address> //void RAP_ReadBytes(byte address, byte * data, byte count) void RAP_ReadBytes(uint8_t address, uint8_t * data, uint8_t count) { byte cmdByte = TOUCHPAD_READ_MASK | address; // Form the READ command byte SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE1)); Assert_SS(); SPI.transfer(cmdByte); // Signal a RAP-read operation starting at <address> SPI.transfer(0xFC); // Filler byte SPI.transfer(0xFC); // Filler byte for(byte i = 0; i < count; i++) { data[i] = SPI.transfer(0xFC); // Each subsequent SPI transfer gets another register's contents } DeAssert_SS(); SPI.endTransaction(); } // Writes single-byte <data> to <address> void RAP_Write(uint8_t address, uint8_t data) { byte cmdByte = TOUCHPAD_WRITE_MASK | address; // Form the WRITE command byte SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE1)); Assert_SS(); SPI.transfer(cmdByte); // Signal a write to register at <address> SPI.transfer(data); // Send <value> to be written to register DeAssert_SS(); SPI.endTransaction(); } void Assert_SS() { digitalWrite(PIN_TOUCHPAD_SLAVE_SELECT, LOW); } void DeAssert_SS() { digitalWrite(PIN_TOUCHPAD_SLAVE_SELECT, HIGH); } bool isDataAvailable() { return digitalRead(PIN_TOUCHPAD_DATA_READY); } Gesture isGesture() { for (int i = 0; i < sizeOfGestureArray - 1; i++) { xGestureArray[sizeOfGestureArray-1-i] = xGestureArray[sizeOfGestureArray-2-i]; yGestureArray[sizeOfGestureArray-1-i] = yGestureArray[sizeOfGestureArray-2-i]; } xGestureArray[0] = TouchPad::touchData.xDelta; yGestureArray[0] = TouchPad::touchData.yDelta; int xSumArray = 0; int ySumArray = 0; for (int i = 0; i < sizeOfGestureArray - 1; i++) { xSumArray += xGestureArray[i]; ySumArray += yGestureArray[i]; } if (xSumArray > xSwipeThreshold) { // Serial.println("Swipe Left"); for (int i = 0; i < sizeOfGestureArray - 1; i++) { xGestureArray[i] = 0; yGestureArray[i] = 0; } return Gesture::Left; } else if (xSumArray < -xSwipeThreshold) { // Serial.println("Swipe Right"); for (int i = 0; i < sizeOfGestureArray - 1; i++) { xGestureArray[i] = 0; yGestureArray[i] = 0; } return Gesture::Right; } else if (ySumArray > ySwipeThreshold) { // Serial.println("Swipe Up"); for (int i = 0; i < sizeOfGestureArray - 1; i++) { xGestureArray[i] = 0; yGestureArray[i] = 0; } return Gesture::Up; } else if (ySumArray < -ySwipeThreshold) { // Serial.println("Swipe Down"); for (int i = 0; i < sizeOfGestureArray - 1; i++) { xGestureArray[i] = 0; yGestureArray[i] = 0; } return Gesture::Down; } else { return Gesture::Nope; } } void doGesture(Gesture currentGesture) { switch (currentGesture) { case Gesture::Left: break; case Gesture::Right: break; case Gesture::Up: setChannel(-1); break; case Gesture::Down: setChannel(1); break; } } void setChannel(int channelIncrement) { int band = Receiver::activeChannel / 8; int channel = Receiver::activeChannel % 8; if (channelIncrement == 8) { band = band + 1; } if (channelIncrement == -8) { band = band - 1; } if (channelIncrement == 1 ) { channel = channel + 1; if (channel > 7) { channel = 0; } } if (channelIncrement == -1 ) { channel = channel - 1; if (channel < 0) { channel = 7; } } int newChannelIndex = band * 8 + channel; if (newChannelIndex >= CHANNELS_SIZE) { newChannelIndex = newChannelIndex - CHANNELS_SIZE; } if (newChannelIndex < 0) { newChannelIndex = newChannelIndex + CHANNELS_SIZE; } Receiver::setChannel(newChannelIndex); EepromSettings.startChannel = newChannelIndex; EepromSettings.save(); } }
29.627692
106
0.525392
JyeSmith
184d39ab016eb1247371cdd0e7f3d52e7518e5b1
301
cpp
C++
LR/SLRUtils.cpp
jhxqy/LL-1-analyzer
ccd299a84e5698044a852be8c6fce7d6f655778b
[ "MIT" ]
2
2020-11-11T14:44:01.000Z
2020-12-20T12:39:18.000Z
LR/SLRUtils.cpp
jhxqy/LL-SLR-analyzer
ccd299a84e5698044a852be8c6fce7d6f655778b
[ "MIT" ]
null
null
null
LR/SLRUtils.cpp
jhxqy/LL-SLR-analyzer
ccd299a84e5698044a852be8c6fce7d6f655778b
[ "MIT" ]
null
null
null
// // SLRUtils.cpp // LR // // Created by 贾皓翔 on 2019/9/18. // Copyright © 2019 贾皓翔. All rights reserved. // #include "SLRUtils.hpp" std::unordered_set<int> Sequence(int from,int to){ std::unordered_set<int> res; for(int i=from;i<=to;i++){ res.insert(i); } return res; }
16.722222
50
0.598007
jhxqy
4c76a8d67538cd5144cc96f4660164b0f45b9ce3
2,215
hpp
C++
include/sprout/rational/literals.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/rational/literals.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/rational/literals.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_RATIONAL_LITERALS_HPP #define SPROUT_RATIONAL_LITERALS_HPP #include <sprout/config.hpp> #include <sprout/rational/rational.hpp> #include <sprout/detail/udl_namespace.hpp> #if SPROUT_USE_USER_DEFINED_LITERALS namespace sprout { namespace literals { namespace rational { // // _r // inline SPROUT_CONSTEXPR sprout::rational<int> operator"" _r(unsigned long long x) { return sprout::rational<int>(static_cast<int>(x)); } // // _rl // _rL // inline SPROUT_CONSTEXPR sprout::rational<long> operator"" _rl(unsigned long long x) { return sprout::rational<long>(static_cast<long>(x)); } inline SPROUT_CONSTEXPR sprout::rational<long> operator"" _rL(unsigned long long x) { return sprout::rational<long>(static_cast<long>(x)); } // // _rll // _rLL // inline SPROUT_CONSTEXPR sprout::rational<long long> operator"" _rll(unsigned long long x) { return sprout::rational<long long>(x); } inline SPROUT_CONSTEXPR sprout::rational<long long> operator"" _rLL(unsigned long long x) { return sprout::rational<long long>(x); } } // namespace rational using sprout::literals::rational::operator"" _r; using sprout::literals::rational::operator"" _rl; using sprout::literals::rational::operator"" _rL; using sprout::literals::rational::operator"" _rll; using sprout::literals::rational::operator"" _rLL; } // namespace literals using sprout::literals::rational::operator"" _r; using sprout::literals::rational::operator"" _rl; using sprout::literals::rational::operator"" _rL; using sprout::literals::rational::operator"" _rll; using sprout::literals::rational::operator"" _rLL; } // namespace sprout #endif // #if SPROUT_USE_USER_DEFINED_LITERALS #endif // #ifndef SPROUT_RATIONAL_LITERALS_HPP
30.763889
79
0.665011
thinkoid
4c7801bee82fb2529d9b945733a293a14fc940e2
892
cpp
C++
Semester1/Test3/3.3.2/3.3.2/3.3.2.cpp
yuniyakim/Homework
21f879fe16d75003cfcc142dd6874bde1279b70c
[ "Apache-2.0" ]
1
2019-03-30T17:45:08.000Z
2019-03-30T17:45:08.000Z
Semester1/Test3/3.3.2/3.3.2/3.3.2.cpp
yuniyakim/Homework
21f879fe16d75003cfcc142dd6874bde1279b70c
[ "Apache-2.0" ]
2
2019-04-13T14:23:47.000Z
2020-06-07T01:35:00.000Z
Semester1/Test3/3.3.2/3.3.2/3.3.2.cpp
yuniyakim/Homework
21f879fe16d75003cfcc142dd6874bde1279b70c
[ "Apache-2.0" ]
1
2019-04-12T14:34:20.000Z
2019-04-12T14:34:20.000Z
#include "pch.h" #include <iostream> #include <fstream> #include "restaurant.h" #include "test.h" using namespace std; int main() { test(); ifstream file("3.3.2.txt", ios::in); if (!file.is_open()) { cout << "File not found" << endl; return 1; } int maxHour = readAndSummarize(file); if (maxHour == -2) { cout << "Invalid data" << endl; } else { cout << "An hour with the largest amount of visitors is " << maxHour << endl; } file.close(); return 0; } // В ресторане в течение рабочего дня для всех посетителей регистрируется время прихода и ухода в виде пары моментов времени. // На входе файл, описывающий статистику посещений за день в виде строк следующего формата: // hourStart minuteStart hourFinish minuteFinish // Требуется вычислить, в течение какого из часовых отрезков в сутках в ресторане находилось одновременно наибольшее количество посетителей.
22.871795
140
0.707399
yuniyakim
4c7b064d7dcdf4c5a1fe76d607d257f75590ce67
2,669
cpp
C++
src/proto/unit_test/helpers_test.cpp
jonesholger/lbann
3214f189a1438565d695542e076c4fa8e7332d34
[ "Apache-2.0" ]
194
2016-07-19T15:40:21.000Z
2022-03-19T08:06:10.000Z
src/proto/unit_test/helpers_test.cpp
jonesholger/lbann
3214f189a1438565d695542e076c4fa8e7332d34
[ "Apache-2.0" ]
1,021
2016-07-19T12:56:31.000Z
2022-03-29T00:41:47.000Z
src/proto/unit_test/helpers_test.cpp
jonesholger/lbann
3214f189a1438565d695542e076c4fa8e7332d34
[ "Apache-2.0" ]
74
2016-07-28T18:24:00.000Z
2022-01-24T19:41:04.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2021, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 <catch2/catch.hpp> #include "lbann/proto/helpers.hpp" #include <callbacks.pb.h> #include <model.pb.h> #include <training_algorithm.pb.h> using namespace lbann::proto::helpers; TEST_CASE("Oneof utilities", "[utils][proto]") { lbann_data::Callback callback; SECTION("Valid oneof") { REQUIRE_FALSE(has_oneof(callback, "callback_type")); callback.mutable_hang()->set_rank(123); REQUIRE(has_oneof(callback, "callback_type")); auto const& hang_msg = get_oneof_message(callback, "callback_type"); REQUIRE_NOTHROW( dynamic_cast<lbann_data::Callback::CallbackHang const&>(hang_msg)); } SECTION("Invalid oneof") { REQUIRE_FALSE(has_oneof(callback, "potato")); REQUIRE_THROWS(get_oneof_message(callback, "broccoli")); } } TEST_CASE("Message type names", "[utils][proto]") { lbann_data::TrainingAlgorithm algo; lbann_data::Callback callback; lbann_data::Model model; SECTION("Plain ol' messages") { REQUIRE(message_type(algo) == "TrainingAlgorithm"); REQUIRE(message_type(callback) == "Callback"); REQUIRE(message_type(model) == "Model"); } SECTION("\'Any\' messages") { google::protobuf::Any algo_any, callback_any, model_any; algo_any.PackFrom(algo); callback_any.PackFrom(callback); model_any.PackFrom(model); REQUIRE(message_type(algo_any) == "TrainingAlgorithm"); REQUIRE(message_type(callback_any) == "Callback"); REQUIRE(message_type(model_any) == "Model"); } }
32.156627
80
0.675159
jonesholger
4c9abf4989ce06dd1f643db4ad2807f08b689297
2,332
hpp
C++
include/boost/hana/take.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
2
2015-12-06T05:10:14.000Z
2021-09-05T21:48:27.000Z
include/boost/hana/take.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
null
null
null
include/boost/hana/take.hpp
qicosmos/hana
b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f
[ "BSL-1.0" ]
1
2017-06-06T10:50:17.000Z
2017-06-06T10:50:17.000Z
/*! @file Defines `boost::hana::take` and `boost::hana::take_c`. @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_TAKE_HPP #define BOOST_HANA_TAKE_HPP #include <boost/hana/fwd/take.hpp> #include <boost/hana/at.hpp> #include <boost/hana/concept/integral_constant.hpp> #include <boost/hana/concept/sequence.hpp> #include <boost/hana/core/dispatch.hpp> #include <boost/hana/core/make.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/length.hpp> #include <cstddef> #include <utility> namespace boost { namespace hana { //! @cond template <typename Xs, typename N> constexpr auto take_t::operator()(Xs&& xs, N const& n) const { using S = typename hana::tag_of<Xs>::type; using Take = BOOST_HANA_DISPATCH_IF(take_impl<S>, Sequence<S>::value && IntegralConstant<N>::value ); #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS static_assert(Sequence<S>::value, "hana::take(xs, n) requires 'xs' to be a Sequence"); static_assert(IntegralConstant<N>::value, "hana::take(xs, n) requires 'n' to be an IntegralConstant"); #endif return Take::apply(static_cast<Xs&&>(xs), n); } //! @endcond template <typename S, bool condition> struct take_impl<S, when<condition>> : default_ { template <typename Xs, std::size_t ...n> static constexpr auto take_helper(Xs&& xs, std::index_sequence<n...>) { return hana::make<S>(hana::at_c<n>(static_cast<Xs&&>(xs))...); } template <typename Xs, typename N> static constexpr auto apply(Xs&& xs, N const&) { constexpr std::size_t n = N::value; constexpr std::size_t size = decltype(hana::length(xs))::value; return take_helper(static_cast<Xs&&>(xs), std::make_index_sequence<(n < size ? n : size)>{}); } }; template <std::size_t n> struct take_c_t { template <typename Xs> constexpr auto operator()(Xs&& xs) const { return hana::take(static_cast<Xs&&>(xs), hana::size_c<n>); } }; }} // end namespace boost::hana #endif // !BOOST_HANA_TAKE_HPP
31.093333
79
0.634648
qicosmos