blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
8d562627ea7bf3c8ac752cee63d625dba61a6880
C++
nvtienanh/Hitechlab_humanoid
/nimbro/cv/classificator/colorlut.h
UTF-8
737
3.203125
3
[]
no_license
// Color classification LUT // Author: Max Schwarz <max.schwarz@uni-bonn.de> #ifndef COLORLUT_H #define COLORLUT_H #include <stdint.h> #include <vector> class ColorLUT { public: ColorLUT() { m_lut.resize(256*256); } inline uint8_t color(int y, int u, int v) const { return m_lut[256*u + v]; } inline uint8_t& operator()(int u, int v) { return m_lut[256*u + v]; } inline uint32_t meanColor(int color) const { return m_colors[color]; } inline void setMeanColor(int color, int rgb) { m_colors[color] = rgb; } inline void setNumColors(int numColors) { m_colors.resize(numColors); } inline size_t numColors() const { return m_colors.size(); } private: std::vector<uint8_t> m_lut; std::vector<uint32_t> m_colors; }; #endif
true
0f43d376d1ae6d2bf5879c911a9cbbabaf800855
C++
Ballester/RMM
/Huffman/huffman.cpp
UTF-8
7,936
3.109375
3
[]
no_license
#include "huffman.h" #include <cstdio> #include <vector> #include <algorithm> #include <string.h> #include <iostream> #include <string> #include <fstream> #include <bitset> std::map<char, float> Coder::calcProbabilities(std::string str) { std::map<char, int> count; std::cout << "Calculating probabilities for " << str << std::endl; std::map<char, int>::iterator it; for (int i=0; i<str.size(); i++) { it = count.find(str[i]); if (it == count.end()) { count[str[i]] = 0; } count[str[i]] += 1; } std::map<char, float> probabilities; for(it=count.begin(); it!=count.end(); ++it) { probabilities[it->first] = it->second/((float) str.size()); // std::cout << it->first << std::endl; // std::cout << probabilities[it->first] << std::endl; } return probabilities; } Tree::Tree() { } Tree::Tree(char value, float prob) { this->value = value; this->prob = prob; // this->value = value; // this->prob = prob; } Tree* Coder::createTree(std::map<char, float> prob) { std::cout << "In Create Tree\n"; Tree *head; std::map<char, float>::iterator it; float min_prob; int min_pos = 0; float pos_counter; std::vector<Tree*> alphabet; Tree *t, *s0, *s1, *x; //Get first value for(it=prob.begin(); it!=prob.end(); it++) { t = new Tree(); t->value = it->first; t->prob = it->second; alphabet.push_back(t); } std::cout << "Input: " << std::endl; for (int i=0; i<alphabet.size(); i++) { alphabet[i]->left = alphabet[i]->right = NULL; std::cout << alphabet[i]->value << " " << alphabet[i]->prob << std::endl; } t = new Tree(); while (alphabet.size() > 1) { s0 = new Tree(); s1 = new Tree(); x = new Tree(); min_prob = alphabet[0]->prob; min_pos = 0; for(int i=0; i<alphabet.size(); i++) { if (alphabet[i]->prob < min_prob) { min_pos = i; min_prob = alphabet[i]->prob; } } s0 = alphabet[min_pos]; alphabet.erase(alphabet.begin() + min_pos); //Get second value min_prob = alphabet[0]->prob; min_pos = 0; for(int i=0; i<alphabet.size(); i++) { if (alphabet[i]->prob < min_prob) { min_pos = i; min_prob = alphabet[i]->prob; } } s1 = alphabet[min_pos]; alphabet.erase(alphabet.begin() + min_pos); x->prob = s0->prob + s1->prob; x->left = s1; x->right = s0; std::cout << "Created node: " << x->value << " " << x->prob << std::endl; std::cout << "Left: " << x->left->value << " " << x->left->prob << std::endl; std::cout << "Right: " << x->right->value << " " << x->right->prob << std::endl; alphabet.push_back(x); // for (int i=0; i<alphabet.size(); i++) { // std::cout << alphabet[i]->value << std::endl; // } // if (s1->value == 'd') { // std::cout << "BUG: " << s1->value << " " << s1->prob << " " << s1->left << " " << s1->right->value << std::endl; // } } return alphabet[0]; // Tree::printTree(x); } void Tree::printTree(int spaces) { for (int i=0; i<spaces; i++) { std::cout << " "; } if (this->value) { std::cout << " "; } std::cout << this->value << " " << this->prob << std::endl; if (this->left != NULL) this->left->printTree(spaces+2); if (this->right != NULL) this->right->printTree(spaces+2); } void Tree::insertLeft(Tree* node) { this->left = node; } void Tree::insertRight(Tree* node) { this->right = node; } void Tree::createAlphabetCodes(int spaces, std::string str_codes){ for (int i=0; i<spaces; i++) { std::cout << " "; } if (this->value) { codes[this->value] = str_codes; std::map<char, std::string>::iterator it; // int i=0; // for(it=codes.begin(); it!=codes.end(); it++) { // std::cout << "CREATE NODE: " << i++ << std::endl; // std::cout << it->first << " " << it->second << std::endl; // } // std::cout << "CREATE NODE: " << this->value << " " << this->codes[this->value] << std::endl; } std::cout << this->value << " " << this->prob << std::endl; if (this->left != NULL){ str_codes += "1"; this->left->createAlphabetCodes(spaces+2,str_codes); } str_codes.erase(str_codes.end() -1); if (this->right != NULL){ str_codes += "0"; this->right->createAlphabetCodes(spaces+2, str_codes); } // str_codes.erase(str_codes.end() -1); } std::string Coder::generateCode(std::string input) { std::string code = ""; // std::map<char, std::string>::iterator it; // int i=0; // for(it=this->codes.begin(); it!=this->codes.end(); it++) { // std::cout << it->first << " " << it->second << std::endl; // } for(int i=0; i<input.size(); i++) { // std::cout << codes[input[i]] << std::endl; code += codes[input[i]]; } return code; } std::string Coder::decode(std::string code) { std::string to_decode = ""; std::string output = ""; std::map<char, std::string>::iterator it; for (int i=0; i<code.size(); i++) { to_decode += code[i]; for(it=this->codes.begin(); it!=this->codes.end(); it++) { if(it->second == to_decode) { output += it->first; to_decode = ""; } } } return output; } void saveProbToFile(std::map<char, float> probs) { freopen("probs.txt","w",stdout); std::map<char, float>::iterator it; for(it=probs.begin(); it!=probs.end(); it++) { std::cout << it->first << " " << it->second << std::endl; } freopen ("/dev/tty", "a", stdout); } std::map<char, float> loadProbFromFile() { char value; float prob; std::map<char, float> probs; std::cout << "OPENING FILE" << std::endl; FILE *f = fopen("probs.txt", "r"); while (fscanf(f, "%c %f", &value, &prob) != -1) { std::cout << value << " " << prob << std::endl; probs[value] = prob; } return probs; } int main() { std::string input = "aaaaaaaaabbbbcccdddeef"; Coder *coder = new Coder(); std::map<char, float> prob; int controler; std::ofstream myfile; std::cout << "Entre com uma das entradas abaixo:\n" << "1. Para rodar o teste default com a entrada default\n" << "2. Para rodar com as probabilidades do arquivo\n" << "3. Para salvar as probabilidades no arquivo\n" << std::endl; std:: cin >> controler; if(controler == 1){ myfile.open ("input.bin"); for (std::size_t i = 0; i < input.size(); ++i){ myfile << std::bitset<8>(input.c_str()[i]); } myfile.close(); prob = coder->calcProbabilities(input); Tree* t = coder->createTree(prob); std::cout << "Printing all nodes..." << std::endl; std::string str_codes; t->printTree(0); t->createAlphabetCodes(0, str_codes); std::cout << "Printing codes..." << std::endl; std::map<char, std::string>::iterator it; for(it=codes.begin(); it!=codes.end(); it++) { coder->codes[it->first] = it->second; } std::cout << "Probabilidades salva no arquivo probs.txt" << std::endl; saveProbToFile(prob); } if(controler == 2){ prob = loadProbFromFile(); Tree* t = coder->createTree(prob); std::cout << "Printing all nodes..." << std::endl; std::string str_codes; t->printTree(0); t->createAlphabetCodes(0, str_codes); std::cout << "Printing codes..." << std::endl; std::map<char, std::string>::iterator it; for(it=codes.begin(); it!=codes.end(); it++) { coder->codes[it->first] = it->second; } } if(controler == 3){ prob = coder->calcProbabilities(input); Tree* t = coder->createTree(prob); std::string str_codes; t->printTree(0); t->createAlphabetCodes(0, str_codes); std::cout << "Printing codes..." << std::endl; std::map<char, std::string>::iterator it; for(it=codes.begin(); it!=codes.end(); it++) { coder->codes[it->first] = it->second; } std::cout << "Probabilidades salva no arquivo probs.txt" << std::endl; saveProbToFile(prob); } if(controler < 4){ std::cout << "Enconded: "; std::string code = coder->generateCode(input); std::cout << code << std::endl; std::string toWrite = code; myfile.open ("output.bin"); for (std::size_t i = 0; i < toWrite.size(); ++i){ myfile << std::bitset<1>(toWrite.c_str()[i]); } myfile.close(); std::cout << "Decoded: "; std::cout << coder->decode(code) << std::endl; } return 0; }
true
37aabb764c3b6833c0f97c9805d319f095e29235
C++
megortel/2D-Graphics-Library
/ZachMatrix.cpp
UTF-8
2,309
3.140625
3
[]
no_license
#include <math.h> #include "GMatrix.h" //Note, we are not subclassing, but simply implementing methods void GMatrix::setIdentity() { this->set6(1, 0, 0, 0, 1, 0); } void GMatrix::setTranslate(float tx, float ty) { this->set6(1, 0, tx, 0, 1, ty); } void GMatrix::setScale(float sx, float sy) { this->set6(sx, 0, 0, 0, sy, 0); } void GMatrix::setRotate(float radians) { this->set6(cos(radians), -1 * sin(radians), 0, sin(radians), cos(radians), 0); } void GMatrix::setConcat(const GMatrix &secundo, const GMatrix &primo) { //If you first apply primo matrix to the points, then the second, you must do secundo*primo //Note: watch out for aliasing - store temp A's and then store in matrix float a = secundo[0] * primo[0] + secundo[1] * primo[3]; float b = secundo[0] * primo[1] + secundo[1] * primo[4]; float c = secundo[0] * primo[2] + secundo[1] * primo[5] + secundo[2]; float d = secundo[3] * primo[0] + secundo[4] * primo[3]; float e = secundo[3] * primo[1] + secundo[4] * primo[4]; float f = secundo[3] * primo[2] + secundo[4] * primo[5] + secundo[5]; this->set6(a, b, c, d, e, f); } /** * If current matrix is invertable, invert and set GMatrix parameter to that Matrix */ bool GMatrix::invert(GMatrix *inverse) const {\ float a = this->fMat[0]; float b = this->fMat[1]; float c = this->fMat[2]; float d = this->fMat[3]; float e = this->fMat[4]; float f = this->fMat[5]; float determinant = a * e - b * d; if (determinant == 0) { return false; } float multiplier = 1 / determinant; inverse->set6( e * multiplier, -b * multiplier, (b * f - c * e) * multiplier, -d * multiplier, a * multiplier, (c * d - a * f) * multiplier); return true; } void GMatrix::mapPoints(GPoint dst[], const GPoint src[], int count) const { //Take points in src, apply matrix, store it in points - client makes sure he passes in correct points for (int i = 0; i < count; i++) { float x = this->fMat[0] * src[i].x() + this->fMat[1] * src[i].y() + this->fMat[2]; //ax + by +c float y = this->fMat[3] * src[i].x() + this->fMat[4] * src[i].y() + this->fMat[5]; dst[i].set(x, y); //Calls default constructor, hits none, so you can do this } return; }
true
1c143f84fa880dd048605f74a0979ff1f4c67cf8
C++
MohitBhola/CPP
/Utilities/ThreadSafePointer/thread_safe_ptr.cpp
UTF-8
22,148
3.390625
3
[]
no_license
#include <iostream> #include <memory> #include <mutex> #include <map> #include <string> #include <thread> // a manual replacement for std::void_t (available since C++17) template< typename...> using VoidT = void; template< typename T, typename = VoidT<>> struct DisableIfIndirection : std::false_type {}; template< typename T> struct DisableIfIndirection<T, VoidT<decltype(std::declval<T>().operator->())>> : std::true_type {}; // the primary template // later specialized for underlying types that are wrappers themselves, that is, types that implement operator->() // please read more comments elsewhere template< typename Resource, typename mutex_t = std::recursive_mutex, typename lock_t = std::unique_lock<mutex_t>, bool = DisableIfIndirection<Resource>::value> class thread_safe_ptr { /* A thread_safe_ptr object *owns* an underlying object. There could be 2 types of underlyings: 1. A normal, regular type that isn't providing wrapper semantics. That is, a type that doesn't overloads the indirection operator. This includes both fundamental types and most user defined types. For such types, a thread_safe_ptr could be created as follows: a. Pass (to a thread_safe_ptr ctor) no arguments / all arguments necessary to invoke the default / user defined ctor of the underlying. b. Pass (to a thread_safe_ptr ctor) an lvalue / rvalue reference to the underlying. As usual, lvalues would be copied in, and rvalues would be moved in. c. Invoke thread_safe_ptr's copy construction / assignment. The thread_safe_ptr object thus constructed shall aggregate a shared_ptr to the underlying. As such, each such thread_safe_ptr object shall *always* have an underlying, and clients need not check them for NULL prior to dereferencing. As aforementioned in # c, it is possible to copy a thread_safe_ptr object. Each such copy shall contain its own shared_ptr to the *same* underlying, and would provide thread-safe access to that *same* underlying. It isn't possible to move a thread_safe_ptr object, though. Why? If move semantics are supported, the moved-from thread_safe_ptr object shall lose its underlying, and thus couldn't be dereferenced. This would necessitate the client code to first check for NULL prior to dereferencing. 2. A *wrapper*, such as a shared_ptr<T>, or an IRef (in the DVA world). That is, something that has an underlying of its own, and could be detected at compile time (SFINAE) via the availability of an overloaded indirection operator (operator->()). As an aside, note that as per classic C++ language rules, the result of an indirection should either result in a raw pointer, or should result in an object of a class that itself overloads the indirection operator. The process continues until the compiler arrives at a raw pointer. If not, the compile emits an error. For such types, a thread_safe_ptr could be created as follows: a. Pass (to the thread_safe_ptr ctor) no arguments / all arguments necessary to invoke the default / user defined ctor of the underlying wrapper. b. Pass (to the thread_safe_ptr ctor) an rvalue reference to the underlying, which would be moved in. Note that lvalue references are disallowed here. More on this below. c. Invoke thread_safe_ptr's copy/move construction or copy/move assignment. For such *wrapper* underlyings, the thread_safe_ptr object shall *directly* aggregate them. Note that we would like to access both the underlying wrapper, and the underlying wrapper's underlying. For example, if the underlying wrapper is shared_ptr<Foo>, we would like access the public interface of both shared_ptr<Foo> (to invoke, for example, its reset() API), and the underlying Foo as well! The former requirement implies that clients of such thread_safe_ptr objects should be prepared to check the wrapper underlying to be NULL prior to accessing the real underlying. This also implies that such thread_safe_ptr objects are both copyable and moveable. [SUBTLE] Why can't we create a thread_safe_ptr object via an lvalue reference to a wrapper underlying? Because the ownership group of the real underlying needs to be a closed one. If there remains an lvalue reference to a wrapper underlying after having constructed one or more thread_safe_ptr's from it, the access to the real underlying from that lvalue reference shall *NOT* be thread safe. Hence it is forbidden. */ std::shared_ptr<Resource> ptr{}; // the underlying std::shared_ptr<mutex_t> mtx{}; // the protection // The Surrogate // What's this? // // To access the underlying shared resource, clients *always* need to invoke the Lock() API on the thread_safe_ptr // This invocation returns a proxy object which provides for the thread safe access to the underlying. // The associated mutex of the shared resource gets locked (explicitly) in the proxy's ctor, and the same gets released (implicitly) in its dtor. // The proxy objects are thus used in an RAII based manner in client code. // It also provides for an implicit conversion to the underlying. template< typename ResourceT, typename requested_lock_t> class proxy { ResourceT* pUnderlying{nullptr}; requested_lock_t lock{}; public: // by default, the underlying isn't available and thus the lock on the underlying isn't acquired proxy() = default; // when the proxy object is created, acquire a lock on the underlying *explicitly* proxy(ResourceT* const p, mutex_t& mtx) : pUnderlying(p), lock(mtx) /* HERE */ {} proxy(proxy&& rhs) : pUnderlying(std::move(rhs.pUnderlying)), lock(std::move(rhs.lock)) {} // when the proxy object is destroyed, release the lock on the underlying *implicitly* ~proxy() noexcept = default; // overload the indirection operator to reach out to the underlying ResourceT* operator->() { return pUnderlying; } ResourceT const* operator->() const { return pUnderlying; } // overload the dereference operator to reach out to the underlying ResourceT& operator*() { return *pUnderlying; } ResourceT const& operator*() const { return *pUnderlying; } }; public: // default constructing a thread_safe_ptr assumes that it is possible to default construct the underlying thread_safe_ptr() : ptr(std::make_unique<Resource>()), mtx(std::make_shared<mutex_t>()) {} // universal ctor // intended to construct the underlying by invoking a viable ctor of the underlying using the parameters of this universal ctor // such viable ctors include normal ctors taking multiple arguments as well as copy / move ctors // // [SUBTLE] // this ctor would shadow the normal copy ctor of thread_safe_ptr while trying to create a copy of a thread_safe_ptr // thus disabled for such scenarios template< typename T, typename... Args, typename = std::enable_if_t<!std::is_same<std::decay_t<T>, thread_safe_ptr>::value>> thread_safe_ptr(T&& t, Args&&... args) : ptr(std::make_shared<Resource>(std::forward<T>(t), std::forward<Args>(args)...)), mtx(std::make_shared<mutex_t>()) {} // copy construction / assignment thread_safe_ptr(thread_safe_ptr const& source) = default; thread_safe_ptr& operator=(thread_safe_ptr const&) = default; // *don't* provide move semantics thread_safe_ptr(thread_safe_ptr const&&) = delete; thread_safe_ptr& operator=(thread_safe_ptr&&) = delete; // implement the *BasicLockable* interface // enables thread_safe_ptr objects to be used in the std::lock(...) API // helps to acquire a lock on multiple thread_safe_ptr objects in different threads without risking a deadlock void lock() { mtx->lock(); } bool try_lock() { return mtx->try_lock(); } void unlock() { mtx->unlock(); } // ALL and ANY access to the underlying is via the Lock() API // helps to eliminate the class of bugs arising out of locking the wrong mutex or forgetting to lock a mutex while trying to access the shared underlying auto Lock() { return ptr ? proxy<Resource, lock_t>(ptr.get(), *mtx) : proxy<Resource, lock_t>(); } auto Lock() const { return ptr ? proxy<Resource const, lock_t>(ptr.get(), *mtx) : proxy<Resource const, lock_t>(); } }; // thread_safe_ptr specialized for *wrapper* underlyings // note that we would like to access the public interface of both the wrapper underlying, as well as the wrapper underlying's underlying template< typename Resource, typename mutex_t, typename lock_t> class thread_safe_ptr<Resource, mutex_t, lock_t, true> { Resource res; // the underlying (note direct aggregation!) std::shared_ptr<mutex_t> mtx; // the protection template< typename ResourceT, typename requested_lock_t> class proxy { ResourceT * const pUnderlying{nullptr}; requested_lock_t lock {}; public: // when the proxy object is created, acquire a lock on the underlying *explicitly* proxy(ResourceT* const p, mutex_t& mtx) : pUnderlying(p), lock(mtx) /* HERE */ {} proxy(proxy&& rhs) : pUnderlying(std::move(rhs.pUnderlying)), lock(std::move(rhs.lock)) {} // when the proxy object is destroyed, release the lock on the underlying *implicitly* ~proxy() noexcept = default; // [SUBTLE] // *wrapper* underlyings may get reset // thus, we need to provide a way for the clients to check for the same (via an implicit conversion to bool) prior to dereferencing it operator bool() const { return static_cast<bool>(pUnderlying ? *pUnderlying : 0); } // (special) overloaded indirection to the wrapper underlying's underlying // this let's the client code to access the public interface of the wrapper underlying's underlying via a consistent syntax auto* operator->() { return pUnderlying->operator->(); } auto const* operator->() const { return pUnderlying->operator->(); } // overload the dereference operator to reach out to the *wrapper's underlying* // this lets the clients to access the public interface of the wrapper underlying itself // for example, to access the reset() API of the underlying shared_ptr<Foo> ResourceT& operator*() { return *pUnderlying; } ResourceT const& operator*() const { return *pUnderlying; } }; public: // universal ctor // intended to construct the underlying by invoking a viable ctor of the underlying using the parameters of this universal ctor // such viable ctors include normal ctors taking multiple arguments as well as copy / move ctors // // [SUBTLE] // this ctor would shadow the normal copy ctor of thread_safe_ptr while trying to create a copy of a thread_safe_ptr // thus disabled for such scenarios template< typename T, typename... Args, typename = std::enable_if_t<!(std::is_lvalue_reference<T>::value && std::is_same<Resource, std::decay_t<T>>::value)>, typename = std::enable_if_t<!std::is_same<std::decay_t<T>, thread_safe_ptr>::value>> thread_safe_ptr(T&& t, Args&&... args) : res(std::forward<T>(t), std::forward<Args>(args)...), mtx(std::make_shared<mutex_t>()) {} // provide for copy construction / assignment thread_safe_ptr(thread_safe_ptr const& source) = default; thread_safe_ptr& operator=(thread_safe_ptr const&) = default; // provide for move construction / assignment thread_safe_ptr(thread_safe_ptr const&&) = delete; thread_safe_ptr& operator=(thread_safe_ptr&&) = delete; // implement the *BasicLockable* interface // enables thread_safe_ptr objects to be used in the std::lock(...) API // helps to acquire a lock on multiple thread_safe_ptr objects in different threads without risking a deadlock void lock() { mtx->lock(); } bool try_lock() { return mtx->try_lock(); } void unlock() { mtx->unlock(); } // ALL and ANY access to the underlying is via the Lock() API // helps to eliminate the class of bugs arising out of locking the wrong mutex or forgetting to lock a mutex while trying to access the shared underlying auto Lock() { return proxy<Resource, lock_t>(std::addressof(res), *mtx); } auto const Lock() const { return proxy<Resource const, lock_t>(std::addressof(res), *mtx); } }; struct Foo { Foo() = default; void doSomething1() { std::cout << "Foo::doSomething1()\n"; } void doSomething2() { std::cout << "Foo::doSomething2()\n"; } void doSomething3() { std::cout << "Foo::doSomething3()\n"; } int i{42}; float f{42.0}; char c{'a'}; }; // works with fundamental types thread_safe_ptr<int> safeInt(42); // works with user defined types thread_safe_ptr<Foo> safeFoo{}; // works with library types thread_safe_ptr<std::map<int, int>> safeMap{}; thread_safe_ptr<std::map<int, int>> safeMap_copy{}; thread_safe_ptr<std::string> safeStr1{"abc"}; thread_safe_ptr<std::string> safeStr2{"xyz"}; // works with *wrapper* types (that provide indirection) too! thread_safe_ptr<std::shared_ptr<Foo>> safeSP{std::make_shared<Foo>()}; void f1() { { // in order to do anything with the underlying, clients first need to invoke the Lock() API on the synchronized ptr // otherwise, the code won't compile // this would prevent the class of bugs arising out of having locked a wrong mutex or forgotten to lock a mutex at all // while trying to access the shared resource auto intRef = safeInt.Lock(); // once we have obtained the proxy to an underlying, clients need to dereference it to do a thread safe access to that underlying *intRef += 42; } // the proxy goes out of scope here and releases the lock on the underlying // this covers both normal returns and exceptions as well // performing a thread safe singular operation // indirection is *natural*; just use operator-> on the proxy returned by the thread_safe_ptr, and it seamlessly redirects to the underlying { auto fooRef = safeFoo.Lock(); fooRef->doSomething1(); } // performing a thread safe transaction { auto fooRef = safeFoo.Lock(); fooRef->doSomething2(); fooRef->doSomething3(); } } void f2() { { // accessing the safeInt in a thread safe manner along with such an access in function f1() auto intRef = safeInt.Lock(); *intRef += 42; // a thread safe increment } // a thread safe singular operation, as in function f1() { auto fooRef = safeFoo.Lock(); fooRef->doSomething2(); } // a thread safe transaction, as in function f1() { auto fooRef = safeFoo.Lock(); fooRef->doSomething2(); fooRef->doSomething3(); } } // the functions f3() and f4() below are made to run on different threads, and each tries to copy assign to safeMap_copy from safeMap // either f3() or f4() does the copy assignment, depending on which of them successfully acquires a lock on *both* safeMap and safeMap_copy first // [SUBTLE] // this is an example of a transaction that involves two shared resources: safeMap_copy and safeMap // we need to acquire a lock on *both* of them // but different threads may try to acquire those locks in different orders which is a classic recipe for a deadlock! // for example, note that functions f3() and f4() below acquire those locks in different orders // we need to acquire these locks atomically // thankfully, std::lock() allows just that! void f3() { // avoid risking a deadlock while acquiring multiple locks by leveraging the std::lock(...) API (since C++11) // since a thread_safe_ptr implements the BasicLockable interface, they could be used with this API! // NOTE: from C++17 onwards, we should be using std::scoped_lock here, else we need to explicitly unlock the thread_safe_ptrs as below std::lock(safeMap, safeMap_copy); { // acquiring the proxies to access the public API of the underlying // this would acquire the locks again, so the mutex better be recursive auto mapRef = safeMap.Lock(); auto mapCopyRef = safeMap_copy.Lock(); if (mapCopyRef->empty()) { *mapCopyRef = *mapRef; } } // since we locked the thread_safe_ptrs explicitly, we need to unlock them explicitly too! // from C++17 onwards, this wouldn't be necessary by using std::scoped_lock to acquire the locks safeMap.unlock(); safeMap_copy.unlock(); } void f4() { // note different order of arguments to the std::lock(...) API than in f3() // this is the kind of mistake that is too easy to make by having to lock multiple mutexes manually // since thread_safe_ptr objects implement the BasicLockable interface, we avoid this risk altogether // developers just need to follow the rule of thumb that if a CriticalSection requires locking multiple thread_safe_ptr objects, // they should do so via std::lock(...) API; the order of argument(s) to this API doesn't matter std::lock(safeMap_copy, safeMap); { auto mapRef = safeMap.Lock(); auto mapCopyRef = safeMap_copy.Lock(); if (mapCopyRef->empty()) { *mapCopyRef = *mapRef; } } safeMap.unlock(); safeMap_copy.unlock(); } int main() { std::thread t1(f1); std::thread t2(f2); t1.join(); t2.join(); // thread_safe_ptr<int> allows access to the underlying shared resource (int) via dereferencing // this is guaranteed to print 126 since increments happen in a thread safe manner in threads t1 and t2 // NOTE: the proxy is an rvalue here and it gets destroyed (and this releases the lock on the underlying) at the end of the statement std::cout << *safeInt.Lock() << '\n'; // thread_safe_ptr<Foo> allows for transparent indirection to access the public API of the underlying std::cout << safeFoo.Lock()->c << '\n'; // populate safeMap in a thread safe manner { auto mapRef = safeMap.Lock(); (*mapRef)[1] = 1; (*mapRef)[2] = 2; std::cout << (*mapRef)[1] << '\n'; std::cout << (*mapRef)[2] << '\n'; } std::thread t3(f3); std::thread t4(f4); t3.join(); t4.join(); // safeMap_copy got populated in a thread safe manner // in either thread t3 or thread t4 (depending upon which was able to acquire a lock (atomically) on both safeMap and safeMap_copy) { auto mapCopyRef = safeMap_copy.Lock(); std::cout << (*mapCopyRef)[1] << '\n'; std::cout << (*mapCopyRef)[2] << '\n'; } { // use std::scoped_lock from C++17 onwards... std::lock(safeStr1, safeStr2); auto str1Ref = safeStr1.Lock(); auto str2Ref = safeStr2.Lock(); std::cout << std::boolalpha << (*str1Ref > *str2Ref) << '\n'; std::cout << std::boolalpha << (*str1Ref != *str2Ref) << '\n'; // ...to avoid this safeStr1.unlock(); safeStr2.unlock(); } // sp is a *wrapper* underlying std::shared_ptr<int> sp(new int(9999)); // ERROR: cannot create thread_safe_ptr objects from lvalues of wrapper underlyings. // Why? Because the ownership group of thread_safe_ptr objects needs to be a closed one. // If allowed, access to the underlying would NOT be thread safe. //thread_safe_ptr<std::shared_ptr<int>> ts_sp{sp}; // can create thread_safe_ptr objects from rvalues of wrapper underlyings thread_safe_ptr<std::shared_ptr<int>> ts_sp1{std::move(sp)}; // NOTE *double* indirection to access the wrapper underlying's underlying { auto sp1Ref = ts_sp1.Lock(); **sp1Ref *= 2; // access the real underlying int std::cout << **sp1Ref << '\n'; } { // can create thread_safe_ptr objects from rvalues of wrapper underlyings thread_safe_ptr<std::shared_ptr<Foo>> ts_sp2{std::make_shared<Foo>()}; // indirection is *natural*; just use operator->() on the proxy, // and it redirects all the way to the wrapper underlying's underlying auto sp2Ref = ts_sp2.Lock(); sp2Ref->doSomething1(); // actually invoke Foo::doSomething1() } { // can create copies of thread_safe_ptrs thread_safe_ptr<std::shared_ptr<int>> ts_sp3{ts_sp1}; auto sp3Ref = ts_sp3.Lock(); // NOTE *double* dereference to access the wrapper underlying's underlying **sp3Ref *= 2; std::cout << **sp3Ref << '\n'; // NOTE *single* dereference to the wrapper underlying itself (*sp3Ref).reset(); // proxy's implicit conversion to bool to indicate whether the wrapper underlying / wrapper underlying's underlying exists or not if (!sp3Ref) { std::cout << "ts_sp3's underlying is now indeed NULL\n\n"; } } return 0; } /* OUTPUT (-std=c++14) Foo::doSomething1() Foo::doSomething2() Foo::doSomething3() Foo::doSomething2() Foo::doSomething2() Foo::doSomething3() 126 a 1 2 1 2 false true 19998 Foo::doSomething1() 39996 ts_sp3's underlying is now indeed NULL */
true
f4381481c1e93e857bf2419cfcd5bbe099f51774
C++
Vichugov/Labs
/GrafLab/graf.cpp
UTF-8
2,569
2.59375
3
[]
no_license
#include "graf.h" #include "ui_graf.h" struct Uzel{ int *way; bool take=0; int from=1000; }; Uzel uzel[6]; Graf::Graf(QWidget *parent) : QMainWindow(parent) , ui(new Ui::Graf) { ui->setupUi(this); ui->button->setShortcut(Qt::Key_Return); uzel[0].way= new int[6]{0,2,0,0,0,57}; uzel[1].way= new int[6]{2,0,3,8,0,13}; uzel[2].way= new int[6]{0,3,0,5,0,0}; uzel[3].way= new int[6]{0,8,5,0,34,21}; uzel[4].way= new int[6]{0,0,0,34,0,45}; uzel[5].way= new int[6]{57,13,0,21,45,0}; } Graf::~Graf() { delete ui; } void Process(Uzel &cur){ int mini=1000; for (int i=0;i<6;i++){ if (cur.way[i]&&cur.way[i]+cur.from<uzel[i].from) uzel[i].from=cur.way[i]+cur.from; if (cur.way[i]&&!uzel[i].take&&cur.way[i]<mini) mini=cur.way[i]; } cur.take=1; for (int i=0;i<6;i++) if (cur.way[i]==mini&&!uzel[i].take)Process(uzel[i]); } void Graf::paintEvent(QPaintEvent *) { QPainter paint; QPen pen; pen.setColor(Qt::green); pen.setWidth(5); paint.begin(this); paint.setPen(pen); paint.drawEllipse(200,10,80,80); paint.drawEllipse(50,300,80,80); paint.drawEllipse(20,500,80,80); paint.drawEllipse(400,600,80,80); paint.drawEllipse(900,400,80,80); paint.drawEllipse(800,100,80,80); paint.drawLine(240,90,130,340); paint.drawLine(240,90,800,140); paint.drawLine(130,340,100,540); paint.drawLine(130,340,440,600); paint.drawLine(130,340,800,140); paint.drawLine(100,540,440,600); paint.drawLine(440,600,900,440); paint.drawLine(440,600,800,140); paint.drawLine(800,140,900,440); paint.end(); } void Graf::on_button_clicked() { for (int i=0;i<6;i++){ uzel[i].from=1000; uzel[i].take=0; } int k = ui->line->text().toInt()-1; if (k<0||k>5){ ui->line->setText(""); ui->statusbar->showMessage("Номер вершины должен быть в диапазоне от 1 до 6! "); } else{ ui->statusbar->showMessage(""); uzel[k].from=0; Process(uzel[k]); QString s = QString::number(uzel[0].from); ui->u->setText(s); s = QString::number(uzel[1].from); ui->u_2->setText(s); s = QString::number(uzel[2].from); ui->u_3->setText(s); s = QString::number(uzel[3].from); ui->u_4->setText(s); s = QString::number(uzel[4].from); ui->u_5->setText(s); s = QString::number(uzel[5].from); ui->u_6->setText(s); } }
true
827c969692c53131d13df130d5b775bdf7c96176
C++
naturalleo/game_login
/src/AuthServer/IOBuffer.cpp
UTF-8
1,620
2.703125
3
[]
no_license
// IOBuffer.cpp: implementation of the CIOBuffer class. // ////////////////////////////////////////////////////////////////////// #include "IOBuffer.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CIOBuffer::CIOBuffer() { } CIOBuffer::~CIOBuffer() { } CIOBufferPool::Slot CIOBufferPool::m_slot[16]; long CIOBufferPool::m_alloc = -1; long CIOBufferPool::m_free = 0; CIOBufferPool g_bufferPool; CIOBuffer *CIOBuffer::Alloc() { CIOBufferPool::Slot *pSlot = &CIOBufferPool::m_slot[InterlockedIncrement(&CIOBufferPool::m_alloc) & 15]; CIOBuffer *pNewBuffer; pSlot->m_lock.Enter(); if((pNewBuffer = pSlot->m_pBuffer) != NULL) { pSlot->m_pBuffer = pNewBuffer->m_pNext; pSlot->m_lock.Leave(); } else { pSlot->m_lock.Leave(); pNewBuffer = new CIOBuffer; } // memset(&(pNewBuffer->m_buffer), 0, sizeof(BUFFER_SIZE)); pNewBuffer->m_size = 0; pNewBuffer->m_ref = 1; pNewBuffer->m_pNext = NULL; return pNewBuffer; } void CIOBuffer::Free() { CIOBufferPool::Slot *pSlot = &CIOBufferPool::m_slot[InterlockedDecrement(&CIOBufferPool::m_free) & 15]; pSlot->m_lock.Enter(); m_pNext = pSlot->m_pBuffer; pSlot->m_pBuffer = this; pSlot->m_lock.Leave(); } void CIOBuffer::FreeAll() { for(int i = 0 ; i < 16; i++) { CIOBufferPool::Slot *pSlot = &CIOBufferPool::m_slot[i]; pSlot->m_lock.Enter(); CIOBuffer *pBuffer; while ((pBuffer = pSlot->m_pBuffer) != NULL) { pSlot->m_pBuffer = pBuffer->m_pNext; delete pBuffer; } pSlot->m_lock.Leave(); } }
true
f2218cbba344591e9a3dac121634fca137d68d95
C++
verngutz/Aura-Mismo
/magnitude_point.cpp
UTF-8
373
3.234375
3
[]
no_license
class magnitude_point { public: int index; double magnitude; magnitude_point(int index, double magnitude) { this->index = index; this->magnitude = magnitude; } bool operator <(const magnitude_point &other) const { return magnitude < other.magnitude; } }; bool index_sort(const magnitude_point &i, const magnitude_point &j) { return i.index < j.index; }
true
0734bd9a1482590d1655c10bb5f7b511594fd556
C++
newbazz/legend-of-zeida
/src/island.cpp
UTF-8
2,792
3.0625
3
[ "MIT" ]
permissive
#include "island.h" #include "main.h" Island::Island(float x, float y, color_t color) { this->position = glm::vec3(x, y, -5); this->rotation = 0; // Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices GLfloat vertex_buffer_data[1176139]; float k,r=10; int idx=0; for(int i=0;i<=360;++i){ for(int j=0;j<=180;j++){ float c=r*cos(M_PI*j/180),a=r*sin(M_PI*j/180)*cos(M_PI*i/180),b=r*sin(M_PI*j/180)*sin(M_PI*i/180); vertex_buffer_data[idx++]=r*sin(M_PI*j/180)*cos(M_PI*(i+1)/180),vertex_buffer_data[idx++]=r*sin(M_PI*j/180)*sin(M_PI*(i+1)/180),vertex_buffer_data[idx++]=r*cos(M_PI*j/180); vertex_buffer_data[idx++]=a,vertex_buffer_data[idx++]=b,vertex_buffer_data[idx++]=c; k=j+1; c=r*cos(M_PI*k/180),a=r*sin(M_PI*k/180)*cos(M_PI*i/180),b=r*sin(M_PI*k/180)*sin(M_PI*i/180); vertex_buffer_data[idx++]=a,vertex_buffer_data[idx++]=b,vertex_buffer_data[idx++]=c; } } for(int i=0;i<=360;i++){ for(int j=0;j<=180;j++){ float c=r*cos(M_PI*(j+1)/180),a=r*sin(M_PI*(j+1)/180)*cos(M_PI*(i+1)/180),b=r*sin(M_PI*(j+1)/180)*sin(M_PI*(i+1)/180); vertex_buffer_data[idx++]=r*sin(M_PI*j/180)*cos(M_PI*(i+1)/180),vertex_buffer_data[idx++]=r*sin(M_PI*j/180)*sin(M_PI*(i+1)/180),vertex_buffer_data[idx++]=r*cos(M_PI*j/180); vertex_buffer_data[idx++]=a,vertex_buffer_data[idx++]=b,vertex_buffer_data[idx++]=c; k=j+1; c=r*cos(M_PI*k/180),a=r*sin(M_PI*k/180)*cos(M_PI*i/180),b=r*sin(M_PI*k/180)*sin(M_PI*i/180); vertex_buffer_data[idx++]=a,vertex_buffer_data[idx++]=b,vertex_buffer_data[idx++]=c; } } this->object = create3DObject(GL_TRIANGLES, 130682*3, vertex_buffer_data, color, GL_FILL); } void Island::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 2)); // No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); } bounding_box_t Island::bounding_box() { float x = this->position.x, y = this->position.y,z = this->position.z; bounding_box_t bbox = { x, y, z, 20,10,10}; return bbox; }
true
47c385c463e28019064967f0af5fbed86164b6da
C++
Derydoca/derydocaengine
/DerydocaEngine/src/Rendering/Renderer.h
UTF-8
843
2.59375
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include "Rendering\Display.h" #include "Timing\Clock.h" #include "Scenes\Scene.h" namespace DerydocaEngine::Rendering { class RendererImplementation { public: RendererImplementation(std::string title, int width, int height); virtual void init() = 0; virtual void renderFrame(const float deltaTime) = 0; std::shared_ptr<DerydocaEngine::Rendering::Display> getDisplay() { return m_display; } void render( const glm::mat4& projectionMatrix, const std::shared_ptr<Scenes::Scene> scene ); protected: std::shared_ptr<DerydocaEngine::Rendering::Display> m_display; }; class Renderer { public: Renderer(RendererImplementation& implementation); void init(); int runRenderLoop(); private: unsigned long m_minFrameTime; Timing::Clock m_clock; RendererImplementation& m_implementation; }; }
true
ea6cbf5b1c3b74ad0b0a34fc48238c75285061df
C++
benedicka/Competitive-Programming
/Gym/100030C/27078812_AC_92ms_3784kB.cpp
UTF-8
1,092
2.90625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define lld long long int const lld MOD = 1e9 + 7; int nCrModp(lld n, lld r, lld p) { // Optimization for the cases when r is large if (r > n - r) r = n - r; // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr lld C[r + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (lld i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); lld n,m; cin >> n >> m; if(m < n) { cout << 0 << '\n'; } else { cout << nCrModp(m,n,MOD) << '\n'; } return 0; }
true
01b0ac948f31d8d0a2cfca1690aeb9b714433ec4
C++
TheMarlboroMan/navigator
/class/app/interfaces/movil.h
UTF-8
1,448
3.015625
3
[]
no_license
#ifndef MOVIL_H #define MOVIL_H /*Modelo de cosa que se mueve en el espacio... En todo caso, esta es la base para el cálculo de movimiento y tiene algunas cosas de gravedad también. */ #include <herramientas/vector_2d/vector_2d.h> namespace App_Interfaces { class Movil { ////////////////////// // Definiciones... public: enum class t_vector {V_X=0, V_Y=1}; /////////////////////// // Interface pública. public: Movil(); virtual ~Movil(); const DLibH::Vector_2d_pantalla& acc_vector() const {return vector;} DLibH::Vector_2d_pantalla acc_vector() {return vector;} float acc_vector_x() {return vector.x;} float acc_vector_y() {return vector.y;} void accion_gravedad(float delta, float valor_gravedad=1.0f); //delta: tiempo que ha pasado, vector: referencia a la parte del vector, factor: cantidad de fuerza a aplicar al vector. float integrar_vector(float delta, float& vector, float factor); void sumar_vector(float, t_vector); void establecer_vector(float, t_vector); void establecer_vector(const DLibH::Vector_2d v) {vector=v;} float& ref_vector_x() {return vector.x;} float& ref_vector_y() {return vector.y;} /////////////////////// //A implementar. virtual float obtener_peso() const=0; virtual float obtener_max_velocidad_caida() const=0; ////////////////////// // Propiedades... private: DLibH::Vector_2d_pantalla vector; }; } #endif
true
9dc005c17483bdbed1e205c14316f3fa1fc4d9f3
C++
rajeevranjancom/Leetcode_Cpp
/047. Permutations II.cpp
UTF-8
589
3.015625
3
[ "MIT" ]
permissive
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>>res; DFS(res, nums, 0); return res; } void DFS(vector<vector<int>>& res, vector<int> nums, int pos){ if(pos == nums.size() - 1){ res.push_back(nums); return; } for(int i = pos; i < nums.size(); i++){ if(i != pos && nums[i] == nums[pos]) continue; swap(nums[pos], nums[i]); DFS(res, nums, pos + 1); } } };
true
614b0aa4583dcfb892a05ba24b83567854386bcf
C++
ninjalp/gtu-elec-433-631
/src/codes/w_05/boost_bind_examples_cpp/cpp/initial_boost_bind_test.cc
UTF-8
527
3.203125
3
[]
no_license
// Onder Suvak (C) 2020 #include <boost/config.hpp> #include <boost/bind.hpp> #include <iostream> #include <iomanip> void increment (int val, int & number) { number += val; } int main(void) { using namespace std; const int val = 5; int number = 10; auto fh = boost::bind( increment, val, _1 ); cout << "Number:" << setw(6) << number << endl; fh(number); cout << "Number:" << setw(6) << number << endl; fh(number); fh(number); cout << "Number:" << setw(6) << number << endl; return 0; }
true
75563acbb3286e19bc954aae0a2d6f46af82e4df
C++
ives560/EmbroiderApp
/widget.cpp
UTF-8
5,029
2.65625
3
[]
no_license
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); // this->showFullScreen(); CurSel=0; InitSelectArray(); InitWidgetsText(); SelPlugin(0); m_devThread=new DevicesThread(); ui->widget_7->m_devThread=m_devThread;//线程指针赋值 } Widget::~Widget() { delete m_devThread; delete ui; } //初始化花样装入窗口 void Widget::InitEnterForm() { EnterForm *enterForm; enterForm=new EnterForm(this); enterForm->show(); enterForm->move(0,50); enterForm->setFocus(); } //初始化参数设置窗口 void Widget::InitSetForm() { SetForm *setForm; setForm=new SetForm(this); setForm->show(); setForm->move(30,50); setForm->setFocus(); } //初始化手动移绷窗口 void Widget::InitHandForm() { HandForm *handForm; handForm=new HandForm(this); handForm->show(); handForm->move(160,50); handForm->setFocus(); } ////初始化系统测试窗口 void Widget::InitTestForm() { TestForm *testForm; testForm=new TestForm(this); testForm->show(); testForm->move(250,50); testForm->setFocus(); } ////初始化显示花样管理窗口 void Widget::InitManageForm() { ManageForm *manageForm; manageForm=new ManageForm(this); manageForm->show(); manageForm->move(0,50); manageForm->setFocus(); } //键盘按键单击事件 void Widget::keyPressEvent(QKeyEvent *k) { int c=-1; switch(k->key()) { case Qt::Key_1:c=0; break; case Qt::Key_2:c=1; break; case Qt::Key_3:c=2; break; case Qt::Key_4:c=3; break; case Qt::Key_5:c=4; break; case Qt::Key_6:c=5; break; case Qt::Key_Left: ArrowsSelPlugin(false); break; case Qt::Key_Right: ArrowsSelPlugin(true); break; case Qt::Key_Return: case Qt::Key_Enter: SetPromptText(CurSel); PressEnterKey(CurSel); break; case Qt::Key_Escape: break; default: QWidget::keyPressEvent(k); break; } if(c>0) { SelPlugin(c); SetPromptText(CurSel); PressEnterKey(CurSel); } } //按下回车键 void Widget::PressEnterKey(int sel) { switch(sel) { case 0: InitEnterForm(); break; case 1: InitSetForm(); break; case 2: InitHandForm(); break; case 3: InitTestForm(); break; case 4: InitManageForm(); break; case 5: this->close(); break; default: break; } } //初始化菜单项数组 void Widget::InitSelectArray() { SelectArray[0]=ui->widget; SelectArray[1]=ui->widget_2; SelectArray[2]=ui->widget_3; SelectArray[3]=ui->widget_4; SelectArray[4]=ui->widget_5; SelectArray[5]=ui->widget_6; } //初始化菜单项显示文字 void Widget::InitWidgetsText() { SelectArray[0]->label->setText(tr("1.花样装入")); SelectArray[1]->label->setText(tr("2.参数设定")); SelectArray[2]->label->setText(tr("3.手动移棚")); SelectArray[3]->label->setText(tr("4.系统测试")); SelectArray[4]->label->setText(tr("5.花样管理")); SelectArray[5]->label->setText(tr("6.退出")); //调整大小 for(int i=0;i<6;i++) { SelectArray[i]->AdjustPluginSize(); } } //菜单项提示信息字符串 void Widget::SetPromptText(int sel) { switch(sel) { case 0: ui->label_prompt->setText(tr("提示:输入花样的序号或按箭头键↑↓→←移动,按回车键确定选择,按ESC键退出。")); break; case 1: ui->label_prompt->setText(tr("提示:按数字键或按箭头键↑↓移动再按回车,选择要进行的操作,按ESC键返回。")); break; case 2: ui->label_prompt->setText(tr("提示:按箭头键↑↓→←移动,按F1键改变移动速度,按ESC键退出。")); break; case 3: ui->label_prompt->setText(tr("提示:开关各个传感器改变状态,按F1启动或停止主轴,F2或F3加减速主轴,ESC键退出。")); break; case 4: ui->label_prompt->setText(tr("提示:按数字键或按箭头键↑↓移动,再按回车键即可选择要进行的操作。")); break; case 5: ui->label_prompt->setText(tr("提示:退出。")); break; default: break; } } //改变选择新菜单项的颜色 void Widget::SelPlugin(int sel) { SelectArray[CurSel]->SelectFocusOut(QColor(0,0,0,0));//无色 CurSel=sel; SelectArray[CurSel]->SelectFocusIn(QColor(55,255,55));//绿色 } //菜单项选择移动方向 //true为向右移动 //false为向左移动 void Widget::ArrowsSelPlugin(bool UpDown) { int newSel=CurSel; if(UpDown==true)//Down { newSel++; if(newSel==6) newSel=0; SelPlugin(newSel); } else if(UpDown==false)//Up { newSel--; if(newSel==-1) newSel=5; SelPlugin(newSel); } }
true
1964d47e8ad8101152103e4dca3cd098dfde19db
C++
RtsAiResearch/IStrategizer
/src/IStrategizer/EntityClassExist.h
UTF-8
867
2.53125
3
[ "Apache-2.0" ]
permissive
///> [Serializable] #ifndef ENTITYCLASSEXIST_H #define ENTITYCLASSEXIST_H #include "ConditionEx.h" #include <vector> #include <map> namespace IStrategizer { ///> class=EntityClassExist ///> parent=ConditionEx class EntityClassExist : public ConditionEx { OBJECT_SERIALIZABLE_P(EntityClassExist, ConditionEx); public: EntityClassExist() {} EntityClassExist(PlayerType p_player); EntityClassExist(PlayerType p_player, EntityClassType p_unitClassId, ObjectStateType state = OBJSTATE_END, bool checkFree = false); EntityClassExist(PlayerType p_player, EntityClassType p_unitClassId, int p_amount, ObjectStateType state = OBJSTATE_END, bool checkFree = false); bool Evaluate(RtsGame& game); bool Consume(int p_amount); private: bool m_checkFree; }; } #endif // ENTITYCLASSEXIST_H
true
037e19f96a219f8dcdd534420e8cb0a090514325
C++
KrGolovin/SortsTypes
/BasicSorts.cpp
UTF-8
2,663
3.390625
3
[]
no_license
// // Created by Macbook Pro on 12.04.2020. // #include "BasicSorts.h" #include "List.h" #include <cmath> int countOfBitwise(int number) { if (number == 0) { return 1; } int count = 0; while (number > 0) { count++; number /= 10; } return count; } int getBitwise(int number, int k) { return ((number / (int)pow(10, k - 1)) % 10); } void copyArray(int * first, int * second, int size) { for (int i = 0; i < size; ++i) { first[i] = second[i]; } } void counterSort(int *array, int size) { if (array == nullptr) { throw "nullpointer excepted"; } if (size <= 0) { throw "Invalid size of array"; } int k = 0; for (int i = 0; i < size; ++i) { if (array[i] < 0) { throw "invalid value in array"; } k = (array[i] > k) ? array[i] : k; } int *c = new int[k + 1]; for (int i = 0; i < k + 1; ++i) { c[i] = 0; } for (int i = 0; i < size; ++i) { c[array[i]]++; } for (int i = 1; i < k + 1; ++i) { c[i] += c[i - 1]; } int j = 0; for (int i = 0; i < k + 1; ++i) { for (; j < c[i]; ++j) { array[j] = i; } } delete[] c; } void radixSort(int *array, int size) { if (array == nullptr) { throw "nullpointer excepted"; } if (size <= 0) { throw "Invalid size of array"; } int maxCountOfBitwise = 1; for (int i = 0; i < size; ++i) { if (array[i] < 0) { throw "invalid value in array"; } int currCount = countOfBitwise(array[i]); maxCountOfBitwise = (currCount > maxCountOfBitwise) ? currCount : maxCountOfBitwise; } for (int k = 1; k <= maxCountOfBitwise; ++k) { int c[10] = {0}; for (int i = 0; i < size; ++i) { c[getBitwise(array[i], k)]++; } int counter = 0; for (int i = 0; i < 10; ++i) { std::swap (counter, c[i]); counter += c[i]; } int * b = new int[size]; for (int i = 0; i < size; ++i) { int d = getBitwise(array[i], k); b[c[d]] = array[i]; c[d]++; } copyArray(array, b, size); delete[] b; } } void bucketSort(double * array, int size) { if (array == nullptr) { throw "nullpointer excepted"; } if (size <= 0) { throw "Invalid size of array"; } List<double> * b = new List<double>[size]; for (int i = 0; i < size; ++i) { if ((array[i] < 0) || (array[i] >= 1)) { throw "invalid value in array"; } b[(int)floor((array[i] * size))] += array[i]; } int counter = 0; for (int i = 0; i < size; ++i) { for (List<double>::Elem* curr = b[i].head_; curr != nullptr; curr = curr->getNext()) { array[counter] = curr->getValue(); counter++; } } delete[] b; }
true
70f41aab4f4e7082a453f363a1a3e739ff8b6dd3
C++
AvivDavid23/Interpreter_FlightGear
/Interpreter/Commands/CommandExpression.cpp
UTF-8
444
2.78125
3
[]
no_license
#include "CommandExpression.h" /** * * @return the command execution value. */ double CommandExpression::calculate() { command->execute(words); return 0; } CommandExpression::~CommandExpression() { delete this->command; } /** * @param command the command * @param words the array of orders. */ CommandExpression::CommandExpression(Command *command, const vector<string> &words) : command( command), words(words) {}
true
9bb58301b49141f7722de51afc65206c0aa78e56
C++
rockdonald2/studying
/schoolWork/AlgsAndDataStructures/Laborhazik/Projektek/hazi_3/feladat_9.cpp
UTF-8
2,515
3.265625
3
[]
no_license
// // 9. Feladat forráskódja // /* Hallgató neve: Lukács Zsolt Csoport: 1. csoport Feladat sorszáma: 9. */ using ll = long long; #include <iostream> #include <fstream> #include <cmath> #include <algorithm> ll orosz_szorzas(const ll &szam1, const ll &szam2); int main() { /* ALGORITMUS LEÍRÁSA * Be szam1, szam2 - beolvassuk a vizsgált számokat, amelyek összeszorzunk * Lehív orosz_szorzas(szam1, szam2), ahol: * - mindig az lesz az első paraméterje a rekurzív függvénynek, amelynek az értéke kisebb, * így biztosítjuk, hogy a legkevesebb lépésszám kelljen az eredményhez való eljutáshoz * - a rekurzív függvényen belül, az 1-vel való egyenlőség a megállási feltétel, * amíg eljutunk 1-ig mindig a kisebbik számot osszuk kettővel, míg a nagyobbat szorozzuk kettővel; * - az orosz szorzási módszer szerint a páratlan szam2 értékekek összege képezi a szorzás eredményét, * így csak azokat adjuk hozzá az eredményhez; * Kiír szorzási eredmény * */ std::ifstream bemeneti_all("be_9.txt"); ll szam1; ll szam2; if (bemeneti_all.is_open()) { bemeneti_all >> szam1 >> szam2; } else { std::cout << "Nem sikerult a bemeneti allomany megnyitasa. \nEllenorizd le a bemeneti allomany eleresi utvonalat.\n"; } bemeneti_all.close(); std::ofstream kimeneti_all("ki_9.txt"); // mindig a szam1 kell a kisebbik paraméter legyen, biztosítva a minimális ismétlésszámot az eredményhez való eljutáshoz if (szam1 > szam2) { std::swap(szam1, szam2); } if (kimeneti_all.is_open()) { kimeneti_all << orosz_szorzas(szam1, szam2); } else { std::cout << "Nem sikerult a kimeneti allomany megnyitasa. \nEllenorizd le a kimeneti allomany eleresi utvonalat.\n"; } kimeneti_all.close(); return 0; } ll orosz_szorzas(const ll &szam1, const ll &szam2) { // a megállási feltételünk az 1-el való egyenlőség if (szam1 == 1) { return szam2; } else if (szam1 % 2) { // amennyiben a jelenlegi szam1 szám páratlan, akkor az aktuális szam2 szám az eredmény részét fogja képezni return szam2 + orosz_szorzas(std::floor(szam1 / 2), szam2 * 2); } // ha a jelenlegi szam1 szám páros, akkor a szam2 paraméter értéke az eredmény részét nem képezi return orosz_szorzas(std::floor(szam1 / 2), szam2 * 2); }
true
cc01d33da48e8a3f6fd29f59405b32ebc6fb6262
C++
smarrog/smr-library-cpp
/src/commands/commandErrors.hpp
UTF-8
712
2.65625
3
[]
no_license
#pragma once #include "commandError.hpp" #include <vector> #include <functional> namespace smr { class CommandErrors { public: using Handler = std::function<void(const CommandError&)>; void addError(std::string message); void addError(std::string message, Handler handler); void addErrors(const CommandErrors& errors); void callHandlers() const; void reset(); bool hasUnhandledError() const { return !_unhandledErrors.empty(); } bool hasError() const { return !_unhandledErrors.empty() || !_handledErrors.empty(); } std::string getMessage() const; private: std::vector<CommandError> _unhandledErrors; std::vector<std::pair<CommandError, Handler>> _handledErrors; }; }
true
9c03936fd013ca6d17241e08928303c9822e2546
C++
0x00-pl/lispl
/lispl/parse.h
GB18030
4,294
2.6875
3
[]
no_license
#pragma once #include<iostream> #include<sstream> #include<limits> #include"base.h" using namespace std; std::string trim(std::string& str) { str.erase(0, str.find_first_not_of(' ')); //prefixing spaces str.erase(str.find_last_not_of(' ')+1); //surfixing spaces return str; } void pick_space(string& str){ str.erase(str.find_last_not_of(' ')+1); } string first_term(const string& str){ size_t min_index= str.find_first_of(' '); min_index= min(min_index, str.find_first_of(')')); min_index= min(min_index, str.find_first_of('}')); min_index= min(min_index, str.find_first_of('>')); return str.substr(0, min_index); } node* make_quote(shared_ptr<node> val){ list* ret= new list(); ret->sub.push_back(new quote()); ret->sub.push_back(val); return ret; } //(lambda[add 1 &1]) inc //(lambda(list 'lambda (list 'add &1 '&1))) addn //(lambda{lambda ,{add &1 ,&1}}) { ==> (list //(lambda[lambda[add &1 &&1]]) addn //{add &1 1} inc //{'{add <0,1> <1,1>}} addn //(lambda [n] '{[lambda[a b][+ a b]] &1 &n}) addn //symbolԶquote //[]ȼ'() //{}ȼ(lambda ... ) namespace parser_pl_origin{ class parser{ public: virtual~parser(){} virtual bool test(string&){return false;} virtual shared_ptr<node>get_node(string&){return nil;} }; class parser_manager{ public: static parser_manager ins; shared_ptr<node> parse(string& s){ trim(s); if(s.empty()) return nil; for(size_t i=0; i<parser_list.size(); ++i){ if(parser_list[i]->test(s)){ return parser_list[i]->get_node(s); } } return nil; } vector<parser*> parser_list; }; parser_manager parser_manager::ins; class parser_list: public parser{ public: virtual bool test(string& s){ return s[0]=='('; } virtual shared_ptr<node>get_node(string& s){ shared_ptr<list> ret= new list(); s=s.substr(1);//'(' while(s[0]!=')'){ ret->add(parser_manager::ins.parse(s)); } s=s.substr(1);//')' s=trim(s); return ret; } }; class parser_quote: public parser{ public: virtual bool test(string& s){ return s[0]=='\''; } virtual shared_ptr<node>get_node(string& s){ shared_ptr<list> ret= new list(); s=s.substr(1);//''' ret->add(new quote()); ret->add(parser_manager::ins.parse(s)); return ret; } }; template<typename T> class parser_func: public parser{ public: parser_func(string _name){name=_name;} virtual bool test(string& s){ return name==first_term(s); } virtual shared_ptr<node>get_node(string& s){ size_t tl= first_term(s).length(); s= s.substr(tl); s= trim(s); return make_quote(new T()); } string name; }; template<typename T> class parser_type: public parser{ public: virtual bool test(string& s){ stringstream ss; ss<<first_term(s); T f; ss.clear(); ss>>f; return !ss.fail(); } virtual shared_ptr<node>get_node(string& s){ string sft=first_term(s); stringstream ss; ss<<sft; T val; ss>>val; size_t tl= sft.length(); s= s.substr(tl); s= trim(s); return make_quote(new lispl_type<T>(val)); } }; //<lvl,index> class parser_symbol: public parser{ public: virtual bool test(string& s){ return s[0]=='<'; } virtual shared_ptr<node>get_node(string& s){ string symbol_text= s.substr(0, s.find_first_of('>')+1); s= s.substr(symbol_text.length()); s= trim(s); stringstream ss; ss<<symbol_text; char c; int lvl,offset; //<int,int> ss>>c>>lvl>>c>>offset; if(ss.fail()){return nil;} return new symbol(lvl,offset); } }; //{exp} //('lambda '() '(exp)) class parser_lambda_shortcut: public parser{ public: virtual bool test(string& s){ return s[0]=='{'; } virtual shared_ptr<node>get_node(string& s){ shared_ptr<list> ret= new list(); ret->add(make_quote(new make_lambda())); ret->add(make_quote(nil)); s=s.substr(1);//'{' shared_ptr<list> exp= new list(); while(s[0]!='}'){ exp->add(parser_manager::ins.parse(s)); } ret->add(make_quote(exp)); s=s.substr(1);//'}' pick_space(s); return ret; } }; }
true
901eae728ca78dd711515bf33822e09b1f989f24
C++
TanyaZheleva/Uni-CPP
/Database/ColumnTest/unittest1.cpp
UTF-8
743
2.953125
3
[]
no_license
#include "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; #include "../Project3/Column.h" namespace ColumnTest { TEST_CLASS(UnitTest1) { public: TEST_METHOD(AddCell) { Column a(0, "cost", Double, 0); std::string pi = "3.14"; a.AddCell(pi); Assert::AreEqual(a.GetCellValue(0), pi); } TEST_METHOD(SetCell) { Column a(0, "cost", Double, 0); std::string pi = "3.14", null = "0"; a.AddCell(pi); a.SetCellValue(0, null); Assert::AreEqual(a.GetCellValue(0), null); } TEST_METHOD(ParseToString) { Column a(0, "cost", Double, 0); std::string tmp; a.ConvertToString(tmp); std::string expectedResult = "D cost\n-----"; } }; }
true
e1d26ae5dd818a7cb31c6491fc01ec0f2647ec3b
C++
tom3097/EiTI-Projects
/PROI/Zbiory/zbior.cpp
UTF-8
5,913
3.359375
3
[]
no_license
//Projekt nr 2: klasa reprezentujaca zbior macierzy 3x3 typu float //Przygotowal: Tomasz Bochenski #include "zbior.h" #define POKAZ_KOMUNIKATY_ZBIORY false //ustawienie poczatkowej liczby obiektow na 0 int zbior::ilosc_obiektow = 0; //konstruktor domyslny zbior::zbior() { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono konstruktor domyslny klasy ZBIOR.\n"; ilosc_obiektow++; liczba_elementow_zbioru = 0; poczatek = NULL; } //konstruktor kopiujacy zbior::zbior(const zbior &obiekt) { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono konstruktor kopiujacy klasy ZBIOR.\n"; ilosc_obiektow++; liczba_elementow_zbioru = 0; poczatek = NULL; element *tmp = obiekt.poczatek; while(tmp != NULL) { //bo wiemy ze elementy w zbiorze ktory "kopiujemy" nie powtarzaja sie dodaj_element_bezwarunkowo(tmp->macierz_float); tmp= tmp->nastepny; } } //bezwarunkowe dodawanie elementu void zbior::dodaj_element_bezwarunkowo(const Macierze_3x3<float> &macierz) { liczba_elementow_zbioru++; element *aktualny = new element; aktualny->macierz_float = macierz; aktualny->nastepny = NULL; if(poczatek == NULL) poczatek = aktualny; else { element *tmp = poczatek; while(tmp->nastepny!= NULL) tmp = tmp->nastepny; tmp->nastepny = aktualny; } } //warunkowe dodawanie elementu void zbior::dodaj_element_warunkowo(const Macierze_3x3<float> &macierz) { //gdy podanej macierzy nie ma w zbiorze wywolujemy funkcje dodaj_element_bezwarunkowo //w przeciwnym przypadku macierz nie jest dodawana if(czy_istnieje(macierz) == false) dodaj_element_bezwarunkowo(macierz); } //usuwanie elementu void zbior::usun_element(int numer_macierzy) { //gdy podany numer macierzy jest bledny usuwanie nie zostanie wykonane if(numer_macierzy > liczba_elementow_zbioru || numer_macierzy<1) return; //znajdywanie i usuwanie wybranego elementu liczba_elementow_zbioru--; element *to_kill = poczatek; element *poprzedni; for(int i=1; i<numer_macierzy; i++) { poprzedni = to_kill; to_kill = to_kill->nastepny; } if(to_kill == poczatek) { poczatek = poczatek->nastepny; delete to_kill; } else { poprzedni->nastepny = to_kill->nastepny; delete to_kill; } } bool zbior::czy_istnieje(const Macierze_3x3<float> &macierz)const { bool wynik = false; element *tmp = poczatek; while(tmp != NULL) { if(macierz == tmp->macierz_float) { wynik = true; break; } tmp = tmp->nastepny; } return wynik; } //destruktor zbior::~zbior() { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono destruktor klasy ZBIOR.\n"; ilosc_obiektow--; element *tmp, *to_kill; to_kill = poczatek; //usuwanie alokowanych dynamicznie elementow zbioru while(to_kill != NULL) { tmp = to_kill->nastepny; delete to_kill; to_kill = tmp; } } //przeciazenie operatora = zbior & zbior::operator=(const zbior &obiekt) { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono metode kopiowania zbioru.\n"; //gdy chcemy przypisac obiektowi zbior jego samego if(this == &obiekt) return *this; //usuwanie dotychczasowych elementow element *tmp, *to_kill; to_kill = poczatek; while(to_kill != NULL) { tmp = to_kill->nastepny; delete to_kill; to_kill = tmp; } //dodawanie nowych elementow poczatek = NULL; liczba_elementow_zbioru = 0; tmp = obiekt.poczatek; while(tmp != NULL) { dodaj_element_bezwarunkowo(tmp->macierz_float); tmp= tmp->nastepny; } return *this; } //przeciazenie operatora drukowania ostream& operator << (ostream &wyjscie, const zbior &obiekt) { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono metode drukujaca zawartosc zbioru.\n"; zbior::element * tmp = obiekt.poczatek; if(tmp == NULL) wyjscie<<"Zbior jest pusty.\n"; else { int numer = 1; while(tmp != NULL) { wyjscie<<"Macierz numer:"<<numer<<endl; wyjscie<<tmp->macierz_float<<endl; tmp = tmp->nastepny; numer++; } } return wyjscie; } //przeciazenie operatora porownania bool zbior::operator==(const zbior &obiekt)const { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono metode porownujaca zbiory.\n"; //jesli zbiory maja rozna liczbe elementow to nie sa rowne if(liczba_elementow_zbioru != obiekt.liczba_elementow_zbioru) return false; element *tmp = obiekt.poczatek; while(tmp != NULL) { //jesli zbiory maja taka sama liczbe elementow //i dla kazdej macierzy ze zbioru A istnieje identyczna w zbiorze B to zbiory te sa rowne if(czy_istnieje(tmp->macierz_float) == false) return false; tmp = tmp->nastepny; } return true; } //przeciazenie operatora nierownosci bool zbior::operator!=(const zbior &obiekt)const { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono metode porownujaca zbiory.\n"; //zwraca zanegowana wartosc zwrocona przez operator == return !(*this == obiekt); } //przeciazenie operatora dodawania (suma zbiorow) zbior zbior::operator+(const zbior &obiekt)const { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono metode obliczajaca sume zbiorow.\n"; zbior wynik; //przypisuje jeden z sumowanych zbiorow zbiorowi wynik wynik = *this; element *tmp = obiekt.poczatek; while(tmp != NULL) { //dodaje do zbioru wynik kolejne elementy (macierze) pod warunkiem ze jeszcze ich tam nie ma wynik.dodaj_element_warunkowo(tmp->macierz_float); tmp= tmp->nastepny; } return wynik; } //przeciazenie operatora mnozenia (iloczyn zbiorow) zbior zbior::operator*(const zbior &obiekt)const { if(POKAZ_KOMUNIKATY_ZBIORY == true) cout<<"Uruchomiono metode obliczajaca iloczyn zbiorow.\n"; zbior wynik; element *tmp = obiekt.poczatek; //przeglada kazdy element ze zbioru B i sprawdza czy identyczny istnieje w zbiorze A //gdy element istnieje zarowno w A i B, jest on dodawany bezwarunkowo do obiektu wynik while(tmp != NULL) { if(czy_istnieje(tmp->macierz_float) == true) wynik.dodaj_element_bezwarunkowo(tmp->macierz_float); tmp = tmp->nastepny; } return wynik; }
true
dbad76c841f6ef13253c22f974ce607ff7b38b68
C++
A01351361/Proyecto-Simulacion-Beisbol
/simulacion.h
UTF-8
5,670
3.421875
3
[]
no_license
#ifndef SIMULACION_H //Definir clase #define SIMULACION_H #ifdef _WIN32 #include <Windows.h> //Para PAUSAS #else #include <unistd.h> #endif #include <cstdlib> #include <string> #include <iostream> #include <sstream> #include <stdlib.h> #include <time.h> #include "jugadores.h" //Biblioteca con mis objetos a usar que en este caso es Jugadores #include <stdio.h> #include <random> //Biblioteca para crear numeros aleatorios.. using namespace std; class Simulacion { private: //Declaración de variables int hits; float totalhits; int totalcarreras; float totalhitsv; int totalcarrerasv; public: //Declaración de constructor y metodos Simulacion(): hits(0), totalhits(0), totalcarreras(0), totalhitsv(0), totalcarrerasv(0){};; Simulacion(int h, float th, int tc,float thl, int tcl){ hits = h; totalhits = thl; totalcarreras = tcl; totalhits = th; totalcarreras = tc; } //Construcutor int getHits(){return hits;} int getTotalHits(){return totalhits;} int crea_jugada_local(float &totalhitsl, int &totalcarrerasl); int crea_jugada_visitante(float &totalhits, int &totalcarreras); }; /** * int crea_jugada_visitante crea una jugada aleatoria hit o out de manera randomizada para el visitante. * * random_device crea un numero, uniform_int_distribution un numero entero en el cual 1,5 significa que me lo creara del numero 1 al 5, el ciclo for es para cuando la entrada ya tenga 3 outs entonces salga del ciclo. El if dentro del for es para determinar la jugada dependiendo del numero aleatorio otorgado para un 20% de hit y 80% de out donde se van sumando los hits y las carreras. * * @param ´"totalhits" debe ser float para estadisticas y "totalcarreras" int para la suma por equipo. * @return TotalHits y totalcarreras en el main y se guarda en una variable para la suma final. */ int Simulacion::crea_jugada_visitante(float &totalhits, int &totalcarreras){ random_device rd; //Genero un numero aleatorio de 1 a 5 mt19937 mt(rd()); uniform_int_distribution<int> dist(1, 5); //Rango 1 a 5 int hits =0; int carreras = 0; for (int i=0; i < 3;){ //Funcion for en la cual va de 0 a 3 que quiere decir que hubo 3 outs en la funcion. La funcion consiste en que se genera un numero aleatorio y dependiendo del numero que sera de 1 a 5 se inicializa un if para determinar que jugada fue. sleep(1); if (dist(mt) == 1 ){ hits++; cout << "jugada = Hit" << endl<< endl; ;} else if (dist(mt) == 2 ||dist(mt) == 3 || dist(mt) == 4 || dist(mt) == 5) { cout << "jugada = Out" << endl<< endl;; i++;} } totalhits = hits; if (hits > 2){ // Si hits es mayor a 2 se inicializa esta funcion en la cual la variable carreras es igual a los hits totales del equipo en esa entrada menos 2 ya que si hay 2 hits quiere decir que en las bases se encuentra uno en primera base y otro en segunda base. La probabilidad que si hay otro hit el de 2da base anote. Entonces carreras se iguala a Hits -2. int carreras(0); carreras = hits - 2; cout << "Carreras Anotadas: " << carreras << endl; totalcarreras = carreras;} else { cout << "No hubo carreras anotadas" << endl;} cout << "Hits Totales: " << totalhits <<endl ; sleep(1); return(totalcarreras); } /** * int crea_jugada_local crea una jugada aleatoria hit o out de manera randomizada para el local. * * random_device crea un numero, uniform_int_distribution un numero entero en el cual 1,5 significa que me lo creara del numero 1 al 5, el ciclo for es para cuando la entrada ya tenga 3 outs entonces salga del ciclo. El if dentro del for es para determinar la jugada dependiendo del numero aleatorio otorgado para un 20% de hit y 80% de out donde se van sumando los hits y las carreras. * * @param ´"totalhits" debe ser float para estadisticas y "totalcarreras" int para la suma por equipo. * @return TotalHits y totalcarreras en el main y se guarda en una variable para la suma final. */ int Simulacion::crea_jugada_local(float &totalhitsl, int &totalcarrerasl){ random_device rd; //Genero un numero aleatorio de 1 a 5 mt19937 mt(rd()); uniform_int_distribution<int> dist(1, 5); //Rango 1 a 5 int hitsl =0; int carrerasl = 0; for (int i=0; i < 3;){ //Funcion for en la cual va de 0 a 3 que quiere decir que hubo 3 outs en la funcion. La funcion consiste en que se genera un numero aleatorio y dependiendo del numero que sera de 1 a 5 se inicializa un if para determinar que jugada fue. sleep(1); if (dist(mt) == 1 ){ hitsl++; cout << "jugada = Hit" << endl<< endl; ;} else if (dist(mt) == 2 ||dist(mt) == 3 || dist(mt) == 4 || dist(mt) == 5) { cout << "jugada = Out" << endl<< endl;; i++;} } totalhitsl = hitsl; if (hitsl > 2){// Si hits es mayor a 2 se inicializa esta funcion en la cual la variable carreras es igual a los hits totales del equipo en esa entrada menos 2 ya que si hay 2 hits quiere decir que en las bases se encuentra uno en primera base y otro en segunda base. La probabilidad que si hay otro hit el de 2da base anote. Entonces carreras se iguala a Hits -2. int carrerasl(0); carrerasl = hitsl - 2; cout << "Carreras Anotadas: " << carrerasl << endl; totalcarrerasl = carrerasl;} else { cout << "No hubo carreras anotadas" << endl;} cout << "Hits Totales: " << totalhitsl <<endl ; sleep(1); return(totalcarrerasl); } #endif
true
66dcf7147f7b103430694dd8be84b353a2cfe9a2
C++
SYSUcarey/Survivor_Island
/code/Classes/Monster.h
GB18030
2,187
2.625
3
[]
no_license
#pragma once #include "cocos2d.h" #include "GlobalVar.h" using namespace cocos2d; class MonsterFactory :public cocos2d::Ref { public: //ȡ static MonsterFactory* getInstance(); //һС洢й Sprite* createSmallMonster(); //һ洢й Sprite* createBigMonster(); //ɴֵӵ Sprite* createMonsterBullet(); //жijܷijƶ bool CanMove(Sprite* mons, Vec2 dir); //ейﶼɫƶͨеĹܷ void moveMonster(Vec2 playerPos1, Vec2 playerPos2, float time); //ɫǷڹ﹥Χ void checkAttacker(Vec2 playerPos1, Vec2 playerPos2); //ijԹķλ std::string getDirection(Vec2 dir); // ǹ void hitByPistol(Sprite* mons); // uzi void hitByUzi(Sprite* mons); // void hitByShotGun(Sprite* mons); // ׻ void hitByGrenade(Sprite* mons); // void hitByMissile(Sprite* mons); // void hitByLaserGun(Sprite* mons); //Ƴ void removeMonster(Sprite*); //жײ Sprite* collider(Rect rect); //ʼ֡ void initSpriteFrame(); //ȡijλڵͼе Point getPositionInMap(Point); //õ Vector<Sprite*> getMonster(); Vector<Sprite*> getAttacker1(); Vector<Sprite*> getAttacker2(); Vector<Sprite*> getMonsterBullet(); vector<bool> getIsDone(); void wasHit(Sprite * mons, int type); void setIsDone(int index, bool isdone); void removeMonsterBullet(Sprite * bullet); void clear(); void clearAttacker1(); void clearAttacker2(); private: MonsterFactory(); Vector<Sprite*> monster; Vector<Sprite*> attacker1; Vector<Sprite*> attacker2; Vector<Sprite*> monsterBullet; vector<int> monsterHP; vector<bool> isDone; cocos2d::Vector<SpriteFrame*> monsterDead; static MonsterFactory* factory; std::string Direction[8] = { "West", "NorthWest", "North", "NorthEast", "East", "SouthEast", "South", "SouthWest" }; cocos2d::TMXTiledMap *tileMap; cocos2d::TMXLayer *blockage; };
true
d332647b1f3e58f60826542d32d10ebd4ee3f8b9
C++
niteshcse14/geeksforgeeks
/Find_all_distinct_palindromic_sub_strings_of_a_given_string.cpp
UTF-8
412
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int arr[26]; int main(){ int t; char str[100000]; scanf("%d", &t); while(t--){ scanf("%s", str); memset(arr, 0, sizeof(arr)); int n = strlen(str); for(int i = 0; i < n; ++i){ arr[str[i] - 'a']++; } int sum = 0; for(int i = 0; i < 26; ++i){ sum += (arr[i] > 0) ? (int)pow(2, arr[i] - 1): 0; } printf("%d\n", sum); } return 0; }
true
b4187fd77dd197be479588c7c67e2e705e8ed163
C++
RajeshChilagani/CPPVS2019
/CPPVS2019/Main.h
UTF-8
6,466
3.09375
3
[]
no_license
#pragma once #include "C++/Inheritance.h" #include "Helpers.h" #include "C++/InterestingLearnings.h" #include "C++/String.h" #include "C++/Templates.h" #include "C++/DataStructures.h" void Templates_Main(); void Inheritance_Main(); /*Test Class for Implicit calls*/ class Float { int m_Data; float m_Data1; public: //Float() {} //No initialization in vs 2019 compiler also notifies it - this might not be helpful //Float() = default; Float(int a) :m_Data(a), m_Data1(1.0f) {} //weird but a way to use initializer list Float(const std::initializer_list<int> l) { m_Data = *(l.begin()); m_Data1 = *(l.begin() + 1); } operator float() { return m_Data1; } //operator int*() { return &m_Data; } bool operator==(const Float& i_Rhs) const { std::cout << "Overload Equal" << std::endl; return m_Data == i_Rhs.m_Data && m_Data1 == i_Rhs.m_Data1; } void operator()() //Overload of () operator can be customized as you wish (any no of params/no params) { std::cout << "Overload () operator for Float" << std::endl; } }; class BigFloat { public: //BigFloat() = default; BigFloat() :m_Data(12) { std::cout << "Constructor" << std::endl; } //Dirrect List Initialisation sets the values passed/ sets to default if nothing is passed //BigFloat(Float i_Data) :m_Data(i_Data) {} void Print() { std::cout << "Print IN BigFloat" << std::endl; } ~BigFloat() { std::cout << "BigFloat Destructot" << std::endl; } private: Float m_Data = Float(1); }; /**/ template<typename T> void ForTemp(T&& input) { std::cout << input; } /*Forwarding & template argument deduction*/ void PrintAllIntF(BigFloat&& i1) { i1.Print(); } void PrintAllIntF(int i1) { std::cout << i1; } template<typename... T> void PrintAll(T&&... args) { std::cout << std::is_lvalue_reference<T...>::value << std::endl; std::cout << std::is_rvalue_reference<T...>::value << std::endl; PrintAllIntF(std::forward<T>(args)...); } #define CreateFuncByName(name) void has##name(){std::cout<<"NewFunc From Macro";} CreateFuncByName(Hurrah) template<typename T> void TestF(T value) {} /**/ struct Vertex { float x = 0.0f, y = 0.0f, z = 0.0f; Vertex() = default; ~Vertex() { std::cout << "Destructor Vertex" << std::endl; } Vertex& operator++() { ++x; ++y; ++z; return *this; } Vertex(float i_x, float i_y, float i_z) {} }; struct TestSize { //Vertex m_Vertex; BigFloat m_BigFloat; }; std::ostream& operator<<(std::ostream& os, const Vertex& Vertex) { os << Vertex.x << ',' << Vertex.y << ',' << Vertex.z; return os; } class Tests { public: struct Itr { int a; }itr; }; namespace { extern float FMain; } constexpr float Result(float i_A, float i_B) { return i_A * i_B; } class Comparator { public: static bool Compare(int a, int b) { return a == b; } static bool Compare(std::string a, std::string b) { return a == b; } static bool Compare(const std::vector<int>& a, const std::vector<int>& b) { if (a.size() != b.size()) return false; return a == b; } }; struct Ftest { int a; float b; /*Ftest(int i_a):a(i_a) { b = i_a; this->a += i_a; std::cout << "Constructor" << std::endl; }*/ }; struct Point { float x, y; }; template<typename T> void PrintTemplate(const T& value) { std::cout << value << std::endl; } template<typename... Args> void Fin(const Args&... mArgs) { int a[] = { 0,(PrintTemplate(mArgs),0)... }; } bool IsStringNUmeric(const std::string& String) { if (String[String.size() - 1] == '-') return false; bool isNegativeFound = false; for (auto c : String) { if (c == '-') { isNegativeFound = true; continue; } if (c >= 48 && c <= 58) { if (isNegativeFound) { if (c == 48) { return false; } isNegativeFound = false; } } else { return false; } } return true; } class Camera { public: float FOV; float GetFOV() const { return FOV; } void SetFOV(float i_FOV) { FOV = i_FOV; } }; class tes { public: bool operator<(Camera* value) { return true; } }; void OldMain() { void* Null = nullptr; Camera C1; if (Null < &C1) { std::cout << "Test"; } std::cout << typeid(&C1).name() << std::endl; auto Fn = std::bind(&Camera::SetFOV, &C1, std::placeholders::_1); Fn(1.f, 4, 6, 78); std::cout << IsStringNUmeric("012392-"); Fin(1, "test"); float f1 = 1; int* ii1 = (int*)(&f1); std::cout << *ii1; Ftest AF{}; std::cout << Result(2, 3); float Left, Right; std::cin >> Left >> Right; std::cout << Result(Left, Right); int data = 4; const auto tes = [data] { int MF = 35; return MF; }(); //std::cout << FMain; BigFloat bf; Vertex V; { TestSize T; //Constructors of members are callled in the order of declaration and destructoers are called in reverse order of declaration } std::vector<Vertex> Vertices(2); std::vector<Vertex>::iterator it = Vertices.begin(); Vertices.push_back(V); it = Vertices.begin(); std::cout << 1 << ','; { Vector<String> vStrs; vStrs.PushBack(String("test1")); vStrs.Emplace_Back("test2"); } TestF(1); int i1 = 2; PrintAll(2); std::function<void()> fStd = [=]() { std::cout << "This is a Lambda" << i1; }; Float&& fVarRef = { 1 }; Float* ptr = &fVarRef; ForTemp(fVarRef); std::vector<int> IntVector{ 1,2,3 }; Derived* d1 = new Derived("d1"); Base* b1 = new Base(); Derived* d2 = (Derived*)b1; d2->PrintDer(); //illegal because base is not derived and might not contain func of derived //std::cout<<d2->m_Array[0]; int row = 2, col = 2; int* rows = (int*)malloc(sizeof(int) * col); int** mat = (int**)malloc(sizeof(size_t) * row); for (int i = 0; i < row; ++i) { mat[i] = rows + i; } for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { mat[i][j] = 2; std::cout << mat[i][j]; } std::cout << std::endl; } free(mat); const int size = 2; int array[size]; const Array<int, 5> Ints; Ints[3]; Base* tB = new Derived("Tes"); tB->callPrivate(); Derived Dd("sdsd"); Dd.callPrivate(); DerivedDerived obj; obj.Print(); Base* b = &obj; b->PrintInt(1); Derived* D = new Derived("Killua"); Test test(23); std::function<void(const Derived&)> f = test.Bind(); f(*D); BindExampleTest(test.Bind()); String Test("etsts"); Inheritance_Main(); Templates_Main(); Generic<int>A(1); A.PrintSize(); Generic<float>B(1.0f); A += B; std::cout << A; }
true
932b9639815e61e6155927562ea6d7a9db2df4f6
C++
Flakebi/tox4j
/projects/tox4j/src/main/cpp/tox4j/ToxInstances.h
UTF-8
6,270
2.71875
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include "util/instance_manager.h" #include "util/pp_cat.h" /***************************************************************************** * Identity and unused-value function. */ static auto const identity = [](auto v) { return v; }; template<typename T> static inline void unused (T const &) { } /***************************************************************************** * Error handling code. */ struct ErrorHandling { enum Result { UNHANDLED, SUCCESS, FAILURE }; Result const result; char const *const error; }; static inline ErrorHandling success () { return ErrorHandling { ErrorHandling::SUCCESS, nullptr }; } static inline ErrorHandling failure (char const *error) { return ErrorHandling { ErrorHandling::FAILURE, error }; } static inline ErrorHandling unhandled () { return ErrorHandling { ErrorHandling::UNHANDLED, nullptr }; } template<typename ErrorT> ErrorHandling handle_error_enum (ErrorT error); /***************************************************************************** * Find Tox error code (last parameter). */ template<typename FuncT> struct error_type_of; template<typename Result, typename Head, typename... Tail> struct error_type_of<Result (*) (Head, Tail...)> { typedef typename error_type_of<Result (*) (Tail...)>::type type; }; template<typename Result, typename ErrorCode> struct error_type_of<Result (*) (ErrorCode *)> { typedef ErrorCode type; }; template<typename FuncT> using tox_error_t = typename error_type_of<FuncT>::type; #define ERROR_CODE(METHOD) \ PP_CAT (SUBSYSTEM, _ERR_##METHOD) #define success_case(METHOD) \ case PP_CAT (ERROR_CODE (METHOD), _OK): \ return success() #define failure_case(METHOD, ERROR) \ case PP_CAT (ERROR_CODE (METHOD), _##ERROR): \ return failure (#ERROR) #define HANDLE(NAME, METHOD) \ template<> \ extern char const *const method_name<ERROR_CODE (METHOD)> = NAME; \ \ template<> \ ErrorHandling \ handle_error_enum<ERROR_CODE (METHOD)> (ERROR_CODE (METHOD) error) /** * Package name inside im.tox.tox4j (av or core) in which the subsystem * classes live. */ template<typename Subsystem> extern char const *const module_name; template<typename Subsystem> extern char const *const exn_prefix; template<typename ErrorCode> extern char const *const method_name; template<typename Object, typename ErrorType> void throw_tox_exception (JNIEnv *env, char const *error) { return throw_tox_exception (env, module_name<Object>, exn_prefix<Object>, method_name<ErrorType>, error); } template<typename Object, typename ErrorType> void throw_tox_exception (JNIEnv *env, ErrorType error) { ErrorHandling result = handle_error_enum<ErrorType> (error); switch (result.result) { case ErrorHandling::FAILURE: return throw_tox_exception<Object, ErrorType> (env, result.error); case ErrorHandling::SUCCESS: return throw_illegal_state_exception (env, error, "Throwing OK code"); case ErrorHandling::UNHANDLED: return throw_illegal_state_exception (env, error, "Unknown error code"); } } template<typename Object, typename SuccessFunc, typename ToxFunc, typename ...Args> auto with_error_handling (JNIEnv *env, SuccessFunc success_func, ToxFunc tox_func, Args ...args) { using error_type = tox_error_t<ToxFunc>; using result_type = typename std::result_of< SuccessFunc ( typename std::result_of< ToxFunc (Args..., error_type *) >::type )>::type; error_type error; auto value = tox_func (args..., &error); ErrorHandling result = handle_error_enum<error_type> (error); switch (result.result) { case ErrorHandling::SUCCESS: return success_func (std::move (value)); case ErrorHandling::FAILURE: throw_tox_exception<Object, error_type> (env, result.error); break; case ErrorHandling::UNHANDLED: throw_illegal_state_exception (env, error, "Unknown error code"); break; } return result_type (); } template<typename ObjectP, typename EventsP> struct ToxInstances : instance_manager<ObjectP, EventsP> { typedef typename instance_manager<ObjectP, EventsP>::Object Object; typedef typename instance_manager<ObjectP, EventsP>::Events Events; template<typename SuccessFunc, typename ToxFunc, typename ...Args> auto with_error_handling (JNIEnv *env, SuccessFunc success_func, ToxFunc tox_func, Args ...args) { return ::with_error_handling<Object> (env, success_func, tox_func, args...); } template<typename SuccessFunc, typename ToxFunc, typename ...Args> auto with_instance_err (JNIEnv *env, jint instanceNumber, SuccessFunc success_func, ToxFunc tox_func, Args ...args) { return this->with_instance (env, instanceNumber, [=] (Object *tox, Events &events) { unused (events); return with_error_handling (env, success_func, tox_func, tox, args...); } ); } template<typename ToxFunc, typename ...Args> auto with_instance_ign (JNIEnv *env, jint instanceNumber, ToxFunc tox_func, Args ...args) { struct ignore { void operator () (bool) { } }; return with_instance_err (env, instanceNumber, ignore (), tox_func, args...); } template<typename ToxFunc, typename ...Args> auto with_instance_noerr (JNIEnv *env, jint instanceNumber, ToxFunc tox_func, Args ...args) { return this->with_instance (env, instanceNumber, [&] (Object *tox, Events &events) { unused (events); return tox_func (tox, args...); } ); } };
true
0bfa13e6d4e3828c5b2dc6793e487866a7d897bc
C++
foreverlms/solutions
/cpp/src/yitu/first.cpp
UTF-8
1,503
2.5625
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; int main(void){ int m,n; while (cin>>n>>m) { int a[n],c[n]; string b[n]; string judge; bool d[n]; for (int i = 0; i < n; i++) { cin>>a[i]>>b[i]>>c[i]; cin>>judge; if(judge=="True"){ d[i]=true; }else{ d[i]=false; } } int a_delta,c_x; int c_same[30]; int b_same[300]; int c_different[10000]; for (size_t i = 0; i < m; i++) { int count = 0; cin>>a_delta>>c_x; int z = 0; int t = 0; for (int k = 0; k < n; k++) { if(c[k]!=c_x){ c_different[z]=k; z++; }else{ c_same[t]=k; t++; } } for (int p = 0; p < t; p++) { for (int s = 0; s < z; s++) { int tmp_1 = c_same[p]; int tmp_2 = c_different[s]; if (b[tmp_1] == b[tmp_2] && d[tmp_1] != d[tmp_2] && abs(a[tmp_1]-tmp_2) <= a_delta){ count++; } } } cout << count << endl; } } }
true
e2456f1dea05d16582d9beeca3b2662810f35001
C++
aditya0genius/Learn-C-
/Day01/pattern1.cpp
UTF-8
326
3.03125
3
[]
no_license
#include <iostream> using namespace std; int main() { int row,column; cout<<"Enter number of Rows"; cin>>row; cout<<"Enter number of Columns"; cin>>column; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { cout<<"*"; } cout<<"\n"; } return 0; }
true
71f1073fd986865885865ed4c85173df567ca215
C++
pdalaya/arkanoid
/Arkanoid/PlayerRectangle.h
UTF-8
951
2.953125
3
[]
no_license
#pragma once #include "Rectangle.h" namespace Game { class PlayerRectangle: public Rectangle { private: sf::Sprite m_sprite; sf::Vector2f m_velocity; float m_speed; //keeps track of which size we are so we don't go overboard. I had first 4 different sizes...but now I only have two so this is probably not needed anymore int m_size; public: PlayerRectangle( float _speed, const sf::Vector2f& _position, const sf::Vector2f& _size, const sf::Sprite& _sprite, const sf::Color& _fillColor = sf::Color ::White); ~PlayerRectangle(){}; inline float GetSpeed( ) const { return m_speed; } void SetVelocity( sf::Vector2f _velocity ) { m_velocity = _velocity; } const sf::Sprite& GetSprite() { return m_sprite; } void Update( float _deltaTime ); void OnCollision( std::shared_ptr<Game::Shape> _otherShape ){}; void MultiplySpeed( float _multiplier ); void MultiplySize( float _multiplier ); }; }
true
6c2bdc059374560ca9d1e5fc681950be8fc20d2e
C++
MarcusCasey/MultiDemArrays
/CustomList/listN.h
UTF-8
904
2.921875
3
[]
no_license
/** * Marcus Casey * CS202 * Section 1103 */ #include <iostream> #include <string> #include <fstream> using namespace std; class ListN; class Node { private: Node(int, Node*); int data; Node* next; friend class ListN; friend ostream& operator<<(ostream&, const ListN&); }; class ListN { public: ListN(); ListN(const ListN&); ~ListN(); bool goToBeginning(); bool goToEnd(); bool goToNext(); bool goToPrior(); bool insertBefore(int); bool insertAfter(int); bool remove(); bool isEmpty() const; bool isFull() const; // Return False by default void clear(); bool readFile(string); // added read file for data bool get(int&) const; // added get fnc int count(); // added count, for binary search ListN& operator=(const ListN&); friend ostream& operator<<(ostream&, const ListN&); private: Node* head; Node* cursor; };
true
48de69aaa6037990489042241fe7d928f0c7dca5
C++
Boyzmsc/cpp
/week_3/crossVerHor.cpp
UTF-8
1,869
2.84375
3
[]
no_license
#include <iostream> using namespace std; int sortHigh(int x1, int x2) { int max; if (x1 > x2) { max = x1; } else { max = x2; } return max; } int sortLow(int x1, int x2) { int min; if (x1 > x2) { min = x2; } else { min = x1; } return min; } int main() { int datacase; cin >> datacase; for (int i = 0; i < datacase; i++) { int x1, y1, x2, y2; int k1, q1, k2, q2; cin >> x1 >> y1 >> x2 >> y2; cin >> k1 >> q1 >> k2 >> q2; int result; int xh, yh, xl, yl; int kh, qh, kl, ql; xh = sortHigh(x1, x2); xl = sortLow(x1, x2); yh = sortHigh(y1, y2); yl = sortLow(y1, y2); kh = sortHigh(k1, k2); kl = sortLow(k1, k2); qh = sortHigh(q1, q2); ql = sortLow(q1, q2); if (xh == xl) { if (((qh >= yl and qh <= yh) and kh == xh) or ((qh >= yl and qh <= yh) and kl == xh) or ((kh >= xh and kl <= xh) and qh == yh) or ((kh >= xh and kl <= xh) and qh == yl)) { result = 2; } else if (kh > xh and kl < xh and qh > yl and qh < yh) { result = 1; } else { result = 0; } } else { if (((yh >= ql and yh <= qh) and kh == xh) or ((yh >= ql and yh <= qh) and kh == xl) or ((xh >= kh and xl <= kh) and qh == yh) or ((xh >= kh and xl <= kh) and ql == yh)) { result = 2; } else if (kh < xh and kh > xl and qh > yh and ql < yh) { result = 1; } else { result = 0; } } cout << result << endl; } }
true
f40a8b0c7b12c2c2f00b11a4dfef6edbc9bdc30f
C++
apervushin/leetcode-cpp
/find_the_city_with_the_smallest_number_of_neighbors_at_a_threshold_distance.cpp
UTF-8
1,544
3.078125
3
[]
no_license
#include <vector> #include <climits> #include <iostream> using namespace std; class FindTheCityWithTheSmallestNumberOfNeighborsAtAThresholdDistance { public: int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) { vector<vector<long>> distances(n, vector<long>(n, INT_MAX)); for (vector<int>& e : edges) { distances[e[0]][e[1]] = e[2]; distances[e[1]][e[0]] = e[2]; } for (int i = 0; i < n; i++) { distances[i][i] = 0; } //print(distances); for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { distances[i][j] = min(distances[i][j], distances[i][k] + distances[k][j]); } } } //print(distances); int best = INT_MAX; int best_i = 0; for (int i = 0; i < n; i++) { int tmp = 0; for (int j = 0; j < n; j++) { if (i != j && distances[i][j] <= distanceThreshold) { tmp++; } } if (tmp <= best) { best_i = i; best = tmp; } } return best_i; } private: void print(const vector<vector<long>>& distances) { for (const auto & distance : distances) { for (long j : distance) { cout << j << " "; } cout << "\n"; } cout << endl; } };
true
70323eedfb1c7bf3bc4f6c727bfff32e2e3ce179
C++
DoumanAsh/c--test-exe
/what_a_nice_day/main.cpp
UTF-8
3,552
3.796875
4
[ "Apache-2.0" ]
permissive
#include <cassert> #include <string> #include <vector> /** * Returns whether text is present in dictionary * * We could do better with std::string_view * * @note assumes no duplicate words are present in dictionary. */ static inline size_t look_up_dict(const std::vector<std::string>& dictionary, const std::string& text, size_t start, size_t size) { for (const auto& word : dictionary) { //We need to make sure that range size is equal to word size //as compare will compare up to size so you can get partial match as full match //Reasoning to use this akward way: to replace std::string_view if (size != word.size() || text.compare(start, size, word) != 0) continue; else return word.size(); } return std::string::npos; } /** * Determines whether the text can be broken into words from dictionary * * Complexity: text.size() * dictionary.size() */ bool break_into_words(const std::string& text, const std::vector<std::string>& dictionary) { if (dictionary.size() == 0) return false; size_t text_len = text.size(); if (text_len == 0) return true; //Collect previous matches. //We add std::string::npos which is -1 std::vector<size_t> matches(1, std::string::npos); for (size_t idx = 0; idx < text_len; idx++) { bool is_found = false; //The loop attempts to check all possible ranges of previous matches starting from the last one //If there is no match, then we try full range using std::string::npos. // //Unsigned overflow is well defined //std::string::npos + 1 = 0 //idx - std::string::npos = idx + 1 for (size_t m_idx = matches.size() - 1; m_idx != std::string::npos; m_idx--) { if (look_up_dict(dictionary, text, matches[m_idx] + 1, idx - matches[m_idx]) != std::string::npos) { is_found = true; break; } } if (is_found) { matches.push_back(idx); } } //if we were able to split using our dictionary fully //we're going to have text.size() - 1 as last match return matches[matches.size() - 1] == text_len - 1; } int main() { std::vector<std::string> dictionary{"a", "what", "an", "nice", "day"}; //Test look-up { const std::string text = "whatacutie"; assert(look_up_dict(dictionary, text, 0, 4) == 4); assert(look_up_dict(dictionary, text, 1, 4) == std::string::npos); assert(look_up_dict(dictionary, text, 4, 1) == 1); } assert(break_into_words("a", dictionary)); assert(break_into_words("aaaaaa", dictionary)); assert(break_into_words("day", dictionary)); assert(break_into_words("whataniceday", dictionary)); assert(break_into_words("niceday", dictionary)); assert(break_into_words("nicedayan", dictionary)); assert(!break_into_words("nicedayt", dictionary)); assert(!break_into_words("whatanceday", dictionary)); assert(break_into_words("niceday", {"n", "y", "i", "c", "e", "d", "a"})); assert(!break_into_words("niceday", {"n", "i", "c", "e", "d", "a"})); assert(!break_into_words("niceday", {"y", "i", "c", "e", "d", "a"})); assert(!break_into_words("niceday", {"n", "y", "i", "e", "d", "a"})); assert(!break_into_words("niceda", {"niceday"})); assert(!break_into_words("niceday", {"iceday"})); assert(!break_into_words("niceday", {"n", "y"})); assert(!break_into_words("niceday", {})); assert(!break_into_words("nice", {})); return 0; }
true
bf6fdc14766cb76180fe84dd2c79652316d6d597
C++
selonsy/leetcode
/LeetcodeCplusplus/temp/设计模式/策略模式.cpp
UTF-8
1,141
3.40625
3
[]
no_license
#include <iostream> using namespace std; #define free_ptr(p) \ if (p) \ delete p; \ p = NULL; class IWind { public: virtual ~IWind(){}; virtual void blowWind() = 0; }; class ColdWind : public IWind { public: void blowWind() { cout << "Blowing cold wind!" << endl; }; }; class WarmWind : public IWind { public: void blowWind() { cout << "Blowing warm wind!" << endl; } }; class NoWind : public IWind { public: void blowWind() { cout << "No Wind!" << endl; } }; class WindMode { public: WindMode(IWind *wind) : m_wind(wind){}; ~WindMode() { free_ptr(m_wind); } void blowWind() { m_wind->blowWind(); }; private: IWind *m_wind; }; int main(int argc, char *argv[]) { WindMode *warmWind = new WindMode(new WarmWind()); WindMode *coldWind = new WindMode(new ColdWind()); WindMode *noWind = new WindMode(new NoWind()); warmWind->blowWind(); coldWind->blowWind(); noWind->blowWind(); free_ptr(warmWind); free_ptr(coldWind); free_ptr(noWind); system("pause"); return 0; }
true
5cc5601259e9b47e8ce662ace8ae430f14f58754
C++
gabrielgregh1/Algoritmo_Arvore_Binaria
/Algoritmo de Inserção em Arvore.cpp
UTF-8
1,838
3.546875
4
[]
no_license
#include<stdio.h> #include<stdlib.h> typedef struct tree{ int info; struct tree* right; struct tree* left; }no; //RAIZ no*root = NULL; void menu(); struct tree *insere(struct tree* raiz,struct tree* aux,int v); void preOrdem(struct tree *aux); void inOrdem(struct tree *aux); void posOrdem(struct tree *aux); int main(){ menu(); preOrdem(root); printf("\n"); inOrdem(root); printf("\n"); posOrdem(root); } //Menu para INSERIR de valores void menu(){ int valor; int opcao = 1; do{ printf("Informe um numero: "); scanf("%d",&valor); if(root == NULL) root = insere(root, root, valor); else insere(root, root, valor); printf("Deseja continuar? <1> SIM | <qualquer outro> NAO\n"); scanf("%d",&opcao); }while(opcao == 1); } //Forma de INSERECAO em ARVORE struct tree *insere(struct tree* raiz,struct tree* aux,int v){ if(aux == NULL){ aux = (struct tree*)malloc(sizeof(struct tree)); if(aux == NULL){ printf("Memoria Cheia"); exit(0); } aux->right = NULL; aux->left = NULL; aux->info = v; if(root == NULL) return aux; if(raiz->info > aux->info) raiz->left = aux; else raiz->right = aux; return aux; } if(aux->info > v) return insere(aux, aux->left, v); else return insere(aux, aux->right, v); } //Forma de EXIBICAO PREORDEM void preOrdem(struct tree *aux){ if(aux == NULL) return; if(aux->info) printf("%d",aux->info); preOrdem(aux->left); preOrdem(aux->right); } //Forma de EXIBICAO INORDEM void inOrdem(struct tree *aux){ if(aux == NULL) return; preOrdem(aux->left); if(aux->info) printf("%d",aux->info); preOrdem(aux->right); } //Forma de EXIBICAO POSORDEM void posOrdem(struct tree *aux){ if(aux == NULL) return; preOrdem(aux->left); preOrdem(aux->right); if(aux->info) printf("%d",aux->info); }
true
2af8d69f5e4ee671b6101329861e9975909480f1
C++
zhyuzhya/oop_labs
/oop_lab_1/Octagon.cpp
UTF-8
597
3.734375
4
[]
no_license
#include "Octagon.h" #include <iostream> #include <cmath> Octagon::Octagon() : Octagon(0) { } Octagon::Octagon(size_t a) : side(a) { std::cout << "Octagon created with side = " << side << std::endl; } Octagon::Octagon(std::istream &is) { is >> side; } Octagon::Octagon(const Octagon& orig) { std::cout << "Octagon copy created" << std::endl; side = orig.side; } double Octagon::Square() { return 2 * (1 + sqrt(2)) * side * side; } void Octagon::Print() { std::cout << "Side of Octagon a = " << side << std::endl; } Octagon::~Octagon() { std::cout << "Octagon deleted" << std::endl; }
true
958f57e123339245060998be28f2ae7d4b59af38
C++
vagnerlands/GameAvatar
/GameAvatar/Application/Utilities/CPngLoader.cpp
UTF-8
2,310
2.625
3
[]
no_license
#include "CPngLoader.h" #include "png.h" CPngLoader::CPngLoader() { m_fileContent.status = false; m_fileContent.width = -1; m_fileContent.height = -1; m_fileContent.pPixels = nullptr; } CPngLoader::~CPngLoader() { if (m_fileContent.status) { // frees dynamic allocated memory for (Int32 __i = 0; __i < m_fileContent.height; __i++) { free(m_fileContent.pPixels[__i]); } free(m_fileContent.pPixels); } } bool CPngLoader::loadPngFile(const Byte* filePath) { bool retVal = false; FILE *fp = fopen(filePath, "rb"); png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png) abort(); png_infop info = png_create_info_struct(png); if (!info) abort(); if (setjmp(png_jmpbuf(png))) abort(); png_init_io(png, fp); png_read_info(png, info); m_fileContent.width = png_get_image_width(png, info); m_fileContent.height = png_get_image_height(png, info); m_fileContent.color_type = png_get_color_type(png, info); m_fileContent.bit_depth = png_get_bit_depth(png, info); // Read any color_type into 8bit depth, RGBA format. // See http://www.libpng.org/pub/png/libpng-manual.txt if (m_fileContent.bit_depth == 16) png_set_strip_16(png); if (m_fileContent.color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png); // PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth. if (m_fileContent.color_type == PNG_COLOR_TYPE_GRAY && m_fileContent.bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png); if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png); // These color_type don't have an alpha channel then fill it with 0xff. if (m_fileContent.color_type == PNG_COLOR_TYPE_RGB || m_fileContent.color_type == PNG_COLOR_TYPE_GRAY || m_fileContent.color_type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png, 0xFF, PNG_FILLER_AFTER); if (m_fileContent.color_type == PNG_COLOR_TYPE_GRAY || m_fileContent.color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png); png_read_update_info(png, info); m_fileContent.pPixels = (png_bytep*)malloc(sizeof(png_bytep) * m_fileContent.height); for (int y = 0; y < m_fileContent.height; y++) { m_fileContent.pPixels[y] = (png_byte*)malloc(png_get_rowbytes(png, info)); } png_read_image(png, m_fileContent.pPixels); fclose(fp); return retVal; }
true
5b171db75dd6c2717432408bc7913360d729dda5
C++
MonsterLock/MonsterLock
/Unit Test/ML_ArrayList_Test.cpp
UTF-8
3,698
3.0625
3
[]
no_license
/* R.A. Bickell [https://github.com/MonsterLock] ML_ArrayList_Test.cpp Last Updated: 2019-09-19 07::09::07 AM */ #include "CppUnitTest.h" #include "../CoreLibrary/ML_ArrayList.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest { using namespace ML::DSA; TEST_CLASS( ArrayListTest ) { struct test_value { enum { A = 'A', B, C, D, E, F, G, SIZE }; }; struct test_capacity { enum { FIRST = 1, SECOND = 2, THIRD = 4, FOURTH = 8, FIFTH = 16, SIXTH = 32, SEVENTH = 64, EIGHTH = 128, NINTH = 256, TENTH = 512 }; }; public: TEST_METHOD( ArrayListPushBack ) { array_list<size_t> test_array; for( size_t i = test_value::A; i < test_value::SIZE; i++ ) { test_array.push_back( i ); } Assert::IsTrue( test_array.size( ) == 7 ); for( size_t i = 0; i < test_array.size( ); i++ ) { Assert::IsTrue( test_array[i] == test_value::A + i ); } } TEST_METHOD( ArrayListReserve ) { array_list<size_t> test_array; for( size_t i = test_value::A; i < test_value::SIZE; i++ ) { test_array.push_back( i ); } Assert::IsTrue( test_array.capacity( ) == test_capacity::FOURTH ); test_array.reserve( 2 ); Assert::IsTrue( test_array.capacity( ) == test_capacity::FOURTH ); for( size_t i = 0; i < test_array.size( ); i++ ) { Assert::IsTrue( test_array[i] == test_value::A + i ); } test_array.reserve( 10 ); Assert::IsTrue( test_array.capacity( ) == 10 ); for( size_t i = 0; i < test_array.size( ); i++ ) { Assert::IsTrue( test_array[i] == test_value::A + i ); } test_array.push_back( 'H' ); test_array.push_back( 'I' ); test_array.push_back( 'J' ); test_array.push_back( 'K' ); Assert::IsTrue( test_array.capacity( ) == 20 ); for( size_t i = 0; i < test_array.size( ); i++ ) { Assert::IsTrue( test_array[i] == test_value::A + i ); } } TEST_METHOD( ArrayListClear ) { array_list<size_t> test_array; for( size_t i = test_value::A; i < test_value::SIZE; i++ ) { test_array.push_back( i ); } test_array.clear( ); Assert::IsTrue( test_array.size() == 0 ); Assert::IsTrue( test_array.capacity() == 0 ); Assert::IsTrue( &test_array[0] == nullptr ); for( size_t i = test_value::A; i < test_value::SIZE; i++ ) { test_array.push_back( i ); } Assert::IsTrue( test_array.size( ) == 7 ); Assert::IsTrue( test_array.capacity( ) == test_capacity::FOURTH ); for( size_t i = 0; i < test_array.size( ); i++ ) { Assert::IsTrue( test_array[i] == test_value::A + i ); } test_array.clear( ); Assert::IsTrue( test_array.size() == 0 ); Assert::IsTrue( test_array.capacity() == 0 ); Assert::IsTrue( &test_array[0] == nullptr ); } TEST_METHOD( ArrayListMemory ) { array_list<size_t> test_array; for( size_t i = test_value::A; i < test_value::SIZE; i++ ) { test_array.push_back( i ); } array_list<size_t> test_array2( test_array ); Assert::IsTrue( test_array2.capacity( ) == test_capacity::FOURTH ); Assert::IsTrue( test_array2.size( ) == 7 ); for( size_t i = 0; i < test_array2.size( ); i++ ) { Assert::IsTrue( test_array2[i] == test_value::A + i ); } array_list<size_t> test_array3; for( size_t i = test_value::A; i < test_value::SIZE; i++ ) { test_array3.push_back( i+5 ); } test_array3 = test_array; Assert::IsTrue( test_array3.capacity( ) == test_capacity::FOURTH ); Assert::IsTrue( test_array3.size( ) == 7 ); for( size_t i = 0; i < test_array3.size( ); i++ ) { Assert::IsTrue( test_array3[i] == test_value::A + i ); } } }; }
true
de7cc92bc2a8d0db1b8a7edd83644d62639d3af7
C++
hyrise/hyrise
/src/lib/operators/import.hpp
UTF-8
2,150
2.609375
3
[ "MIT" ]
permissive
#pragma once #include <optional> #include <string> #include "abstract_read_only_operator.hpp" #include "import_export/csv/csv_meta.hpp" #include "import_export/file_type.hpp" #include "types.hpp" #include "SQLParser.h" namespace hyrise { /* * This operator reads a file, creates a table from that input and adds it to the storage manager. * Supported file types are .tbl, .csv and Hyrise .bin files. * For .csv files, a CSV config is additionally required, which is commonly located in the <filename>.json file. * Documentation of the file formats can be found in BinaryWriter and CsvWriter header files. */ class Import : public AbstractReadOnlyOperator { public: /** * @param filename Path to the input file. * @param tablename Name of the table to store in the StorageManager. * @param chunk_size Optional. Chunk size. Does not effect binary import. * @param file_type Optional. Type indicating the file format. If not present, it is guessed by the filename. * @param csv_meta Optional. A specific meta config, used instead of filename + '.json' */ explicit Import(const std::string& init_filename, const std::string& tablename, const ChunkOffset chunk_size = Chunk::DEFAULT_SIZE, const FileType file_type = FileType::Auto, const std::optional<CsvMeta>& csv_meta = std::nullopt); const std::string& name() const final; const std::string filename; protected: std::shared_ptr<const Table> _on_execute() final; std::shared_ptr<AbstractOperator> _on_deep_copy( const std::shared_ptr<AbstractOperator>& /*copied_left_input*/, const std::shared_ptr<AbstractOperator>& /*copied_right_input*/, std::unordered_map<const AbstractOperator*, std::shared_ptr<AbstractOperator>>& /*copied_ops*/) const override; void _on_set_parameters(const std::unordered_map<ParameterID, AllTypeVariant>& parameters) override; private: // Name for adding the table to the StorageManager const std::string _tablename; const ChunkOffset _chunk_size; FileType _file_type; const std::optional<CsvMeta> _csv_meta; }; } // namespace hyrise
true
f6a98309eceb4498a3f93b49db4f474904c4f9bf
C++
jameslarrue/enzo-e
/src/Enzo/enzo_EnzoInitialInclinedWave.cpp
UTF-8
31,069
2.8125
3
[ "BSD-3-Clause", "NCSA", "BSD-2-Clause" ]
permissive
// See LICENSE_CELLO file for license and copyright information /// @file enzo_EnzoInitialInclinedWave.cpp /// @author Matthew Abruzzo (matthewabruzzo@gmail.com) /// @date 2019-04-27 /// @brief Implementation of EnzoInitialInclinedWave for initializing /// inclined linear MHD waves and inclined circularly polarized /// alfven waves detailed in Gardiner & Stone (2008). These are used /// to test the VL+CT MHD integrator. An inclined sound wave can also /// be initialized (its initial conditions were inspired by the /// Athena test suite) // Using the coordinate systems given by eqn 68 of Gardiner & Stone (2008) // (except that index numbers start at 0) // The system of the mesh are x,y,z // The system of the linear wave is x0, x1, x2 // The linear waves are defined along x0 // {{x0}, {{ cos(a), 0, sin(a)}, {{ cos(b), sin(b), 0}, {{x}, // {x1}, = { 0, 1, 0}, . {-sin(b), cos(b), 0}, . {y}, // {x2}} {-sin(a), 0, cos(a)}} { 0, 0, 1}} {z}} // R2 R1 // R1, the second matix, rotates a 3D vector about it's third dimension by // angle -b. In this case, if z-axis points out of the page, then rotate // axes clockwise. The rotated y-axis now points along the x1 dimension // // R2, the first matrix, rotates a 3D vector about it's second axis by angle // -a. In this case, if the axis along the second dimension (x1) points out of // the page, then rotate the other axes clockwise. The rotated x- and z- axes // now point along the x0- and x2- axes // // Note that they give transformation of x0,x1,x2 -> x,y,z while the // implementation primarily use x,y,z -> x0,x1,x2 (since the the rotation is // easier to visualize) // // // In general, this implementation is more complicated than it needs to be. // It could definitely be simplified (although the Rotation class probably // shouldn't be touched since it will be reused) #include <sstream> // std::stringstream #include "enzo.hpp" #include "charm_enzo.hpp" #include "cello.hpp" //---------------------------------------------------------------------- // This will be reused to implement Cosmic Rays // When we do that this should probably be made into a class template // so that the values don't necessarily have to be cast to doubles // (We uses doubles by default for it's current use because the convention // is to perform all operations on position using Double precision) class Rotation { public: Rotation(double a, double b) { matrix_[0][0] = std::cos(a)*std::cos(b); matrix_[0][1] = std::cos(a)*std::sin(b); matrix_[0][2] = std::sin(a); matrix_[1][0] = -1.*std::sin(b); matrix_[1][1] = std::cos(b); matrix_[1][2] = 0.; matrix_[2][0] = -1.*std::sin(a)*std::cos(b); matrix_[2][1] = -1.*std::sin(a)*std::sin(b); matrix_[2][2] = std::cos(a); } // rotates vector {v0, v1, v2} to {rot0, rot1, rot2} void rot(double v0, double v1, double v2, double &rot0, double &rot1, double &rot2) { rot0 = matrix_[0][0]*v0 + matrix_[0][1]*v1 + matrix_[0][2]*v2; rot1 = matrix_[1][0]*v0 + matrix_[1][1]*v1 + matrix_[1][2]*v2; rot2 = matrix_[2][0]*v0 + matrix_[2][1]*v1 + matrix_[2][2]*v2; } // rotates vector {rot0, rot1, rot2} to {v0, v1, v2} void inv_rot(double rot0, double rot1, double rot2, double &v0, double &v1, double &v2) { v0 = matrix_[0][0]*rot0 + matrix_[1][0]*rot1 + matrix_[2][0]*rot2; v1 = matrix_[0][1]*rot0 + matrix_[1][1]*rot1 + matrix_[2][1]*rot2; v2 = matrix_[0][2]*rot0 + matrix_[1][2]*rot1 + matrix_[2][2]*rot2; } // For debugging void print_matrix() { for (int j = 0; j<3; j++){ if (j == 0){ CkPrintf("{"); } else { CkPrintf(" "); } CkPrintf(" %.5g, %.5g, %.5g}", matrix_[j][0], matrix_[j][1], matrix_[j][2]); if (j == 2){ CkPrintf("}\n"); } else { CkPrintf("\n"); } } } private: double matrix_[3][3]; }; //---------------------------------------------------------------------- // Use initializer functors to set up the grid // - for scalars: density, total energy density // - for vectors: momentum, magnetic vector potential // These functors are most frequently most easily defined along axes that are // rotated with respect to the grid. RotatedScalarInit and // RotatedVectorInit are defined wrap around such initializers // There are large similarities between Scalar and Vector Inits, there // may be a way to consolidate class ScalarInit{ public: virtual ~ScalarInit() {} virtual double operator() (double x0, double x1, double x2)=0; }; //---------------------------------------------------------------------- class LinearScalarInit : public ScalarInit{ public: LinearScalarInit(double background, double eigenvalue, double amplitude, double lambda) : background_(background), eigenvalue_(eigenvalue), amplitude_(amplitude), lambda_(lambda) {} double operator() (double x0, double x1, double x2){ return (background_ + amplitude_ * eigenvalue_ * std::cos(x0*2.*cello::pi/lambda_)); } protected: // value of the background state double background_; // value of the eigenvalue for a given mode double eigenvalue_; // perturbation amplitude double amplitude_; // wavelength double lambda_; }; //---------------------------------------------------------------------- class RotatedScalarInit : public ScalarInit { public: RotatedScalarInit(double a, double b, ScalarInit *inner) : ScalarInit() { rot_ = new Rotation(a,b); inner_ = inner; } ~RotatedScalarInit() { delete inner_; delete rot_; } double operator() (double x, double y, double z) { double x0,x1,x2; rot_->rot(x,y,z,x0,x1,x2); return (*inner_)(x0,x1,x2); } private: Rotation *rot_; ScalarInit *inner_; }; //---------------------------------------------------------------------- class VectorInit { public: virtual ~VectorInit() {} virtual void operator() (double x0, double x1, double x2, double &v0, double &v1, double &v2)=0; }; //---------------------------------------------------------------------- class LinearVectorInit : public VectorInit { public: LinearVectorInit(double back0, double back1, double back2, double ev0, double ev1, double ev2, double amplitude, double lambda) : VectorInit(), back0_(back0), back1_(back1), back2_(back2), ev0_(ev0), ev1_(ev1), ev2_(ev2), amplitude_(amplitude), lambda_(lambda) {} void operator() (double x0, double x1, double x2, double &v0, double &v1, double &v2) { v0 = (back0_ + amplitude_*ev0_*std::cos(x0*2.*cello::pi/lambda_)); v1 = (back1_ + amplitude_*ev1_*std::cos(x0*2.*cello::pi/lambda_)); v2 = (back2_ + amplitude_*ev2_*std::cos(x0*2.*cello::pi/lambda_)); } protected: // value of the background state double back0_, back1_, back2_; // value of the eigenvalue for a given mode double ev0_, ev1_, ev2_; // perturbation amplitude double amplitude_; // wavelength double lambda_; }; //---------------------------------------------------------------------- class RotatedVectorInit : public VectorInit { public: RotatedVectorInit(double a, double b, VectorInit *inner) : VectorInit() { rot_ = new Rotation(a,b); inner_ = inner; } ~RotatedVectorInit() { delete inner_; delete rot_; } void operator() (double x, double y, double z, double &v0, double &v1, double &v2) { double x0,x1,x2, rot0, rot1, rot2; rot_->rot(x,y,z,x0,x1,x2); (*inner_)(x0,x1,x2,rot0,rot1,rot2); rot_->inv_rot(rot0,rot1,rot2,v0,v1,v2); } private: Rotation *rot_; VectorInit *inner_; }; //---------------------------------------------------------------------- class LinearVectorPotentialInit : public VectorInit { public: // The absence of ev_B0 is intentional LinearVectorPotentialInit(double back_B0, double back_B1, double back_B2, double ev_B1, double ev_B2, double amplitude, double lambda) :VectorInit(), back_B0_(back_B0), back_B1_(back_B1), back_B2_(back_B2), ev_B1_(ev_B1), ev_B2_(ev_B2), amplitude_(amplitude), lambda_(lambda) {} void operator() (double x0, double x1, double x2, double &v0, double &v1, double &v2) { v0 = (x2 * amplitude_ * ev_B1_ * std::cos(2. * cello::pi * x0/ lambda_) - x1 * amplitude_ * ev_B2_ * std::cos(2. * cello::pi * x0/ lambda_)); v1 = back_B2_ * x0; // For Gardiner & Stone (2008) setup, should be 0 v2 = back_B0_ * x1 - back_B1_ * x0; } protected: // value of the magnetic field background state double back_B0_, back_B1_, back_B2_; // magnetic field eigenvalue for a given mode (its always 0, along dim 0) double ev_B1_, ev_B2_; // perturbation amplitude double amplitude_; // wavelength double lambda_; }; //---------------------------------------------------------------------- class CircAlfvenMomentumInit : public VectorInit { public: // The absence of ev_B0 is intentional CircAlfvenMomentumInit(double p0, double lambda) :VectorInit(), p0_(p0), lambda_(lambda) {} void operator() (double x0, double x1, double x2, double &v0, double &v1, double &v2) { v0 = p0_; v1 = 0.1 * std::sin(2. * cello::pi * x0/ lambda_); v2 = 0.1 * std::cos(2. * cello::pi * x0/ lambda_); } protected: // momentum along p0 double p0_; // wavelength double lambda_; }; //---------------------------------------------------------------------- class CircAlfvenVectorPotentialInit : public VectorInit { public: // The absence of ev_B0 is intentional CircAlfvenVectorPotentialInit(double lambda) :VectorInit(), lambda_(lambda) {} void operator() (double x0, double x1, double x2, double &v0, double &v1, double &v2) { v0 = (x2 * 0.1 * std::sin(2. * cello::pi * x0/ lambda_) - x1 * 0.1 * std::cos(2. * cello::pi * x0/ lambda_)); v1 = 0.0; v2 = x1; } protected: // wavelength double lambda_; }; //---------------------------------------------------------------------- class MeshPos { public: MeshPos(Block *block) { Field field = block->data()->field(); // lower left edge of active region block->data()->lower(&x_left_edge_,&y_left_edge_,&z_left_edge_); // cell widths block->data()->field_cell_width(&dx_,&dy_,&dz_); // ghost depth field.ghost_depth(0,&gx_,&gy_,&gz_); } // compute positions at cell-centers double x(int k, int j, int i){ return x_left_edge_ + dx_* (0.5+(double)(i-gx_));} double y(int k, int j, int i){ return y_left_edge_ + dy_* (0.5+(double)(j-gy_));} double z(int k, int j, int i){ return z_left_edge_ + dz_* (0.5+(double)(k-gz_));} // computes the x, y, or z position for the cell corner at the // (i-1/2, j,k), (i,j-1/2,k) or (i,j, k-1/2) double x_face(int k, int j, int i){ return x_left_edge_ + dx_* (double)(i-gx_);} double y_face(int k, int j, int i){ return y_left_edge_ + dy_* (double)(j-gy_);} double z_face(int k, int j, int i){ return z_left_edge_ + dz_* (double)(k-gz_);} double dx() {return dx_;} double dy() {return dy_;} double dz() {return dz_;} private: // the starting position of the edge of the active grid double x_left_edge_, y_left_edge_, z_left_edge_; // ghost depth (and the index at the start of the active region) int gx_, gy_, gz_; double dx_, dy_, dz_; }; //---------------------------------------------------------------------- // Components of the magnetic field from the vector potential void setup_bfield(Block * block, VectorInit *a, MeshPos &pos, int mx, int my, int mz) { Field field = block->data()->field(); ASSERT("setup_bfield", ("Can only currently handle initialization of " "B-fields if interface values are used"), field.is_field("bfieldi_x") && field.is_field("bfieldi_y") && field.is_field("bfieldi_z")); EnzoFieldArrayFactory array_factory(block); EFlt3DArray bfieldi_x = array_factory.from_name("bfieldi_x"); EFlt3DArray bfieldi_y = array_factory.from_name("bfieldi_y"); EFlt3DArray bfieldi_z = array_factory.from_name("bfieldi_z"); if (a == NULL){ for (int iz=0; iz<mz+1; iz++){ for (int iy=0; iy<my+1; iy++){ for (int ix=0; ix<mx+1; ix++){ if ((iz != mz) && (iy != my)) { bfieldi_x(iz,iy,ix) = 0; } if ((iz != mz) && (ix != mx)) { bfieldi_y(iz,iy,ix) = 0; } if ((iy != my) && (ix != mx)) { bfieldi_z(iz,iy,ix) = 0; } } } } EnzoInitialBCenter::initialize_bfield_center(block); return; } // allocate corner-centered arrays for the magnetic vector potentials // Ax, Ay, and Az are always cell-centered along the x, y, and z dimensions, // respectively CelloArray<double,3> Ax(mz+1,my+1,mx); CelloArray<double,3> Ay(mz+1,my,mx+1); CelloArray<double,3> Az(mz,my+1,mx+1); // Compute the Magnetic Vector potential at all points on the grid for (int iz=0; iz<mz+1; iz++){ for (int iy=0; iy<my+1; iy++){ for (int ix=0; ix<mx+1; ix++){ double temp_ax, temp_ay, temp_az; if (ix != mx){ (*a)(pos.x(iz,iy,ix), pos.y_face(iz,iy,ix), pos.z_face(iz,iy,ix), Ax(iz,iy,ix), temp_ay, temp_az); } if (iy != my){ (*a)(pos.x_face(iz,iy,ix), pos.y(iz,iy,ix), pos.z_face(iz,iy,ix), temp_ay, Ay(iz,iy,ix), temp_az); } if (iz != mz){ (*a)(pos.x_face(iz,iy,ix), pos.y_face(iz,iy,ix), pos.z(iz,iy,ix), temp_ax, temp_ay, Az(iz,iy,ix)); } } } } // Compute the Interface B-fields EnzoInitialBCenter::initialize_bfield_interface(block, Ax, Ay, Az); // Compute the Cell-Centered B-fields EnzoInitialBCenter::initialize_bfield_center(block); } //---------------------------------------------------------------------- void setup_eint_(Block *block) { // because cell-centered bfields for CT are computed in terms of enzo_float, // this calculation is handled in terms of enzo_float // This operation could be split off and placed in a separate initializer EnzoFieldArrayFactory array_factory(block); Field field = block->data()->field(); EFlt3DArray density, etot, eint; density = array_factory.from_name("density"); etot = array_factory.from_name("total_energy"); eint = array_factory.from_name("internal_energy"); EFlt3DArray velocity_x, velocity_y, velocity_z; velocity_x = array_factory.from_name("velocity_x"); velocity_y = array_factory.from_name("velocity_y"); velocity_z = array_factory.from_name("velocity_z"); const bool mhd = field.is_field("bfield_x"); EFlt3DArray bfield_x, bfield_y, bfield_z; if (mhd){ bfield_x = array_factory.from_name("bfield_x"); bfield_y = array_factory.from_name("bfield_y"); bfield_z = array_factory.from_name("bfield_z"); } for (int iz=0; iz<density.shape(0); iz++){ for (int iy=0; iy<density.shape(1); iy++){ for (int ix=0; ix<density.shape(2); ix++){ enzo_float kinetic, magnetic; kinetic = 0.5 * (velocity_x(iz,iy,ix) * velocity_x(iz,iy,ix) + velocity_y(iz,iy,ix) * velocity_y(iz,iy,ix) + velocity_z(iz,iy,ix) * velocity_z(iz,iy,ix)); if (mhd){ magnetic = 0.5 * (bfield_x(iz,iy,ix)*bfield_x(iz,iy,ix) + bfield_y(iz,iy,ix)*bfield_y(iz,iy,ix) + bfield_z(iz,iy,ix)*bfield_z(iz,iy,ix)) / density(iz,iy,ix); } else { magnetic = 0.; } eint(iz,iy,ix) = etot(iz,iy,ix) - kinetic - magnetic; } } } } //---------------------------------------------------------------------- void setup_fluid(Block *block, ScalarInit *density_init, ScalarInit *total_energy_density_init, VectorInit *momentum_init, MeshPos &pos, int mx, int my, int mz, double gamma) { EFlt3DArray density, specific_total_energy; EnzoFieldArrayFactory array_factory(block); density = array_factory.from_name("density"); specific_total_energy = array_factory.from_name("total_energy"); EFlt3DArray velocity_x, velocity_y, velocity_z; velocity_x = array_factory.from_name("velocity_x"); velocity_y = array_factory.from_name("velocity_y"); velocity_z = array_factory.from_name("velocity_z"); for (int iz=0; iz<mz; iz++){ for (int iy=0; iy<my; iy++){ for (int ix=0; ix<mx; ix++){ double x,y,z; double rho, px, py, pz, etot_dens; x = pos.x(iz,iy,ix); y = pos.y(iz,iy,ix); z = pos.z(iz,iy,ix); rho = (*density_init)(x,y,z); density(iz,iy,ix) = (enzo_float)rho; (*momentum_init)(x, y, z, px, py, pz); velocity_x(iz,iy,ix) = (enzo_float)(px/rho); velocity_y(iz,iy,ix) = (enzo_float)(py/rho); velocity_z(iz,iy,ix) = (enzo_float)(pz/rho); etot_dens = (*total_energy_density_init)(x,y,z); specific_total_energy(iz,iy,ix) = (enzo_float)(etot_dens/rho); } } } // If present, setup internal energy (to test dual energy formalism): Field field = block->data()->field(); if (field.is_field("internal_energy")) { setup_eint_(block); } } //---------------------------------------------------------------------- void setup_circ_polarized_alfven(Block *block, ScalarInit *density_init, VectorInit *momentum_init, MeshPos &pos, int mx, int my, int mz, double gamma) { // this function directly sets pressure = 0.1 by hand // Gardiner & Stone (2008) explicitly as states that the truncation error of // B_perp**2/P is important EFlt3DArray density, specific_total_energy; EnzoFieldArrayFactory array_factory(block); density = array_factory.from_name("density"); specific_total_energy = array_factory.from_name("total_energy"); EFlt3DArray velocity_x, velocity_y, velocity_z; velocity_x = array_factory.from_name("velocity_x"); velocity_y = array_factory.from_name("velocity_y"); velocity_z = array_factory.from_name("velocity_z"); EFlt3DArray bfield_x, bfield_y, bfield_z; bfield_x = array_factory.from_name("bfield_x"); bfield_y = array_factory.from_name("bfield_y"); bfield_z = array_factory.from_name("bfield_z"); Field field = block->data()->field(); EFlt3DArray specific_internal_energy; const bool dual_energy = field.is_field("internal_energy"); if (dual_energy){ specific_internal_energy = array_factory.from_name("internal_energy"); } for (int iz=0; iz<mz; iz++){ for (int iy=0; iy<my; iy++){ for (int ix=0; ix<mx; ix++){ double x,y,z; double rho, px, py, pz; x = pos.x(iz,iy,ix); y = pos.y(iz,iy,ix); z = pos.z(iz,iy,ix); rho = (*density_init)(x,y,z); density(iz,iy,ix) = (enzo_float)rho; (*momentum_init)(x, y, z, px, py, pz); velocity_x(iz,iy,ix) = (enzo_float)(px/rho); velocity_y(iz,iy,ix) = (enzo_float)(py/rho); velocity_z(iz,iy,ix) = (enzo_float)(pz/rho); // Because of the truncation concerns we use the cell-centered values enzo_float eint = (enzo_float)(0.1/(gamma - 1.)/rho); enzo_float mag = 0.5*(bfield_x(iz,iy,ix) * bfield_x(iz,iy,ix) + bfield_y(iz,iy,ix) * bfield_y(iz,iy,ix) + bfield_z(iz,iy,ix) * bfield_z(iz,iy,ix))/density(iz,iy,ix); enzo_float kin = 0.5 * (velocity_x(iz,iy,ix) * velocity_x(iz,iy,ix) + velocity_y(iz,iy,ix) * velocity_y(iz,iy,ix) + velocity_z(iz,iy,ix) * velocity_z(iz,iy,ix)); specific_total_energy(iz,iy,ix) = eint + mag + kin; if (dual_energy) { specific_internal_energy(iz,iy,ix) = eint;} } } } } //---------------------------------------------------------------------- EnzoInitialInclinedWave::EnzoInitialInclinedWave (int cycle, double time, double alpha, double beta, double gamma, double amplitude, double lambda, double parallel_vel,bool pos_vel, std::string wave_type) throw() : Initial (cycle,time), alpha_(alpha), beta_(beta), gamma_(gamma), amplitude_(amplitude), lambda_(lambda), parallel_vel_(parallel_vel), pos_vel_(pos_vel), wave_type_(wave_type) { std::vector<std::string> mhd_waves = mhd_waves_(); std::vector<std::string> hd_waves = hd_waves_(); if (std::find(mhd_waves.begin(), mhd_waves.end(), wave_type_) != mhd_waves.end()) { // specified wave is an MHD wave, make sure parallel_vel_ isn't specified ASSERT1("EnzoInitialInclinedWave", "parallel_vel can't be specified for a wave_type: \"%s\"", wave_type.c_str(), !specified_parallel_vel_()); } else if (std::find(hd_waves.begin(), hd_waves.end(), wave_type_) == hd_waves.end()) { // wave_type_ isn't a known type. Raise error with list of known // wave_types (follows https://stackoverflow.com/a/1430774): std::stringstream ss; for (std::vector<std::string>::size_type i = 0; i < mhd_waves.size(); i++){ if (i != 0) { ss << ", "; } ss << "'" << mhd_waves[i] << "'"; } for (std::vector<std::string>::size_type i = 0; i < hd_waves.size(); i++){ ss << "'" << mhd_waves[i] << "'"; } std::string s = ss.str(); ERROR1("EnzoInitialInclinedWave", "Invalid wave_type, must be %s", s.c_str()); } } //---------------------------------------------------------------------- std::vector<std::string> EnzoInitialInclinedWave::mhd_waves_() const throw() { std::vector<std::string> v = {"fast", "alfven", "slow", "mhd_entropy", "circ_alfven"}; return v; } //---------------------------------------------------------------------- std::vector<std::string> EnzoInitialInclinedWave::hd_waves_() const throw() { std::vector<std::string> v = {"sound", "hd_entropy", // perturb v0 "hd_transv_entropy_v1", // perturb v1 "hd_transv_entropy_v2"}; // perturb v2 return v; } //---------------------------------------------------------------------- void EnzoInitialInclinedWave::enforce_block(Block * block, const Hierarchy * hierarchy) throw() { // Set up the test problem // Only currently works on unigrid and only currently supports hydro methods // and VLCT (PPML initial conditions are much more complicated) ScalarInit *density_init = nullptr; ScalarInit *total_energy_density_init = nullptr; VectorInit *momentum_init = nullptr; VectorInit *a_init = nullptr; Field field = block->data()->field(); const bool mhd = field.is_field("bfield_x"); std::vector<std::string> hd_waves = hd_waves_(); if (std::find(hd_waves.begin(), hd_waves.end(), wave_type_) != hd_waves.end()) { prepare_HD_initializers_(&density_init, &total_energy_density_init, &momentum_init); } else { ASSERT("EnzoInitialInclinedWave::enforce_block", "A MHD wave requires fields to store magnetic field values.", mhd); prepare_MHD_initializers_(&density_init, &total_energy_density_init, &momentum_init, &a_init); } // load the dimensions and initialize object to compute positions int mx,my,mz; const int id = field.field_id ("density"); field.dimensions (id,&mx,&my,&mz); MeshPos pos(block); if (mhd) { // Initialize bfields. If the wave is purely hydrodynamical, they will be // all be set to 0. setup_bfield(block, a_init, pos, mx, my, mz); } if (wave_type_ != "circ_alfven"){ setup_fluid(block, density_init, total_energy_density_init, momentum_init, pos, mx, my, mz, gamma_); } else { setup_circ_polarized_alfven(block, density_init, momentum_init, pos, mx, my, mz, gamma_); } delete density_init; delete momentum_init; delete total_energy_density_init; if (a_init != nullptr) { delete a_init; } } //---------------------------------------------------------------------- void EnzoInitialInclinedWave::prepare_MHD_initializers_ (ScalarInit **density_init, ScalarInit **etot_dens_init, VectorInit **momentum_init, VectorInit **a_init) { double lambda = lambda_; if (wave_type_ == "circ_alfven"){ *density_init = new LinearScalarInit(1.0,0.0,0.0,lambda); *momentum_init = new RotatedVectorInit(alpha_,beta_, new CircAlfvenMomentumInit(0.0, lambda)); // we don't actually use etot for initializing *etot_dens_init = new LinearScalarInit(0.66,0.0,0.0,lambda); *a_init = new RotatedVectorInit(alpha_,beta_, new CircAlfvenVectorPotentialInit(lambda)); } else { // wsign indicates direction of propogation. double wsign = 1.; if (!pos_vel_){ wsign = -1; } // initialize the background values: // density = 1, pressure = 1/gamma, mom1 = 0, mom2 = 0, B0 = 1, B1=1.5, B2=0 // For entropy wave, mom0 = 1. Otherwise, mom0 = 0. double density_back = 1; double mom0_back = 0; double mom1_back = 0; double mom2_back = 0; double b0_back = 1.; double b1_back = 1.5; double b2_back = 0.0; // etot = pressure/(gamma-1)+0.5*rho*v^2+.5*B^2 double etot_back = (1./gamma_)/(gamma_-1.)+1.625; if (wave_type_ == "mhd_entropy"){ mom0_back = wsign; etot_back += 0.5; } // Get the eigenvalues for density, velocity, and etot double density_ev, mom0_ev, mom1_ev, mom2_ev, etot_ev, b1_ev, b2_ev; // intentionally omit b0_ev if (wave_type_ == "fast"){ double coef = 0.5/std::sqrt(5.); density_ev = 2. *coef; mom0_ev = wsign*4. * coef; mom1_ev = -1.*wsign*2. * coef; mom2_ev = 0; etot_ev = 9. * coef; b1_ev = 4. * coef; b2_ev = 0; } else if (wave_type_ == "alfven") { density_ev = 0; mom0_ev = 0; mom1_ev = 0; mom2_ev = -1.*wsign*1; etot_ev = 0; b1_ev = 0; b2_ev = 1.; } else if (wave_type_ == "slow") { double coef = 0.5/std::sqrt(5.); density_ev = 4. *coef; mom0_ev = wsign*2. * coef; mom1_ev = wsign*4. * coef; mom2_ev = 0; etot_ev = 3. * coef; b1_ev = -2. * coef; b2_ev = 0; } else { // wave_type_ == "mhd_entropy" double coef = 0.5; density_ev = 2. *coef; mom0_ev = 2. * coef * wsign; mom1_ev = 0; mom2_ev = 0; etot_ev = 1. * coef; b1_ev = 0; b2_ev = 0; } double amplitude = amplitude_; // Now allocate the actual Initializers alloc_linear_HD_initializers_(density_back, density_ev, etot_back, etot_ev, mom0_back, mom1_back, mom2_back, mom0_ev, mom1_ev, mom2_ev, density_init, etot_dens_init, momentum_init); *a_init = new RotatedVectorInit(alpha_, beta_, new LinearVectorPotentialInit(b0_back, b1_back, b2_back, b1_ev, b2_ev, amplitude, lambda)); } } //---------------------------------------------------------------------- void EnzoInitialInclinedWave::prepare_HD_initializers_ (ScalarInit **density_init, ScalarInit **etot_dens_init, VectorInit **momentum_init) { // wsign indicates direction of propogation. double wsign = 1.; if (!pos_vel_){ wsign = -1; } // the values for initializing hydrodynamical equations comes from columns of // the matrix in B3 of Stone+08. We assume the background values of // density=1, pressure = 1/gamma // // Because the calculation of the perturbations is MUCH simpler for HD than // for MHD, we allow the user to specify custom velocities. For completeness // and easy comparision to the MHD wave initialization, we specify the values // the eigenvalues, dU = (rho,rho*v0, rho*v1, rho*v2, etot_dens), under the // assumptions that v1=v2=0 and gamma = 5/3 below: // - for sound wave we assume bkg v0 = 0. To propagate at +-cs (or +-1) // In this case, dU = (1,+-1,0,0,1.5) // - For all 3 entropy waves, bkg v0 = +- 1. The requirements are: // - hd_entropy needs dU = (1,+-1,0,0,0.5) where the sign of the second // element corresponds to the sign of the bkg v0 // - hd_transv_entropy_v1: (0,0,1,0,0) // - hd_transv_entropy_v2: (0,0,0,1,0) // determine the background velocity values: double v0_back, v1_back, v2_back; v0_back = 0; v1_back = 0; v2_back = 0; if (specified_parallel_vel_()){ v0_back = parallel_vel_; } else if (wave_type_ != "sound"){ // For all types of entropy waves, if parallel_vel_ is not specified , // pos_vel_ is used to initialize the wave to 1 or -1. But if parallel_vel_ // is specified, then pos_vel_ is ignored v0_back = wsign; } // Setup the conserved background values double squared_v_back = v0_back*v0_back + v1_back*v1_back + v2_back*v2_back; double density_back, mom0_back, mom1_back, mom2_back, etot_back; density_back = 1; mom0_back = v0_back; mom1_back = v1_back; mom2_back = v2_back; etot_back = ((1. / gamma_) / (gamma_ - 1.) + 0.5 * squared_v_back); // now compute eigenvalues: double density_ev, mom0_ev, mom1_ev, mom2_ev, etot_ev; if (wave_type_ == "sound") { // under assumption that density_back = 1 and pressure_back = 1/gamma: double h_back = 1/(gamma_ - 1.) + 0.5 * squared_v_back; // enthalpy double signed_cs = wsign * 1; density_ev = 1; mom0_ev = v0_back + signed_cs; mom1_ev = v1_back; mom2_ev = v2_back; etot_ev = h_back + v0_back * signed_cs; } else if (wave_type_ == "hd_entropy") { // entropy wave where v0 is perturbed // Equivalent to "mhd_entropy" without bfield density_ev = 1; mom0_ev = v0_back; mom1_ev = v1_back; mom2_ev = v2_back; etot_ev = 0.5*squared_v_back; } else if (wave_type_ == "hd_transv_entropy_v1") { // entropy wave where v1 is perturbed density_ev = 0; mom0_ev = 0; mom1_ev = 1; mom2_ev = 0; etot_ev = v1_back; } else { // (wave_type_ == "hd_transv_entropy_v2") // entropy wave where v2 is perturbed density_ev = 0; mom0_ev = 0; mom1_ev = 0; mom2_ev = 1; etot_ev = v2_back; } //CkPrintf(("U = [rho, rho*vx, rho*vy, rho*vz, etot_dens]\n" // "bkg:[%lf, %lf, %lf, %lf, %lf]\n" // "ev: [%lf, %lf, %lf, %lf, %lf]\n"), // density_back, mom0_back, mom1_back, mom2_back, etot_back, // density_ev, mom0_ev, mom1_ev, mom2_ev, etot_ev); // Now allocate the actual Initializers alloc_linear_HD_initializers_(density_back, density_ev, etot_back, etot_ev, mom0_back, mom1_back, mom2_back, mom0_ev, mom1_ev, mom2_ev, density_init, etot_dens_init, momentum_init); } //---------------------------------------------------------------------- void EnzoInitialInclinedWave::alloc_linear_HD_initializers_ (double density_back, double density_ev, double etot_back, double etot_ev, double mom0_back, double mom1_back, double mom2_back, double mom0_ev, double mom1_ev, double mom2_ev, ScalarInit **density_init, ScalarInit **etot_dens_init, VectorInit **momentum_init) { *density_init = new RotatedScalarInit(alpha_, beta_, new LinearScalarInit(density_back, density_ev, amplitude_, lambda_)); *etot_dens_init = new RotatedScalarInit(alpha_, beta_, new LinearScalarInit(etot_back, etot_ev, amplitude_, lambda_)); *momentum_init = new RotatedVectorInit(alpha_, beta_, new LinearVectorInit(mom0_back, mom1_back, mom2_back, mom0_ev, mom1_ev, mom2_ev, amplitude_, lambda_)); }
true
6b4daad22da665ad8ea96b8d03e7c427ae6e745d
C++
robinlzw/Lemon-OS
/Applications/LemonPaint/paint.h
UTF-8
1,124
2.53125
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include <lemon/gfx/surface.h> #include <lemon/gui/widgets.h> #include <stdint.h> class Brush{ public: surface_t data; void Paint(int x, int y, uint8_t r, uint8_t g, uint8_t b, double scale, class Canvas* canvas); }; class Canvas : public Lemon::GUI::Widget { protected: vector2i_t lastMousePos; void DragBrush(vector2i_t a, vector2i_t b); Lemon::GUI::ScrollBar sBarVert; Lemon::GUI::ScrollBarHorizontal sBarHor; public: Brush* currentBrush; surface_t surface; rgba_colour_t colour; double brushScale = 1; bool pressed = false; Canvas(rect_t bounds, vector2i_t canvasSize); void DrawText(char* text, int size); void OnMouseDown(vector2i_t mousePos); void OnMouseUp(vector2i_t mousePos); void OnMouseMove(vector2i_t mousePos); void Paint(surface_t* surface); void ResetScrollbars(); }; class Colour : public Lemon::GUI::Widget { public: rgba_colour_t colour; Colour(rect_t rect){ bounds = rect; } void Paint(surface_t* surface); void OnMouseDown(vector2i_t mousePos); };
true
c9516b671fd020d58b115b7766bb8e5ed787046a
C++
willwhitney/kinova-raw
/c++ docs/Examples/Example_MonitoreTemp/src/Example_MonitorTemp.cpp
UTF-8
2,948
2.734375
3
[]
no_license
#include <iostream> #include <dlfcn.h> #include <vector> #include "../../../API/USBCommLayerUbuntu/Projects/Eclipse/Kinova.API.CommLayerUbuntu.h" #include "../../../API/USBCommandLayerUbuntu/Projects/Eclipse/Kinova.API.UsbCommandLayerUbuntu.h" #include "../../../API/USBCommandLayerUbuntu/Projects/Eclipse/KinovaTypes.h" #include <stdio.h> using namespace std; int main() { int result; GeneralInformations data; //Handle for the library's command layer. void * commandLayer_handle; //Function pointers to the functions we need int (*MyInitAPI)(); int (*MyCloseAPI)(); int (*MyGetGeneralInformations)(GeneralInformations &Response); int (*MyGetDevices)(KinovaDevice devices[MAX_KINOVA_DEVICE], int &result); int (*MySetActiveDevice)(KinovaDevice device); //We load the library commandLayer_handle = dlopen("Kinova.API.USBCommandLayerUbuntu.so",RTLD_NOW|RTLD_GLOBAL); //We load the functions from the library MyInitAPI = (int (*)()) dlsym(commandLayer_handle,"InitAPI"); MyCloseAPI = (int (*)()) dlsym(commandLayer_handle,"CloseAPI"); MyGetGeneralInformations = (int (*)(GeneralInformations &info)) dlsym(commandLayer_handle,"GetGeneralInformations"); MyGetDevices = (int (*)(KinovaDevice devices[MAX_KINOVA_DEVICE], int &result)) dlsym(commandLayer_handle,"GetDevices"); MySetActiveDevice = (int (*)(KinovaDevice devices)) dlsym(commandLayer_handle,"SetActiveDevice"); //If the was loaded correctly if((MyInitAPI == NULL) || (MyCloseAPI == NULL) || (MyGetDevices == NULL) || (MySetActiveDevice == NULL)) { cout << "* * * E R R O R D U R I N G I N I T I A L I Z A T I O N * * *" << endl; } else { cout << "I N I T I A L I Z A T I O N C O M P L E T E D" << endl << endl; result = (*MyInitAPI)(); cout << "Initialization's result :" << result << endl; KinovaDevice list[MAX_KINOVA_DEVICE]; int devicesCount = MyGetDevices(list, result); for(int i = 0; i < devicesCount; i++) { cout << "Found a robot on the USB bus (" << list[i].SerialNumber << ")" << endl; //Setting the current device as the active device. MySetActiveDevice(list[i]); MyGetGeneralInformations(data); cout << "*********************************" << endl; cout << "Actuator 1 temperature : " << data.ActuatorsTemperatures[0] << " °C" << endl; cout << "Actuator 2 temperature : " << data.ActuatorsTemperatures[1] << " °C" << endl; cout << "Actuator 3 temperature : " << data.ActuatorsTemperatures[2] << " °C" << endl; cout << "Actuator 4 temperature : " << data.ActuatorsTemperatures[3] << " °C" << endl; cout << "Actuator 5 temperature : " << data.ActuatorsTemperatures[4] << " °C" << endl; cout << "Actuator 6 temperature : " << data.ActuatorsTemperatures[5] << " °C" << endl; cout << "*********************************" << endl << endl << endl; } cout << endl << "C L O S I N G A P I" << endl; result = (*MyCloseAPI)(); } dlclose(commandLayer_handle); return 0; }
true
8c4e651cc4bf20285d81c594567e14701f3c2570
C++
viniciusbandeira/Dauphine
/src/Enemy.cpp
UTF-8
8,800
3
3
[]
no_license
/* Dauphine * Universidade de Brasília - FGA * Técnicas de Programação, 2/2017 * @Enemy.cpp * File responsible for implementing the enemies of the game (except the boss). * They define the basic image and characteristics of the enemy, upgrade, destruction, collision among others. * License: Copyright (C) 2014 Alke Games. */ #include <assert.h> #include "Enemy.h" #include "Logger.h" #include "LuaScript.h" #include <cmath> #include "EStateIdle.h" #include "EStatePatrolling.h" #include "EStateAerial.h" #include "EStateCurious.h" #include "EStateAlert.h" #include "EStateAttack.h" #include "EStateDead.h" #include "Window.h" #define ADD_STATE_EMPLACE(stateEnum, stateClass) this -> states_map.emplace(stateEnum, new stateClass( this )) #define ADD_STATE_INSERT(stateEnum, stateClass) this -> states_map.insert(std::make_pair<EStates, StateEnemy*>(stateEnum, new stateClass( this ))); //Declaring and initialing position enemy in the origin of the x axis double Enemy::px = 0.0; //Declaring and initialing position enemy in the origin of the y axis double Enemy::py = 0.0; //Declaring the enemy with 3 life quantity unsigned int Enemy::points_life = 3; //Check if enemy is position vulnerable bool Enemy::position_vulnerable = false; //Declaring the value for range dangerous of proximity for a enemy double Enemy::alert_range = 300.0; //Double value existing at pvulnerable double Enemy::curious_range = 600.0; /* * Method used to create all characteristics Enemy * @param x_ : Position on the x axis of the enemy * @param y_ : Position on the y axis of the enemy * @param PATH : The path to the desired sprite * @param patrol_ : Defines if the enemy patrols. * @param patrolLength_ : Defines the space traveled by the patrolman */ Enemy::Enemy( const double x_, const double y_, const std::string& PATH, const bool patrol_, const double patrolLength_ ) : DynamicEntity(x_, y_, PATH), original_X(x_), patrol(patrol_), patrol_length(patrolLength_), life(100), current_state(nullptr), animation(nullptr), states_map(), dead(false) { // Initialize all the states in Enemy. initializeStates(); this -> speed = 3.0; //Getting information from lua script. LuaScript luaEnemy("lua/Enemy.lua"); // Setting the level width/height. this -> width = luaEnemy.unlua_get<int>("enemy.dimensions.width"); this -> height = luaEnemy.unlua_get<int>("enemy.dimensions.height"); this -> animation = new Animation(0, 0, this -> width, this -> height, 0, false); //Condition to attribute the states map to current state. if ( this -> patrol ) { this -> current_state = this -> states_map.at(PATROLLING); } else { this -> current_state = this -> states_map.at(IDLE); } this -> current_state -> enter(); } /* * Method to destroy the enemy */ Enemy::~Enemy() { //Attribute null to current state if ( this -> current_state != nullptr ) { this -> current_state -> exit(); this -> current_state = nullptr; } else { Log ( INFO ) << "\tEnemy is null"; } //Attribute null to animation if ( this -> animation != nullptr ) { delete this -> animation; this -> animation = nullptr; } else { Log ( INFO ) << "\tAnimation is null"; } destroyStates(); } /* * Method to update characteristics of the enemy * @param dt : delta time (time elapsed) */ void Enemy::update( const double DELTA_TIME) { assert( DELTA_TIME >= 0 ); //const double dt is passed as a parameter to know the time elapsed. this -> current_state -> update( DELTA_TIME); forceMaxSpeed(); scoutPosition( DELTA_TIME); this -> animation -> update( this -> animationClip, DELTA_TIME); updateBoundingBox(); //Array to detect collision with enemy const std::array<bool, CollisionSide::SOLID_TOTAL> detections = detectCollision(); handleCollision(detections); updatePosition( DELTA_TIME); } /* * Method to update characteristics of the enemy * @param cameraX_ : Define the locate for the camera on the x-axis * @param cameraY_ : Define the locate for the camera on the y-axis */ void Enemy::render( const double cameraX_, const double cameraY_) { const double dx = this -> x - cameraX_; const double dy = this -> y - cameraY_; /////////////////////////////////////////////////////////////////////////////////////////// // // Actual. // SDL_Rect actualRect = {(int)dx, (int)dy, (int)this->width, (int)this->height}; // SDL_SetRenderDrawColor( Window::getRenderer(), 0x00, 0x00, 0x00, 0xFF); // SDL_RenderFillRect(Window::getRenderer(), &actualRect); // Bounding box. // SDL_Rect boundingBox2 = {(int)(this->boundingBox.x - cameraX_), (int)(this->boundingBox.y - cameraY_), (int)this->boundingBox.w, (int)this->boundingBox.h}; // SDL_SetRenderDrawColor( Window::getRenderer(), 0xFF, 0xFF, 0xFF, 0xFF); // SDL_RenderFillRect(Window::getRenderer(), &boundingBox2); // /////////////////////////////////////////////////////////////////////////////////////////// if ( this -> sprite != nullptr ) { SDL_RendererFlip flip = getFlip(); if ( flip == SDL_FLIP_HORIZONTAL ) { this -> sprite->render(dx - 120, dy, &this -> animationClip, false, 0.0, nullptr, flip); } else { this -> sprite -> render(dx, dy, &this -> animationClip, false, 0.0, nullptr, flip); } } } /* * Initialize all the states in Enemy here. */ void Enemy::initializeStates() { ADD_STATE_INSERT(IDLE, EStateIdle); ADD_STATE_INSERT(CURIOUS, EStateCurious); ADD_STATE_INSERT(PATROLLING, EStatePatrolling); ADD_STATE_INSERT(ALERT, EStateAlert); ADD_STATE_INSERT(AERIAL, EStateAerial); ADD_STATE_INSERT(ATTACK, EStateAttack); ADD_STATE_INSERT(DEAD, EStateDead); } /* * Delete all the states in Enemy here. */ void Enemy::destroyStates() { std::map<EStates, StateEnemy*>::const_iterator it; for ( it = this -> states_map.begin(); it != this -> states_map.end(); it++ ) { delete it->second; } } /* * Method used to exchange enemy of position * @param state_ : Define state enemy */ void Enemy::changeState( const EStates state_) { this -> current_state -> exit(); this -> current_state = this -> states_map.at(state_); this -> current_state -> enter(); } /* * Method used to check collision in enemy * @param detections : Pass an array of array containing the type of collision. */ void Enemy::handleCollision( std::array<bool, CollisionSide::SOLID_TOTAL> detections_) { //Collision on top if ( detections_.at(CollisionSide::SOLID_TOP) ) { this -> velocity_y_axis = 0.0; } else { Log ( INFO ) << "\tColision not detected"; } //Collision on bottom if ( detections_.at(CollisionSide::SOLID_BOTTOM) ) { if ( this -> current_state == this -> states_map.at(EStates::AERIAL) || this -> current_state == this -> states_map.at (EStates::DEAD)) { this -> nextY -= fmod( this -> nextY, 64.0 ) - 16.0; this -> velocity_y_axis = 0.0; if ( this -> isDead() ) { this -> changeState(EStates::DEAD); } else { Log ( INFO ) << "\tColision not detected"; } if ( this -> patrol ) { this -> changeState(EStates::PATROLLING); } else { this -> changeState(EStates::IDLE); return; } } else { Log ( INFO ) << "\tColision not detected"; } } else { if ( this -> current_state != this -> states_map.at(EStates::AERIAL) ) { changeState(EStates::AERIAL); } else { // No Action. } } //Collision on left if ( detections_.at(CollisionSide::SOLID_LEFT) ) { this -> nextX = this -> x; this -> velocity_x_axis = 0.0; } else { Log ( INFO ) << "\tColision not detected"; } //Collision on right if ( detections_.at(CollisionSide::SOLID_RIGHT) ) { this -> nextX = this -> x; this -> velocity_x_axis = -0.001; } else { Log ( INFO ) << "\tColision not detected"; } } /* * Designates maximum velocity on the x-axis and y */ void Enemy::forceMaxSpeed() { this -> velocity_x_axis = ( this -> velocity_x_axis >= this -> maxSpeed) ? this -> maxSpeed : this -> velocity_x_axis ; this -> velocity_y_axis = ( this -> velocity_y_axis >= this -> maxSpeed) ? this -> maxSpeed : this -> velocity_y_axis ; } /* * Reference the specific animation. */ Animation *Enemy::getAnimation() { return ( this -> animation ); } /* * Setting enemy is dead * @param isDead_ : It says if it is alive or dead */ void Enemy::set_dead( bool isDead_) { this -> dead = isDead_; } /* * Inform that enemy is dead */ bool Enemy::isDead() { return this -> dead; } /* * Method to delimit enemy dimensions update */ void Enemy::updateBoundingBox() { //Bounding box at x position this -> boundingBox.x = (int) this -> nextX + 40; //Bounding box at y position this -> boundingBox.y = (int) this -> nextY + 40; //Bounding box at width this -> boundingBox.w = 150; //Bounding box at height this -> boundingBox.h = 200; }
true
a6c5571036119f714edd7a4683c3677ef4c87aff
C++
iskislamov/metaprogramming
/task2/Source.cpp
UTF-8
1,395
2.546875
3
[]
no_license
#include "typelist.h" #include "hierarchy.h" #include "fibonacci.h" #include <typeinfo> class A { }; class B : A { }; using TL1 = TypeList<int>; using TL2 = TypeList<char, short, std::string>; using TL3 = TypeList<double, float, float, double, int, char, int, NullType>; using TL4 = TypeList<long int, std::string, float, double, int, char, char, int, char, A>; using TL5 = TypeList<NullType>; using GLH = GenLinearHierarchy<Fibonacci<8>::value, TL3, Unit>; using GSH = GenScatterHierarchy<TL4, Unit>; void test() { std::cout << std::boolalpha << IsEmpty<TL1>::value << " " << IsEmpty<EmptyList>() << std::endl; std::cout << Length<TL3>::value << " " << Length<EmptyList>::value << std::endl; std::cout << Length<TL5>::value << std::endl; static_assert(std::is_same<TypeAt<1, TL2>::type, short>::value, "Something wrong!"); printTypeList<TL4>(); std::cout << typeid(TypeAt<7, TL4>::type).name(); printTypeList<Skip<Fibonacci<6>::value, TL4>::result>(); } int main() { GLH glh; GSH gsh; //test(); std::cout << sizeof(static_cast<GenLinearHierarchy<Fibonacci<0>::value , TL4, Unit>> (gsh)) << std::endl; std::cout << sizeof(TypeAt<0, TL4>::type) << std::endl; std::cout << sizeof(static_cast<GenLinearHierarchy<Fibonacci<1>::value, Skip<Fibonacci<0>::value, TL4>::result, Unit>> (gsh)) << std::endl; std::cout << sizeof(TypeAt<1, TL4>::type) << std::endl; return 0; }
true
64a374a10794394f9663e086ebec7730d17fd46a
C++
SuHe36/Algorithm
/C++/code/常量/main2.cpp
UTF-8
959
4.03125
4
[]
no_license
/* 使用const关键字进行修饰 const修饰指针时,有三种情况: --1, const修饰指针指向的内容,即内容不可变量; 如: const int *p=8;【此时const位于*号的左边】 --2, const修饰指针,即指针为不可变量,但是指针修饰的内容可以改变;如: int a=8; int* const p = &a; *p = 9;//正确 int b=7; p = &b;//错误 对于const修饰指针,即指针的内存地址不可以改变,但是它修饰的内容可以改变,此时const位于*号的右边; --3, const修饰指针和指针指向的内容,也就是指针和指针指向的内容都为不可变量;此时为1,2两种情况的合并; int a=8; const int* const p = &a; */ #include <iostream> using namespace std; int main() { const int LENGTH = 19; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; }
true
6433117ea048f2806e7de39258b28280d34b8b9c
C++
ryanignatius/CPLibrary
/src/dmst.cpp
UTF-8
2,613
2.9375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long weightType; const weightType INF = 1e18; const int MAXN = 1010; class DMST { private: int n, m; int back[MAXN], label[MAXN], bio[MAXN]; weightType cost[MAXN]; vector<int> x, y; vector<weightType> w; public: DMST(int N, int M) { n = N; m = M; x.clear(); y.clear(); w.clear(); } void addEdge(int from, int to, weightType weight) { x.push_back(from); y.push_back(to); w.push_back(weight); } weightType dmst(int root) { int curroot = root; int curn = n; weightType ret = 0; while (1) { for (int i=0; i<curn; i++) { cost[i] = INF; } for (int i=0; i<m; i++) { if (x[i] == y[i]) continue; if (w[i] < cost[y[i]]) { cost[y[i]] = w[i]; back[y[i]] = x[i]; } } cost[curroot] = 0; for (int i=0; i<curn; i++) { if (cost[i] == INF) { return -1; } ret += cost[i]; } int comp = 0; int temp; memset(label, -1, sizeof label); memset(bio, -1, sizeof bio); for (int i=0; i<curn; i++) { temp = i; for (; temp != curroot && bio[temp] == -1; temp = back[temp]) { bio[temp] = i; } if (temp != curroot && bio[temp] == i) { for (; label[temp] == -1; temp = back[temp]) { label[temp] = comp; } comp++; } } if (comp == 0) break; for (int i=0; i<curn; i++) { if (label[i] == -1) { label[i] = comp; comp++; } } int xx, yy; for (int i=0; i<m; i++) { xx = label[x[i]]; yy = label[y[i]]; if (xx != yy) { w[i] -= cost[y[i]]; } x[i] = xx; y[i] = yy; } curroot = label[curroot]; curn = comp; } return ret; } }; int main() { DMST dmst(3, 4); dmst.addEdge(0, 1, 40); dmst.addEdge(0, 2, 50); dmst.addEdge(1, 2, 20); dmst.addEdge(2, 1, 0); cout << "minimal cost: " << dmst.dmst(0) << endl; return 0; }
true
be4449a0c0c8dcc37ee144fa8c62ddc272fb61a7
C++
HSchmale16/NumberHunterGame
/src/UI.cpp
UTF-8
4,727
3.03125
3
[ "CC-BY-3.0" ]
permissive
/** UI Class Implementation * @author Henry Schmale * @date October 5, 2014 * @file src/UI.cpp */ #include "../include/UI.h" #include "../FilePaths.h" #include "../config.h" #include <stdio.h> // for sprintf #include <math.h> // for sqrt UI::UI() { //ctor // load font and bind it to sf::Text Objects if(!font.loadFromFile(MAIN_FONT)) { hjs::logToConsole("Failed to load MAIN_FONT in UI"); } if(!m_texBG.loadFromFile(config.Get("ui_config", "ui_texture", "NULL"))) { hjs::logToConsole("Failed to load ui texture"); exit(2); } // setup Background m_BG.setSize(sf::Vector2f(375, 50)); m_BG.setPosition(0, 600); m_BG.setFillColor(sf::Color::White); m_BG.setTexture(&m_texBG); // setup score m_nScore = 0; //init to 0 points m_ScoreText.setFont(font); m_ScoreText.setCharacterSize(12); m_ScoreText.setPosition(5, 605); m_ScoreText.setColor(sf::Color::White); char numStr[20]; sprintf(numStr, "Points: %d", m_nScore); // convert m_nScore to char array m_ScoreText.setString(numStr); // set up target condition setCondition(EVEN_NUM); m_TargetText.setFont(font); m_TargetText.setCharacterSize(12); m_TargetText.setPosition(200, 605); m_TargetText.setColor(sf::Color::White); // setup health bar m_MaxHealth = 100; m_CurrentHealth = m_MaxHealth; m_HealthBox.setOutlineColor(sf::Color::Black); m_HealthBox.setOutlineThickness(1); m_HealthBox.setPosition(5, 630); m_HealthBox.setSize(sf::Vector2f(m_MaxHealth, 15)); m_HealthBox.setFillColor(sf::Color::Transparent); m_HealthBar.setFillColor(sf::Color::Red); m_HealthBar.setSize(sf::Vector2f(m_MaxHealth, 15)); m_HealthBar.setPosition(5, 630); } UI::~UI() { //dtor } void UI::Reset() { // reset score m_nScore = 0; char numStr[20]; sprintf(numStr, "Points: %d", m_nScore); // convert m_nScore to char array m_ScoreText.setString(numStr); } void UI::draw(sf::RenderTarget &target, sf::RenderStates states)const { target.draw(m_BG, states); // draw the bg target.draw(m_ScoreText, states); // draw scoreText target.draw(m_TargetText, states); // draw TargetText target.draw(m_HealthBar, states); target.draw(m_HealthBox, states); } void UI::addPoints(int points) { m_nScore += points; char numStr[20]; sprintf(numStr, "Points: %d", m_nScore); // convert m_nScore to char array m_ScoreText.setString(numStr); } // Random Target Selection void UI::setNewCondition() { // perform a static cast to convert an int into a valid enumerated value m_eTarget = static_cast<SalvCondition>(rand() % NUM_TYPES_SALVCONDITION); updateTarget(); // update the target on UI bar } // set m_eTarget to specified condition void UI::setCondition(SalvCondition condition) { m_eTarget = condition; updateTarget(); } // updates the prompt on screen for which type of salvage to collect void UI::updateTarget() { switch(m_eTarget) { case EVEN_NUM: m_TargetText.setString("Find an Even Number"); break; case ODD_NUM: m_TargetText.setString("Find an Odd Number"); break; case PRIME_NUM: m_TargetText.setString("Find a Prime Number"); break; default: hjs::logToConsole("Invalid Value in UI SalvageValue Enumeration"); exit(2); } } bool UI::isSalvValGood(int val) { switch(m_eTarget) { case EVEN_NUM: /// @todo action on even if(val % 2 == 0) return true; else return false; break; case ODD_NUM: /// @todo action on odd if(val % 2 == 1) return true; else return false; break; case PRIME_NUM: // Basic Prime Number Test if(val <= 3) { return val > 1; } else if ((val % 2 == 0) | (val % 3 == 0)) { return false; } else { for(int i = 5; i < sqrt(val) + 1; i += 6) { if((val % i == 0) | (val % (i + 2) == 0)) { return false; } } return true; } break; default: /// something bad happened hjs::logToConsole("Invalid Value in UI SalvageValue Enumeration"); exit(2); } } int UI::getScore() { return m_nScore; } void UI::updateHealth(int n) { m_CurrentHealth += n; m_HealthBar.setSize(sf::Vector2f(m_CurrentHealth, 15)); } void UI::resetHealth() { m_CurrentHealth = m_MaxHealth; m_HealthBar.setSize(sf::Vector2f(m_MaxHealth, 15)); }
true
e9b56e9146bee76ef348c0fb80a796d65ffe17fe
C++
robinsinghpatiyal/CppCodes
/Array/pair_with_given_diff.cpp
UTF-8
682
3.03125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void sol(int arr[], int n, int diff) { int start = 0; int end = 1; sort(arr, arr + n); int flag = 0; while (n > 0) { if (arr[end] - arr[start] == diff) { cout << arr[start] << " " << arr[end] << " " << endl; flag = 1; return; } else if (arr[end] - arr[start] > diff) { start++; } else { end++; } n--; } if (flag == 0) { cout << -1; } } int main() { int n = 5; int diff = 45; int arr[] = {90, 70, 20, 80, 50}; sol(arr, n, diff); }
true
a2405451a2a8cb8d6b725940b75d71110c04926f
C++
scottgw/quicksilver
/runtime/tests/sched_layer/sched_layer.cpp
UTF-8
2,195
2.671875
3
[]
no_license
#include <gtest/gtest.h> #include <libqs/sync_ops.h> #include <libqs/sched_task.h> #include <internal/executor.h> #include <internal/task.h> #define SCHEDULE_MULTIPLE_NUM 1000 int32_t finished; void exec_tester(int num_tasks, int num_execs, void (*f)(void*)) { // volatile means we can ask gdb about it later volatile sync_data_t sync_data = sync_data_new(num_tasks); sched_task_t *task_array = (sched_task_t*) malloc(num_tasks * sizeof(sched_task_t)); finished = 0; for (int i = 0; i < num_tasks; i++) { sched_task_t stask = stask_new(sync_data); task_array[i] = stask; stask_set_func(stask, f, stask); } sync_data_create_executors (sync_data, num_execs); ASSERT_EQ(sync_data_num_processors(sync_data), num_tasks); for (int i = 0; i < num_tasks; i++) { sched_task_t stask = task_array[i]; sync_data_enqueue_runnable(sync_data, stask); } sync_data_join_executors(sync_data); ASSERT_EQ(finished, num_tasks); ASSERT_EQ(sync_data_num_processors(sync_data), 0); sync_data_free(sync_data); free(task_array); } void schedule_multiple(void* data) { __sync_add_and_fetch(&finished, 1); } TEST(SchedTask, ScheduleSingleTask) { exec_tester(1, 1, schedule_multiple); } TEST(SchedTask, ScheduleMultipleTasksSingleExecutor) { exec_tester(SCHEDULE_MULTIPLE_NUM, 1, schedule_multiple); } TEST(SchedTask, ScheduleMultipleTasksMultipleExecutors) { exec_tester(SCHEDULE_MULTIPLE_NUM, 8, schedule_multiple); } void preempt_task(void* data) { sched_task_t stask = (sched_task_t) data; task_set_state(stask->task, TASK_TRANSITION_TO_RUNNABLE); stask_yield_to_executor(stask); schedule_multiple(NULL); task_set_state(stask->task, TASK_TRANSITION_TO_RUNNABLE); stask_yield_to_executor(stask); } TEST(SchedTask, SchedulePreempt1SingleExecutor) { exec_tester(1, 1, preempt_task); } TEST(SchedTask, SchedulePreemptSingleExecutor) { exec_tester(SCHEDULE_MULTIPLE_NUM, 1, preempt_task); } TEST(SchedTask, SchedulePreemptMultipleExecutors) { exec_tester(SCHEDULE_MULTIPLE_NUM, 8, preempt_task); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
06654f476bda0ab0fa1d3eb82a8ce76cdd650510
C++
Wanghailin2019/dataStructureUsingCpp
/chapter7_linked_list/237_circular_linked_list.cpp
UTF-8
2,545
3.671875
4
[]
no_license
/******************************************************** Filename:237_circular_linked_list.c Author name: Timothy Time:2021/08/10 Version:v1 Description: Creating Circular Header Linked List. 注:代码逻辑有一些问题! *********************************************************/ # include <stdio.h> # include <stdlib.h> # include <iostream> #include <iomanip> #include <conio.h> using namespace std; struct link { int info; struct link *next; }; int i; /* Represents number of nodes in the list */ int number=0; struct link start,*node, *new1; void create() { char ch; node = &start; /* Point to the header node in the list */ i = 0; do { node->next = (struct link* ) malloc(sizeof(struct link)); node = node->next; cout<<"\n Input the node"<<i+1<<": "; // fflush(stdin); // fflush(stdout); cin>>node->info; // fflush(stdout); cout<<"\n DO YOU WANT TO CREATE MORE[Y/N] "; cin>>ch; i++; }while(ch=='y' || ch=='Y'); node->next = &start; start.info = i; /* Assign total number of nodes to the header node */ } void insertion() { struct link *first; first=&start; node=start.next; int opt; int count = node->info; int node_number = 1; int insert_node; node = node->next; cout<<"\n Input node number you want to insert. "; cout<<"\n Value should be less are equal to the"; cout<<"\n number of nodes in the list: "; cin>>insert_node; while(count--) { if(node_number == insert_node) { new1 = (struct link* )malloc(sizeof(struct link)); first->next=new1; new1->next = node; cout<<"\n Input the node value: "; cin>>new1->info; opt=1; break; } else { node = node->next; first=first->next; } node_number ++; } if (opt==1) { node = &start; /* Points to header node */ node->info = node->info+1; } } /* Display the list */ void display() { node=&start; int count = node->info; do { cout<<setw(5)<<node->info; //使用setw()函数需要包含头文件<iomanip> node = node->next; }while(count--); } int main() { create(); cout<<"\n Before inserting a node list is as follows:\n"; display(); insertion(); cout<<"\n After inserting a node list is as follows:\n"; display(); }
true
86cd972f06f21987ca87edd10951c608551e1eac
C++
rushioda/PIXELVALID_athena
/athena/ForwardDetectors/FPTracker/src/SimpleLogger.cxx
UTF-8
2,958
2.515625
3
[]
no_license
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "FPTracker/SimpleLogger.h" #include <algorithm> namespace FPTracker { struct Consolidator { void operator()( const std::pair< unsigned int, std::string >& element) { m_msg += element.second; } std::string m_msg; }; std::string consolidate(std::vector< std::pair< unsigned int, std::string > > msgs) { return std::for_each( msgs.begin(), msgs.end(), Consolidator() ).m_msg; } SimpleLogger* SimpleLogger::m_instance = 0; SimpleLogger* SimpleLogger::getLogger() { if ( m_instance == 0 ) { m_instance = new SimpleLogger; } return m_instance; } void SimpleLogger::debug (const std::string& msg) { m_debugMsg.push_back ( std::pair< unsigned int, std::string >( m_index, msg) ); ++m_index; } void SimpleLogger::info (const std::string& msg) { m_infoMsg.push_back ( std::pair< unsigned int, std::string >( m_index, msg) ); ++m_index; } void SimpleLogger::warning(const std::string& msg) { m_warningMsg.push_back( std::pair< unsigned int, std::string >( m_index, msg) ); ++m_index; } void SimpleLogger::error (const std::string& msg) { m_errorMsg.push_back ( std::pair< unsigned int, std::string >( m_index, msg) ); ++m_index; } void SimpleLogger::debug (const std::ostringstream& msg) { this->debug( msg.str() ); } void SimpleLogger::info (const std::ostringstream& msg) { this->info( msg.str() ); } void SimpleLogger::warning(const std::ostringstream& msg) { this->warning( msg.str() ); } void SimpleLogger::error (const std::ostringstream& msg) { this->error( msg.str() ); } std::vector< std::pair< unsigned int, std::string > > SimpleLogger::debugMsgs () const { return m_debugMsg; } std::vector< std::pair< unsigned int, std::string > > SimpleLogger::infoMsgs () const { return m_infoMsg; } std::vector< std::pair< unsigned int, std::string > > SimpleLogger::warningMsgs() const { return m_warningMsg; } std::vector< std::pair< unsigned int, std::string > > SimpleLogger::errorMsgs () const { return m_errorMsg; } std::string SimpleLogger::debug () const { return consolidate(m_debugMsg); } std::string SimpleLogger::info () const { return consolidate(m_infoMsg); } std::string SimpleLogger::warning() const { return consolidate(m_warningMsg); } std::string SimpleLogger::error () const { return consolidate(m_errorMsg); } void SimpleLogger::reset() { m_index = 0; m_debugMsg.erase ( m_debugMsg.begin(), m_debugMsg.end() ); m_infoMsg.erase ( m_infoMsg.begin(), m_infoMsg.end() ); m_warningMsg.erase( m_warningMsg.begin(), m_warningMsg.end() ); m_errorMsg.erase ( m_errorMsg.begin(), m_errorMsg.end() ); } SimpleLogger::SimpleLogger():m_index(0){} }
true
2ea25da83c47c6912d8747cd22e54ae285e6f348
C++
lauralex/Cpp-Experiments
/Experiments/SmartPointer-example/SmartPointer-example.cpp
UTF-8
1,238
3.6875
4
[ "MIT" ]
permissive
#include <iostream> #include <memory> #include <string> #include <utility> /** * \brief This is a class using a std::string to allocate memory */ class std_string { public: explicit std_string(std::string my_string); void print() const; std_string() = delete; private: std::string my_string_; }; std_string::std_string(std::string my_string) : my_string_{std::move(my_string)} { } void std_string::print() const { std::cout << my_string_; } /** * \brief This is a class using a unique pointer to allocate memory */ class smart_ptr { public: explicit smart_ptr(const std::string& my_string); smart_ptr() = delete; private: std::unique_ptr<char[]> my_string_; }; smart_ptr::smart_ptr(const std::string& my_string) { my_string_ = std::make_unique<char[]>(20); my_string.copy(my_string_.get(), 20, 0); } void check_mem() { const std_string pex{"hello"}; // Use a std::string to allocate memory const smart_ptr rex{"neck"}; // Use a unique pointer to allocate memory (both will manage memory deallocation!) pex.print(); } int main() { // Check if there are any memory leaks! (if we use smart pointers, there won't be any!) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); check_mem(); return 0; }
true
36a7ca567dd58815db013b5a12a607deca11fa2c
C++
chromium/chromium
/ui/gfx/animation/slide_animation.h
UTF-8
4,201
2.578125
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_ANIMATION_SLIDE_ANIMATION_H_ #define UI_GFX_ANIMATION_SLIDE_ANIMATION_H_ #include "base/memory/raw_ptr.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/gfx/animation/tween.h" namespace gfx { // Slide Animation // // Used for reversible animations and as a general helper class. Typical usage: // // #include "ui/gfx/animation/slide_animation.h" // // class MyClass : public AnimationDelegate { // public: // MyClass() { // animation_ = std::make_unique<SlideAnimation>(this); // animation_->SetSlideDuration(base::Milliseconds(500)); // } // void OnMouseOver() { // animation_->Show(); // } // void OnMouseOut() { // animation_->Hide(); // } // void AnimationProgressed(const Animation* animation) { // if (animation == animation_.get()) { // Layout(); // SchedulePaint(); // } else if (animation == other_animation_.get()) { // ... // } // } // void Layout() { // if (animation_->is_animating()) { // hover_image_.SetOpacity(animation_->GetCurrentValue()); // } // } // private: // std::unique_ptr<SlideAnimation> animation_; // } class ANIMATION_EXPORT SlideAnimation : public LinearAnimation { public: explicit SlideAnimation(AnimationDelegate* target); SlideAnimation(const SlideAnimation&) = delete; SlideAnimation& operator=(const SlideAnimation&) = delete; ~SlideAnimation() override; // Set the animation to some state. virtual void Reset(double value = 0); // Begin a showing animation or reverse a hiding animation in progress. // Animates GetCurrentValue() towards 1. virtual void Show(); // Begin a hiding animation or reverse a showing animation in progress. // Animates GetCurrentValue() towards 0. virtual void Hide(); // Sets the time a slide will take. Note that this isn't actually // the amount of time an animation will take as the current value of // the slide is considered. virtual void SetSlideDuration(base::TimeDelta duration); base::TimeDelta GetSlideDuration() const { return slide_duration_; } void SetTweenType(Tween::Type tween_type) { tween_type_ = tween_type; } // Dampens the reduction in duration for an animation which starts partway. // The default value of 1 has no effect. void SetDampeningValue(double dampening_value); double GetCurrentValue() const override; // TODO(bruthig): Fix IsShowing() and IsClosing() to be consistent. e.g. // IsShowing() will currently return true after the 'show' animation has been // completed however IsClosing() will return false after the 'hide' animation // has been completed. bool IsShowing() const { return direction_ == Direction::kShowing || (!direction_ && value_current_ == 1); } bool IsClosing() const { return direction_ == Direction::kHiding && value_end_ < value_current_; } class TestApi; private: // Gets the duration based on the dampening factor and whether the animation // is showing or hiding. base::TimeDelta GetDuration(); enum class Direction { kShowing, kHiding, }; // Implementation of Show() and Hide(). void BeginAnimating(Direction direction); // Overridden from Animation. void AnimateToState(double state) override; raw_ptr<AnimationDelegate, DanglingUntriaged> target_; Tween::Type tween_type_ = Tween::EASE_OUT; // Current animation direction, or nullopt if not animating. absl::optional<Direction> direction_; // Animation values. These are a layer on top of Animation::state_ to // provide the reversability. double value_start_ = 0; double value_end_ = 0; double value_current_ = 0; // How long a hover in/out animation will last for. This can be overridden // with SetSlideDuration(). base::TimeDelta slide_duration_ = base::Milliseconds(120); // Dampens the reduction in duration for animations which start partway. double dampening_value_ = 1.0; }; } // namespace gfx #endif // UI_GFX_ANIMATION_SLIDE_ANIMATION_H_
true
4ed1d0444992941e414382f08b18f21eab538569
C++
lavalake/myLeetcode
/bitm/reversebit.cpp
UTF-8
403
3.546875
4
[]
no_license
#include <iostream> #include <stdlib.h> unsigned int reverseBits(unsigned int num){ int i=0; int num_bits = sizeof(num) * 8; int reversed = 0; for(i=0; i<num_bits; ++i){ if(num & (1<<i)) reversed |= 1<<(num_bits-1-i); } return reversed; } int main(){ unsigned int input = 121; int reversed=0; reversed = reverseBits(input); std::cout<<"input:"<<input; std::cout<<"reverse:"<<reversed; }
true
76a22200d4b888586916e016556d782f6973960e
C++
Nemolicious15/Lab10-OOP
/Lab10Matrice/Lab10Matrice/pixelgri.cpp
UTF-8
512
2.84375
3
[]
no_license
#include "pixelgri.h" Gri :: Gri() { gri=0; } Gri :: Gri(int g) { gri=g; } Gri :: Gri(Gri& g) { gri=g.gri; } Gri ::~Gri() { } void Gri:: setgri(int g){ gri=g; } int Gri :: getgri(){ return gri; } Gri& Gri :: operator= (const Gri& g){ gri=g.gri; return* this; } bool Gri:: operator== (const Gri& g){ if (gri==g.gri) return true; else return false; } bool Gri:: operator!=(const Gri& g){ if (gri=!g.gri) return true; else return false; }
true
cc5918affeeefe55e92e7da9f0af410e265544a3
C++
danzmoses/cs100-project
/header/prototypes/armor/LeatherArmorPrototype.h
UTF-8
769
2.90625
3
[]
no_license
#ifndef __LEATHERARMOR_PROTOTYPE__ #define __LEATHERARMOR_PROTOTYPE__ #include "ArmorPrototype.h" class LeatherArmorPrototype : public ArmorPrototype { public: LeatherArmorPrototype() : ArmorPrototype() { this->setName("Leather Armor"); this->setCost(50); baseStats->ATK = 0; baseStats->DEF = 1; baseStats->HP = 0; baseStats->maxHP = 0; combatStats->ATK = 0; combatStats->DEF = 1; combatStats->HP = 0; combatStats->maxHP = 0; } LeatherArmorPrototype(std::string name) : ArmorPrototype(name) {} virtual ArmorPrototype* Clone() { return new LeatherArmorPrototype(); } }; #endif // __LEATHERARMOR_PROTOTYPE__
true
682589c0b9c5e2472f5a8cdc46249d7d04300adc
C++
Fumikage8/gen7-source
/gflib2/debug/source/DynamicHeader/gfl2_DebugCppEnumHeaderParser.cpp
UTF-8
7,427
2.703125
3
[]
no_license
//============================================================================= /** * @brief ヘッダファイルを解析しEnumの定義を取得するクラスの実装 * @file gfl2_DebugCppEnumHeaderParser.cpp * @author Kanamaru Masanori * @date 2015.2.20 */ //============================================================================= #include <debug/include/DynamicHeader/internal/gfl2_DebugCppEnumHeaderParser.h> #include <stdlib.h> //use stdtol namespace { // ヘッダ解析に必要な処理のみ実装した文字列クラス template<int TLength> class XString { char buffer[TLength]; public: // 文字列前後の空白文字と制御文字を取り除く void Trim() { size_t length = 0; if (this->buffer[0] == '\0') { return; } length = strlen(this->buffer); // rigthTrim for (int i = strlen(this->buffer); i >=0; --i) { if (this->buffer[i] >= '!') { length = i+1; break; } } this->buffer[length] = '\0'; // leftTrim s32 new_start = -1; for (u32 i = 0; i <= length; ++i) { if(new_start == -1 && this->buffer[i] >= '!') { new_start = static_cast<s32>(i); } if (new_start > -1) { this->buffer[i - new_start] = this->buffer[i]; } } } // 特定の文字列で開始しているか判定 bool StartWith(const char* query) { size_t t_length = strlen(this->buffer); size_t q_length = strlen(query); if (t_length < q_length) { return false; } for (u32 i=0; i < q_length; ++i) { if (this->buffer[i] != query[i]) { return false; } } return true; } // 空白文字と制御文字で文字列を分割する int Split(char out[][TLength]) { size_t length = strlen(this->buffer); int outIndex = 0; int outInnerIndex = 0; bool delimiter = true; for (u32 i = 0; i < length; ++i) { if (this->buffer[i] < '!') { if (delimiter == false) { out[outIndex][outInnerIndex] = '\0'; ++outIndex; outInnerIndex = 0; } delimiter = true; } else { out[outIndex][outInnerIndex] = this->buffer[i]; ++outInnerIndex; delimiter = false; } } if (delimiter == false) { out[outIndex][outInnerIndex] = '\0'; } return outIndex + (delimiter ? 0 : 1); } // 生文字列へのポインタを取得する char* GetCStr() { return this->buffer; } }; } namespace gfl2 { namespace debug { namespace DynamicHeader { //---------------------------------------- /** * @brief 初期化処理 * * @param path 処理するファイルのパス * @param pRootPath pathのルート設定 * @param pHeap 使用するヒープへのポインタ */ //---------------------------------------- void CppEnumHeaderParser::Initialize(const char* path, const RootPathConfig* pRootPath, gfl2::heap::HeapBase* pHeap) { this->trs.Initialize(path, pRootPath, pHeap); this->stateStack.Push(Global); this->currentValue = -1; } //---------------------------------------- /** * @brief enumで定義された定数値のキーと値の組を1組取得する * * @param outKey キー文字列 * @param outValue キーに対応する値 * * @retval true 定義を取得した * @retval false 定義を取得できず、ファイルを末端まで読み終わった */ //---------------------------------------- bool CppEnumHeaderParser::ReadDefinition(char* outKey, int* outValue) { XString<LineMaxLength> line; while(this->trs.ReadLine(line.GetCStr(), LineMaxLength) != 0) { // 前後の空白・制御文字削除 line.Trim(); if (strlen(line.GetCStr()) == 0) { continue; } State currentState; this->stateStack.Peek(&currentState); // 1行コメント if (line.StartWith("//")) { continue; } // ブロックコメント開始 if (currentState != BlockComment && line.StartWith("/*")) { this->stateStack.Push(BlockComment); continue; } switch (currentState) { case CppEnumHeaderParser::Global: if (line.StartWith("enum")) { char parts[3][LineMaxLength]; if (line.Split(parts) > 1 && parts[1][0] == '{') // Enum開始 { this->stateStack.Push(Enum); this->currentValue = -1; } else { this->stateStack.Push(EnumReady); } } break; case CppEnumHeaderParser::EnumReady: if (line.StartWith("{")) { this->stateStack.Push(Enum); this->currentValue = -1; } break; case CppEnumHeaderParser::BlockComment: if (line.StartWith("*/")) // ブロックコメントの終了 { State dumy; this->stateStack.Pop(&dumy); } break; case CppEnumHeaderParser::Enum: if (line.StartWith("};")) // Enum終了 { State dumy; this->stateStack.Pop(&dumy); break; } // Enum内容 char parts[4][256]; int p_amount = line.Split(parts); if (p_amount > 0) { if (p_amount > 2 && strcmp(parts[1], "=") == 0) // 値が明示的に指定されている場合 { this->currentValue = ::strtol(parts[2], NULL, 0); } else // 値が指定されていない { // 前の定義から値を決定 ++this->currentValue; int tail = strlen(parts[0]) - 1; // キー文字列末尾の「,」を取り除く if (parts[0][tail] == ',') { parts[0][tail] = '\0'; }; } memcpy(outKey, parts[0], strlen(parts[0])+1); (*outValue) = this->currentValue; return true; } break; } } return false; } //---------------------------------------- /** * @brief 終了処理 */ //---------------------------------------- void CppEnumHeaderParser::Finalize() { this->trs.Finalize(); this->stateStack.Clear(); } } // DynamicHeader } // debug } // gfl
true
f4ef829a7b8035b25892f763f23f1e9a9f6cb086
C++
youoj/Algorithm
/Baekjoon/[10844]쉬운계단수.cpp
UTF-8
707
3.09375
3
[]
no_license
/* 10844번 쉬운계단수(Dynamic Programming) * https://www.acmicpc.net/problem/10844 */ #include <iostream> #include <vector> using namespace std; int main() { int inputN = 0; cin >> inputN; vector<vector<long long> > dp(inputN, vector<long long>(10, 0)); for (int i = 1; i <= 9; i++) dp[0][i] = 1; for (int i = 1; i < inputN; i++) { for (int j = 0; j < 10; j++) { if (j == 0) dp[i][j] = dp[i - 1][j + 1]; else if (j == 9) dp[i][j] = dp[i - 1][j - 1]; else dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]) % 1000000000; } } long long sum = 0; for (int i = 0; i < 10; i++) { sum += dp[inputN - 1][i]; sum %= 1000000000; } cout << sum << endl; return 0; }
true
c29accfe8aa0f2322faedf8c96bfdb9a0f419169
C++
davenguyen19/Data-Structures
/AggregationClasses/drinkItems.cpp
UTF-8
947
3.359375
3
[]
no_license
#include "drinkItems.h" #include <iostream> #include <string> #include <iomanip> using namespace std; drinkItems::drinkItems() { name = " "; price = 0.0; quantity = 0; } drinkItems::drinkItems(string n, double p, int q) { name = n; price = p; quantity = q; } void drinkItems::getItem(string n, double p, int q) { name = n; price = p; quantity = q; } string drinkItems::getName() { return name; } double drinkItems::getPrice() { return price; } int drinkItems::getQuantity() { return quantity; } void drinkItems::subQuantity(int q) { quantity -= q; } void drinkItems::printDrinkItem() { cout << name << endl; cout << price << fixed << setprecision(2) <<endl; } void drinkItems::change(double amount, double p) { double change = 0.0; change = amount - p; if (change < 0) { cout << "Not enough!" << endl; } else { cout << endl; cout << "Your change is: " << change; cout << endl; } }
true
06bfa61d711b52b3b1ca2e199212d119721afb5b
C++
yeireiChen/posd
/105598075_HW6/src/Cmd.cpp
UTF-8
37,003
2.546875
3
[]
no_license
#include "Cmd.h" #include <iostream> #include <cstring> #include <sstream> #include <map> #include <typeinfo> #include <cxxabi.h> #include <fstream> #include "MediaDirector.h" #include "combMediaBuilder.h" #include "ShapeMediaBuilder.h" <<<<<<< HEAD ======= <<<<<<< HEAD >>>>>>> origin/master #include "AreaVisitor.h" #include "PerimeterVisitor.h" #include "DescriptionVisitor.h" #include "DescriptionNameVisitor.h" #include "Circle.h" typedef std::pair<std::string, Media*> MyPair; template <typename T> char* get_typename(T& object) { return abi::__cxa_demangle(typeid(object).name(), 0, 0, 0); } <<<<<<< HEAD ======= ======= #include "Circle.h" typedef std::pair<std::string, Media*> MyPair; >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master Cmd::Cmd(){} Cmd::~Cmd(){} <<<<<<< HEAD bool checkFileName(std::string fileName){ std::vector<std::string> temp; std::string temper; int top=0; int last=fileName.size(); temper = fileName; //temper = fileName.substr(1,last-2); std::cout << temper << std::endl; int found=temper.find("."); while(found!=-1){ temp.push_back(temper.substr(top,found)); temper = temper.substr(found+1,last-found); found=temper.find("."); } temp.push_back(temper); ======= void add(std::string addName,std::string combName,std::map<std::string,Media*> *names){ std::map<std::string,Media*>::iterator addN; std::map<std::string,Media*>::iterator comb; std::string classN; DescriptionVisitor dVisitor; DescriptionNameVisitor dnVisitor; if(names->find(addName)!=names->end()){ addN = names->find(addName); //std::cout << "found, " << addName<< std::endl; if(names->find(combName)!=names->end()){ //check exit,and check next comb = names->find(combName); classN = get_typename(*(comb->second)); if(classN.compare("combMedia")==0){ //check combMedia //std::cout << "prepare to add" << std::endl; Media *a = addN->second; comb->second->add(a); comb->second->accept(&dVisitor); comb->second->accept(&dnVisitor); std::cout << ">> " << combName << " = " << dnVisitor.getDescription() << "= " << dVisitor.getDescription()<<std::endl; } else{ std::cout << combName << "is not a combMedia" << std::endl; } } else{ std::cout << "Not found "<<combName << std::endl; } } else{ std::cout << "Not found "<<addName << std::endl; } } void save (std::string funName,std::string fileName,std::map<std::string,Media*> *names){ //fileName doesn't check std::map<std::string,Media*>::iterator it; std::string classN; std::fstream fs; DescriptionVisitor dVisitor; DescriptionNameVisitor dnVisitor; std::cout << fileName << std::endl; int last = fileName.size(); fileName = fileName.substr(1,last-2); std::cout << fileName << std::endl; fs.open(fileName, std::ios::out); if(names->find(funName) == names->end()){ std::cout << "not found" << std::endl; } else{ it = names->find(funName); std::cout << "found" << std::endl; classN = get_typename(*(it->second)); //std::cout << classN <<std::endl; if(classN.compare("ShapeMedia")==0) { std::cout << "save ShapeMedia" <<std::endl; //it->second->accept(&aVisitor); //std::cout << ">> " <<aVisitor.getArea()<<std::endl; } else if (classN.compare("combMedia")==0) { std::cout << "prepare datas" <<std::endl; //it->second->accept(&aVisitor); //std::cout << ">> " <<aVisitor.getArea()<<std::endl; it->second->accept(&dVisitor); std::cout << dVisitor.getDescription() << std::endl; it->second->accept(&dnVisitor); std::cout << dnVisitor.getDescription() << std::endl; if(fs.is_open()){ fs << dVisitor.getDescription() <<std::endl; fs << dnVisitor.getDescription() <<std::endl; fs.close(); } else{ std::cout << "should not be here" << std::endl; } /*if(ofs.is_open()){ ofs << dnVisitor.getDescription()<<std::endl; ofs << dVisitor.getDescription()<<std::endl; ofs.close(); } else{ std::cout << "error fileName " << fileName << std::endl; }*/ } else{ std::cout << "wrong type" << std::endl; } } } void calculate(std::string funName,std::string method,std::map<std::string,Media*> *names){ //areaPerimeter.at(0),areaPerimeter.at(1),&names std::map<std::string,Media*>::iterator it; //std::cout << funName << std::endl; //std::cout << method << std::endl; std::string classN; AreaVisitor aVisitor; PerimeterVisitor pVisitor; /*Media *a = new ShapeMedia(new Circle(1,1,1)); //for test get class name Media *b = new combMedia(); b->add(new ShapeMedia(new Circle(1,1,2)));*/ //std::cout << "------------------------------------------" << std::endl; /*for (std::map<std::string,Media*>::iterator it=names->begin(); it!=names->end(); ++it){ //show run()'s names std::cout << it->second->getName() << std::endl; }*/ if(names->find(funName)==names->end()){ //not found std::cout << "not found" <<std::endl; } else{//found //std::cout << "found" <<std::endl; it = names->find(funName); //std::cout << it->second->getName() << std::endl; if(method.compare("area?")==0){ //std::cout << typeid(*b).name() << std::endl; //std::cout << typeid(*(it->second)).name() << std::endl; classN = get_typename(*(it->second)); //std::cout << classN <<std::endl; if(classN.compare("ShapeMedia")==0){ //std::cout << "calculate ShapeMedia area" <<std::endl; it->second->accept(&aVisitor); std::cout << ">> " <<aVisitor.getArea()<<std::endl; } else if (classN.compare("combMedia")==0){ //std::cout << "calculate combMedia area" <<std::endl; it->second->accept(&aVisitor); std::cout << ">> " <<aVisitor.getArea()<<std::endl; } else{ std::cout << "wrong type" << std::endl; } } else if(method.compare("perimeter?")==0){ classN = get_typename(*(it->second)); //std::cout << classN <<std::endl; if(classN.compare("ShapeMedia")==0){ //std::cout << "calculate ShapeMedia perimeter" <<std::endl; it->second->accept(&pVisitor); std::cout << ">> " <<pVisitor.getPerimeter()<<std::endl; } else if (classN.compare("combMedia")==0){ //std::cout << "calculate combMedia perimeter" <<std::endl; it->second->accept(&pVisitor); std::cout << ">> " <<pVisitor.getPerimeter()<<std::endl; } else{ std::cout << "wrong type" << std::endl; } } else{ std::cout << "error method -> "<< method <<" ,should be area? or perimeter? "<<std::endl; } } //it->find(funName); } void split(std::string cmd ,std::vector<std::string> *s){ //- def a = Circle(2,1,1) >>>>>>> origin/master if(temp.size()==2){ //std::cout << "correct fileName" << std::endl; //std::cout << "i(0) "<< temp.at(0) << std::endl; //std::cout << "i(1) "<< temp.at(1) << std::endl; if(temp.at(1).compare("txt")==0) return 1; } else{ /*for(int i=0;i<temp.size();i++) std::cout << temp.at(i) << std::endl;*/ //std::cout << "error fileName" << std::endl; return 0; } } void add(std::string addName,std::string combName,std::map<std::string,Media*> *names){ std::map<std::string,Media*>::iterator addN; std::map<std::string,Media*>::iterator comb; std::string classN; DescriptionVisitor dVisitor; DescriptionNameVisitor dnVisitor; if(names->find(addName)!=names->end()){ addN = names->find(addName); //std::cout << "found, " << addName<< std::endl; if(names->find(combName)!=names->end()){ //check exit,and check next comb = names->find(combName); classN = get_typename(*(comb->second)); if(classN.compare("combMedia")==0){ //check combMedia //std::cout << "prepare to add" << std::endl; Media *a = addN->second; comb->second->add(a); comb->second->accept(&dVisitor); comb->second->accept(&dnVisitor); std::cout << ">> " << combName << " = " << dnVisitor.getDescription() << "= " << dVisitor.getDescription()<<std::endl; } else{ std::cout << combName << "is not a combMedia" << std::endl; } } else{ std::cout << "Not found "<<combName << std::endl; } } else{ std::cout << "Not found "<<addName << std::endl; } <<<<<<< HEAD } void save (std::string funName,std::string fileName,std::map<std::string,Media*> *names){ //fileName doesn't check std::map<std::string,Media*>::iterator it; std::string classN; std::fstream fs; int last=0; DescriptionVisitor dVisitor; DescriptionNameVisitor dnVisitor; /*std::cout << fileName << std::endl; int last = fileName.size(); fileName = fileName.substr(1,last-2); std::cout << fileName << std::endl;*/ if(names->find(funName) == names->end()){ std::cout << "not found" << std::endl; } else{ it = names->find(funName); //std::cout << "found" << std::endl; classN = get_typename(*(it->second)); //std::cout << classN <<std::endl; if(classN.compare("ShapeMedia")==0){ std::cout << "save ShapeMedia" <<std::endl; //it->second->accept(&aVisitor); //std::cout << ">> " <<aVisitor.getArea()<<std::endl; } else if (classN.compare("combMedia")==0){ //std::cout << "prepare datas" <<std::endl; //it->second->accept(&aVisitor); //std::cout << ">> " <<aVisitor.getArea()<<std::endl; last = fileName.size(); fileName = fileName.substr(1,last-2); //delete "" if(checkFileName(fileName)){ std::cout << "correct" << std::endl; fs.open(fileName, std::ios::out); it->second->accept(&dVisitor); std::cout << dVisitor.getDescription() << std::endl; it->second->accept(&dnVisitor); std::cout << dnVisitor.getDescription() << std::endl; if(fs.is_open()){ fs << dVisitor.getDescription() <<std::endl; fs << dnVisitor.getDescription() <<std::endl; fs.close(); } else{ std::cout << "should not be here" << std::endl; } } else{ std::cout << "error fileName" << fileName << std::endl; } } else{ std::cout << "wrong type" << std::endl; } } } ======= <<<<<<< HEAD //std::cout << cmd <<std::endl; ======= std::cout << cmd <<std::endl; >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master void calculate(std::string funName,std::string method,std::map<std::string,Media*> *names){ //areaPerimeter.at(0),areaPerimeter.at(1),&names std::map<std::string,Media*>::iterator it; //std::cout << funName << std::endl; //std::cout << method << std::endl; std::string classN; AreaVisitor aVisitor; PerimeterVisitor pVisitor; if(names->find(funName)==names->end()){ //not found std::cout << "not found" <<std::endl; } else{//found //std::cout << "found" <<std::endl; it = names->find(funName); //std::cout << it->second->getName() << std::endl; if(method.compare("area?")==0){ classN = get_typename(*(it->second)); //std::cout << classN <<std::endl; if(classN.compare("ShapeMedia")==0){ //std::cout << "calculate ShapeMedia area" <<std::endl; it->second->accept(&aVisitor); std::cout << ">> " <<aVisitor.getArea()<<std::endl; } else if (classN.compare("combMedia")==0){ //std::cout << "calculate combMedia area" <<std::endl; it->second->accept(&aVisitor); std::cout << ">> " <<aVisitor.getArea()<<std::endl; } else{ std::cout << "wrong type" << std::endl; } } else if(method.compare("perimeter?")==0){ classN = get_typename(*(it->second)); //std::cout << classN <<std::endl; if(classN.compare("ShapeMedia")==0){ //std::cout << "calculate ShapeMedia perimeter" <<std::endl; it->second->accept(&pVisitor); std::cout << ">> " <<pVisitor.getPerimeter()<<std::endl; } else if (classN.compare("combMedia")==0){ //std::cout << "calculate combMedia perimeter" <<std::endl; it->second->accept(&pVisitor); std::cout << ">> " <<pVisitor.getPerimeter()<<std::endl; } else{ std::cout << "wrong type" << std::endl; } } else{ std::cout << "error method -> "<< method <<" ,should be area? or perimeter? "<<std::endl; } } } void split(std::string cmd ,std::vector<std::string> *s){ //- def a = Circle(2,1,1) std::string temp=""; char tab2[1024]; //std::cout << cmd <<std::endl; std::strcpy(tab2, cmd.c_str()); //std::cout << strlen(tab2) <<std::endl; for(int i=0; i<strlen(tab2); i++){ if(tab2[i]==' '){//split command //std::cout << temp <<std::endl; s->push_back(temp); temp.clear(); } else{ temp+=tab2[i]; if(i==strlen(tab2)-1){ s->push_back(temp); temp.clear(); } } } } void splitPoint(std::string number,std::vector<std::string> *s){ //a.area()? b.perimeter()? std::string temp = number; std::string temper; int last = temp.size(); int first =0; int found ;// temp.find_first_of(")") -- > not found is -1 //std::cout << "number is " << temp<<std::endl; //std::cout << "size is " << last <<std::endl; //std::cout << "first appear is "<< temp.find_first_of(",") <<std::endl; if(temp.find_first_of(".")!=-1){ while(temp.find_first_of(".")!=-1){ //std::cout << "=============" <<std::endl; found = temp.find_first_of("."); temper = temp.substr(first,found-first); s->push_back(temper); //std::cout << "number is " << temper <<std::endl; temp = temp.substr(found+1,last-found); //std::cout << "last number is " << temp<<std::endl; } s->push_back(temp); //final number need to push } else{ std::cout << "should not be here" <<std::endl; } } void splitDot(std::string number,std::vector<std::string> *s){ //2,1,1 std::string temp = number; std::string temper; int last = temp.size(); int first =0; int found ;// temp.find_first_of(")") -- > not found is -1 //std::cout << "number is " << temp<<std::endl; //std::cout << "size is " << last <<std::endl; //std::cout << "first appear is "<< temp.find_first_of(",") <<std::endl; if(temp.find_first_of(",")!=-1){ while(temp.find_first_of(",")!=-1){ //std::cout << "=============" <<std::endl; found = temp.find_first_of(","); temper = temp.substr(first,found-first); s->push_back(temper); //std::cout << "number is " << temper <<std::endl; temp = temp.substr(found+1,last-found); //std::cout << "last number is " << temp<<std::endl; } s->push_back(temp); //final number need to push } else{ //only on value s->push_back(temp); } <<<<<<< HEAD ======= /*if(s->size()!=0){ //show number for(int i=0;i<s->size();i++) std::cout << s->at(i) <<std::endl; }*/ >>>>>>> origin/master } void def(std::string name,std::string formula,std::map<std::string,Media*> *names){ MediaDirector dc; ShapeMediaBuilder shB; combMediaBuilder comB; std::vector<std::string> numbers; std::vector<std::string> shpNames; std::vector<Media*> combMaterial; std::string temp=formula; std::string typeN; std::string number; std::map<std::string,Media*>::iterator it; bool yesToC=0; //std::cout << name <<"___" <<formula <<std::endl; int shLocation = temp.find("("); //doesn't find is -1 int shLast = temp.length() - shLocation - 2; int cLocation = temp.find("{"); //doesn't find is -1 int cLast = temp.length() - cLocation - 2; if(shLocation!=-1){ // shape() //std::cout << "(((----------------------------------------------" <<std::endl; //std::cout << "shLocation is " << shLocation <<std::endl; //std::cout << "shLast is " << shLast <<std::endl; typeN = temp.substr(0,shLocation); //std::cout << " typeN is "<<typeN << std::endl; number = temp.substr(shLocation+1,shLast); //std::cout << " number is "<<number << std::endl; if(typeN.compare("Circle")==0){ //(std::string content,std::vector<double> *n,MediaBuilder *s) //std::cout << "Circle" <<std::endl; //std::cout << "number is " << number<<std::endl; splitDot(number,&numbers); /*if(numbers.size()!=0) //show number { for(int i=0; i<numbers.size(); i++) std::cout << numbers.at(i) <<std::endl; }*/ if(numbers.size()==3){ <<<<<<< HEAD //std::cout << "correct parameter structure in " << name << "->"<<typeN<<std::endl; ======= <<<<<<< HEAD //std::cout << "correct parameter structure in " << name << "->"<<typeN<<std::endl; ======= std::cout << "correct parameter structure in " << typeN<<std::endl; >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master dc.buildShpae(typeN,&numbers,&shB); Media *s = shB.getMedia(); s->setName(name); names->insert(MyPair(name,s)); <<<<<<< HEAD //std::cout << "create successuflly " << name << "->"<<typeN<<std::endl; //it = names->find(name); std::cout << ">> " << formula <<std::endl; }else{ std::cout << "error parameter structure in " << name << "->"<< typeN<<std::endl; ======= <<<<<<< HEAD //std::cout << "create successuflly " << name << "->"<<typeN<<std::endl; //it = names->find(name); std::cout << ">> " << formula <<std::endl; }else{ std::cout << "error parameter structure in " << name << "->"<< typeN<<std::endl; ======= }else{ std::cout << "error parameter structure in " << typeN<<std::endl; >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master } } else if(typeN.compare("Rectangle")==0){ //std::cout << "Rectangle" <<std::endl; //std::cout << "number is " << number<<std::endl; splitDot(number,&numbers); <<<<<<< HEAD if(numbers.size()==4){ //std::cout << "correct parameter structure in " << name << "->"<< typeN<<std::endl; ======= /*if(numbers.size()!=0) //show number { for(int i=0; i<numbers.size(); i++) std::cout << numbers.at(i) <<std::endl; }*/ if(numbers.size()==4){ <<<<<<< HEAD //std::cout << "correct parameter structure in " << name << "->"<< typeN<<std::endl; ======= std::cout << "correct parameter structure in " << typeN<<std::endl; >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master dc.buildShpae(typeN,&numbers,&shB); Media *s = shB.getMedia(); s->setName(name); names->insert(MyPair(name,s)); <<<<<<< HEAD std::cout << ">> " << formula <<std::endl; //std::cout << "create successuflly " << name << "->"<<typeN<<std::endl; ======= <<<<<<< HEAD std::cout << ">> " << formula <<std::endl; //std::cout << "create successuflly " << name << "->"<<typeN<<std::endl; ======= >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master }else{ std::cout << "error parameter structure in " << name << "->"<< typeN<<std::endl; } } else if(typeN.compare("Triangle")==0){ //std::cout << "Triangle" <<std::endl; //std::cout << "number is " << number<<std::endl; splitDot(number,&numbers); <<<<<<< HEAD if(numbers.size()==6){ ======= /*if(numbers.size()!=0) //show number { for(int i=0; i<numbers.size(); i++) std::cout << numbers.at(i) <<std::endl; }*/ if(numbers.size()==6){ <<<<<<< HEAD >>>>>>> origin/master //std::cout << "correct parameter structure in " << name << "->"<< typeN<<std::endl; try{ dc.buildShpae(typeN,&numbers,&shB); Media *s = shB.getMedia(); s->setName(name); names->insert(MyPair(name,s)); std::cout << ">> " << formula <<std::endl; //std::cout << "create successuflly " << name << "->"<<typeN<<std::endl; }catch(std::string s){ std::cout << s<< std::endl; } <<<<<<< HEAD ======= ======= std::cout << "correct parameter structure in " << typeN<<std::endl; dc.buildShpae(typeN,&numbers,&shB); Media *s = shB.getMedia(); s->setName(name); names->insert(MyPair(name,s)); >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master }else{ std::cout << "error parameter " << name << "->"<< typeN<<std::endl; } } else{ std::cout << "error function " << name << "->" << typeN<<std::endl; } } else if(cLocation!=-1){ //combo{} (std::string content,std::vector<Media*> *n,MediaBuilder *s) //std::cout << "{{{----------------------------------------------" <<std::endl; //std::cout << "cLocation is " << cLocation <<std::endl; //std::cout << "cLast is " << cLast <<std::endl; typeN = temp.substr(0,cLocation); //std::cout << " typeN is "<<typeN << std::endl; number = temp.substr(cLocation+1,cLast); //std::cout << " number is "<<number << std::endl; if(typeN.compare("combo")==0){ //std::cout << "combo" <<std::endl; splitDot(number,&shpNames); //std::cout << "composition names \""<< name << "\" -> " << typeN <<" are follows "<<std::endl; /*if(shpNames.size()!=0){ //show for(int i=0; i<shpNames.size(); i++) std::cout << shpNames.at(i) <<std::endl; }*/ <<<<<<< HEAD ======= //std::map<std::string,Media*> *names /*for (std::map<std::string,Media*>::iterator it=names.begin(); it!=names.end(); ++it){ //show run()'s names std::cout << it->second->getName() << std::endl; }*/ /*std::map<std::string,Media*>::iterator it; it = names->find("cSmall"); std::cout << it->second->getName() << std::endl;*/ >>>>>>> origin/master if(shpNames.size()!=0){ for(int i=0; i<shpNames.size(); i++){ //std::cout << shpNames.at(i) <<std::endl; if(names->find(shpNames.at(i))==names->end()){ //not found std::cout << shpNames.at(i) <<" doesn't exist "<<std::endl; yesToC=0; } else{ //found //std::cout << shpNames.at(i) <<" exist "<<std::endl; yesToC=1; } } <<<<<<< HEAD ======= >>>>>>> origin/master } //end if if(yesToC){ //std::cout << "----------------------------------------------------------"<<std::endl; //std::cout << " prepare to create combo "<<std::endl; //MediaDirector::buildComb(std::string content,std::vector<Media*> *n,MediaBuilder *s) for(int i=0; i<shpNames.size(); i++){ it = names->find(shpNames.at(i)); //std::cout << it->second->getName() <<std::endl; combMaterial.push_back(it->second); } <<<<<<< HEAD ======= >>>>>>> origin/master /*for(int i=0;i<combMaterial.size();i++) std::cout << combMaterial.at(i)->getName() << std::endl;*/ dc.buildComb(&combMaterial,&comB); Media *s = comB.getMedia(); s->setName(name); names->insert(MyPair(name,s)); //std::cout << "create successuflly " << name << "->"<<typeN<<std::endl; }else{ std::cout << "----------------------------------------------------------"<<std::endl; std::cout << " upper names don't exit,so it can't build combo "<<std::endl; } } else{ std::cout << "error function " << typeN <<std::endl; } } else{ <<<<<<< HEAD std::cout << "error syntax in def {}()" <<std::endl; } ======= <<<<<<< HEAD std::cout << "error syntax in def {}()" <<std::endl; } //std::cout << "name test--------------------------------------" <<std::endl; //std::map<std::string,Media*> *names //std::map<std::string,Media*>::iterator it; ======= std::cout << "error syntax in def" <<std::endl; } //std::cout << "name test--------------------------------------" <<std::endl; //std::map<std::string,Media*> *names std::map<std::string,Media*>::iterator it; >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 /*it = names->find("cSmall"); std::cout << it->second->getName() << std::endl;*/ /*for (std::map<std::string,Media*>::iterator it=names->begin(); it!=names->end(); ++it) //show run()'s names std::cout << it->first << " => " << it->second->getName() << std::endl;*/ //- def a = Circle(2,1,1) //- def a = combo{abc,abc} >>>>>>> origin/master } void Cmd::run(){ std::vector<std::string> cmds; std::vector<std::string> areaPerimeter; std::map<std::string,Media*>::iterator it; std::map<std::string,Media*> names; std::string cmd; /*ShapeMedia *t = new ShapeMedia(new Circle(2,1,1)); t->setName("test1234"); names.insert(MyPair("test",t)); //upper for test in def-*/ while(cmd!="exit"){ std::cout << "enter cmd " <<std::endl<<":-"; std::getline(std::cin,cmd); //std::cout << "enter cmd is " <<cmd <<std::endl;'s split(cmd,&cmds); if(!cmds.empty()){ //check cmds.at(0)=="-" else continue if(cmds.size()>=1 || cmds.size()<=5){ //std::cout << "correct syntax" <<std::endl; } else{ //error syntax std::cout << "error syntax first" <<std::endl; cmds.clear(); continue; } /*if(cmds.at(0).compare("-")!=0 && cmds.size()<2 && cmds.size()>5){ std::cout << "error syntax" <<std::endl; cmds.clear(); continue; }*/ if(cmds.at(0).compare("def")==0){ if(cmds.at(2).compare("=")==0 && cmds.size()==4){ <<<<<<< HEAD //std::cout << "Action is def" <<std::endl; //std::cout << "==============" <<std::endl; ======= <<<<<<< HEAD //std::cout << "Action is def" <<std::endl; //std::cout << "==============" <<std::endl; def(cmds.at(1),cmds.at(3),&names); ======= std::cout << "Action is def" <<std::endl; >>>>>>> origin/master def(cmds.at(1),cmds.at(3),&names); } else{ //error syntax std::cout << "error syntax at def structure" <<std::endl; //cmds.clear(); //continue; } } else if(cmds.at(0).compare("add")==0){ if(cmds.size()==4 && cmds.at(2).compare("to")==0){ //std::cout << "Action is add" <<std::endl; //std::cout << "==============" <<std::endl; add(cmds.at(1),cmds.at(3),&names); } else{ std::cout << "error syntax at def structure" <<std::endl; } } else if(cmds.at(0).compare("delete")==0){ std::cout << "Action is delete" <<std::endl; std::cout << "================" <<std::endl; } else if(cmds.at(0).compare("show")==0){ //std::cout << "Action is show" <<std::endl; //std::cout << "==============" <<std::endl; for (std::map<std::string,Media*>::iterator it=names.begin(); it!=names.end(); ++it) //show run()'s names std::cout << it->second->getName() << std::endl; } else if(cmds.at(0).compare("save")==0){ if(cmds.size()==4 && cmds.at(2).compare("to")==0){ //std::cout << "Action is save" <<std::endl; //std::cout << "==============" <<std::endl; save(cmds.at(1),cmds.at(3),&names); } else{ std::cout << "save ,, but wrong structure " <<std::endl; } } else if(cmds.at(0).compare("load")==0){ std::cout << "Action is load" <<std::endl; std::cout << "==============" <<std::endl; } else{ //area() perimeter() cmds.at(0) splitPoint(cmds.at(0),&areaPerimeter); /*for(int i=0;i<areaPerimeter.size();i++){ //show std::cout << "i(" << i <<")"<<areaPerimeter.at(i) << std::endl; }*/ if(areaPerimeter.size()<=2){ if(names.find(areaPerimeter.at(0))==names.end()){ //not found obj's name std::cout << areaPerimeter.at(0) <<" doesn't exist "<<std::endl; } else{ //found //std::cout << "prepare to calculate " << areaPerimeter.at(1) << std::endl; calculate(areaPerimeter.at(0),areaPerimeter.at(1),&names); } }else{ std::cout << "error cmd structure - >" << cmds.at(0) << " ,should be A.area? or A.perimeter?" << std::endl; } } } std::cout << "----------------------------------------------" <<std::endl; cmds.clear(); areaPerimeter.clear(); }//end while <<<<<<< HEAD ======= split(cmd,&cmds); //std::cout << "size is " << cmds.size() << std::endl; if(!cmds.empty()){ //check cmds.at(0)=="-" else continue if(cmds.at(0).compare("-")==0 && cmds.size()>=2 && cmds.size()<=5){ //std::cout << "correct syntax" <<std::endl; } else{ //error syntax std::cout << "error syntax" <<std::endl; cmds.clear(); continue; } if(cmds.at(1).compare("def")==0){ if(cmds.at(3).compare("=")==0 && cmds.size()==5){ std::cout << "Action is def" <<std::endl; def(cmds.at(2),cmds.at(4),&names); >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 } else{ //error syntax std::cout << "error syntax at def structure" <<std::endl; //cmds.clear(); //continue; } } else if(cmds.at(0).compare("add")==0){ if(cmds.size()==4 && cmds.at(2).compare("to")==0){ //std::cout << "Action is add" <<std::endl; //std::cout << "==============" <<std::endl; add(cmds.at(1),cmds.at(3),&names); } else{ std::cout << "error syntax at def structure" <<std::endl; } } else if(cmds.at(0).compare("delete")==0){ std::cout << "Action is delete" <<std::endl; std::cout << "================" <<std::endl; } else if(cmds.at(0).compare("show")==0){ //std::cout << "Action is show" <<std::endl; //std::cout << "==============" <<std::endl; for (std::map<std::string,Media*>::iterator it=names.begin(); it!=names.end(); ++it) //show run()'s names std::cout << it->second->getName() << std::endl; } else if(cmds.at(0).compare("save")==0){ if(cmds.size()==4 && cmds.at(2).compare("to")==0){ std::cout << "Action is save" <<std::endl; std::cout << "==============" <<std::endl; save(cmds.at(1),cmds.at(3),&names); } else{ std::cout << "save ,, but wrong structure " <<std::endl; } } else if(cmds.at(0).compare("load")==0){ std::cout << "Action is load" <<std::endl; std::cout << "==============" <<std::endl; } else{ //area() perimeter() cmds.at(0) /*for(int i=0;i<cmds.size();i++){ std::cout << "Action is load" <<std::endl; std::cout << "==============" <<std::endl; std::cout << cmds.at(i) << std::endl; }*/ //std::cout << cmds.at(0) << std::endl; //std::vector<std::string> areaPerimeter; splitPoint(cmds.at(0),&areaPerimeter); /*for(int i=0;i<areaPerimeter.size();i++){ //show std::cout << "i(" << i <<")"<<areaPerimeter.at(i) << std::endl; }*/ if(areaPerimeter.size()<=2){ if(names.find(areaPerimeter.at(0))==names.end()){ //not found obj's name std::cout << areaPerimeter.at(0) <<" doesn't exist "<<std::endl; } else{ //found //std::cout << "prepare to calculate " << areaPerimeter.at(1) << std::endl; calculate(areaPerimeter.at(0),areaPerimeter.at(1),&names); } }else{ std::cout << "error cmd structure - >" << cmds.at(0) << " ,should be A.area? or A.perimeter?" << std::endl; } } } <<<<<<< HEAD std::cout << "----------------------------------------------" <<std::endl; /*for(int i=0; i<cmds.size(); i++){ std::cout << cmds.at(i) <<std::endl; }*/ cmds.clear(); areaPerimeter.clear(); }//end while ======= std::cout << "----------------------------------------------" <<std::endl; cmds.clear(); }*/ >>>>>>> e9174e45616b41952ca6b74d1a113054fa3fb436 >>>>>>> origin/master }
true
263b75fb9a241f6883ca64fd3226efd377edf52e
C++
Uiopio/technicalVision
/ПаньковИС/assignment_2/src/main/morphological_filter.cpp
UTF-8
6,860
3.125
3
[]
no_license
#include "morphological_filter.h" using namespace std; using namespace cv; void MorphologicalFilter::setStructuringElement(Mat structuringElement) { m_structuringElement = binarize(structuringElement); auto anchor = Point2i(structuringElement.cols / 2, structuringElement.rows / 2); setAnchor(anchor); } Mat MorphologicalFilter::getStructuringElement() const { return normalize(m_structuringElement); } void MorphologicalFilter::setAnchor(const Point2i anchor) { m_anchor = anchor; vector<int32_t> border = { m_anchor.y, m_anchor.x, m_structuringElement.rows - (m_anchor.y + 1), m_structuringElement.cols - (m_anchor.x + 1) }; m_border = border; } Point2i MorphologicalFilter::getAnchor() const { return m_anchor; } void MorphologicalFilter::setImage(Mat image) { m_image = binarize(image); } Mat MorphologicalFilter::getImage() const { return normalize(m_image); } void MorphologicalFilter::erode() { if (m_image.empty() == true) { return; } if (m_structuringElement.empty() == true) { return; } if (m_anchor.x < 0 || m_anchor.x >= m_structuringElement.cols) { return; } if (m_anchor.y < 0 || m_anchor.y >= m_structuringElement.rows) { return; } auto cols = m_image.cols + m_border[LEFT] + m_border[RIGHT]; auto rows = m_image.rows + m_border[TOP] + m_border[BOTTOM]; auto buffer = Mat(rows, cols, CV_8UC1); m_image.copyTo(buffer(Rect(m_anchor.x, m_anchor.y, m_image.cols, m_image.rows))); fillBorders(buffer); for (auto col = 0; col < m_image.cols; col++) { for (auto row = 0; row < m_image.rows; row++) { auto box = Mat(buffer, Rect(col, row, m_structuringElement.cols, m_structuringElement.rows)); if (compare(box, MorphologicalOperation::EROSION) == true) { m_image.at<uint8_t>(row, col) = 1; } else { m_image.at<uint8_t>(row, col) = 0; } } } } void MorphologicalFilter::dilate() { if (m_image.empty() == true) { return; } if (m_structuringElement.empty() == true) { return; } if (m_anchor.x < 0 || m_anchor.x >= m_structuringElement.cols) { return; } if (m_anchor.y < 0 || m_anchor.y >= m_structuringElement.rows) { return; } auto cols = m_image.cols + m_border[LEFT] + m_border[RIGHT]; auto rows = m_image.rows + m_border[TOP] + m_border[BOTTOM]; auto buffer = Mat(rows, cols, CV_8UC1); m_image.copyTo(buffer(Rect(m_anchor.x, m_anchor.y, m_image.cols, m_image.rows))); fillBorders(buffer); for (auto col = 0; col < m_image.cols; col++) { for (auto row = 0; row < m_image.rows; row++) { auto box = Mat(buffer, Rect(col, row, m_structuringElement.cols, m_structuringElement.rows)); if (compare(box, MorphologicalOperation::DILATION) == true) { m_image.at<uint8_t>(row, col) = 1; } else { m_image.at<uint8_t>(row, col) = 0; } } } } void MorphologicalFilter::open() { erode(); dilate(); } void MorphologicalFilter::close() { dilate(); erode(); } void MorphologicalFilter::fillBorders(Mat& buffer) { for (auto col = 0; col < m_border[LEFT]; col++) { for (auto row = 0; row < buffer.rows; row++) { buffer.at<uint8_t>(row, col) = buffer.at<uint8_t>(row, 2 * m_border[LEFT] - (col + 1)); } } for (auto col = 0; col < m_border[RIGHT]; col++) { for (auto row = 0; row < buffer.rows; row++) { buffer.at<uint8_t>(row, (buffer.cols - 1) - col) = buffer.at<uint8_t>(row, buffer.cols - 2 * m_border[RIGHT] + col); } } for (auto col = 0; col < buffer.cols; col++) { for (auto row = 0; row < m_border[TOP]; row++) { buffer.at<uint8_t>(row, col) = buffer.at<uint8_t>(2 * m_border[TOP] - (row + 1), col); } } for (auto col = 0; col < buffer.cols; col++) { for (auto row = 0; row < m_border[BOTTOM]; row++) { buffer.at<uint8_t>((buffer.rows - 1) - row, col) = buffer.at<uint8_t>(buffer.rows - 2 * m_border[BOTTOM] + row, col); } } } bool MorphologicalFilter::compare(const cv::Mat& box, MorphologicalOperation operation) { switch (operation) { case MorphologicalOperation::EROSION: for (auto col = 0; col < box.cols; col++) { for (auto row = 0; row < box.rows; row++) { if (m_structuringElement.at<uint8_t>(row, col) != 1) { continue; } if (m_structuringElement.at<uint8_t>(row, col) == box.at<uint8_t>(row, col)) { return true; } } } return false; case MorphologicalOperation::DILATION: for (auto col = 0; col < box.cols; col++) { for (auto row = 0; row < box.rows; row++) { if (m_structuringElement.at<uint8_t>(row, col) != 1) { continue; } if (m_structuringElement.at<uint8_t>(row, col) != box.at<uint8_t>(row, col)) { return false; } } } return true; dafault: return false; } return false; } Mat MorphologicalFilter::binarize(const cv::Mat& image) const { auto buffer = Mat(); cvtColor(image, buffer, COLOR_BGR2GRAY); for (auto col = 0; col < image.cols; col++) { for (auto row = 0; row < image.rows; row++) { /*if (image.at<Vec3b>(row, col)[RED] <= 0x7F && image.at<Vec3b>(row, col)[GREEN] <= 0x7F && image.at<Vec3b>(row, col)[BLUE] <= 0x7F)*/ if (buffer.at<uint8_t>(row, col) <= 0x7F) { buffer.at<uint8_t>(row, col) = 1; } else { buffer.at<uint8_t>(row, col) = 0; } } } return buffer; } Mat MorphologicalFilter::normalize(const cv::Mat& image) const { auto buffer = Mat(image.rows, image.cols, CV_8UC1); for (auto col = 0; col < image.cols; col++) { for (auto row = 0; row < image.rows; row++) { if (image.at<uint8_t>(row, col) == 1) { buffer.at<uint8_t>(row, col) = 0x00; } else { buffer.at<uint8_t>(row, col) = 0xFF; } } } return buffer; }
true
3d34f4d17ed7561fdd0826ff537ba91645e9c87d
C++
Malenczuk/inertia-oplosser
/src/board/Move.h
UTF-8
637
2.953125
3
[]
no_license
#ifndef DIAMONDSANDMINES_MOVE_H #define DIAMONDSANDMINES_MOVE_H struct Position { int y, x; }; namespace Movement { enum Type { N = 0, NE = 1, E = 2, SE = 3, S = 4, SW = 5, W = 6, NW = 7, }; static const Movement::Type All[] = { N, NE, E, SE, S, SW, W, NW }; Position move(Type movement, Position position); } class Field; class Move { public: Movement::Type movement; Field *src; Field *dst; Move(Movement::Type movement, Field *src, Field *dst) : movement(movement), src(src), dst(dst) {} }; #endif //DIAMONDSANDMINES_MOVE_H
true
a15f630da7c9334c0c989aadae54e18d99c2bd18
C++
erisonliang/GDIPlusC
/GDI+ C/gdipluspixelformats.cpp
UTF-8
530
2.703125
3
[]
no_license
#include "stdafx.h" UINT WINAPI GetPixelFormatSize(PixelFormat pixfmt) { return (pixfmt >> 8) & 0xff; } BOOL WINAPI IsIndexedPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormatIndexed) != 0; } BOOL WINAPI IsAlphaPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormatAlpha) != 0; } BOOL WINAPI IsExtendedPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormatExtended) != 0; } BOOL WINAPI IsCanonicalPixelFormat(PixelFormat pixfmt) { return (pixfmt & PixelFormatCanonical) != 0; }
true
b49891029d82200877a4d6056903a578d38f7dde
C++
JunchenZ/SpaceshipGame
/main.cpp
UTF-8
1,370
2.8125
3
[]
no_license
// // main.cpp // asteroids // // Created by Gregory Colledge on 9/19/17. // Copyright © 2017 Gregory Colledge. All rights reserved. // //References: // for sort algorithm - https://stackoverflow.com/questions/4892680/sorting-a-vector-of-structs //for input/output - http://www.cplusplus.com/doc/tutorial/files/ //for graphics - https://www.sfml-dev.org/tutorials/2.4/ //for math - http://www.cplusplus.com/reference/cmath/ #include "WorldClass.hpp" #include "HighScores.hpp" #include <math.h> #include <SFML/Audio.hpp> int main(int argc, const char * argv[]) { if(argc != 2){//check that correct input was given std::cout << "Incorrect input was given on the command line.\nA High Score file must be given as the only argument."; return 1; } //run the game bool userContinue; do{ World game;//play a round of asteroids long userScore = (game.getScore() + game.getTime()/10000); //calculate score /*commented out for projector userContinue = displayHighScore(game.getWidth(), game.getHeight(), userScore, argv[1]);//display score and ask user if he/she wants to continue */ userContinue = displayHighScore(2500, 1250, userScore, argv[1]);//display score and ask user if he/she wants to continue }while(userContinue==true); return 0; //github.com/UtahMSD/GregAndJunchen.git }
true
146aa07b470c634cfa3bd5be8db323708e81ca5b
C++
slowriot/voro--
/branches/dynamic/examples/dynamic/square_test.cc
UTF-8
1,712
3.03125
3
[ "BSD-3-Clause-LBNL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Voronoi calculation example code // // Author : Chris H. Rycroft (LBL / UC Berkeley) // Email : chr@alum.mit.edu // Date : July 1st 2008 #include "voro++.cc" #include "dynamic.cc" // Set up constants for the container geometry const fpoint x_min=-5,x_max=5; const fpoint y_min=-5,y_max=5; const fpoint z_min=-0.5,z_max=0.5; // Set the computational grid size const int n_x=8,n_y=8,n_z=1; // Set the number of particles that are going to be randomly introduced const int particles=100; // This function returns a random double between 0 and 1 double rnd() {return double(rand())/RAND_MAX;} void output_all(container_dynamic &con,int i) { char q[256]; sprintf(q,"output/%04d_p.pov",i);con.draw_particles_pov(q); sprintf(q,"gzip -f -9 output/%04d_p.pov",i);system(q); sprintf(q,"output/%04d_v.pov",i);con.draw_cells_pov(q); sprintf(q,"gzip -f -9 output/%04d_v.pov",i);system(q); } int main() { int i=0; fpoint x,y; // Create a container with the geometry given above, and make it // non-periodic in each of the three coordinates. Allocate space for // eight particles within each computational block. container_dynamic con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z, false,false,false,8); // Add a cylindrical wall to the container // wall_sphere sph(0,0,0,7); // con.add_wall(sph); // Randomly add particles into the container while(i<particles) { x=x_min+rnd()*(x_max-x_min); y=y_min+rnd()*(y_max-y_min); con.put(i,x,y,0); i++; } output_all(con,0); for(i=0;i<=10;i++) con.full_relax(0.8); output_all(con,1); for(i=20;i<=1000;i++) { con.spot(0,0,0,0.005,0.005,0,2.5); // con.relax(4,4,0,3.5,0.8); con.full_relax(0.8); if(i%10==0) { output_all(con,i/10); } } }
true
ce16a08aac1333bd9d2868c74adb8d66e714f3e8
C++
GunnDawg/Gunngine3D
/G3D/src/Engine/G3D_Mouse.cpp
UTF-8
999
2.671875
3
[ "Apache-2.0" ]
permissive
#include "G3D_Mouse.h" namespace G3D { bool Mouse::Initialize() { RAWINPUTDEVICE rid; ZeroMemory(&rid, sizeof(RAWINPUTDEVICE)); rid.usUsagePage = 0x01; rid.usUsage = 0x02; rid.dwFlags = 0u; rid.hwndTarget = 0u; if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) { MessageBox(nullptr, "Error registering RAW input device. Most likely a mouse", "RAW Input Startup Error", MB_OK); return G3D_ERROR; } DisableCursor(); return G3D_OK; } Mouse::Event Mouse::Read() { if (buffer.size() > 0u) { Mouse::Event e = buffer.front(); buffer.pop(); return e; } else { return Mouse::Event(); } } void Mouse::OnMouseMove(u16 newX, u16 newY) { x = newX; y = newY; buffer.push(Mouse::Event(Mouse::Event::Type::Move, *this)); TrimBuffer(); } void Mouse::OnMouseMoveRaw(u16 newX, u16 newY) { if (RawMouseEnabled) { dx = newX; dy = newY; buffer.push(Mouse::Event(Mouse::Event::Type::RAW_MOVE, *this)); TrimBuffer(); } } }
true
a5c03391ef075d19c8c1a7f378bc140d6e4b880a
C++
barchinsky/2d-world
/dev/Moon.cpp
UTF-8
657
2.9375
3
[]
no_license
#include <iostream> #include "Moon.hpp" #include "math.h" Moon::Moon() // init moon { moonT.loadFromFile("moon.png"); moonT.setSmooth(1); moon = sf::Sprite(moonT); currX = -200.; currY = 50; h = 0.8; } sf::Sprite Moon::getMoon() // return moon-object { return moon; // return Moon sprite } void Moon::move() // move moon { currX += 0.1; // change current x-position //currY = 100*currX*currX + h*currX + 50; // set moon trajectory currY += 0.05; if(currX > 1400) { currX = -350;} // reset moon posotion if(currY > 350) { //std::cout << "Signal\n"; } moon.setPosition(currX,currY); }
true
d20321ef23ba4107ce8c3488d21a17d03864f13c
C++
siddharthtejas/HackerRankCodes
/Diagonal Difference.cpp
UTF-8
593
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int arr[n][n]; int i,j; int sum=0,sum2=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { cin>>arr[i][j]; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i==j) { sum=sum+arr[i][j]; } } } for(i=0;i<n;i++) { int k=n-(i+1); sum2=sum2+arr[i][k]; } int diff=abs(sum-sum2); cout<<diff; }
true
0b4acd47d7b06c1fb7f2f38622c38a743bb38505
C++
DrBit/Seed-Counter
/XYfuntcions.ino
UTF-8
10,493
2.828125
3
[]
no_license
// ************************************************************ // ** INIT FUNCTIONS // ************************************************************ // *********************** // ** Physical limits of the motors // *********************** // Init the both axes at the same time to save time. #define max_insensor_stepsError 4000 #define Xaxis_cycles_limit 280 #define Yaxis_cycles_limit 18 boolean XYaxes_init () { send_action_to_server (XY_init); // few previous calculations for the different speeds profiles int speed1 = motor_speed_XY; // Main speed is always the slowest and safer int speed2 = speed1 - (motor_speed_XY/5); int speed3 = speed2 - (motor_speed_XY/5); int speed4 = speed3 - (motor_speed_XY/5); unsigned long vIncrement = 900; // Amount f time in ms that motors will increase speed // IMPLEMENT THE FOLLOWING: // There are two scenarios in which we can find our X axis and Y axis motors: // 1: We are hitting the sensor, means we are in a place we shouldn't be, so we go back in mode 1 // and when we are out of sensor we go forward again in mode 8 till we touch it again. Then we are at position 0 // 2: We are not hitting the sensor, means we need to find it. We go fas to it, wen we touch it // we go back slow till we don touch it anymore // This way the motors will be very accurate. // We should move the motors at this point in mode 1 for top speed /////////////////// LOGICS /* one or both sensors are outside the sensor both or one go inside at max speed delay to stop inertia when both inside they go outside at min speed till we release the sensor done! */ boolean both_sensors = false; // Falg for sensor checking unsigned long temp_counter=0; // Counter for error checking Xaxis.set_direction (!default_sensor_directionX); // Goes back till we find the sensor Yaxis.set_direction (!default_sensor_directionY); // Goes back till we find the sensor // set speed max Xaxis.change_step_mode(4); // Set stepper mode to 1 (Max speed) Yaxis.change_step_mode(4); // Set stepper mode to 1 (Max speed) unsigned long start_time = millis (); boolean skip_x = false; boolean skip_y = false; #if defined Xmotor_debug skip_x = true; #endif #if defined Ymotor_debug skip_y = true; #endif // We should move the motors at this point in mode 1 at top speed while (!both_sensors) { // While we dont hit the sensor... if (!Xaxis.sensor_check()) { Xaxis.do_step(); }else{ delayMicroseconds(19); } if (!Yaxis.sensor_check()) { Yaxis.do_step(); }else{ delayMicroseconds(19); } if ((Xaxis.sensor_check() || skip_x) && (Yaxis.sensor_check() || skip_y)) { // When both sensors are activated means we reached both init points both_sensors = true; } // Speed handeling unsigned long now = millis(); if ((now - start_time) < vIncrement) { delayMicroseconds(speed1); // Serial.print("s1"); }else if ((now - start_time) < (2*vIncrement)) { delayMicroseconds(speed2); // Serial.print("s2"); }else if ((now - start_time) < (3*vIncrement)) { delayMicroseconds(speed3); // Serial.print("s3"); }else { delayMicroseconds(speed4); // Serial.print("s4"); } // Error checking, if we cannot reach a point where we hit the sensor means that there is a problem temp_counter++; if ((temp_counter/1600) > Yaxis_cycles_limit) { // recheck the limit of revolutions send_error_to_server (init_Y1_fail); //still to implement an error message system return false; } if ((temp_counter/1600) > Xaxis_cycles_limit) { // recheck the limit of revolutions send_error_to_server (init_X1_fail); //still to implement an error message system return false; } } // we can stop at maximum speed as we didnt init motors yet, so we dont care if we lose steps. delay (500); // Enough for the motor to completely stop the inertia temp_counter = 0; // Reset the temop counter for error checking next step both_sensors = false; // Reset sensors variable Xaxis.set_direction (!default_sensor_directionX); // Goes forth till we are not hitting the sensor Yaxis.set_direction (default_sensor_directionY); // Goes forth till we are not hitting the sensor // set speed max Xaxis.change_step_mode(8); // Set stepper mode to 8 (Max speed) Yaxis.change_step_mode(8); // Set stepper mode to 8 (Max speed) while (!both_sensors) { // While we are hitting the sensor // change mode to hi speed if (Xaxis.sensor_check()) { Xaxis.do_step(); }else{ delayMicroseconds(19); } if (Yaxis.sensor_check()) { Yaxis.do_step(); }else{ delayMicroseconds(19); } // Serial.print ("skip_Y = "); Serial.println ((!Xaxis.sensor_check() || (skip_x)) && (!Yaxis.sensor_check() || (skip_y))); if ((!Xaxis.sensor_check() || skip_x) && (!Yaxis.sensor_check() || skip_y)) { // When both sensors are NOT activated means we are inside the safe zone, now we can correctly init the axes both_sensors = true; } //Serial.print ("both_sensors = "); Serial.println (both_sensors); delayMicroseconds(motor_speed_XY); // here we go at minimum speed so we asure we wont lose any step and we will achieve maximum acuracy // Error checking, if we cannot reach a point where we dont hit the sensor meands that there is a problem temp_counter++; if (temp_counter > max_insensor_stepsError) { // recheck the limit of revolutions send_error_to_server (init_Y2_fail); //still to implement an error message system return false; } if (temp_counter > max_insensor_stepsError) { // recheck the limit of revolutions send_error_to_server (init_X2_fail); //still to implement an error message system return false; } } delay (500); // Enough for the motor to completely stop the inertia // we set init ponts for both sensors Xaxis.set_init_position(); Yaxis.set_init_position(); Yaxis.set_direction(false); // All correct , return true return true; } // ************************************************************ // ** POSITION FUNCTIONS // ************************************************************ /* *********************** ** DEFINE ARRAY DIMENSION FOR BLISTERS *********************** ** ** Basic Positions: ** ** 1. X - INIT POSITION Y - INIT POSITION ** 2. X - Right before the blisters Y - INIT POSITION ** 3. X - Printer position Y - Printer position ** 4. X - Exit position Y - Exit position ** ** ** Blister type 10 Holes: ** ** 5. X - Hole 1 Y - Row 1 ** 6. X - Hole 2 Y - Row 2 ** 7. X - Hole 3 Y - Row 1 ** 8. X - Hole 4 Y - Row 2 ** 9. X - Hole 5 Y - Row 1 ** 10. X - Hole 6 Y - Row 2 ** 11. X - Hole 7 Y - Row 1 ** 12. X - Hole 8 Y - Row 2 ** 13. X - Hole 9 Y - Row 1 ** 14. X - Hole 10 Y - Row 2 ** ** ** Blister type 5 Holes: ** ** 15. X - Hole 1 Y - Row 1 ** 16. X - Hole 2 Y - Row 1 ** 17. X - Hole 3 Y - Row 1 ** 18. X - Hole 4 Y - Row 1 ** 19. X - Hole 5 Y - Row 1 ** ** ** Extra positions ** ** 20. X - Brush position Y - Brush position ** ********************************************************/ // read back a 2-byte int example: // pgm_read_word_near(y_axis_set + N) // calculate cycle index position if index is N -- > N = N + (N - 1) // calculate step index position if index is N -- > N = N + N // advice: change names to Coarse & fine // READ int get_cycle_Xpos_from_index(int index) { db.read(index, DB_REC mposition); return mposition.Xc; } int get_step_Xpos_from_index(int index) { db.read(index, DB_REC mposition); return mposition.Xf; } int get_cycle_Ypos_from_index(int index) { db.read(index, DB_REC mposition); return mposition.Yc; } int get_step_Ypos_from_index(int index) { db.read(index, DB_REC mposition); return mposition.Yf; } void go_to_memory_position (int position_index_to_go) { // Disable this function in case we are ending batch if (!skip_function()) { check_status (false); // Check for any pause button //send_position_to_server (position_index_to_go); // Inform server that we are going to a position int Xcycles = get_cycle_Xpos_from_index(position_index_to_go); int Xsteps = get_step_Xpos_from_index(position_index_to_go); int Ycycles = get_cycle_Ypos_from_index(position_index_to_go); int Ysteps = get_step_Ypos_from_index(position_index_to_go); go_to_posXY (Xcycles, Xsteps, Ycycles, Ysteps) ; } } void go_to_safe_position () { int safe_pos = 2; int Xcycles = get_cycle_Xpos_from_index(safe_pos); int Xsteps = get_step_Xpos_from_index(safe_pos); int Ycycles = get_cycle_Ypos_from_index(safe_pos); int Ysteps = get_step_Ypos_from_index(safe_pos); go_to_posXY (Xcycles, Xsteps, Ycycles, Ysteps) ; } void go_to_print_position () { int brush_pos = 20; int Xcycles = get_cycle_Xpos_from_index(brush_pos); int Xsteps = get_step_Xpos_from_index(brush_pos); int Ycycles = get_cycle_Ypos_from_index(brush_pos); int Ysteps = get_step_Ypos_from_index(brush_pos); Yaxis.got_to_position (Ycycles,Ysteps) ; // First move Y axis Xaxis.got_to_position (Xcycles,Xsteps) ; int print_pos = 4; Xcycles = get_cycle_Xpos_from_index(print_pos); Xsteps = get_step_Xpos_from_index(print_pos); Ycycles = get_cycle_Ypos_from_index(print_pos); Ysteps = get_step_Ypos_from_index(print_pos); Yaxis.got_to_position (Ycycles,Ysteps) ; // First move Y axis Xaxis.got_to_position (Xcycles,Xsteps) ; } void eject_blister () { int Xcycles = get_cycle_Xpos_from_index(4); // Exit position int Xsteps = get_step_Xpos_from_index(4); // Exit position int Ycycles = get_cycle_Ypos_from_index(20); // Brush Position int Ysteps = get_step_Ypos_from_index(20); // Brush Position Yaxis.got_to_position (Ycycles,Ysteps) ; // First move Y axis Xaxis.got_to_position (Xcycles,Xsteps) ; } void go_to_posXY (int Xcy,int Xst,int Ycy,int Yst) { Xaxis.got_to_position (Xcy,Xst) ; Yaxis.got_to_position (Ycy,Yst) ; } // Global vars for recorded position (for save mode) int temp_Xcycles = 0; int temp_Xsteps = 0; int temp_Ycycles = 0; int temp_Ysteps = 0; void record_actual_position () { temp_Xcycles = Xaxis.get_steps_cycles(); temp_Xsteps = Xaxis.get_steps(); temp_Ycycles = Yaxis.get_steps_cycles(); temp_Ysteps = Yaxis.get_steps(); } void go_to_last_saved_position () { go_to_posXY (temp_Xcycles, temp_Xsteps, temp_Ycycles, temp_Ysteps) ; }
true
8f589d3ac70c28320e3f1d3a525d459c700a3f7a
C++
sunilkrg/TheCPSquad
/Sahil Rana/Arrays/Valid_Sudoko.cpp
UTF-8
1,049
2.796875
3
[]
no_license
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { unordered_set<string> StringSet; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ if(board[i][j]!='.'){ string s(1,board[i][j]); string s1=s+"found in row"+to_string(i); string s2=s+"found in col"+to_string(j); string s3=s+"found in box"+to_string(i/3)+to_string(j/3); if(StringSet.find(s1)!=StringSet.end()) return false; if(StringSet.find(s2)!=StringSet.end()) return false; if(StringSet.find(s3)!=StringSet.end()) return false; StringSet.insert(s1); StringSet.insert(s2); StringSet.insert(s3); } } } return true; } };
true
1e91a1aaa2782cd009820efc0e96874e6978a24d
C++
panm111/oF_S16
/Week_2_Homework/src/ofApp.cpp
UTF-8
3,413
2.640625
3
[]
no_license
#include "ofApp.h" void ofApp::pentogon(int px1, int py1, int px2, int py2, int px3, int py4, int px5, int py5){ //Line 1 ofLine(px1, py1, px2, py2); //Line 2 ofLine(px2, py2, px3, py3); //Line 3 ofLine(px3, py3, px4, py4); //Line 4 ofLine(px4, py4, px5, py5); //Line 5 ofLine(px5, py5, px1, py1); } void ofApp::octogon(){ //Line 1 ofLine(ox1, oy1, ox2, oy2); //Line 2 ofLine(ox2, oy2, ox3, oy3); //Line 3 ofLine(ox3, oy3, ox4, oy4); //Line 4 ofLine(ox4, oy4, ox5, oy5); //Line 5 ofLine(ox5, oy5, ox6, oy6); //Line 6 ofLine(ox6, oy6, ox7, oy7); //Line 7 ofLine(ox7, oy7, ox8, oy8); //Line 8 ofLine(ox8, oy8, ox1, oy1); } void ofApp::star(){ //Line 1 ofLine(sx1,sy1, sx2, sy2); //Line 2 ofLine(sx2, sy2, sx3, sy3); //Line 3 ofLine(sx3, sy3, sx4, sy4); //Line 4 ofLine(sx4, sy4, sx5, sy5); //Line 5 ofLine(sx5, sy5, sx1, sy1); } //-------------------------------------------------------------- void ofApp::setup(){ px1 = 80; py1 = ofGetHeight()/2; px2 = 160; py2 = ofGetHeight()/2 -80; px3 = 240; py3 = ofGetHeight()/2; px4 = 200; py4 = ofGetHeight()/2 + 80; px5 = 120; py5 = ofGetHeight()/2 + 80; ox1 = 300; oy1 = ofGetHeight()/2-80; ox2 = 360; oy2 = ofGetHeight()/2-80; ox3 = 400; oy3 = ofGetHeight()/2-30; ox4 = 400; oy4 = ofGetHeight()/2 + 30; ox5 = 360; oy5 = ofGetHeight()/2+80; ox6 = 300; oy6 = ofGetHeight()/2+80; ox7 = 260; oy7 = ofGetHeight()/2 +30; ox8 = 260; oy8 = ofGetHeight()/2-30; sx1 = 450; sy1 = ofGetHeight()/2+80; sx2 = 550; sy2 = ofGetHeight()/2-80; sx3 = 650; sy3 = ofGetHeight()/2+80; sx4 = 450; sy4 = ofGetHeight()/2; sx5 = 650; sy5 = ofGetHeight()/2; for(int i=0; i<NUMROBOTS; i++){ rob[i].setup(); } } //-------------------------------------------------------------- void ofApp::update(){ for(int i=0; i<NUMROBOTS; i++){ rob[i].move(); } } //-------------------------------------------------------------- void ofApp::draw(){ // ofSetColor(255, 0, 0); // ofFill(); pentogon(px1, py1, px2, py2, px3, py4, px5, py5); octogon(); star(); for(int i=0; i<NUMROBOTS; i++){ rob[i].display(); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
true
2980c02c9f9da111e4a90324fb814ec646a8458b
C++
hossainmurad/mycppcgi
/base/utility/General.cpp
UTF-8
163
2.546875
3
[]
no_license
#include "General.h" void parse_path_info(string& s){ for (int i = 0; i< s.size() ; ++i) switch(s[i]){ case '/': s[i] = ' '; break; } }
true
6ac993aa34aaa945430b834e557fae0f9ee69b04
C++
Connor-F/ncurses_snake
/Snake.cpp
UTF-8
2,875
3.515625
4
[]
no_license
#include "Snake.h" #include "Window.h" Snake_Segment& Snake::get_segment(std::vector<Snake_Segment>::size_type index) // todo: remove? { return snake.at(index); } /* * allows user to get the front (head) * of the snake * return: the Snake_Segment at the front of the snake */ Snake_Segment& Snake::get_front() { return snake.at(0); } /* * allows user to get the back (end) * of the snake * return: the Snake_Segment at the back of the snake */ const Snake_Segment& Snake::get_back() { return snake.at(snake.size() - 1); } /* * creates the intial snake */ void Snake::go() { snake.push_back(Snake_Segment(Pos(Window::max_x / 2, Window::max_y / 2), NORTH)); } /* * allows snake to grow after eating some food */ void Snake::grow() { Snake_Segment last = get_back(); int new_x = last.get_pos().get_x_pos(); int new_y = last.get_pos().get_y_pos(); // works out new coords for the new segment according to the // tail of the snake (as new segment gets added after tail) switch(last.get_direction()) { case NORTH: new_y++; break; case EAST: new_x--; break; case SOUTH: new_y--; break; case WEST: new_x++; break; } snake.push_back(Snake_Segment(Pos(new_x, new_y), last.get_direction())); } /* * used to get the whole snake (every segment) * return: const reference to a vector that makes up the snake */ std::vector<Snake_Segment>& Snake::get_segments() { return snake; } /* * checks if the front of the snake has hit a wall (game over) * return: true if it has, false if not */ bool Snake::has_hit_wall() { Snake_Segment head = get_front(); int x = head.get_pos().get_x_pos(); int y = head.get_pos().get_y_pos(); return x == 0 || x == Window::max_x || y == 0 || y == Window::max_y; // hit a wall, dead } /* * checks to see if the head collided with part of the body * return: true if it did, false if it didn't */ bool Snake::has_hit_self() { Snake_Segment head = get_front(); int x_head = head.get_pos().get_x_pos(); int y_head = head.get_pos().get_y_pos(); // + 1 to not included head for(std::vector<Snake_Segment>::const_iterator it = snake.begin() + 1; it != snake.end(); it++) { int x_seg = it->get_pos().get_x_pos(); int y_seg = it->get_pos().get_y_pos(); //todo: if(pos == pos) here, not x and y if(x_head == x_seg && y_head == y_seg) // head collided with a body segment return true; } return false; } /* * checks if the snake has died from crashing into wall / itself * return: true if the snake has died, false if not */ bool Snake::has_died() { return has_hit_wall() || has_hit_self(); }
true
0a90534677ded0c87ba8107f4b686a182d1df9cc
C++
sgondala/Compilers
/Part3/classes.hpp
UTF-8
11,593
3.03125
3
[]
no_license
#include <iostream> #include <list> #include <stdio.h> using namespace std; class abstract_astnode { public: virtual void print () = 0; }; class ExpAst : public abstract_astnode { public: void print (); }; class StmtAst : public abstract_astnode { public: void print (); }; class ForAst: public StmtAst { private: abstract_astnode* exp1; abstract_astnode* exp2; abstract_astnode* exp3; abstract_astnode* stmt; public: void print (); ForAst(abstract_astnode *a, abstract_astnode *b, abstract_astnode* c, abstract_astnode* d); }; class WhileAst: public StmtAst { private: abstract_astnode* exp; abstract_astnode* stmt; public: void print(); WhileAst(abstract_astnode *a, abstract_astnode *b); }; class IfAst: public StmtAst { private: abstract_astnode* exp; abstract_astnode* stmt1; abstract_astnode* stmt2; public: void print(); IfAst(abstract_astnode *a, abstract_astnode *b, abstract_astnode *c); }; class ReturnAst: public StmtAst { private: abstract_astnode* exp; public: void print(); ReturnAst(abstract_astnode* a); }; class AssAst: public StmtAst { private: abstract_astnode* exp1; abstract_astnode* exp2; public: void print(); AssAst(abstract_astnode* a, abstract_astnode* b); }; class EmptyAst: public StmtAst { public: void print(); EmptyAst(); }; class BlockAst: public abstract_astnode { private: list<abstract_astnode*> block; public: void print(); BlockAst(abstract_astnode* a); void add(abstract_astnode* a); }; /////////////////////////////////////////////// Valar Doherias class OpAst: public ExpAst{ enum OPERATOR { OR = 1, AND, EQ_OP, NE_OP, LT, GT, LE_OP, GE_OP, PLUS, MINUS, MULT, ASSIGN }; std::string rank[12] = { "OR", "AND", "EQ_OP", "NE_OP", "LT", "GT", "LE_OP", "GE_OP", "PLUS", "MINUS", "MULT", "ASSIGN" }; abstract_astnode* exp1; abstract_astnode* exp2; OPERATOR op; public: void print(); OpAst(OPERATOR a, abstract_astnode* b, abstract_astnode* c); }; class UnopAst: public ExpAst{ enum OPERATOR { UMINUS=1, NOT, PP }; std::string rank[3] = { "UMINUS", "NOT", "PP"}; OPERATOR op; abstract_astnode* exp1; public: UnopAst(OPERATOR a, abstract_astnode* b); void print(); }; class FloatConstAst: public ExpAst{ float f; public: FloatConstAst(float a); void print(); }; class IntConstAst: public ExpAst{ int i; public: IntConstAst(int a); void print(); }; class StringConstAst: public ExpAst{ std::string s; public: StringConstAst(std::string a); void print(); }; class IdentifierAst: public ExpAst{ std::string s; public: void print(); IdentifierAst(std::string a); }; /* ///////////////////////////////// definitions void ExpAst::print(){} void StmtAst::print(){} void ForAst::print () { std::cout << "(For "; exp1->print(); std::cout << std::endl; exp2->print(); std::cout << std::endl; exp3->print(); std::cout << std::endl; stmt->print(); std::cout << ")"; } ForAst::ForAst(abstract_astnode *a, abstract_astnode *b, abstract_astnode* c, abstract_astnode* d) : exp1(a), exp2(b), exp3(c), stmt(d) {} void WhileAst::print() { std::cout << "(While "; exp->print(); std::cout << std::endl; stmt->print(); std::cout << ")"; } WhileAst::WhileAst(abstract_astnode* a, abstract_astnode* b) { exp = a; stmt = b; } void IfAst::print() { std::cout << "(If "; exp->print(); std::cout << std::endl; stmt1->print(); std::cout << std::endl; stmt2->print(); std::cout << ")"; } IfAst::IfAst(abstract_astnode* a, abstract_astnode* b, abstract_astnode* c) { exp = a; stmt1 = b; stmt2 = c; } void ReturnAst::print() { std::cout << "(Return "; exp->print(); //std::cout << std::endl; std::cout << ")"; } ReturnAst::ReturnAst(abstract_astnode* a) { exp = a; } void AssAst::print() { std::cout << "(Assignment "; exp1->print(); std::cout << " "; // std::endl; exp2->print(); std::cout << ")"; } AssAst::AssAst(abstract_astnode* a, abstract_astnode* b) { exp1 = a; exp2 = b; } void EmptyAst::print() { std::cout << "(Empty)"; } EmptyAst::EmptyAst(){} void BlockAst::print() { std::cout << "(Block [" ; list<abstract_astnode*>::iterator it; for(it = block.begin(); it!= block.end(); it++) { (*it)->print(); //if(it != block.end()-1) std::cout << std::endl; } std::cout << "])" << std::endl; } BlockAst::BlockAst(abstract_astnode* a) { block.push_back(a); } void BlockAst::add(abstract_astnode* a) { block.push_back(a); } //////////////////////////////////////// Valar Morghulis! void OpAst::print(){ std::cout<<"( "<<rank[op-1]<<" "; exp1->print(); std::cout<<" "; exp2->print(); std::cout<<" ) "; } OpAst::OpAst(OPERATOR a, abstract_astnode* b, abstract_astnode* c){ op=a; exp1=b; exp2=c; } UnopAst::UnopAst(OPERATOR a, abstract_astnode* b){ op = a; exp1 = b; } void UnopAst::print(){ std::cout<<"( "<<rank[op-1]<<" "; exp1->print(); std::cout<<" ) \n"; } FloatConstAst::FloatConstAst(float a){ f=a; } void FloatConstAst::print(){ printf("(FLOATCONST %f)",f); } IntConstAst::IntConstAst(int a){ i=a; } void IntConstAst::print(){ printf("(INTCONST %i)",i); } StringConstAst::StringConstAst(std::string a){ s=a; } void StringConstAst::print(){ printf("(STRINGCONST %s)",s.c_str()); } IdentifierAst::IdentifierAst(std::string a){ s=a; } void IdentifierAst::print(){ printf("(IDENTIFIER %s)",s.c_str()); } //// end int main() {} #include <iostream> #include <list> #include <stdio.h> using namespace std; class abstract_astnode { public: virtual void print () = 0; }; class ExpAst : public abstract_astnode { public: void print (); }; class StmtAst : public abstract_astnode { public: void print (); }; class ForAst: public StmtAst { private: abstract_astnode* exp1; abstract_astnode* exp2; abstract_astnode* exp3; abstract_astnode* stmt; public: void print (); ForAst(abstract_astnode *a, abstract_astnode *b, abstract_astnode* c, abstract_astnode* d); }; class WhileAst: public StmtAst { private: abstract_astnode* exp; abstract_astnode* stmt; public: void print(); WhileAst(abstract_astnode *a, abstract_astnode *b); }; class IfAst: public StmtAst { private: abstract_astnode* exp; abstract_astnode* stmt1; abstract_astnode* stmt2; public: void print(); IfAst(abstract_astnode *a, abstract_astnode *b, abstract_astnode *c); }; class ReturnAst: public StmtAst { private: abstract_astnode* exp; public: void print(); ReturnAst(abstract_astnode* a); }; class AssAst: public StmtAst { private: abstract_astnode* exp1; abstract_astnode* exp2; public: void print(); AssAst(abstract_astnode* a, abstract_astnode* b); }; class EmptyAst: public StmtAst { public: void print(); EmptyAst(); }; class BlockAst: public abstract_astnode { private: list<abstract_astnode*> block; public: void print(); BlockAst(abstract_astnode* a); void add(abstract_astnode* a); }; /////////////////////////////////////////////// Valar Doherias class OpAst: public ExpAst{ enum OPERATOR { OR = 1, AND, EQ_OP, NE_OP, LT, GT, LE_OP, GE_OP, PLUS, MINUS, MULT, ASSIGN }; std::string rank[12] = { "OR", "AND", "EQ_OP", "NE_OP", "LT", "GT", "LE_OP", "GE_OP", "PLUS", "MINUS", "MULT", "ASSIGN" }; abstract_astnode* exp1; abstract_astnode* exp2; OPERATOR op; public: void print(); OpAst(OPERATOR a, abstract_astnode* b, abstract_astnode* c); }; class UnopAst: public ExpAst{ enum OPERATOR { UMINUS=1, NOT, PP }; std::string rank[3] = { "UMINUS", "NOT", "PP"}; OPERATOR op; abstract_astnode* exp1; public: UnopAst(OPERATOR a, abstract_astnode* b); void print(); }; class FloatConstAst: public ExpAst{ float f; public: FloatConstAst(float a); void print(); }; class IntConstAst: public ExpAst{ int i; public: IntConstAst(int a); void print(); }; class StringConstAst: public ExpAst{ std::string s; public: StringConstAst(std::string a); void print(); }; class IdentifierAst: public ExpAst{ std::string s; public: void print(); IdentifierAst(std::string a); }; ///////////////////////////////// definitions void ExpAst::print(){} void StmtAst::print(){} void ForAst::print () { std::cout << "(For "; exp1->print(); std::cout << std::endl; exp2->print(); std::cout << std::endl; exp3->print(); std::cout << std::endl; stmt->print(); std::cout << ")"; } ForAst::ForAst(abstract_astnode *a, abstract_astnode *b, abstract_astnode* c, abstract_astnode* d) : exp1(a), exp2(b), exp3(c), stmt(d) {} void WhileAst::print() { std::cout << "(While "; exp->print(); std::cout << std::endl; stmt->print(); std::cout << ")"; } WhileAst::WhileAst(abstract_astnode* a, abstract_astnode* b) { exp = a; stmt = b; } void IfAst::print() { std::cout << "(If "; exp->print(); std::cout << std::endl; stmt1->print(); std::cout << std::endl; stmt2->print(); std::cout << ")"; } IfAst::IfAst(abstract_astnode* a, abstract_astnode* b, abstract_astnode* c) { exp = a; stmt1 = b; stmt2 = c; } void ReturnAst::print() { std::cout << "(Return "; exp->print(); //std::cout << std::endl; std::cout << ")"; } ReturnAst::ReturnAst(abstract_astnode* a) { exp = a; } void AssAst::print() { std::cout << "(Assignment "; exp1->print(); std::cout << " "; // std::endl; exp2->print(); std::cout << ")"; } AssAst::AssAst(abstract_astnode* a, abstract_astnode* b) { exp1 = a; exp2 = b; } void EmptyAst::print() { std::cout << "(Empty)"; } EmptyAst::EmptyAst(){} void BlockAst::print() { std::cout << "(Block [" ; list<abstract_astnode*>::iterator it; for(it = block.begin(); it!= block.end(); it++) { (*it)->print(); //if(it != block.end()-1) std::cout << std::endl; } std::cout << "])" << std::endl; } BlockAst::BlockAst(abstract_astnode* a) { block.push_back(a); } void BlockAst::add(abstract_astnode* a) { block.push_back(a); } //////////////////////////////////////// Valar Morghulis! void OpAst::print(){ std::cout<<"( "<<rank[op-1]<<" "; exp1->print(); std::cout<<" "; exp2->print(); std::cout<<" ) "; } OpAst::OpAst(OPERATOR a, abstract_astnode* b, abstract_astnode* c){ op=a; exp1=b; exp2=c; } UnopAst::UnopAst(OPERATOR a, abstract_astnode* b){ op = a; exp1 = b; } void UnopAst::print(){ std::cout<<"( "<<rank[op-1]<<" "; exp1->print(); std::cout<<" ) \n"; } FloatConstAst::FloatConstAst(float a){ f=a; } void FloatConstAst::print(){ printf("(FLOATCONST %f)",f); } IntConstAst::IntConstAst(int a){ i=a; } void IntConstAst::print(){ printf("(INTCONST %i)",i); } StringConstAst::StringConstAst(std::string a){ s=a; } void StringConstAst::print(){ printf("(STRINGCONST %s)",s.c_str()); } IdentifierAst::IdentifierAst(std::string a){ s=a; } void IdentifierAst::print(){ printf("(IDENTIFIER %s)",s.c_str()); } //// end int main() {} */
true
97c32654bc85872d3dbce079c0c0009ca047e8f6
C++
bcumming/tracey
/src/id.hpp
UTF-8
599
2.515625
3
[]
no_license
#pragma once #include <atomic> #include <mutex> #include <string_view> #include <unordered_map> #include <vector> #include <tracey/tracey.hpp> namespace tracey { class id_dictionary { public: trace_id lookup(std::string_view name); std::string name(trace_id id) const; std::size_t size() const; std::vector<std::string> names() const; private: std::atomic<trace_id> count_ = 0; mutable std::mutex mutex_; std::vector<std::string> names_; std::unordered_map<std::string_view, trace_id> map_; }; trace_id unique_trace_id(std::string_view); } // namespace tracey
true
25125577ac9f2ee0778cc12d58930555427e62c4
C++
oaleshina/pscx_emulator
/pscx_emulator/pscx_disc.h
UTF-8
3,866
2.796875
3
[]
no_license
#pragma once #include <fstream> #include "pscx_minutesecondframe.h" // Size of a CD sector in bytes. const size_t SECTOR_SIZE = 2352; // CD-ROM sector sync pattern: 10 0xff surrounded by two 0x00. Not // used in CD-DA audio tracks. const uint8_t SECTOR_SYNC_PATTERN[] = { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 }; // Disc region coding. enum Region { // Japan (NTSC): SCEI. REGION_JAPAN, // North Ametica (NTSC): SCEA. REGION_NORTH_AMERICA, // Europe (PAL): SCEE. REGION_EUROPE }; // Structure representing a single CD-ROM XA sector. struct XaSector { XaSector(); // Return payload data byte at "index". uint8_t getDataByte(uint16_t index) const; enum XaSectorStatus { XA_SECTOR_STATUS_OK, XA_SECTOR_STATUS_INVALID_DATA, XA_SECTOR_STATUS_INVALID_INPUT }; struct ResultXaSector { ResultXaSector(const XaSector* sector, XaSectorStatus status) : m_sector(sector), m_status(status) { } const XaSector* getSectorPtr() const { return m_sector; } XaSectorStatus getSectorStatus() const { return m_status; } private: const XaSector* m_sector; XaSectorStatus m_status; }; // Validate CD-ROM XA Mode 1 or 2 sector. ResultXaSector validateMode1_2(const MinuteSecondFrame& minuteSecondFrame); // Parse and validate CD-ROM XA mode 2 sector. // Regular CD-ROM defines mode 2 as just containing 0x920 bytes of // "raw" data after the 16 byte sector header. However the CD-ROM XA spec // defines two possible "forms" for this mode 2 data, there's an 8 byte sub-header // at the beginning of the data that will tell us how to interpret it. ResultXaSector validateMode2(); // CD-ROM XA Mode 2 Form 1: 0x800 bytes of data protected by a // 32 bit CRC for error detection and 276 bytes of error correction codes. ResultXaSector validateMode2Form1() const; // CD-ROM XA Mode 2 Form 2: 0x914 bytes of data without ECC or EDC. // Last 4 bytes are reserved for quality control, but the CDi spec doesn't // mandare what goes in it exactly, only that it is recommended that the same // EDC algorithm should be used here as is used for the Form 1 sectors. If this // algorithm is not used, then the reserved bytes are set to 0. ResultXaSector validateMode2Form2() const; // Return the MinuteSecondFrame structure in the sector's header. MinuteSecondFrame getMinuteSecondFrame() const; // Return the raw sector as a byte slice. const uint8_t* getRawSectorInBytes() const; //private: // The raw array of 2352 bytes contained in the sector. uint8_t m_raw[SECTOR_SIZE]; }; // Playstation disc struct Disc { Disc(std::ifstream&& file, Region region); enum DiscStatus { DISC_STATUS_OK, DISC_STATUS_INVALID_PATH, DISC_STATUS_INVALID_DATA }; struct ResultDisc { ResultDisc(const Disc* disc, DiscStatus status) : m_disc(disc), m_status(status) { } const Disc* m_disc; DiscStatus m_status; }; // Reify a disc from file at "path" and attempt to identify it. static ResultDisc initializeFromPath(const std::string& path); Region getRegion() const; // Attempt to discover the region of the disc. This way we know // which string to return in the CD-ROM drive's "get id" command // and we can decide which BIOS and output video standard to use // based on the game disk. ResultDisc extractRegion(); // Read a Mode 1 or 2 CD-ROM XA sector and validate it. The function // will return an error if used on a CD-DA raw audio sector. XaSector::ResultXaSector readDataSector(const MinuteSecondFrame& minuteSecondFrame); // Read a raw CD sector without any validation. For Mode 1 and 2 // sectors XaSector::validateMode1_2 should be called to make sure // the sector is valid. XaSector::ResultXaSector readSector(const MinuteSecondFrame& minuteSecondFrame); private: // BIN file std::ifstream m_file; // Disc region Region m_region; };
true
d3dc1727b68364ac878a52b4642b202916abe43c
C++
pwnlogs/EasyNetIITM
/mainwindow.cpp
UTF-8
4,926
2.578125
3
[]
no_license
/* * Project name hardcoded in function "on_approve_b_clicked" */ #include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <QSettings> #include <QTime> #include "python2.7/Python.h" #include <stdlib.h> // Testing pupose libs #include <QtDebug> #include <QDir> int vaildate(QString password, QString username) { /* * validate the username and password in the textBox. * Pop error ig textBox is empty. * * return value: * 0: Credentials succesfuly validated. * 2: Credentials are invalid * 1: Validation failed. Possibly connection problem * -1: Validation failed due to bug in program * */ Py_Initialize(); PyRun_SimpleString("import sys\n" "import os"); PyRun_SimpleString("sys.path.append( os.path.dirname(os.getcwd()) +'/EasyNetIITM/')"); PyObject *pName, *pModule, *pFunc, *pArgs; pName = PyString_FromString("UsrValidation"); pModule = PyImport_Import(pName); Py_DECREF(pName); if(pModule!=NULL){ qDebug()<<"validate module found"<<endl; pFunc = PyObject_GetAttrString(pModule, (char*)"validate"); if(pFunc==NULL){ qDebug()<<"Validation Failed"<<endl; Py_Finalize(); return -1; } pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, PyString_FromString(username.toStdString().c_str())); PyTuple_SetItem(pArgs, 1, PyString_FromString(password.toStdString().c_str())); PyObject_CallObject(pFunc, pArgs); } else{ qDebug()<<"Validation failed"<<endl; PyErr_Print(); qDebug()<<endl; Py_Finalize(); return -1; } Py_Finalize(); return 1; } int approve(QString password, QString username) { Py_Initialize(); PyRun_SimpleString("import sys\n" "import os"); PyRun_SimpleString("sys.path.append( os.path.dirname(os.getcwd()) +'/EasyNetIITM/')"); PyObject *pName, *pModule, *pFunc, *pArgs, *pRet; pName = PyString_FromString("NetApprove"); pModule = PyImport_Import(pName); Py_DECREF(pName); if( pModule!=NULL){ pFunc = PyObject_GetAttrString(pModule, (char*)"approve"); pArgs = PyTuple_New(3); PyTuple_SetItem(pArgs, 0, PyInt_FromLong(1)); PyTuple_SetItem(pArgs, 1, PyString_FromString(username.toStdString().c_str())); PyTuple_SetItem(pArgs, 2, PyString_FromString(password.toStdString().c_str())); pRet = PyObject_CallObject(pFunc, pArgs); if(PyLong_AsLong(pRet)==0){ // Successful approval return 0; } else if(PyLong_AsLong(pRet)==1){ // TODO: retry return 1; } } else{ qDebug()<<"approve Python module not found"<<endl; PyErr_Print(); qDebug()<<endl; } Py_Finalize(); return 1; } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void delay(int n) { QTime dieTime= QTime::currentTime().addSecs(n); while (QTime::currentTime() < dieTime) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } void MainWindow::on_save_b_clicked() { QString pass = ui->password_le->text(); QString usrn = ui->username_le->text(); // int valid = validate_pass_usrn(pass, usrn); int valid = 1; if(valid == 1) // valid password { QSettings settings; settings.setValue("username", usrn); settings.setValue("password", pass); QMessageBox::information(this,"Success", "Credentials saved successfully"); } else if(valid == 2) // could not validate: possibly connection unavailable { QMessageBox::warning(this, "Validation Fail", "Failed to validate Credentials\n" "Check your connection"); } else{ QMessageBox::critical(this, "Invalid Credentials", "Invalid username or password"); } } void MainWindow::on_approve_b_clicked() { QSettings settings; QString password = settings.value("password").toString(); QString username = settings.value("username").toString(); QMessageBox::information(this, "Credentials", "Pass:"+password+" User:"+username); approve(password, username); } void MainWindow::on_validate_b_clicked() { QString password = ui->password_le->text(); QString username = ui->username_le->text(); if(password==NULL || username==NULL){ // TODO: Disable button if password/ username field is empty QMessageBox::warning(this, "Empty Credentials", "Password or Username field is empty"); return; } else{ vaildate(password, username); } }
true
100ec1eeb73b06612cff4032e5c65ce4c869b443
C++
Yapami/playground
/template-specialization/TemplateSpecialization.cpp
UTF-8
879
3.59375
4
[]
no_license
#include <gmock/gmock.h> #include <gtest/gtest.h> class TemplateSpecialization : public testing::Test { public: enum class Digits { ONE, TWO, THREE, }; template<Digits> uint32_t digit() { throw std::runtime_error("Wrong enum value"); return 0; } }; template<> uint32_t TemplateSpecialization::digit<TemplateSpecialization::Digits::ONE>() { return 1; } template<> uint32_t TemplateSpecialization::digit<TemplateSpecialization::Digits::TWO>() { return 2; } template<> uint32_t TemplateSpecialization::digit<TemplateSpecialization::Digits::THREE>() { return 3; } TEST_F(TemplateSpecialization, test) { EXPECT_EQ(digit<Digits::ONE>(), 1); EXPECT_EQ(digit<Digits::TWO>(), 2); EXPECT_EQ(digit<Digits::THREE>(), 3); EXPECT_THROW(digit<static_cast<Digits>(5)>(), std::runtime_error); }
true
f2da08a5217c3fda55212e3a90ac7f57decde542
C++
weininglee/CPP_HW
/CS1010301HW04/TS0404/BankAccount.h
UTF-8
628
3.3125
3
[]
no_license
static int total = 0; class BankAccount { private: int balance; public: BankAccount(); BankAccount(int input); void withdraw(int output); void save(int input); int getBalance(); static int getAllMoneyInBank(); }; BankAccount::BankAccount() { balance = 0; total += balance; } BankAccount::BankAccount(int input) { balance = input; total += balance; } void BankAccount::withdraw(int output) { balance -= output; total -= output; } void BankAccount::save(int input) { balance += input; total += input; } int BankAccount::getBalance() { return balance; } int BankAccount::getAllMoneyInBank() { return total; }
true
f166fad2d52e956f524281771dad79b32dccb521
C++
edgar2020/colaborative_labs_and_assignments_CS10C
/Assignments/simpleDataCompression/HashTable.cpp
UTF-8
2,743
3.640625
4
[]
no_license
#include "HashTable.h" #include "WordEntry.h" #include <iostream> #include <fstream> #include <cstdlib> using namespace std; /* HashTable constructor * input s is the size of the array * set s to be size * initialize array of lists of WordEntry */ HashTable::HashTable (int s) { // 1) Create an array of Word Entry with size s size = s; //WordEntry* words[size]; hashTable = new WordEntry[size]; } /* computeHash * return an integer based on the input string * used for index into the array in hash table * be sure to use the size of the array to * ensure array index doesn't go out of bounds */ int HashTable::computeHash(const string &s) { unsigned hash = 0; for( char c : s) { // hash += c; hash = (((hash * 378551)%size) + c); } return (hash) % size; } int HashTable::contains(const string & s) { int index = computeHash(s); //look if already exists while(hashTable[index].getWord() != "")//.getWord() != " ") { if(hashTable[index].getWord() == s) { return hashTable[index].getKey(); } index++; if(index >= size) { index = 0; } } return hashTable[index].getKey(); } /* put * input: string word and int score to be inserted * First, look to see if word already exists in hash table * if so, addNewAppearence with the score to the WordEntry * if not, create a new Entry and push it on the list at the * appropriate array index */ void HashTable::put(const string &s) { //go to array index of hash int index = computeHash(s); //look if already exists while(hashTable[index].getWord() != "")//.getWord() != " ") { if(hashTable[index].getWord() == s) { hashTable[index].addNewAppearance(); return; } index++; if(index >= size) { index = 0; } } // WordEntry temp = hashTable[index].setWord(s); hashTable[index].setAppearences(1); } void HashTable::put( WordEntry &s) { //go to array index of hash int index = computeHash(s.getWord()); //look if already exists while(hashTable[index].getWord() != "")//.getWord() != " ") { index++; if(index >= size) { index = 0; } } // WordEntry temp = hashTable[index] = s; } // void HashTable::put(const string &s) { // //go to array index of hash // int index = computeHash(s); // //look if already exists // while(*(hashTable + index) != nullptr)//.getWord() != " ") // { // if((*hashTable + index)->getWord() == s) // { // (*hashTable + index)->addNewAppearance(); // } // index++; // } // // WordEntry temp = // hashTable[index] = new WordEntry(s); // }
true
838c5e6d60f018099f4fa3f1979f1894f5fbf4fb
C++
davjd/fantasy_ball
/src/team_fetcher.h
UTF-8
1,712
2.609375
3
[]
no_license
#ifndef TEAM_FETCHER_H_ #define TEAM_FETCHER_H_ #include "curl_fetch.h" #include "util.h" #include <nlohmann/json.hpp> #include <string> #include <vector> namespace fantasy_ball { class TeamFetcher { public: struct GameMatchup { GameMatchup() = default; std::string home_team; int home_team_id; std::string away_team; int away_team_id; int home_score; int away_score; int event_id; static GameMatchup deserialize_json(const nlohmann::json &json_content) { GameMatchup matchup = {}; matchup.event_id = -1; if (!json_content.contains("schedule") || !json_content.contains("score")) { return matchup; } const auto &schedule = json_content["schedule"]; const auto &score = json_content["score"]; matchup.home_team = schedule["homeTeam"]["abbreviation"].get<std::string>(); matchup.home_team_id = schedule["homeTeam"]["id"].get<int>(); matchup.away_team = schedule["awayTeam"]["abbreviation"].get<std::string>(); matchup.away_team_id = schedule["awayTeam"]["id"].get<int>(); matchup.home_score = score["homeScoreTotal"].get<int>(); matchup.away_score = score["awayScoreTotal"].get<int>(); matchup.event_id = schedule["id"].get<int>(); return matchup; } }; TeamFetcher(CurlFetch *curl_fetch); ~TeamFetcher(); std::vector<GameMatchup> GetGameReferences(endpoint::Options *options); private: static const std::string kBaseUrl; // NOTE: This class doesn't have ownership of this object. CurlFetch *curl_fetch_; std::string construct_endpoint_url(endpoint::Options *options); }; } // namespace fantasy_ball #endif // TEAM_FETCHER_H_
true
9104f647caebb0de2608d3ca5b0a777ef858b15a
C++
sprinfall/opengl-study
/tutorials/07_rotation/07_rotation.cpp
UTF-8
3,038
2.6875
3
[ "MIT" ]
permissive
#include <cmath> #include <cstdio> #include <string> #include <GL/glew.h> #include <GL/freeglut.h> #include "ogldev_math_3d.h" #include "utility.h" // 这个例子与 06_translation 几乎一样,除了矩阵不同。 GLuint g_vbo; GLuint g_world_location; static void RenderSceneCB() { glClear(GL_COLOR_BUFFER_BIT); static float scale = 0.0f; scale += 0.001f; // Matrix4f.m : float m[4][4] Matrix4f world; // 绕着 Z 轴旋转,注意 InitRotateTransform() 的参数为 radian 角度。 world.InitRotateTransform(0.0f, 0.0f, ToDegree(scale)); // 原来的写法: // world.m[0][0]=cosf(scale); world.m[0][1]=-sinf(scale); world.m[0][2]=0.0f; world.m[0][3]=0.0f; // world.m[1][0]=sinf(scale); world.m[1][1]=cosf(scale); world.m[1][2]=0.0f; world.m[1][3]=0.0f; // world.m[2][0]=0.0f; world.m[2][1]=0.0f; world.m[2][2]=1.0f; world.m[2][3]=0.0f; // world.m[3][0]=0.0f; world.m[3][1]=0.0f; world.m[3][2]=0.0f; world.m[3][3]=1.0f; // 把 matrix 传给 shader。 // 注意最后一个参数不能直接写成 world.m,因为它的类型是 float (*)[4]。 glUniformMatrix4fv(g_world_location, 1, GL_TRUE, &world.m[0][0]); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, g_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); glutSwapBuffers(); } static void InitializeGlutCallbacks() { glutDisplayFunc(RenderSceneCB); glutIdleFunc(RenderSceneCB); } static void CreateVertexBuffer() { Vector3f vertices[3]; vertices[0] = Vector3f(-1.0f, -1.0f, 0.0f); vertices[1] = Vector3f(1.0f, -1.0f, 0.0f); vertices[2] = Vector3f(0.0f, 1.0f, 0.0f); glGenBuffers(1, &g_vbo); glBindBuffer(GL_ARRAY_BUFFER, g_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); } int main(int argc, char** argv) { glutInitContextVersion(4, 5); glutInitContextProfile(GLUT_CORE_PROFILE); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize(1024, 768); glutInitWindowPosition(100, 100); glutCreateWindow("06 - Translation Transform"); InitializeGlutCallbacks(); // Must be done after glut is initialized! GLenum res = glewInit(); if (res != GLEW_OK) { fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res)); return 1; } printf("GL version: %s\n", glGetString(GL_VERSION)); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // 关于 VAO,详见 04_shaders 示例里的注释。 GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); CreateVertexBuffer(); GLuint shader_program = CreateProgram("shader.vs", "shader.fs"); // 拿到一致变量的位置(且只有在链接之后才能拿到这个位置),随后便可通过 // glUniform 设置一致变量的值,或通过 glGetUniform 得到它的值。 g_world_location = glGetUniformLocation(shader_program, "gWorld"); assert(g_world_location != 0xFFFFFFFF); glutMainLoop(); return 0; }
true
b7a883c427928069af7be6eb46a493bf3fb39b1b
C++
Phantsure/algo-rythm-urf-algorithm
/graph/c++/dijkstra.cpp
UTF-8
2,225
3.796875
4
[]
no_license
#include<bits/stdc++.h> using namespace std; class DirectedGraph { typedef vector< vector < pair<int, long long> > > AdjList; int V; // Number of vertices AdjList adjList; public: DirectedGraph(int V); void addEdge(int u, int v, long long w); // Finds the shortest path from source to destination long long shortestPathDijkstra(int source, int destination, vector<int>& path); }; DirectedGraph::DirectedGraph(int n) : adjList(n), V(n) { } void DirectedGraph::addEdge(int u, int v, long long w) { adjList[u].emplace_back(v, w); } long long DirectedGraph::shortestPathDijkstra(int source, int destination, vector<int>& path) { vector< int > parent(V, -1); vector< long long > minCost(V, LLONG_MAX); set< pair<long long, int> > pq; minCost[source] = 0LL; pq.insert( make_pair(0LL, source) ); while(!pq.empty()) { set< pair<long long, int> >::iterator it = pq.begin(); int u = it->second; pq.erase(it); if(u == destination) break; for(int i=0; i < adjList[u].size(); ++i) { int v = adjList[u][i].first; long long w = adjList[u][i].second; if(minCost[v] > minCost[u] + w) { pq.erase( make_pair(minCost[v], v) ); minCost[v] = minCost[u] + w; pq.insert( make_pair(minCost[v], v) ); parent[v] = u; } } } int tmp = destination; while(tmp != -1) { path.push_back(tmp); tmp = parent[tmp]; } reverse(path.begin(), path.end()); return minCost[destination]; } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram DirectedGraph g(5); g.addEdge(0, 1, 3LL); g.addEdge(1, 3, 6LL); g.addEdge(3, 4, 2LL); g.addEdge(1, 2, 4LL); g.addEdge(2, 3, 1LL); vector<int> path; long long cost = g.shortestPathDijkstra(0, 4, path); cout << "Shortest path from vertex 0 to vertex 4 costs " << cost << " and follows the vertices:" << endl; for(int i = 0; i < path.size(); ++i) { cout << path[i] << endl; } return 0; }
true
53d0bfce0d6c0670a06271e9238b03b693c9e959
C++
Lee-Seungwook/Cetc
/vs/C++/projects/PersonEx0408/pointerex0415/pointerex0415.cpp
UTF-8
1,886
2.75
3
[]
no_license
// pointerex0415.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // #include "pch.h" #include <iostream> using namespace std; int main() { int a = 7, b = 8; int* pa = 0; //포인터 변수의 크기는 무조건 4바이트 pa = &a; int* pb = &b; char str[4] = "box"; char* pt = str; for (int i = 0; i <= 3; i++) cout << "pt[" << i << "]=" << pt[i] << endl; /* short int a = 7, b = 8; shortint* pa = 0; pa = &a; short int* pb = &b; //포인터 변수의 크기는 무조건 4바이트 */ //pb = &b cout << "pt=" << pt << endl; //컴파일러는 cout.operator << (char*) pt cout << "a의 시작주소=" << &a << endl; cout << "pa가 저장한주소=" << pa << endl; // 컴파일러는 cout.operator << (int*) pa cout << "a=" << a << endl; cout << "*pa=" << *pa << endl; cout << "b=" << b << endl; cout << "*pb=" << pb << endl; *pa = *pb; //a = 8 cout << "*pa = *pb 실행 후 a=" << a << endl; return 0; } // 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴 // 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴 // 시작을 위한 팁: // 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다. // 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다. // 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다. // 4. [오류 목록] 창을 사용하여 오류를 봅니다. // 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다. // 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
true
2ada223d66477d58706c95c57223e1cc8378b569
C++
lxdfigo/Leetcode
/Maximum Depth of Binary Tree.h
UTF-8
762
3.25
3
[]
no_license
#include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: void depth_iteration(TreeNode *node,int depth, int &maxdepth) { if (depth > maxdepth) maxdepth = depth; if (node->left != NULL) depth_iteration(node->left,depth+1,maxdepth); if (node->right != NULL) depth_iteration(node->right,depth+1,maxdepth); } int maxDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return 0; int maxd = 0; depth_iteration(root,1,maxd); return maxd; } };
true
9bc001bc757afb17185934e68c52e2c0607a36ff
C++
C-Smith-UALR/C.Smith.2376.Class.Practice
/CS.Class.Practice/Source.cpp
UTF-8
1,389
2.859375
3
[]
no_license
/* Clark Smith CPSC 2376 July 25, 2018 A program that creates a "ward" of patients and obtains and displays objective data. */ #include <iostream> #include "WardPatient.h" enum VITALS { HEART_RATE, RESP_RATE, SYS_BP, DIA_BP, SATS, VITAL_COUNT }; int main() { std::string fileName = "vitals.txt"; enum CHOICE {DISPLAY_VITALS, ADD_VITALS, CHANGE_VITALS, ABNORMAL_REPORT, QUIT}; //WardPatient patientOne; //WardPatient patientTwo("Bob", "White", 2644); //deleteME, early tests of class //patientOne.print(); //patientTwo.print(); WardPatient*** ward; ward = new WardPatient**[2]; // ward --> [--> ][--> ] for (int i = 0; i < 2; ++i) { ward[i] = new WardPatient*[8]; // ward--> [-->[*][*][*][*][*][*][*][*] ] for (int j = 0; j < 8; ++j) { // [-->[*][*][*][*][*][*][*][*] ] ward[i][j] = new WardPatient; } } float* tempColumn = nullptr; tempColumn = new float[16]; int** vsTable = nullptr; vsTable = new int*[16]; for (int i = 0; i < 16; ++i) { vsTable[i] = new int[5]; for (int j = 0; j < 5; ++j) { vsTable[i][j] = 0; } } ward[0][0]->setTemp(98.9); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 8; ++j) { ward[i][j]->print(); } } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 8; ++j) { delete ward[i][j]; } } delete[] ward; delete[] tempColumn; system("PAUSE"); return 0; }
true
fa93c3d35418daff9d100e2d0e5a464c9eb1ceb9
C++
RickSteman/EPO-4-A05
/Module-3/carmodel/rir_generator_x.cpp
UTF-8
17,866
2.5625
3
[]
no_license
/* Program : Room Impulse Response Generator Description : Function for simulating the impulse response of a specified room using the image method [1,2]. [1] J.B. Allen and D.A. Berkley, Image method for efficiently simulating small-room Acoustics, Journal Acoustic Society of America, 65(4), April 1979, p 943. [2] P.M. Peterson, Simulating the response of multiple microphones to a single acoustic source in a reverberant room, Journal Acoustic Society of America, 80(5), November 1986. Author : dr.ir. E.A.P. Habets (ehabets@dereverberation.org) modified : Jorge Martinez, Msc. (J.A.MartinezCastaneda@TuDelft.nl) Original Version : 1.8.20080713 Last Modification : 20090427 History : 1.0.20030606 Initial version 1.1.20040803 + Microphone directivity + Improved phase accuracy [2] 1.2.20040312 + Reflection order 1.3.20050930 + Reverberation Time 1.4.20051114 + Supports multi-channels 1.5.20051116 + High-pass filter [1] + Microphone directivity control 1.6.20060327 + Minor improvements 1.7.20060531 + Minor improvements 1.8.20080713 + Minor improvements (Compiled using Matlab R2008a) Modifications: 20080806 + Supports multiple sound sources. Delivers the impulse responses in column vectors. 20081212 + BUG FIX (Direct Path erasing problem). + Hability use either the original version of Allen & Berkley or the enhanced LPF-based version from Peterson. 20090427 + The LPF hanning window length can be specified. + The room dimension now can be specified with a 1 X 3 boolean vector which controls the projection of the space on any of the Cartesian coordinates. Copyright (C) 2003-2008 E.A.P. Habets, The Netherlands. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define _USE_MATH_DEFINES #include "matrix.h" #include "mex.h" #include "math.h" #define ROUND(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) double sinc(double x) { if (x == 0) return(1.); else return(sin(x)/x); } double sim_microphone(double x, double y, double angle, char* mtype) { double a, refl_theta, P, PG; refl_theta = atan2(y,x) - angle; // Polar Pattern P PG // ------------------------------------ // Omnidirectional 1 0 // Subcardioid 0.75 0.25 // Cardioid 0.5 0.5 // Hypercardioid 0.25 0.75 // Bidirectional 0 1 switch(mtype[0]) { case 'o': P = 1; PG = 0; break; case 's': P = 0.75; PG = 0.25; break; case 'c': P = 0.5; PG = 0.5; break; case 'h': P = 0.25; PG = 0.75; break; case 'b': P = 0; PG = 1; break; default: P = 1; PG = 0; break; }; a = P + PG * cos(refl_theta); return a; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs == 0) { mexPrintf("--------------------------------------------------------------------\n" "| Room Impulse Response Generator |\n" "| |\n" "| Function for simulating the impulse response of a specified |\n" "| room using the image method [1,2]. |\n" "| |\n" "| Author : dr.ir. Emanuel Habets (ehabets@dereverberation.org) |\n" "| modified : |\n" "| Jorge Martinez, Msc. (J.A.MartinezCastaneda@TuDelft.nl) |\n" "| Original Version : 1.8.20080713 |\n" "| Last modification : 20090427 |\n" "| Copyright (C) 2003-2008 E.A.P. Habets, The Netherlands. |\n" "| |\n" "| [1] J.B. Allen and D.A. Berkley, |\n" "| Image method for efficiently simulating small-room Acoustics,|\n" "| Journal Acoustic Society of America, |\n" "| 65(4), April 1979, p 943. |\n" "| |\n" "| [2] P.M. Peterson, |\n" "| Simulating the response of multiple microphones to a single |\n" "| acoustic source in a reverberant room, Journal Acoustic |\n" "| Society of America, 80(5), November 1986. |\n" "--------------------------------------------------------------------\n\n" "function [h, beta_hat] = rir_generator(c, fs, r, s, L, beta, nsample, mtype," " order, dim, orientation, hp_filter, lp_filter, window_l);\n\n" "Input parameters:\n" " c = sound velocity in m/s.\n" " fs = sampling frequency in Hz.\n" " r = M x 3 array specifying the (x,y,z) coordinates of the receiver(s) in m.\n" " s = N x 3 vector specifying the (x,y,z) coordinates of the source(s) in m.\n" " L = 1 x 3 vector specifying the room dimensions (x,y,z) in m.\n" " beta = 1 x 6 vector specifying the reflection coefficients" " [beta_x1 beta_x2 beta_y1 beta_y2\n" " beta_z1 beta_z2] or beta = Reverberation Time (T_60) in seconds.\n" " nsample = number of samples to calculate, default is T_60*fs.\n" " mtype = [omnidirectional, subcardioid, cardioid, hypercardioid, bidirectional]," " default is omnidirectional.\n" " order = reflection order, default is -1, i.e. maximum order).\n" " dim = room dimension. 1 x 3 boolean vector which specifies if the room space" " is defined over the corresponding Cartesian coordinate ([X Y Z]).\n" " orientation = specifies the angle (in rad) in which the microphone is pointed," " default is 0.\n" " hp_filter = use 'false' to disable high-pass filter, the high-pass filter is" " enabled by default.\n" " lp_filter = use 'false' to disable low-pass filtering of the pulses and use" " rounding of the arrival time in the impulse responses (Allen & Berkley) original" " algorithm, the low_pass filter is enabled by default.\n" " window_l = Time length (in seconds) of the Hanning window used in the LPF.\n\n" "Output parameters:\n" " h = nsample X M X N matrix containing the calculated room impulse response(s).\n" " beta_hat = In case a reverberation time is specified as an input parameter the " "corresponding reflection coefficient is returned.\n\n"); return; } // Check for proper number of arguments if (nrhs < 6) mexErrMsgTxt("Error: There are at least six input parameters required."); if (nrhs > 14) mexErrMsgTxt("Error: Too many input arguments."); if (nlhs > 2) mexErrMsgTxt("Error: Too many output arguments."); // Check for proper arguments if (!(mxGetN(prhs[0])==1) || !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) mexErrMsgTxt("Invalid input arguments!"); if (!(mxGetN(prhs[1])==1) || !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1])) mexErrMsgTxt("Invalid input arguments!"); if (!(mxGetN(prhs[2])==3) || !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2])) mexErrMsgTxt("Invalid input arguments!"); if (!(mxGetN(prhs[3])==3) || !mxIsDouble(prhs[3]) || mxIsComplex(prhs[3])) mexErrMsgTxt("Invalid input arguments!"); if (!(mxGetN(prhs[4])==3) || !mxIsDouble(prhs[4]) || mxIsComplex(prhs[4])) mexErrMsgTxt("Invalid input arguments!"); if (!(mxGetN(prhs[5])==6 || mxGetN(prhs[5])==1) || !mxIsDouble(prhs[5]) || mxIsComplex(prhs[5])) mexErrMsgTxt("Invalid input arguments!"); // Load parameters double c = mxGetScalar(prhs[0]); double fs = mxGetScalar(prhs[1]); const double* rr = mxGetPr(prhs[2]); int nr_of_mics = (int) mxGetM(prhs[2]); const double* ss = mxGetPr(prhs[3]); int nr_of_louds = (int) mxGetM(prhs[3]); const double* LL = mxGetPr(prhs[4]); const double* beta_ptr = mxGetPr(prhs[5]); double* beta = new double[6]; int nsamples; char* mtype; int order; int dim; double angle; int hp_filter; int lp_filter; double TR; double Wl; int* dim_s = new int[3]; plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); double* beta_hat = mxGetPr(plhs[1]); beta_hat[0] = 0; // Reflection coefficients or Reverberation Time? if (mxGetN(prhs[5])==1) { double V = LL[0]*LL[1]*LL[2]; double S = 2*(LL[0]*LL[2]+LL[1]*LL[2]+LL[0]*LL[1]); TR = beta_ptr[0]; double alfa = 24*V*log(10.0)/(c*S*TR); if (alfa > 1) mexErrMsgTxt("Error: The reflection coefficients cannot be calculated using the current " "room parameters, i.e. room size and reverberation time.\n Please " "specify the reflection coefficients or change the room parameters."); beta_hat[0] = sqrt(1-alfa); for (int i=0;i<6;i++) beta[i] = beta_hat[0]; } else { for (int i=0;i<6;i++) beta[i] = beta_ptr[i]; } // Time window length of the LPF (optional) if(nrhs > 13) { Wl = (double) mxGetScalar(prhs[13]); } else { Wl=0.008; //8ms default. } //Low-pass filter for interaural preservation or shifted pulses? (optional) if(nrhs > 12) { lp_filter = (int) mxGetScalar(prhs[12]); } else { lp_filter = 1; } // High-pass filter (optional) if (nrhs > 11) { hp_filter = (int) mxGetScalar(prhs[11]); } else { hp_filter = 1; } // Microphone orientation (optional) if (nrhs > 10) { angle = (double) mxGetScalar(prhs[10]); } else { angle = 0; } // Room Dimension (optional) if (nrhs > 9) { if (!(mxGetN(prhs[9])==3) || !mxIsDouble(prhs[9]) || mxIsComplex(prhs[9])) mexErrMsgTxt("Invalid input arguments!"); const double* dim = mxGetPr(prhs[9]); if (dim[0] == 0) { beta[0] = 0; beta[1] = 0; dim_s[0] = 0; } else { dim_s[0] = 1; } if (dim[1] == 0) { beta[2] = 0; beta[3] = 0; dim_s[1] = 0; } else { dim_s[1] = 1; } if (dim[2] == 0) { beta[4] = 0; beta[5] = 0; dim_s[2] = 0; } else { dim_s[2] = 1; } } else { dim_s[0] = 1; dim_s[1] = 1; dim_s[2] = 1; } // Reflection order (optional) if (nrhs > 8 && mxIsEmpty(prhs[8]) == false) { order = (int) mxGetScalar(prhs[8]); if (order < -1) mexErrMsgTxt("Invalid input arguments!"); } else { order = -1; } // Type of microphone (optional) if (nrhs > 7 && mxIsEmpty(prhs[7]) == false) { mtype = new char[mxGetN(prhs[7])+1]; mxGetString(prhs[7], mtype, mxGetN(prhs[7])+1); } else { mtype = new char[1]; mtype[0] = 'o'; } // Number of samples (optional) if (nrhs > 6 && mxIsEmpty(prhs[6]) == false) { nsamples = (int) mxGetScalar(prhs[6]); } else { if (mxGetN(prhs[5])>1) { double V = LL[0]*LL[1]*LL[2]; double S = 2*(LL[0]*LL[2]+LL[1]*LL[2]+LL[0]*LL[1]); double alpha = ((1-pow(beta[0],2))+(1-pow(beta[1],2)))*LL[0]*LL[2] + ((1-pow(beta[2],2))+(1-pow(beta[3],2)))*LL[1]*LL[2] + ((1-pow(beta[4],2))+(1-pow(beta[5],2)))*LL[0]*LL[1]; TR = 24*log(10.0)*V/(c*alpha); if (TR < 0.128) TR = 0.128; } nsamples = (int) (TR * fs); } // Create output vector int dims_out_array[3]={nsamples,nr_of_mics,nr_of_louds}; plhs[0] = mxCreateNumericArray(3,dims_out_array,mxDOUBLE_CLASS,mxREAL); double* imp = mxGetPr(plhs[0]); // Temporary variables and constants (high-pass filter) const double W = 2*M_PI*100/fs; const double R1 = exp(-W); const double R2 = R1; const double B1 = 2*R1*cos(W); const double B2 = -R1 * R1; const double A1 = -(1+R2); const double A2 = R2; double X0, Y0, Y1, Y2; // Temporary variables and constants (image-method) const double Fc = 1; const int Tw = (ROUND(Wl*fs) < 1) ? 1 : ROUND(Wl*fs); const double cTs = c/fs; double* hanning_window = new double[Tw+1]; double* LPI = new double[Tw+1]; double* r = new double[3]; double* s = new double[3]; double* L = new double[3]; double hu[6]; double refl[3]; double dist; double ll; double strength; int pos, fdist; int n1,n2,n3; int q, j, k; int mx, my, mz; int n; L[0] = LL[0]/cTs; L[1] = LL[1]/cTs; L[2] = LL[2]/cTs; // Hanning window for (n = 0 ; n < Tw+1 ; n++) { hanning_window[n] = 0.5 * (1 + cos(2*M_PI*(n+Tw/2)/Tw)); } int abs_counter=0; for (int loud_nr = 0; loud_nr < nr_of_louds; loud_nr++ ) { s[0] = ss[loud_nr + 0*nr_of_louds] / cTs; s[1] = ss[loud_nr + 1*nr_of_louds] / cTs; s[2] = ss[loud_nr + 2*nr_of_louds] / cTs; for (int mic_nr = 0; mic_nr < nr_of_mics ; mic_nr++) { // [x_1 x_2 ... x_N y_1 y_2 ... y_N z_1 z_2 ... z_N] r[0] = rr[mic_nr + 0*nr_of_mics] / cTs; r[1] = rr[mic_nr + 1*nr_of_mics] / cTs; r[2] = rr[mic_nr + 2*nr_of_mics] / cTs; n1 = ceil(nsamples/(2*L[0]))*dim_s[0]; n2 = ceil(nsamples/(2*L[1]))*dim_s[1]; n3 = ceil(nsamples/(2*L[2]))*dim_s[2]; // Generate room impulse response for (mx = -n1 ; mx <= n1 ; mx++) { hu[0] = 2*mx*L[0]; for (my = -n2 ; my <= n2 ; my++) { hu[1] = 2*my*L[1]; for (mz = -n3 ; mz <= n3 ; mz++) { hu[2] = 2*mz*L[2]; for (q = 0 ; q <= 1*dim_s[0] ; q++) { hu[3] = s[0] - r[0] + 2*q*r[0] + hu[0]; refl[0] = pow(beta[0], abs(mx)) * pow(beta[1], abs(mx+q)); for (j = 0 ; j <= 1*dim_s[1] ; j++) { hu[4] = s[1] - r[1] + 2*j*r[1] + hu[1]; refl[1] = pow(beta[2], abs(my)) * pow(beta[3], abs(my+j)); for (k = 0 ; k <= 1*dim_s[2] ; k++) { hu[5] = s[2] - r[2] + 2*k*r[2] + hu[2]; refl[2] = pow(beta[4],abs(mz)) * pow(beta[5], abs(mz+k)); dist = sqrt(pow(hu[3], 2) + pow(hu[4], 2) + pow(hu[5], 2)); fdist = (int) floor(dist); if (abs(2*mx+q)+abs(2*my+j)+abs(2*mz+k) <= order || order == -1) { if (fdist < nsamples) { //if ( mx == 0 && my == 0 && mz == 0 && q == 0 && j == 0 && k==0) //{ // mexPrintf("x: %f | y: %f | z: %f \n",refl[0],refl[1],refl[2]); //} strength = sim_microphone(hu[3], hu[4], angle, mtype) * refl[0]*refl[1]*refl[2]/(4*M_PI*dist*cTs); //if ( mx == 0 && my == 0 && mz == 0 && q == 0 && j == 0 && k==0) //{ // mexPrintf("str: %f | dist: %f | dist*cTs: %f \n",strength,dist,dist*cTs); //} if (lp_filter == 1) { for (n = 0 ; n < Tw+1 ; n++) LPI[n] = hanning_window[n] * Fc * sinc( M_PI*Fc*(n-(dist-fdist)-(Tw/2)) ); pos = fdist-(Tw/2); for (n = 0; n < Tw+1; n++) { if (pos+n >=0 && pos+n < nsamples) { //if ( mx == 0 && my == 0 && mz == 0) imp[ abs_counter + (pos+n)] += strength * LPI[n]; } } } else { //if ( mx == 0 && my == 0 && mz == 0) imp[ abs_counter + fdist] += strength; } } } } } } } } } // 'Original' high-pass filter as proposed by Allen and Berkley. if (hp_filter == 1) { Y0 = 0; Y1 = 0; Y2 = 0; for (int idx = 0 ; idx < nsamples ; idx++) { X0 = imp[ abs_counter + idx]; Y2 = Y1; Y1 = Y0; Y0 = B1*Y1 + B2*Y2 + X0; imp[ abs_counter + idx] = Y0 + A1*Y1 + A2*Y2; } } abs_counter+=nsamples; } } }
true
6029915bf36164ce0a8ba5df0bfeeaf7e89724b6
C++
cxvisa/Wave
/C++/source/Framework/Types/WorldWideName.h
UTF-8
2,223
2.65625
3
[ "Apache-2.0" ]
permissive
/*************************************************************************** * Copyright (C) 2005-2010 Vidyasagara Guntaka * * All rights reserved. * * Author : Vidyasagara Reddy Guntaka * ***************************************************************************/ #ifndef WORLDWIDENAME_H #define WORLDWIDENAME_H #include <string> #include "Framework/Types/Types.h" namespace WaveNs { class WorldWideName { private : static bool isAValidHexaDecimalCharacter (const char &ch); protected : public : WorldWideName (); WorldWideName (const UI8 worldWideName[8]); WorldWideName (const string &worldWideNameInStringFormat); WorldWideName (const WorldWideName &worldWideName); ~WorldWideName (); string toString () const; void fromString (const string &worldWideNameInStringFormat); static bool isValidWorldWideNameString (const string &worldWideNameInStringFormat); UI8 &operator [] (const UI32 &i) const; bool operator == (const WorldWideName &worldWideName) const; bool operator != (const WorldWideName &worldWideName) const; WorldWideName &operator = (const WorldWideName &worldWideName); void setSeparator (const char &separator); char getSeparator () const; ResourceId loadFromPlainString (const string &worldWideNameInPlainStringFormat); // Now the data members private : UI8 *m_pName; static const UI32 m_nameLength = 8; char m_separator; protected : public : }; } #endif // WORLDWIDENAME_H
true
f8d82d01898c5539591434fe64f074e64f856110
C++
Roboticsotago/robotics_repo
/Projects/2016/MIDIBots/arduino/midi_keyboard/midi_keyboard.ino
UTF-8
3,691
3.125
3
[]
no_license
// A simple MIDI keyboard for Arduino // CME 2016-03 // This polls for input switch states and outputs MIDI note on/off messages when they change, i.e. when a switch is pressed/released. // We reserve a block of contiguous input pins to keep the code simple and scalable. // To monitor MIDI messages: // aseqdump -p 20:0 // To play via Yoshimi: // yoshimi --alsa-midi=20:0 --alsa-audio=pulse --load-instrument=/usr/share/yoshimi/banks/Will_Godfrey_Collection/0033-Medium\ Saw.xiz // Here we define a couple of arrays for the current and previous state of all the key switches: // Notably, we need to keep the TX pin free for MIDI transmission. Also the LED_BUILTIN pin so we can indicate activity. // NOTE: on the Arduino Mega, the big double-row of pins starts has a pair of 5V pins, then digital pins 22 and 23. The last digital pin is 53, and then there are two grounds at the end. const int NUM_KEYS = 32; const int FIRST_KEY_PIN = 22; // Here are the arrays. // NOTE: awkward mismatch of pin numbers and array indexes, since we're not necessarily starting at 0! It's a bit wasteful of memory, but let's just make the array bigger, and ignore any we aren't using, and use the same numbering for the array elements as for the pin numbers for the input switches. int currSwitchState[NUM_KEYS + FIRST_KEY_PIN]; int prevSwitchState[NUM_KEYS + FIRST_KEY_PIN]; void setup() { // Set up serial port for MIDI baud rate (31.25 kbit/s): Serial.begin(31250); // We might want to use the LED to indicate activity (though don't use delay() unnecessarily (e.g. blink())). pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); // Set up input pins and initialise switch state arrays: for (int pin = FIRST_KEY_PIN; pin <= FIRST_KEY_PIN + NUM_KEYS - 1; pin++) { pinMode(pin, INPUT_PULLUP); currSwitchState[pin] = 0; prevSwitchState[pin] = 0; } } void loop() { readSwitches(); } void ledOn() {digitalWrite(LED_BUILTIN, HIGH);} void ledOff() {digitalWrite(LED_BUILTIN, LOW);} // This function is used to conveniently generate note on/off MIDI messages. // The first message byte is called the status byte, and indicates the type of message and the channel number being addressed. // Status bytes have a 1 for the MSB, and data bytes always have a 0 there. // 0x9 (0b1001) is the Note On status nybble. // NOTE: the channel number parameter should be the logical (user-centric) channel numbers (1..16), not the internal values used to represent them. void playNote(int channel, int pitch, int velocity) { if (channel > 16 || channel < 1) channel = 1; // Clip to valid range Serial.write(0x90 | (channel-1)); // write status byte, converting channel number to wire format Serial.write(pitch); // data byte 1 Serial.write(velocity); // data byte 2 } // Trigger a MIDI note based input switch activity. We'll use polling for this (there wouldn't be enough interrupts available for an interrupt-based approach). As a result, we need to remember the state of the switch(es) from the last poll so we can recognise on/off transitions. void readSwitches() { // Check each of the pins: for (int pin = FIRST_KEY_PIN; pin <= FIRST_KEY_PIN + NUM_KEYS - 1; pin++) { currSwitchState[pin] = !digitalRead(pin); // Active-low; negate here. // If state changed, output note on/off: if (currSwitchState[pin] != prevSwitchState[pin]) { ledOn(); playNote(1, 36 + pin, currSwitchState[pin] * 100); // Note on/off depending on whether the key is pressed. ledOff(); } prevSwitchState[pin] = currSwitchState[pin]; // Store the state for next time. } delay(1); // Hold off just a little do reduce spurious note on/off due to switch contact bouncing. }
true
93a8c2062b0d47440a61103ca94b98279abdcdce
C++
SergeyStrukov/CCore-3-xx
/Applied/CCore/test/test3019.IntegerSlowMul.cpp
UTF-8
3,085
2.859375
3
[ "FTL", "BSL-1.0" ]
permissive
/* test3019.IntegerSlowMul.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: Applied // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/test/test.h> #include <CCore/inc/math/IntegerSlowAlgo.h> #include <CCore/inc/Random.h> namespace App { namespace Private_3019 { using Unit = uint8 ; using Algo1 = Math::IntegerSlowMulAlgo<Unit> ; using Algo2 = Math::IntegerSlowMulAlgo<Unit,void> ; /* test1() */ void test1(Random &gen,ulen count) { for(; count ;count--) { Unit a=gen.next_uint<Unit>(); Unit b=gen.next_uint<Unit>(); Algo1::DoubleUMul p1(a,b); Algo2::DoubleUMul p2(a,b); if( p1.lo!=p2.lo || p1.hi!=p2.hi ) { Printf(Exception,"error 1"); } } } /* test2() */ void test2(Random &gen,ulen count) { for(; count ;count--) { Unit a=gen.next_uint<Unit>(); Unit b=gen.next_uint<Unit>(); Unit d=gen.next_uint<Unit>(); if( b>=d ) continue; Unit c1=Algo1::DoubleUDiv(b,a,d); Unit c2=Algo2::DoubleUDiv(b,a,d); if( c1!=c2 ) { Printf(Exception,"error 2"); } Algo1::DoubleUMul p(d,c1); if( p.lo<=a ) { if( p.hi!=b ) { Printf(Exception,"error 3"); } if( a-p.lo>=d ) { Printf(Exception,"error 4"); } } else { if( p.hi+1!=b || b==0 ) { Printf(Exception,"error 5"); } if( Unit(a-p.lo)>=d ) { Printf(Exception,"error 6"); } } } } /* test3() */ void test3(Random &gen,ulen count) { for(; count ;count--) { Unit a=gen.next_uint<Unit>(); Unit b=-a; if( b>a ) Swap(a,b); Unit c=Algo2::Inv(a); if( a==b ) { if( c ) { Printf(Exception,"error 7"); } } else { Algo1::DoubleUMul p(a,c); if( b<p.hi ) { Printf(Exception,"error 8"); } if( b==p.hi ) { if( p.lo ) { Printf(Exception,"error 9"); } } else { if( b!=p.hi+1 ) { Printf(Exception,"error 10"); } if( Unit(-p.lo)>=a ) { Printf(Exception,"error 11"); } } } } } } // namespace Private_3019 using namespace Private_3019; /* Testit<3019> */ template<> const char *const Testit<3019>::Name="Test3019 IntegerSlowMul"; template<> bool Testit<3019>::Main() { Random gen; test1(gen,1'000'000); test2(gen,1'000'000); test3(gen,1'000'000); return true; } } // namespace App
true
552cb747ef35ff046c8270789ace7c167815b43e
C++
alucchi/al-raytracer
/ase.h
UTF-8
8,359
2.640625
3
[]
no_license
/** * File : ase.cpp * Description : Import of 3ds models. * * Author(s) : This file has been downloaded from www.GameTutorials.com * Date of creation : 21/02/2008 * Modification(s) : */ #ifndef _ASE_H #define _ASE_H #include "Maths/Vector2.h" #include "Maths/Vector3.h" #include <GL/gl.h> // Header File For The OpenGL32 Library #include <GL/glu.h> // Header File For The GLu32 Library #include <string> #include <vector> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <SDL/SDL.h> using namespace std; typedef unsigned char BYTE; // Below are a all the important tag defines for reading in a .Ase file. // I added the normal ones just in case you want to you read them in instead // of calculate them yourself. #define OBJECT "*GEOMOBJECT" // An object tag for new objects #define NUM_VERTEX "*MESH_NUMVERTEX" // The number of vertices tag #define NUM_FACES "*MESH_NUMFACES" // The number of faces tag #define NUM_TVERTEX "*MESH_NUMTVERTEX" // The number of texture coordinates #define VERTEX "*MESH_VERTEX" // The list of vertices tag #define FACE "*MESH_FACE" // The list of faces tag #define NORMALS "*MESH_NORMALS" // The list of normals tag (If you want) #define FACE_NORMAL "*MESH_FACENORMAL" // The face normal for the current index #define NVERTEX "*MESH_VERTEXNORMAL" // The list of vertex normals #define TVERTEX "*MESH_TVERT" // The texture coordinate index tag #define TFACE "*MESH_TFACE" // The vertex index tag #define TEXTURE "*BITMAP" // The file name for the object's texture map #define UTILE "*UVW_U_TILING" // The U tiling ratio tag #define VTILE "*UVW_V_TILING" // The V tiling ratio tag #define UOFFSET "*UVW_U_OFFSET" // The U tile offset tag #define VOFFSET "*UVW_V_OFFSET" // The V tile offset tag #define MATERIAL_ID "*MATERIAL_REF" // The material ID tag #define MATERIAL_COUNT "*MATERIAL_COUNT" // The material count tag #define MATERIAL "*MATERIAL" // The material tag #define MATERIAL_NAME "*MATERIAL_NAME" // The material name tag #define MATERIAL_COLOR "*MATERIAL_DIFFUSE" // The material color tag // This file includes all of the model structures that are needed to load // in a .ASE file. If you intend to do animation you will need to add on // to this. These structures only support the information that is needed // to load the objects in the scene and their associative materials. #define MAX_TEXTURES 100 // The maximum amount of textures to load void CreateTexture(unsigned int textureArray[],char *strFileName,int textureID); // This is our face structure. This is is used for indexing into the vertex // and texture coordinate arrays. From this information we know which vertices // from our vertex array go to which face, along with the correct texture coordinates. struct tFace { int vertIndex[3]; // indicies for the verts that make up this triangle int coordIndex[3]; // indicies for the tex coords to texture this face }; // This holds the information for a material. It may be a texture map of a color. // Some of these are not used, but I left them because you will want to eventually // read in the UV tile ratio and the UV tile offset for some models. struct tMaterialInfo { char strName[255]; // The texture name char strFile[255]; // The texture file name (If this is set it's a texture map) BYTE color[3]; // The color of the object (R, G, B) from 0 to 255 float fColor[3]; // The color of the object (R, G, B) from 0 to 1 int texureId; // the texture ID float uTile; // u tiling of texture (Currently not used) float vTile; // v tiling of texture (Currently not used) float uOffset; // u offset of texture (Currently not used) float vOffset; // v offset of texture (Currently not used) } ; // This holds all the information for our model/scene. // You should eventually turn into a robust class that // has loading/drawing/querying functions like: // LoadModel(...); DrawObject(...); DrawModel(...); DestroyModel(...); struct t3DObject { int numOfVerts; // The number of verts in the model int numOfFaces; // The number of faces in the model int numTexVertex; // The number of texture coordinates int materialID; // The texture ID to use, which is the index into our texture array bool bHasTexture; // This is TRUE if there is a texture map for this object char strName[255]; // The name of the object Vector3 *pVerts; // The object's vertices Vector3 *pNormals; // The object's normals Vector2 *pTexVerts; // The texture's UV coordinates tFace *pFaces; // The faces information of the object }; // This holds our model information. This should also turn into a robust class. // We use STL's (Standard Template Library) vector class to ease our link list burdens. :) class t3DModel { public: int numOfObjects; // The number of objects in the model int numOfMaterials; // The number of materials for the model vector<tMaterialInfo> pMaterials; // The list of material information (Textures and colors) vector<t3DObject> pObject; // The object list for our model t3DModel(); ~t3DModel(); }; // This class holds all the data and function for loading in a .Ase file. class CLoadASE { public: // This is the only function the client needs to call to load the .ase file bool ImportASE(t3DModel *pModel, char *strFileName); // This is the main loop that parses the .ase file void ReadAseFile(t3DModel *pModel); // This returns the number of objects in the .ase file int GetObjectCount(); // This returns the number of materials in the .ase file int GetMaterialCount(); // This fills in the texture information for a desired texture void GetTextureInfo (tMaterialInfo *pTexture, int desiredMaterial); // This moves our file pointer to the desired object void MoveToObject (int desiredObject); // This reads in a float from the file float ReadFloat(); // This reads a desired object's information (face, vertex and texture coord counts) void ReadObjectInfo(t3DObject *pObject, int desiredObject); // This gets the name of the texture void GetTextureName (tMaterialInfo *pTexture); // This gets the name of the material void GetMaterialName(tMaterialInfo *pTexture); // This loads all the data for the desired object void ReadObjectData(t3DModel *pModel, t3DObject *pObject, int desiredObject); // This is the main load loop inside of ReadObjectData() that calls smaller load functions void GetData(t3DModel *pModel, t3DObject *pObject, char *strDesiredData, int desiredObject); // This reads in a vertice from the file void ReadVertex(t3DObject *pObject); // This reads in a texture coordinate from the file void ReadTextureVertex(t3DObject *pObject, tMaterialInfo texture); // This reads in the vertex indices for a face void ReadFace(t3DObject *pObject); // This reads in texture coordinate indices for a face void ReadTextureFace(t3DObject *pObject); // This computes the vertex normals for our objects void ComputeNormals(t3DModel *pModel); private: // This is our file pointer to load the .ase file FILE *m_FilePointer; }; #endif ///////////////////////////////////////////////////////////////////////////////// // // * QUICK NOTES * // // This file holds the class and defines to load a .Ase file. The .Ase file is // created by 3D Studio Max, but isn't as nice as the .3DS file format. // // // // Ben Humphrey (DigiBen) // Game Programmer // DigiBen@GameTutorials.com // Co-Web Host of www.GameTutorials.com // //
true
7fd29049adc5e9821840c143dfc6eadd65ffe818
C++
nsudhanva/competetive
/HackerRank/Algorithms/Implementation/array.cpp
UTF-8
282
3.09375
3
[ "Unlicense" ]
permissive
#include<iostream> using namespace std; int main() { int a[] = {1, 7, 2, 4}; for(int i = 0; i < 4; i ++){ for(int j = i + 1; j < 4; j++){ cout << a[i] << " + " << a[j] << " = " << a[i] + a[j] << endl; } //cout << a[i] << endl; } }
true
46ae6eac4110f9b1468ebb3e5c91629423de722e
C++
Omnibusangie/notes.1
/A3/tryout 3.10.cpp
UTF-8
330
2.96875
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; int main() { cout << "Please enter an integer: "; int number; cin >> number; srand(number); int randnum_1 = (rand() % 200 + 1), randnum_2 = (rand() % 200 + 1); cout << "randnum_1: " << randnum_1 << ", randnum_2: " << randnum_2 << "." << endl; return 0; }
true
8bd5c543080ab2049d3f5cd44253a1bbc65bd907
C++
infotraining/cpp-17-2020-12-14
/string-view/tests.cpp
UTF-8
2,351
3.71875
4
[]
no_license
#include <algorithm> #include <numeric> #include <iostream> #include <string> #include <vector> #include <array> #include <string_view> #include "catch.hpp" using namespace std; TEST_CASE("string_view") { SECTION("creation") { const char* cstr = "text"; std::string_view sv1 = cstr; REQUIRE(sv1.size() == 4); std::string str = "text"; std::string_view sv2 = str; REQUIRE(sv2.size() == 4); const char* text = "abc def ghi"; std::string_view token(text, 3); REQUIRE(token == "abc"s); } } template <typename Container> void print_all(const Container& container, std::string_view prefix) { cout << prefix << ": [ "; for (const auto& item : container) cout << item << " "; cout << "]\n"; } TEST_CASE("using string_view") { print_all(vector{1, 2, 3}, "vec"s); } string_view get_prefix(std::string&& text, size_t length) = delete; string_view get_prefix(string_view text, size_t length) { return {text.data(), length}; } TEST_CASE("beware") { SECTION("safe") { const char* text = "abcdef"; string_view sv1(text, 3); REQUIRE(sv1 == "abc"sv); } SECTION("string") { string_view sv_evil = "text"s; std::cout << sv_evil << "\n"; SECTION("only valid way") { const std::string input_text = "abc def"; std::string_view prefix = get_prefix(input_text, 3); REQUIRE(prefix == "abc"sv); } //string_view sv_dangling = get_prefix("abc_def"s, 3); //std::cout << sv_dangling << "\n"; } } TEST_CASE("string_view differences") { std::string_view sv; REQUIRE(sv.data() == nullptr); std::string str; REQUIRE(str.data() != nullptr); char tab[] = { 'a', 'b', 'c'}; std::string_view sv_without_null(tab, 3); REQUIRE(sv_without_null == "abc"sv); } TEST_CASE("string_view to string conversion") { std::string_view sv = "text"; std::string s(sv); // explicit conversion } // void print(const std::string& str) // { // std::cout << str << "\n"; // } void print(std::string_view str) { std::cout << str << "\n"; } TEST_CASE("string_view as constexpr") { constexpr array ids = { "ericsson"sv, "nokia"sv, "china"sv }; print(ids[0]); print("text"); }
true
65514660f8a1fb32cb99869fa72d1fc2d787316f
C++
E-gy/parc24
/src/test/grammar/quotexpando.cpp
UTF-8
2,162
3.0625
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
#include <catch2ext.hpp> using Catch::Matchers::Equals; extern "C" { #include <grammar/quotexpando.h> #include <util/null.h> } SCENARIO("word capture", "[word][lexer]"){ GIVEN("empty string") THEN("no capture") REQUIRE(capture_word("") == nullstr); GIVEN("plain simple word followed by weird things"){ auto word = GENERATE("birb", "birb ", "birb ", "birb;", "birb(", "birb)", "birb\n", "birb\r\n", "birb<", "birb>"); CAPTURE(word); THEN("capture until break"){ auto capt = capture_word(word); REQUIRE(capt != nullstr); REQUIRE(capt-word == 4); } } GIVEN("plain word with unspecial chars"){ auto word = GENERATE("125 <$>", "potato <$>", "duk-m <$>", "question_mark,and.most-punctuation?is*not^meta@actually <$>"); CAPTURE(word); THEN("capture them all"){ auto capt = capture_word(word); REQUIRE(capt != nullstr); REQUIRE_THAT(capt, Equals(" <$>")); } } GIVEN("escaped specials"){ auto word = GENERATE("birb\\ <$>", "birb\\ bro <$>", "birb\\ <$>", "birb\\$ <$>", "birb\\; <$>", "birb\\$\\$ <$>", "birb\\( <$>", "birb\\) <$>", "birb\\\n <$>", "birb\\\r\\\n <$>", "birb\\< <$>", "birb\\> <$>"); CAPTURE(word); THEN("capture them all"){ auto capt = capture_word(word); REQUIRE(capt != nullstr); REQUIRE_THAT(capt, Equals(" <$>")); } } GIVEN("single quoted string"){ auto word = GENERATE("'' <$>", "'potato' <$>", "'pum tam dum ""woo' <$>"); CAPTURE(word); THEN("capture them all"){ auto capt = capture_word(word); REQUIRE(capt != nullstr); REQUIRE_THAT(capt, Equals(" <$>")); } } GIVEN("double quoted string"){ auto word = GENERATE("\"\" <$>", "\"potato\" <$>", "\"pum tam dum \\\"\\\"woo\" <$>"); CAPTURE(word); THEN("capture them all"){ auto capt = capture_word(word); REQUIRE(capt != nullstr); REQUIRE_THAT(capt, Equals(" <$>")); } } GIVEN("escape hell"){ REQUIRE_THAT(capture_word("\\a <$>"), Equals(" <$>")); REQUIRE_THAT(capture_word("\\& <$>"), Equals(" <$>")); REQUIRE_THAT(capture_word("\\\\& <$>"), Equals("& <$>")); REQUIRE_THAT(capture_word("\\\\\\& <$>"), Equals(" <$>")); REQUIRE_THAT(capture_word("\\\\\\\\& <$>"), Equals("& <$>")); } }
true
9fd389ce341ac656960181bbe9be429aee3c16f4
C++
duckhee/opencv_study
/chapter4/ex4-3/ex4_3.cpp
UTF-8
791
2.546875
3
[]
no_license
#include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { Mat srcImage = imread("../lena.jpg", IMREAD_GRAYSCALE); if(srcImage.empty()) { printf("not image.\r\n"); return -1; } Mat dstImage = Mat::zeros(srcImage.rows, srcImage.cols, srcImage.type()); int N = 2; int nWidth = srcImage.cols; int nHeight = srcImage.rows; int x, y; Rect rtROI; Mat roi; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { x = j * nWidth; y = i * nHeight; rtROI = Rect(x, y, nWidth, nHeight); roi = srcImage(rtROI); dstImage(rtROI) = mean(roi); } } imshow("dstImage", dstImage); waitKey(); return 0; }
true
0cb3ccc3971f302a9cd5d91ed6649f9aa5a6a856
C++
BelongAl/RSA-encryption-algorithm
/bigint.h
GB18030
804
2.9375
3
[]
no_license
#pragma once #include<string> #include<utility>//pairͷļ #include<iostream> class BigInt { std::string m_number; public: BigInt(const std::string&num) : m_number(num) {} BigInt(const int num) {} BigInt() = default; BigInt operator+(BigInt &bi); BigInt operator-(BigInt &bi); BigInt operator*(BigInt &bi); BigInt operator/(BigInt &bi); BigInt operator%(BigInt &bi); friend std::ostream& operator <<(std::ostream &os, const BigInt &bi); std::string add(std::string num1, std::string num2);//+ std::string sub(std::string num1, std::string num2);//- std::string mul(std::string num1, std::string num2);//* std::pair<std::string, std::string> dev(std::string num1, std::string num2);/// bool less(std::string num1, std::string num2); // // };
true
628e3b4786b05a44e3a969bdc43998ec49d96e16
C++
Brandon-Ashworth/Physics-Simulation
/A star working demo/aStar/aStar/aStar/NavMesh.h
UTF-8
1,586
2.671875
3
[]
no_license
#pragma once #include "as_node.h" #include <iostream> #include <vector> #include <stack> class NavMesh { public: NavMesh(void); ~NavMesh(void); //precalls, must be called before init call void setNavSize(int size); //the world position stuff will be included later //setFisrtPos //setNodeGap //precall gets int getNavSize(); //get first pos //get node gap //initialise the mesh create the mesh variable ect bool initMesh(); //blocking and unblocking nodes, might be an idea to have an ID as well to speed up finding //no out of bounds checking done void blockNode(int x, int y); void unblockNode(int x, int y); as_node *getNode(int x,int y); std::stack<Vector2Int>getPath(as_node *start, as_node *goal); private: //calcHueristics, calcualte the huristics will be called when the //function to calc the path is called void calcHue(as_node *goal); //variables as_node **m_navMesh; int m_MeshSize;//the size of the nav mesh bool createMap(); void cleanMap(); //some calculation things to make it easier to finc values int difference(int num1,int num2);// find the absolute difference between 2 numbers //find the move cost of the current node to the node we might move to int findMoveCost(as_node *currentNode, as_node *movingToNode); //obtain the adjacent nodes void getAdjacentNodes(as_node *currentNode, std::vector<as_node*> *adjacent); void removeBlockedNodes(std::vector<as_node*> *adjacent); //others void resetNodeCreation(); bool checkValidNode(int x, int y); bool onList(as_node *node,std::vector<as_node*> *nodeList); };
true
1942361401266372d6df966cd22d3ac2abad5da2
C++
AlanGarduno/Estructuras-de-datos
/Estructuras y varios/b-busquedasec.cpp
UTF-8
6,982
2.875
3
[]
no_license
#include <stdlib.h> #include<stdio.h> using namespace std; struct lista{ int dato; int busqueda=0; struct lista *apunt; }; typedef struct lista *Tlista; void lista_opciones(); void insertarFinal(Tlista &lista, int datoa); int insertarAntesDespues(int a); void insertarInicio(Tlista &lista, int datoa); void insertarElemento(Tlista &lista, int datoa, int pos,int a); void buscarElemento(Tlista lista, int datoa); //Busqueda secuencial void reportarLista(Tlista lista); void eliminarElemento(Tlista &lista, int datoa); void eliminaRepetidos(Tlista &lista, int datoa); int av; Tlista lista = NULL; void insertarda(Tlista &lista, int datoa, int pos) { Tlista q, t; int i; q = new(struct lista); q->dato = datoa; if(pos==1) { q->apunt = lista; lista = q; } else { int x = insertarAntesDespues(1); t = lista; for(i=1; t!=NULL; i++) { if(i==pos+x) { q->apunt = t->apunt; t->apunt = q; return; } t = t->apunt; } } } void eliminarElementoda(Tlista &lista, int datoa, int pos) { Tlista p, ant; p = lista; if(lista!=NULL) { while(p!=NULL) { if(p->dato==datoa) { if(p==lista) lista = lista->apunt; else ant->apunt = p->apunt; delete(p); return; } ant = p; p = p->apunt; } } insertarda(lista, datoa, pos-1); } int main() { int op; int _dato; int pos; do { lista_opciones(); scanf("%d",& op); switch(op) { case 1: printf( "\n NUMERO A INSERTAR: "); scanf("%d",& _dato); insertarInicio(lista, _dato); break; case 2: printf( "\n NUMERO A INSERTAR: "); scanf("%d",& _dato); insertarFinal(lista, _dato ); break; case 3: printf( "\n NUMERO A INSERTAR: "); scanf("%d",& _dato); printf( " Posicion : "); scanf("%d",& pos); insertarElemento(lista, _dato, pos,0); break; case 4: printf("\n\n MOSTRANDO LISTA\n\n"); reportarLista(lista); break; case 5: printf("\n DATO A BUSCAR: "); scanf("%d",& _dato); buscarElemento(lista, _dato); break; case 6: printf("\n DATO A ELIMINAR: "); scanf("%d",& _dato); eliminarElemento(lista, _dato); break; case 7: printf("\n DATOS REPETIDOS A ELIMINAR "); scanf("%d",& _dato); eliminaRepetidos(lista, _dato); break; default: printf("\noOPCION NO VALIDA\n"); } printf("\n\n"); system("pause"); system("cls"); }while(op!=8); return 0; } void insertarInicio(Tlista &lista, int datoa) { Tlista q; q = new(struct lista); q->dato = datoa; q->apunt = lista; lista = q; } void insertarFinal(Tlista &lista, int datoa) { Tlista t, q = new(struct lista); q->dato = datoa; q->apunt = NULL; if(lista==NULL) { lista = q; } else { t = lista; while(t->apunt!=NULL) { t = t->apunt; } t->apunt = q; } } int insertarAntesDespues(int a) { int _op, da; if(a=1) { da = -1; } else { printf("\n"); printf("\t 1. ANTES DE LA POSICION "); printf("\t 2. DESPUES DE LA POSICION "); "\n\t OPCION : "; scanf("%d",&_op); if(_op==1) da = -1; else da = 0; } return da; } void insertarElemento(Tlista &lista, int datoa, int pos, int a) { Tlista q, t; int i; q = new(struct lista); q->dato = datoa; if(pos==1) { q->apunt = lista; lista = q; } else { int x = insertarAntesDespues(a); t = lista; for(i=1; t!=NULL; i++) { if(i==pos+x) { q->apunt = t->apunt; t->apunt = q; return; } t = t->apunt; } } printf(" \nPOSICION ENCONTRADA\n"); } void buscarElemento(Tlista lista, int datoa) //Busqueda secuencial { Tlista q = lista; Tlista aux; Tlista abc=lista; int i = 1, repeticion = 0,f=0; while(q!=NULL) { if(q->dato==datoa) { printf(" ENCONTRADA EN POSICION %d \n", i ); repeticion=1; q->busqueda=q->busqueda+1; if(q->busqueda>3) { f=q->busqueda; eliminarElemento(lista, datoa); insertarElemento(lista,datoa,i-1,1); } } q = q->apunt; i++; } reportarLista(lista); if(repeticion==0) printf("\n\n NUMERO NO ENCONTRADO\n"); } void reportarLista(Tlista lista) { int i = 0; while(lista != NULL) { printf("%d) %d\n",i+1,lista->dato); lista = lista->apunt; i++; } } void eliminarElemento(Tlista &lista, int datoa) { Tlista p, ant; p = lista; if(lista!=NULL) { while(p!=NULL) { if(p->dato==datoa) { if(p==lista) lista = lista->apunt; else ant->apunt = p->apunt; delete(p); return; } ant = p; p = p->apunt; } } else printf(" LISTA VACIA\n"); } void eliminaRepetidos(Tlista &lista, int datoa) { Tlista q, ant; q = lista; ant = lista; while(q!=NULL) { if(q->dato==datoa) { if(q==lista) { lista = lista->apunt; delete(q); q = lista; } else { ant->apunt = q->apunt; delete(q); q = ant->apunt; } } else { ant = q; q = q->apunt; } } printf("\n\n DATOS ELIMINADOS\n"); } void lista_opciones() { printf(" 1. INSERTAR AL INICIO\n"); printf(" 2. INSERTAR AL FINAL\n"); printf(" 3. INSERTAR EN UNA POSICION\n"); printf(" 4. MOSTRAR LISTA \n"); printf(" 5. BUSCAR ELEMENTO\n"); printf(" 6. ELIMINAR ELEMENTO\n"); printf(" 7. ELIMINAR ELEMENTOS REPETIDOS CON DATO ESPECIFICO \n"); printf(" 8. SALIR \n"); printf("\n ESCOJA UNA OPCION: "); }
true