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
34926938e44a1bdaf078fe55a2636d0380283455
C++
ishaofeng/LeetCode
/ConvertSortedListToBinarySearchTree/ConvertSortedListToBinarySearchTree.cpp
UTF-8
1,468
3.46875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode *sortedListToBST(ListNode *head) { if (head == NULL) { return NULL; } TreeNode *root = NULL; if (head->next == NULL) { root = new TreeNode(head->val); return root; } ListNode *slow = head, *fast = head, *prev = NULL; while (fast->next != NULL) { fast = fast->next; if (fast->next != NULL) { fast = fast->next; prev = slow; slow = slow->next; } } root = new TreeNode(slow->val); if (prev != NULL) { prev->next = NULL; root->left = sortedListToBST(head); } root->right = sortedListToBST(slow->next); return root; } }; int main() { Solution s; vector<ListNode*> lists; ListNode*a = new ListNode(1); a->next = new ListNode(2); a->next->next = new ListNode(3); a->next->next->next = new ListNode(4); a->next->next->next->next = new ListNode(5); s.sortedListToBST(a); return 0; }
true
4952a9d3595147048f4490a9c6d57c83c69fd1a3
C++
cbhramar/archives
/Code/C++ programs/Stanford/recursiveExp.cpp
UTF-8
485
2.859375
3
[]
no_license
#include<simplecpp> long recursiveExp(int n, int k){ // long r = 1; if (k == 0){ return 1; } else { if (k%2 == 1){ return n*recursiveExp(n, k-1); } else return recursiveExp(n, k/2)*recursiveExp(n, k/2); } } main_program{ int n; int k; cout << "Enter n, k in that order :" << endl; cin >> n >> k; cout << "n ^ k is :" << endl; cout << recursiveExp(n, k) << endl; }
true
1ecdcfa931d548c37633ad8ab30558eb99867c04
C++
timlenertz/tff-rqueue
/_prelim/utility.h
UTF-8
1,141
2.953125
3
[]
no_license
#ifndef UTILITY_H_ #define UTILITY_H_ #include <string> void require(bool condition, const char* msg = "", ...); const std::string& thread_name(const std::string& new_name = ""); void log(const char* fmt, ...); void sleep_ms(unsigned ms); using time_unit = std::ptrdiff_t; struct time_span { time_unit begin; time_unit end; time_span() { } time_span(time_unit b, time_unit e) : begin(b), end(e) { } bool contains(time_unit t) const { return (t >= begin) && (t < end); } bool contains(time_span span) const { return (span.begin >= begin) && (span.end <= end); } }; struct read_view { time_unit begin_time; std::ptrdiff_t begin_index; std::ptrdiff_t length; }; template<typename Frame> struct read_handle_base { bool valid; read_view view; virtual ~read_handle_base() { } read_handle_base() : valid(false) { } read_handle_base(bool val, const read_view& vw) : valid(val), view(vw) { } read_handle_base(const read_handle_base&) = default; virtual const Frame& frame(std::ptrdiff_t i) = 0; }; template<typename Frame> struct write_view { bool should_stop; time_unit time; Frame* frame; }; #endif
true
7a637105e36be883c5b72e12762a00ac296bb342
C++
EmmMiranda/Data-Structures-and-Algorithms
/Recursirve_isSorted/main.cpp
UTF-8
456
3.546875
4
[]
no_license
#include <iostream> using namespace std; int isArraySorted(int A[], int n); int main() { int sz = 5; int a[] = {1, 2, 3, 4, 5}; cout << "Is array sorted? " << isArraySorted(a, sz) << '\n'; sz = 5; int b[] = {1, 3, 2, 4, 5}; cout << "Is array sorted? " << isArraySorted(b, sz) << '\n'; return 0; } int isArraySorted(int A[], int n) { if(n == 1) return 1; return (A[n-1] < A[n-2] ? 0 : isArraySorted(A, n-1)); }
true
579415f7eed7f7d8680c7de1267573a40e0f3fa5
C++
edsaedi/TranspisitionCipher
/TranspisitionCipher/TranspisitionCipher/TranspisitionCipher.cpp
UTF-8
3,057
3.421875
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <cmath> std::string Encryption(std::string plaintext, size_t key) { std::string cyphertext = ""; std::vector<std::vector<char>> table; int numrows = std::ceil(plaintext.size() / (double)key); for (size_t row = 0; row < numrows; row++) { table.push_back(std::vector<char>()); for (size_t col = 0; col < key; col++) { table[row].push_back('*'); } } int count{}; for (size_t j = 0; j < numrows; j++) { for (size_t i = 0; i < key; i++) { if (count < plaintext.size()) { table[j][i] = plaintext[count]; } count++; } } for (size_t a = 0; a < key; a++) { for (size_t b = 0; b < numrows; b++) { auto ch = table[b][a]; if (ch != '*') { cyphertext += ch; } } } return cyphertext; } //[row][column] //std::string Decryption(std::string ciphertext, size_t key) //{ // std::string plaintext = ""; // int numrows = std::ceil(ciphertext.size() / (double)key); // std::vector<std::vector<char>> table; // // for (size_t row = 0; row < numrows; row++) // { // table.push_back(std::vector<char>()); // for (size_t col = 0; col < key; col++) // { // table[row].push_back('*'); // } // } // // int count{}; // for (size_t i = 0; i < key; i++) // { // for (size_t j = 0; j < numrows; j++) // { // if (count < ciphertext.size()) // { // table[j][i] = ciphertext[count]; // count++; // } // } // } // // for (size_t x = 0; x < numrows; x++) // { // for (size_t y = 0; y < key; y++) // { // auto ch = table[x][y]; // if (ch != '*') // { // plaintext += ch; // } // } // } // // return plaintext; //} std::string Decryption(std::string ciphertext, int key) { std::string plaintext; const int rows = key; const int columns = std::ceil(ciphertext.size() / (double)key); int remainder = rows - (ciphertext.size() % key); std::vector<std::vector<char>> table; /*for (size_t col = 0; col < columns; col++) { table.push_back(std::vector<char>()); for (size_t row = 0; row < rows; row++) { table[row].push_back('&'); if (col == (columns - 1) && row < (remainder)) { table[row][col] = '*'; } } }*/ for (size_t row = 0; row < rows; row++) { table.push_back(std::vector<char>()); for (size_t col = 0; col < columns; col++) { table[row].push_back('\0'); } } for (size_t i = 1; i <= remainder; i++) { table[rows - i][columns - 1] = '*'; } int count{}; for (size_t row = 0; row < rows; row++) { for (size_t col = 0; col < columns; col++) { if (table[row][col] != '*') { table[row][col] = ciphertext[count]; count++; } } } for (size_t col = 0; col < columns; col++) { for (size_t row = 0; row < rows; row++) { if (table[row][col] != '*') { plaintext += table[row][col]; } } } return plaintext; } int main() { //std::vector<std::vector<char>> table; int key = 5; auto encrypted = Encryption("I believe it works.", key); std::cout << encrypted << "\n"; std::cout << Decryption(encrypted, key); //table. }
true
f3cbfeda0f3e79f58cb174b13339c40665d3e57f
C++
Jiltseb/Leetcode-Solutions
/solutions/1157.online-majority-element-in-subarray.360755942.ac.cpp
UTF-8
1,026
3.359375
3
[ "MIT" ]
permissive
class MajorityChecker { unordered_map<int, vector<int>> indexMap; vector<int> numbers; public: MajorityChecker(vector<int> &arr) : numbers(arr) { for (int i = 0; i < arr.size(); i++) { indexMap[arr[i]].push_back(i); } } int query(int l, int r, int threshold) { int temp = -1; for (int i = 0; i < 10; i++) { int randIndex = rand() % (r - l + 1) + l; int randElement = numbers[randIndex]; auto &indices = indexMap[randElement]; auto upperIndexIterator = upper_bound(indices.begin(), indices.end(), r); auto lowerIndexIterator = lower_bound(indices.begin(), indices.end(), l); int count = upperIndexIterator - lowerIndexIterator; // cout << count << endl; if (count >= threshold) { temp = randElement; break; } } return temp; } }; /** * Your MajorityChecker object will be instantiated and called as such: * MajorityChecker* obj = new MajorityChecker(arr); * int param_1 = obj->query(left,right,threshold); */
true
edc761e6b03f528d9a959ac7300378458d3dc608
C++
Kpure1000/B_project
/B_project/Vector3.h
UTF-8
2,153
3.328125
3
[]
no_license
#pragma once #include<cmath> namespace bf { template <typename T> class Vector3 { public: Vector3() :x(0), y(0), z(0) {} Vector3(T const& X, T const& Y, T const& Z) :x(X), y(Y), z(Z) {} /****************/ template <typename T> Vector3<T> operator+(Vector3<T> const& right) { return Vector3(this->x + right.x, this->y + right.y, this->z + right.z); } template <typename T> Vector3<T> operator-(Vector3<T> const& right) { return Vector3(this->x - right.x, this->y - right.y, this->z - right.z); } template <typename T> Vector3<T> operator*(T right) { return Vector3<T>(this->x *= right, this->y * right, this->z * right); } /****************/ template <typename T> void operator+=(Vector3<T> const& right) { this->x += right.x, this->y += right.y, this->z += right.z; } template <typename T> void operator-=(Vector3<T> const& right) { this->x -= right.x, this->y -= right.y, this->z -= right.z; } template <typename T> void operator*=(T right) { this->x *= right, this->y *= right, this->z *= right; } /****************/ template <typename T> T Magnitude() { return sqrt((this->x * this->x + this->y * this->y + this->z * this->z)); } template <typename T> Vector3<T> Normalize() { T Len = this->Magnitude(); if (abs(Len) > 1e-6) { this->x /= Len; this->y /= Len; this->z /= Len; } return *this; } template <typename T> static T Dot(Vector3<T> left, Vector3<T> right) { return left.x * right.x + left.y * right.y + left.z * right.z; } template <typename T> static Vector3 Cross(Vector3<T>left, Vector3<T> right) { Vector3 vCross; vCross.x = ((left.y * right.z) - (left.z * right.y)); vCross.y = ((left.z * right.x) - (left.x * right.z)); vCross.z = ((left.x * right.y) - (left.y * right.x)); return vCross; } T x, y, z; }; template <typename T> Vector3<T> operator*(T left, Vector3<T> const& right) { return Vector3<T>(right.x *= left, right.y * left, right.z * left); } typedef Vector3<float> Vector3f; typedef Vector3<int> Vector3i; typedef Vector3<double> Vector3d; }
true
b64969cc13410f8bd0b6605658635c2082148a7a
C++
EmlynLXR/Hust
/C/实验4/源程序修改替换.cpp
UTF-8
625
3.515625
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #define max(x,y,z) (x>y?(x>z?x:z):(y>z?y:z)) float sum(float x, float y); int main()//void main(void) { int a, b, c; float d, e; printf("Enter three integers:"); scanf("%d,%d,%d", &a, &b, &c); printf("\nthe maximum of them is %d\n", max(a, b, c)); printf("Enter two floating point numbers:"); scanf("%f,%f", &d, &e); printf("\nthe sum of them is %f\n", sum(d, e)); system("pause"); } /*int max(int x, int y, int z) { int t; if (x>y) t = x; else t = y; if (t<z) t = z; return t; }*/ float sum(float x, float y) { return x + y; }
true
caf342dc64f808f6a1957272df18244cd4143284
C++
scott-sommer/dll_wrapper_prototype
/include/DataTypes.hpp
UTF-8
1,187
2.640625
3
[]
no_license
#pragma once namespace ModelData { struct Vec3D { double x{ 0.0 }; double y{ 0.0 }; double z{ 0.0 }; friend bool operator==(const Vec3D& lhs, const Vec3D& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } }; struct Rot3D { double pitch{ 0.0 }; double yaw{ 0.0 }; double roll{ 0.0 }; friend bool operator==(const Rot3D& lhs, const Rot3D& rhs) { return lhs.pitch == rhs.pitch && lhs.yaw == rhs.yaw && lhs.roll == rhs.roll; } }; typedef Vec3D Location; typedef Rot3D Orientation; struct PlatformTransform { Vec3D location; Vec3D velocity; Rot3D orientation; friend bool operator==(const PlatformTransform& lhs, const PlatformTransform& rhs) { return lhs.location == rhs.location && lhs.orientation == rhs.orientation; } }; struct MissileTransform { Vec3D location; Vec3D velocity; Vec3D accelleration; Rot3D orientation; Rot3D angular_velocity; }; struct InitialiseParams { PlatformTransform transform; }; struct UpdateParams { double delta_seconds = 0.0; PlatformTransform launcher_transform; PlatformTransform target_transform; }; };
true
8a203a0479ce80fa1dd9889376363111068d0f66
C++
kunmukh/CS-475
/CS-475/InClass-Assignment/CS215/lecture31/queue.h
UTF-8
1,647
3.53125
4
[]
no_license
// File: queue.h // Defines QueueType, a queue of items // Array implementation // Based on Dale, et al., C++ Plus Data Structures 6/e, Chapter 5 #ifndef QUEUE_H #define QUEUE_H #include "itemtype.h" // The user of this file must provied a file "itemtype.h" that defines: // ItemType : the class definition of the objects on the stack. class FullQueue {}; class EmptyQueue {}; class QueueType { public: // Class constructor. // Because there is a default constructor, the precondition // that the queue has been initialized is omitted. QueueType(); // Parameterized class constructor. QueueType(int max); // Class destructor. ~QueueType(); // Function: Initializes the queue to an empty state. // Post: Queue is empty. void MakeEmpty(); // Function: Determines whether the queue is empty. // Post: Function value = (queue is empty) bool IsEmpty() const; // Function: Determines whether the queue is full. // Post: Function value = (queue is full) bool IsFull() const; // Function: Adds newItem to the rear of the queue. // Post: If (queue is full) FullQueue exception is thrown // else newItem is at rear of queue. void Enqueue(ItemType newItem); // Function: Removes front item from the queue and passes it back in item. // Post: If (queue is empty) EmptyQueue exception is thrown // and item is undefined // else front element has been removed from queue and // item is a copy of removed element. void Dequeue(ItemType& item); private: int front; int rear; ItemType* items; int maxQue; }; #endif
true
e349b6c4cb1727ddf259e16dedc53ac678b21de5
C++
idkunal/SDE_SHEET_180
/maximum length subarray with given XOR.cpp
UTF-8
508
2.828125
3
[]
no_license
/* INPUT - [4,2,2,6,4], XOR = 6 OUTPUT - 3 */ #include <bits/stdc++.h> #include<map> using namespace std; int main() { int n,k; cin >> n >> k; int arr[n]; for(int i = 0; i < n; i++) cin >> arr[i]; unordered_map<int,int> mp; int xo = 0, len = 0; for(int i = 0; i < n; i++){ xo ^= arr[i]; if(mp.find(xo^k)!=mp.end()) len = max(len,i-mp[xo^k]); else{ if(mp.find(xo)==mp.end()) mp[xo] = i; } } cout << len << endl; return 0; }
true
1e440a62e0c17ed6e40e8bfbba2698c991229839
C++
wakira/mkalpha
/kernel/kernel.h
UTF-8
2,367
2.53125
3
[]
no_license
#ifndef KERNEL_H_ #define KERNEL_H_ #include "app/base.h" #include "oslib/io_events.h" #include "oslib/io_devices.h" #include "mbed.h" #include <list> #include <map> #include <string> // defines the singleton kernel // we define no destructor since the kernel should run forever class LcdFactory; class Kernel { private: Kernel(); // no copy is allowed Kernel(Kernel const&); void operator=(Kernel const&); public: static Kernel& get_instance() { static Kernel KERNEL_INSTANCE; return KERNEL_INSTANCE; } // syncrhonous calls void register_launcher(AppBase *instance); bool register_io_event_handler(AppBase *app, IOEvent event, Callback<void()> handler); void unregister_io_event_handler(AppBase *app, IOEvent event); Device* request_device(AppBase *app, IODevice id); // asynchronous calls void put_foreground(AppBase *launcher, AppBase *target); void put_background(AppBase *target); void launch_app(AppBase *instance); void stop_app(AppBase *instance); // start the kernel void run_kernel(); // run_kernel() never returns private: // private routines void _panic(std::string info = ""); void _launch_app(AppBase *instance); void _stop_app(AppBase *instance); void _setup_isr(); void _on_io_event(IOEvent ev); void _put_foreground(AppBase *target); void _put_background(AppBase *target); // isr void _isr_joystick_fire_rise(); void _isr_joystick_fire_fall(); void _isr_joystick_up_rise(); void _isr_joystick_down_rise(); void _isr_joystick_left_rise(); void _isr_joystick_right_rise(); private: // private states Mutex _kernel_mutex; EventQueue *_event_queue; bool _running; AppBase *_launcher_instance; // std::list<AppBase*> _apps_running; std::map<AppBase*, std::map<IOEvent, Callback<void()> > > _app_io_handlers; AppBase *_app_foreground; LcdFactory *_lcd_factory; // IO devices InterruptIn *_joystick_fire; Timer _fire_timer; InterruptIn *_joystick_up; InterruptIn *_joystick_down; InterruptIn *_joystick_left; InterruptIn *_joystick_right; std::map<IODevice, Device*> _allocated_devices; std::map<Device*, IODevice> _allocated_devices_rev; std::map<AppBase*, std::list<Device*> > _app_devices; }; #endif
true
115de8666d34533d08edd03ec60ac752068c1336
C++
progg1992/School-Projects
/Coding-Projects/C++/Advanced-C++/Engine.cpp
UTF-8
780
3.3125
3
[]
no_license
#include "Engine.h" Engine::Engine() { numCylinders = 0; horsePower = 0; } Engine::Engine(short numCylinders, short horsePower) { setNumCylinders(numCylinders); setHorsePower(horsePower); } Engine::~Engine() { } string Engine::toString() { return "numCylinders: " + to_string(numCylinders) + ", horsePower: " + to_string(horsePower); } short Engine::getNumCylinders() { return numCylinders; } void Engine::setNumCylinders(short numCylinders) { if (numCylinders > 0 && numCylinders < 13) this->numCylinders = numCylinders; else this->numCylinders = 0; } short Engine::getHorsePower() { return horsePower; } void Engine::setHorsePower(short horsePower) { if (horsePower > 0 && horsePower < 1000) this->horsePower = horsePower; else this->horsePower = 0; }
true
3f000343edcb146c759d78cc3bdc6e2d567d6679
C++
ezhangle/node-mapbox-gl-native
/src/compress_png.cpp
UTF-8
3,094
2.625
3
[]
no_license
#include <node.h> #include <nan.h> #include <mbgl/util/image.hpp> namespace node_mbgl { class CompressPNGWorker : public NanAsyncWorker { public: CompressPNGWorker(NanCallback *callback, v8::Local<v8::Object> buffer_, uint32_t width_, uint32_t height_) : NanAsyncWorker(callback), buffer(v8::Persistent<v8::Object>::New(buffer_)), data(node::Buffer::Data(buffer_)), width(width_), height(height_) { assert(width * height * 4 == node::Buffer::Length(buffer_)); } ~CompressPNGWorker() { buffer.Dispose(); } void Execute() { result = mbgl::util::compress_png(width, height, data); } void HandleOKCallback() { NanScope(); auto img = new std::string(std::move(result)); v8::Local<v8::Value> argv[] = { NanNull(), NanNewBufferHandle( const_cast<char *>(img->data()), img->size(), // Retain the std::string until the buffer is deleted. [](char *, void *hint) { delete reinterpret_cast<std::string *>(hint); }, img ) }; callback->Call(2, argv); }; private: // Retains the buffer while this worker is processing. The user may not modify the buffer. v8::Persistent<v8::Object> buffer; void *data; const uint32_t width; const uint32_t height; // Stores the compressed PNG. std::string result; }; NAN_METHOD(CompressPNG) { NanScope(); if (args.Length() <= 0 || !args[0]->IsObject()) { return NanThrowTypeError("First argument must be the data object"); } uint32_t width = 0; uint32_t height = 0; v8::Local<v8::Object> buffer; auto options = args[0]->ToObject(); if (options->Has(NanNew("width"))) { width = options->Get(NanNew("width"))->Uint32Value(); } if (!width) { NanThrowRangeError("Image width must be greater than 0"); } if (options->Has(NanNew("height"))) { height = options->Get(NanNew("height"))->Uint32Value(); } if (!height) { NanThrowRangeError("Image height must be greater than 0"); } if (options->Has(NanNew("pixels"))) { buffer = options->Get(NanNew("pixels")).As<v8::Object>(); } if (!node::Buffer::HasInstance(buffer)) { NanThrowTypeError("Pixels must be a Buffer object"); } if (width * height * 4 != node::Buffer::Length(buffer)) { NanThrowError("Pixel buffer doesn't match image dimensions"); } if (args.Length() < 2) { NanThrowTypeError("Second argument must be a callback function"); } NanCallback *callback = new NanCallback(args[1].As<v8::Function>()); NanAsyncQueueWorker(new CompressPNGWorker(callback, buffer, width, height)); NanReturnUndefined(); } void InitCompressPNG(v8::Handle<v8::Object> target) { target->Set(NanNew<v8::String>("compressPNG"), NanNew<v8::FunctionTemplate>(CompressPNG)->GetFunction()); } }
true
63fd6c6119b6e79524eb4201b21b2bd5a536e3a1
C++
TomekAtomek/MyTimber
/main.cpp
UTF-8
10,232
2.640625
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdlib> #include <ctime> #include <sstream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> using namespace sf; typedef struct mysprite { Sprite sprite; bool isActive; float moveSpeed; } MySprite; void updateBranches( int seed ); const int NUM_BRANCHES = 6; Sprite branches[NUM_BRANCHES]; enum class side {LEFT, RIGHT, NONE}; side branchPositions[NUM_BRANCHES]; int main() { uint8_t c = 'c'; VideoMode vm(1920,1080); RenderWindow window(vm,"MyTimer", Style::Fullscreen); Texture textureBackGround; textureBackGround.loadFromFile("graphics/background.png"); Sprite spriteBackGround; spriteBackGround.setTexture(textureBackGround); spriteBackGround.setPosition(0,0); Texture textureTree; textureTree.loadFromFile("graphics/tree.png"); Sprite spriteTree; spriteTree.setTexture(textureTree); spriteTree.setPosition(810,0); Texture textureBee; textureBee.loadFromFile("graphics/bee.png"); Sprite spriteBee; spriteBee.setTexture(textureBee); spriteBee.setPosition(0,800); bool beeActive = false; float beeSpeed = 0.0f; Texture textureCloud; textureCloud.loadFromFile("graphics/cloud.png"); std::vector<MySprite> clouds; for(int i = 0; i < 3; ++i) { Sprite spriteCloud; spriteCloud.setTexture(textureCloud); spriteCloud.setPosition(0,250 * i); MySprite mySprite; mySprite.sprite = spriteCloud; mySprite.isActive = false; mySprite.moveSpeed = 0.0f; clouds.push_back(mySprite); } Clock clock; RectangleShape timeBar; float timeBarStartWidth = 400; float timeBarHeight = 80; timeBar.setSize(Vector2f(timeBarStartWidth, timeBarHeight)); timeBar.setFillColor(Color::Red); timeBar.setPosition(1920 / 2 - timeBarStartWidth / 2, 80); Time gameTimeTotal; float timeRemaining = 6.0f; float timeBarWidthPerSecond = timeBarStartWidth / timeRemaining; bool paused = true; int score = 0; sf::Text messageText; sf::Text scoreText; Font font; font.loadFromFile("fonts/KOMIKAP_.ttf"); messageText.setFont(font); scoreText.setFont(font); messageText.setString("Press Enter to Start!"); scoreText.setString("Score = 0"); messageText.setCharacterSize(75); scoreText.setCharacterSize(100); messageText.setFillColor(Color::White); scoreText.setFillColor(Color::White); FloatRect textRect = messageText.getLocalBounds(); messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f); scoreText.setPosition(20,20); messageText.setPosition(1920 / 2.0f, 1080 / 2.0f); Texture textureBranch; textureBranch.loadFromFile("graphics/branch.png"); for(int i = 0; i < NUM_BRANCHES; ++i) { branches[i].setTexture(textureBranch); branches[i].setPosition(-2000,-2000); branches[i].setOrigin(220,20); } Texture texturePlayer; texturePlayer.loadFromFile("graphics/player.png"); Sprite spritePlayer; spritePlayer.setTexture(texturePlayer); spritePlayer.setPosition(580,720); side playerSide = side::LEFT; Texture textureRIP; textureRIP.loadFromFile("graphics/rip.png"); Sprite spriteRIP; spriteRIP.setTexture(textureRIP); spriteRIP.setPosition(600,860); Texture textureAxe; textureAxe.loadFromFile("graphics/axe.png"); Sprite spriteAxe; spriteAxe.setTexture(textureAxe); spriteAxe.setPosition(700,830); const float AXE_POSITION_LEFT = 700; const float AXE_POSITION_RIGHT = 1075; Texture textureLog; textureLog.loadFromFile("graphics/log.png"); Sprite spriteLog; spriteLog.setTexture(textureLog); spriteLog.setPosition(810,720); bool logActive = false; float logSpeedX = 1000; float logSpeedY = -1500; bool acceptInput = false; SoundBuffer chopBuffer; chopBuffer.loadFromFile("sound/chop.wav"); Sound chop; chop.setBuffer(chopBuffer); SoundBuffer deathBuffer; deathBuffer.loadFromFile("sound/death.wav"); Sound death; death.setBuffer(deathBuffer); SoundBuffer ootBuffer; ootBuffer.loadFromFile("sound/out_of_time.wav"); Sound outOfTime; outOfTime.setBuffer(ootBuffer); while(window.isOpen()) { if(!paused) { Time deltaTime = clock.restart(); timeRemaining -= deltaTime.asSeconds(); timeBar.setSize(Vector2f( timeBarWidthPerSecond * timeRemaining, timeBarHeight)); if(timeRemaining <= 0.0f) { paused = true; messageText.setString("Out of Time!"); FloatRect textRect = messageText.getLocalBounds(); messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f); messageText.setPosition(1920 / 2.0f, 1080 / 2.0f); outOfTime.play(); } for(int i = 0; i < 3; ++i) { if( !(clouds[i].isActive) ) { clouds[i].isActive = true; //how fast the cloud is srand((int)time(0) * 10 + (10 * i)); clouds[i].moveSpeed = (rand() % 200); if(clouds[i].moveSpeed == 0) { std::cout << "Cloud " << i << " speed is zero" << std::endl; } //how high the cloud is srand((int)time(0) * 10 * (i+1)); int subs = (i == 0) ? 0 : 150; float height = (rand() % (150 + i * 150)) - subs; clouds[i].sprite.setPosition(-200, height); } else { //Sprite tmp = clouds[i].sprite; clouds[i].sprite.setPosition( clouds[i].sprite.getPosition().x + (clouds[i].moveSpeed * deltaTime.asSeconds()), clouds[i].sprite.getPosition().y ); if(clouds[i].sprite.getPosition().x > 1920) { clouds[i].isActive = false; } } } if(!beeActive) { beeActive = true; // how fast the bee is srand((int)time(0)); beeSpeed = (rand() % 200) + 200; // how high the bee is srand((int)time(0) * 10); float height = (rand() % 500) + 500; spriteBee.setPosition(2000, height); } else //move the bee { spriteBee.setPosition(spriteBee.getPosition().x - (beeSpeed * deltaTime.asSeconds()),spriteBee.getPosition().y); if(spriteBee.getPosition().x < -100) { beeActive = false; } } std::stringstream ss; ss << "Score = " << score; scoreText.setString(ss.str()); for(int i = 0; i < NUM_BRANCHES; ++i) { float height = i * 150; if (branchPositions[i] == side::LEFT) { branches[i].setPosition(610, height); branches[i].setRotation(180); } else if (branchPositions[i] == side::RIGHT) { branches[i].setPosition(1330, height); branches[i].setRotation(0); } else { //hide the branch branches[i].setPosition(3000, height); } } if(logActive) { spriteLog.setPosition(spriteLog.getPosition().x + (logSpeedX * deltaTime.asSeconds()), spriteLog.getPosition().y + (logSpeedY * deltaTime.asSeconds())); if(spriteLog.getPosition().x < -100 || spriteLog.getPosition().x > 2000) { logActive = false; spriteLog.setPosition(810, 720); } } if(branchPositions[5] == playerSide) { paused = true; acceptInput =false; spriteRIP.setPosition(525, 760); spritePlayer.setPosition(2000, 660); messageText.setString("SQUISHED!!"); FloatRect textRect = messageText.getLocalBounds(); messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f); messageText.setPosition(1920 / 2.0f , 1080 / 2.0f); death.play(); } }// !paused Event event; while(window.pollEvent(event)) { if(event.type == Event::KeyReleased && !paused) { acceptInput = true; spriteAxe.setPosition(2000, spriteAxe.getPosition().y); } } if(Keyboard::isKeyPressed(Keyboard::Escape)) { window.close(); } if(Keyboard::isKeyPressed(Keyboard::P)) { paused = true; } if(Keyboard::isKeyPressed(Keyboard::Return)) { paused = false; score = 0; timeRemaining = 5; for (int i = 1; i < NUM_BRANCHES; ++i) { branchPositions[i] = side::NONE; } spriteRIP.setPosition(675, 2000); spritePlayer.setPosition(580, 720); acceptInput= true; } if(acceptInput) { if(Keyboard::isKeyPressed(Keyboard::Right)) { playerSide = side::RIGHT; ++score; timeRemaining += (2 / score) + .15; spriteAxe.setPosition(AXE_POSITION_RIGHT, spriteAxe.getPosition().y); spritePlayer.setPosition(1200, 720); updateBranches(score); spriteLog.setPosition(810, 720); logSpeedX = -5000; logActive = true; acceptInput = false; chop.play(); } if(Keyboard::isKeyPressed(Keyboard::Left)) { playerSide = side::LEFT; ++score; timeRemaining += (2 / score) + .15; spriteAxe.setPosition(AXE_POSITION_LEFT, spriteAxe.getPosition().y); spritePlayer.setPosition(580, 720); updateBranches(score); spriteLog.setPosition(810, 720); logSpeedX = 5000; logActive = true; acceptInput = false; chop.play(); } } window.clear(); window.draw(spriteBackGround); window.draw(spriteTree); for (int i = 0; i < NUM_BRANCHES; ++i) { window.draw(branches[i]); } window.draw(spritePlayer); window.draw(spriteAxe); window.draw(spriteLog); window.draw(spriteRIP); window.draw(spriteBee); for (int i = 0; i < 3; ++i) { window.draw(clouds[i].sprite); } if(paused) { window.draw(messageText); } window.draw(scoreText); window.draw(timeBar); window.display(); } std::cout << "MyTimber" << std::endl; return 0; } void updateBranches( int seed ) { //move branches up for (int i = NUM_BRANCHES - 1; i > 0; --i) { branchPositions[i] = branchPositions[i-1]; } srand((int)time(0) + seed); int r = (rand() % 5); switch(r) { case 0: branchPositions[0] = side::LEFT; break; case 1: branchPositions[0] = side::RIGHT; break; default: branchPositions[0] = side::NONE; break; } }
true
ae604f33fc4a4d3d3b6b619ec6cb1bf3acff28e7
C++
eatyourpotato/RobotDo
/Robot rRocks/src/ElementARepresenter.h
UTF-8
559
2.875
3
[]
no_license
#ifndef ELEMENTAREPRESENTER_H_ #define ELEMENTAREPRESENTER_H_ #include <vector> #include "Afficheur.h" using namespace std; class Afficheur; class ElementARepresenter{ private: vector<Afficheur*> v; public: void attacherAfficheur(Afficheur* a){ v.push_back(a); } void detacherAfficheur(Afficheur* a){ vector<Afficheur*>::iterator it = v.begin(); while(it != v.end()){ if(*it == a){ it = v.erase(it); } else{ it ++; } } } void notifier(){ for(int i = 0; i < v.size(); i++){ v[i]->afficher(this); } } }; #endif
true
bca0c900dad5411d22edbdd77fa033cf8601c531
C++
erinsb/tetris
/tetris.ino
UTF-8
3,964
2.765625
3
[]
no_license
#include <Adafruit_GFX.h> // Core graphics library #include <RGBmatrixPanel.h> // Hardware-specific library //#include "tetris.h" #define CLK 11 // MUST be on PORTB! (Use pin 11 on Mega) #define OE 9 #define LAT 10 #define A A0 #define B A1 #define C A2 #define D A3 #define STARTX 12 #define STARTY 10 #define LENGTH 10 #define WIDTH 11 int shape1[4][4] = {{1,1,0,0}, {1,1,0,0}}; //square int shape2[4][4] = {{1,1,1,1}}; //I shape int shape3[4][4] = {{1},{1},{1},{0,1}}; //L int shape4[4][4] = {{1,1},{0,1},{0,1}}; //Z RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false); class Shape { //int shapeMatrix[4][4]; public: Shape(int shape[4][4]); //int shapeMatrix[4][4]; void draw(); void drop(); void rotate(); int startX = STARTX; int startY = STARTY; private: int shapeMatrix[4][4]; }; Shape::Shape(int shape[4][4]){ for(int i=0; i<4; i++) { for(int j=0; j<4; j++){ shapeMatrix[i][j] = shape[i][j]; } }; for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { if(shapeMatrix[i][j] == 1) { matrix.drawPixel(i + startX, j + startY, matrix.Color333(7, 0, 3)); } } }; }; void Shape::draw() { for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { if(shapeMatrix[i][j] == 1) { matrix.drawPixel(i + startX, j + startY, matrix.Color333(7, 0, 3)); } } }; } void Shape::drop() { for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { if(shapeMatrix[i][j] == 1) { matrix.drawPixel(i + startX, j + startY, matrix.Color333(0, 0, 0)); } } } delay(50); startY++; // for(int i=0; i<4; i++) { // for(int j=0; j<4; j++) { // if(shapeMatrix[i][j] == 1) { // matrix.drawPixel(i, j + startY, matrix.Color333(7, 0, 3)); // } // } // } }; void Shape::rotate() { for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { if(shapeMatrix[i][j] == 1) { matrix.drawPixel(i + startX, j + startY, matrix.Color333(0, 0, 0)); } } } // Transpose for (int i=0; i<4; i++) { for (int j=i; j<4; j++) { int temp = shapeMatrix[i][j]; shapeMatrix[i][j] = shapeMatrix[j][i]; shapeMatrix[j][i] = temp; } }; // Reverse columns for (int i=0; i<4; i++) { for (int j=0, k=3; j<k; j++, k--) { int temp = shapeMatrix[j][i]; shapeMatrix[j][i] = shapeMatrix[k][i]; shapeMatrix[k][i] = temp; } }; // for(int i=0; i<4; i++) { // for(int j=0; j<4; j++) { // if(shapeMatrix[i][j] == 1) { // matrix.drawPixel(i, j, matrix.Color333(7, 0, 3)); // } // } // }; } class Board { public: //static const int x = 11; //static const int y = 20; //int gameBoard[x][y]; Board(); void draw(); int x = WIDTH; int y = LENGTH; private: int startX = STARTX; int startY = STARTY; // int x = WIDTH; // int y = LENGTH; int gameBoard[WIDTH][LENGTH] = {}; }; Board::Board() {}; void Board::draw() { matrix.drawLine(startX,startY,startX+x,startY, matrix.Color333(7, 7, 7)); matrix.drawLine(startX-1+x,startY-1,startX+x,startY-1+y, matrix.Color333(7, 7, 7)); }; //Shape shapeTest(shape4); Shape *shapeTest = new Shape(shape3); Board game; //int gameBoard[WIDTH][LENGTH]; void setup() { //Serial.begin(9600); matrix.begin(); //Serial.println("HERE"); game.draw(); shapeTest->draw(); //delay(1000); // put your setup code here, to run once: // matrix.drawPixel(0, 0, matrix.Color333(7, 0, 3)); // matrix.drawPixel(1, 0, matrix.Color333(7, 0, 3)); // matrix.drawPixel(2, 0, matrix.Color333(7, 0, 3)); // matrix.drawPixel(3, 0, matrix.Color333(7, 0, 3)); } //int array shapes = [shape1, shape2, shape3, shape4]; void loop() { // put your main code here, to run repeatedly: delay(500); //Serial.println("HERE"); shapeTest->rotate(); shapeTest->drop(); shapeTest->draw(); }
true
687199537bf849dfd8cad3a75e03cadfabf11dd8
C++
jjzhang166/angle
/vertexbuffer.hpp
UTF-8
4,293
3.125
3
[]
no_license
//@ {"targets":[{"name":"vertexbuffer.hpp","type":"include"}]} #ifndef ANGLE_VERTEXBUFFER_HPP #define ANGLE_VERTEXBUFFER_HPP #include "exceptionhandler.hpp" #include <cassert> #include <utility> namespace Angle { enum class BufferUsage:GLenum { STREAM_DRAW=GL_STREAM_DRAW ,STREAM_READ=GL_STREAM_READ ,STREAM_COPY=GL_STREAM_COPY ,STATIC_DRAW=GL_STATIC_DRAW ,STATIC_READ=GL_STATIC_READ ,STATIC_COPY=GL_STATIC_COPY ,DYNAMIC_DRAW=GL_DYNAMIC_DRAW ,DYNAMIC_READ=GL_DYNAMIC_READ ,DYNAMIC_COPY=GL_DYNAMIC_COPY }; constexpr GLenum native_type(BufferUsage usage_type) noexcept {return static_cast<GLenum>(usage_type);} template<class ElementType,BufferUsage usage_type=BufferUsage::STATIC_DRAW> class VertexBuffer { public: typedef ElementType value_type; static constexpr auto vector_size=sizeof(value_type); static constexpr auto components=1; VertexBuffer(size_t n_elems):m_capacity(n_elems) { glCreateBuffers(1,&m_handle); glNamedBufferData(m_handle,sizeof(ElementType)*n_elems,NULL,native_type(usage_type)); auto error=glGetError(); if(error!=GL_NO_ERROR) { glDeleteBuffers(1,&m_handle); exceptionRaise(Error("Failed to allocate vertex buffer storage.")); } } ~VertexBuffer() noexcept {glDeleteBuffers(1,&m_handle);} VertexBuffer(const VertexBuffer&)=delete; VertexBuffer(VertexBuffer&& obj) noexcept:m_handle(obj.m_handle) {obj.m_handle=0;} VertexBuffer& operator=(const VertexBuffer&)=delete; VertexBuffer& operator=(VertexBuffer&& obj) { std::swap(obj.m_handle,m_handle); return *this; } VertexBuffer& bufferData(const ElementType* data,size_t n_elems) noexcept { assert(m_capacity==n_elems); glNamedBufferSubData(m_handle,0,sizeof(ElementType)*n_elems,data); return *this; } VertexBuffer& bufferDataResize(const ElementType* data,size_t n_elems) { if(m_capacity==n_elems) {glNamedBufferSubData(m_handle,0,sizeof(ElementType)*n_elems,data);} else { glNamedBufferData(m_handle,sizeof(ElementType)*n_elems,NULL,native_type(usage_type)); auto error=glGetError(); if(error!=GL_NO_ERROR) {exceptionRaise(Error("Failed to allocate vertex buffer storage."));} m_capacity=n_elems; } return *this; } GLuint handle() const noexcept {return m_handle;} size_t size() const noexcept {return m_capacity;} private: GLuint m_handle; size_t m_capacity; }; template<BufferUsage usage_type> class VertexBuffer<float __attribute__ ((vector_size (16))),usage_type>: private VertexBuffer<float,usage_type> { public: typedef VertexBuffer<float,usage_type> base; typedef float vector_type __attribute__ ((vector_size (16))); static constexpr auto components=4; static constexpr auto vector_size=components*sizeof(float); using typename base::value_type; VertexBuffer(size_t n_elems):base(components*n_elems) {} VertexBuffer& bufferData(const vector_type* data,size_t n_elems) noexcept { base::bufferData(reinterpret_cast<const float*>(data),components*n_elems); return *this; } VertexBuffer& bufferDataResize(const vector_type* data,size_t n_elems) noexcept { base::bufferDataResize(reinterpret_cast<const float*>(data),components*n_elems); return *this; } using base::handle; }; template<BufferUsage usage_type> class VertexBuffer<float __attribute__ ((vector_size (8))),usage_type>: private VertexBuffer<float,usage_type> { public: typedef VertexBuffer<float,usage_type> base; typedef float vector_type __attribute__ ((vector_size (8))); static constexpr auto components=2; static constexpr auto vector_size=components*sizeof(float); using typename base::value_type; VertexBuffer(size_t n_elems):base(components*n_elems) {} VertexBuffer& bufferData(const vector_type* data,size_t n_elems) noexcept { base::bufferData(reinterpret_cast<const float*>(data),components*n_elems); return *this; } VertexBuffer& bufferDataResize(const vector_type* data,size_t n_elems) noexcept { base::bufferDataResize(reinterpret_cast<const float*>(data),components*n_elems); return *this; } using base::handle; }; }; #endif
true
ac9747fb2e6031ac6cd0af1a149f9dd56b99d89e
C++
F3LuxRay/LattePanda
/DIGITALTOUCH.ino
UTF-8
900
3.046875
3
[]
no_license
/* Arduino Touch Sensor 5V VCC GND GND D3 SIG */ int TouchSensor = 3; //connected to Digital pin D3 int onLed = 6; //connected to pin 6 int offLed = 13; //connected to pin 13 void setup(){ Serial.begin(9600); // Communication speed pinMode(onLed, OUTPUT); pinMode(offLed, OUTPUT); pinMode(TouchSensor, INPUT); } void loop(){ if(digitalRead(TouchSensor)==HIGH) //Read Touch sensor signal { digitalWrite(onLed, HIGH); // if Touch sensor is HIGH, then turn on the onLed digitalWrite(offLed, LOW); // if Touch sensor is LOW, then turn off the offLed Serial.println("Led ON"); } else { digitalWrite(onLed, LOW); // if Touch sensor is LOW, then turn off the onLed digitalWrite(offLed, HIGH); // if Touch sensor is LOW, then turn on the offLed Serial.println("Led OFF"); } }
true
12938a0e1f4ec47e087f94b0afde6ba6f172f074
C++
pushp360/CCC
/C++/Arrays/MinimizetheCellWastage.cpp
UTF-8
1,587
3.234375
3
[]
no_license
/* * Created Date: Saturday June 11th 2019 * Author: Rajeshwari Kalyani * Email-ID: klhn.rajeshwari@gmail.com * ----- * Copyright (c) 2019 Rajeshwari Kalyani */ /* Question source: HackerRank Description: Previously, it was important for every company to have a motto. Now, it is important for every company to have a banner. Since companies want to save their resources, they decided to convert their motto into a banner. How this works is, you create a square matrix of size N x N, and fill in the elements of this matrix using the motto in row-major order.The remaining spaces in the matrix are called waste cells and are to be represented as '?'.You have to choose N in such a way that the number of waste cells is minimized. Input: Input consists of one line only, containing the company motto Output: Output must consist of the matrix formed from the input string Notes: The length of the input string will not exceed 1000 Sample Input 0 nike - just do it! Sample Output 0 */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { string s1; getline(cin,s1); int m; m=s1.length(); char s2[50][50]; //cout<<n<<endl; int n=ceil(sqrt(m)); //cout<<n<<endl; int i,j; int k=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(k<m) s2[i][j]=s1[k++]; else s2[i][j]='?'; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { cout<<s2[i][j]; } cout<<endl; } return 0; }
true
411448051a2dd4359efe195ed33c55dd829e919d
C++
blighli/graphics2020
/22051150李浩雨/编程作业/homework_2/light.cpp
UTF-8
1,356
3.109375
3
[]
no_license
#include "light.h" DirectionalLight::DirectionalLight(int _type, glm::vec3 _angleOrDir, glm::vec3 _color, float _intensity, glm::vec3 _position) { this->color = _color; this->intensity = _intensity; this->position = _position; this->angle = _angleOrDir; this->direction = _angleOrDir; UpdateAngleOrDirection(_type); } void DirectionalLight::UpdateAngleOrDirection(int type) { if (type == ANGLE) { glm::vec3 direction = glm::vec3(0.0f, 0.0f, 1.0f);//like unity direction = glm::rotateZ(direction, angle.z); direction = glm::rotateX(direction, angle.x); direction = glm::rotateY(direction, angle.y); this->direction = direction; } else { glm::vec3 angle(0.0f); angle.x = glm::asin(direction.y); if (direction.z > 0) { angle.y = glm::asin(direction.x / glm::cos(glm::asin(direction.y))); } else { angle.y = glm::acos(-1) - glm::asin(direction.x / glm::cos(glm::asin(direction.y))); } this->angle = angle; } } PointLight::PointLight(glm::vec3 _color, float _intensity, glm::vec3 _position, float _radius) { this->color = _color; this->intensity = _intensity; this->position = _position; this->radius = _radius; this->attenuation1 = 1.0f; this->attenuation2 = 0.7f; this->attenuation3 = 1.8f; if (radius == 50.0f) { this->attenuation1 = 1.0f; this->attenuation2 = 0.09f; this->attenuation3 = 0.032f; } }
true
e4e3547be7bf99d357a30e1fd9be60a55b14567f
C++
zheminggu/computer-graphics
/ComputerGraphics/Draw.cpp
UTF-8
2,086
2.859375
3
[]
no_license
//#include "Utils.h" #include "Vector3.h" #include "Vector4.h" #include "Draw.h" #include <Windows.h> #include <gl\GL.h> #include <iostream> #include <fstream> //#include "Math.h" //using namespace OpenGLUtils; //using namespace Vector; void Draw::DrawLine(Vector3 startPosition, Vector3 endPosition) { //startPosition.Print(); //endPosition.Print(); //std::cout << "start position" << startPosition.GetX() << " " << startPosition.GetY(); //std::cout << "end position" << endPosition.GetX() << " " << endPosition.GetY() << std::endl; glBegin(GL_LINE_STRIP); glVertex2f(startPosition.GetX(), startPosition.GetY()); glVertex2f(endPosition.GetX(), endPosition.GetY()); glEnd(); } void ImageBufferToFile(Vector4 imageBuffer[SCREEN_HEIGHT][SCREEN_WEIGHT]) { std::string data[SCREEN_HEIGHT]; std::ofstream outfile; outfile.open("afile.txt", std::ios::out | std::ios::binary); for (int i = 0; i < SCREEN_HEIGHT; i++) { for (int j = 0; j < SCREEN_WEIGHT; j++) { if (imageBuffer[i][j].GetW() != 0) { /*imageBuffer[i][j].Print();*/ data[i] += '1'; //data[i][j] = 1; } else { data[i] += '0'; //data[i][j] = 0; } //imageBuffer[i][j].Print(); } } for (int i = 0; i < SCREEN_HEIGHT; i++) { outfile << data[i] << "\n"; } outfile << std::endl; outfile.close(); } //bool finish_a_draw = false; void Draw::DrawPoints(float imageBuffer[SCREEN_HEIGHT][SCREEN_WEIGHT][4]) { //glPointSize(5); glBegin(GL_POINTS); for (int i = 0; i <SCREEN_HEIGHT ; i++) { for (int j = 0; j < SCREEN_WEIGHT; j++) { //glPointSize(2.0); glColor3fv(imageBuffer[i][j]); glVertex2f((j-320) /320.f, (i-240) / 240.f); } } glEnd(); /*if (!finish_a_draw) { ImageBufferToFile(imageBuffer); Debug::Log("finish a draw"); } finish_a_draw = true;*/ } void Draw::DrawPoints(int image[256][256][3]) { glBegin(GL_POINTS); for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { //glPointSize(2.0); glColor3fv((const float *)image[i][j]); glVertex2f((j - 320) / 320.f, (i - 240) / 240.f); } } glEnd(); }
true
934bb1f721538d0bfe4682b8d41a379aa229552c
C++
WYuanisme/generateVectorAlgorithm
/Walk_1.cpp
GB18030
725
2.953125
3
[]
no_license
#include "Walk_1.h" #include <vector> using namespace std; Walk_1::Walk_1(int totalNetNum1) { totalNetNum = totalNetNum1; for (int i=0;i!=totalNetNum;++i) // i { vector<int> STV_temp; // һʱiSTV for (int j = 0; j != totalNetNum; ++j) { if (i == j) // MTVĶԽֵΪ1 { STV_temp.push_back(1); } else { STV_temp.push_back(0); } } MTV.push_back(STV_temp); } } Walk_1::~Walk_1() { } vector<vector<int>> Walk_1::getMTV() { return MTV; }
true
dfd900094a967316239d33429b8d976dcbfa68b8
C++
khalilmez/JIN4_quiz
/src/Text.h
ISO-8859-1
952
2.96875
3
[]
no_license
#pragma once #include "Element.h" #include <SFML/Graphics/Font.hpp> #include <SFML/Graphics/Text.hpp> #include <pugixml.hpp> /* Cette classe reprsente les lments textuels d'un cran. */ class Text : public Element { public: explicit Text(pugi::xml_node const &node); explicit Text(const float x, const float y, std::string const &name, std::string const &content, sf::Font const &font, const int characterSize, sf::Color const &color, sf::Text::Style const &style); void render(sf::RenderWindow& window) override; bool verify() override { return false; }; bool contains(const float x, const float y) const override; private: sf::Text text; /* Le contenu textuel de l'lment. */ std::string content; /* La police d'criture. */ sf::Font font; /* La taille d'criture. */ int size; /* La couleur d'criture. */ sf::Color color; /* La dcoration textuelle (gras, soulign...) */ sf::Text::Style style; };
true
539d73f23823d18ef10c154a877279647a3a24c5
C++
chrishopp12/Palomar-CSCI-222
/HoppChris CSCI 222 - Lab 3 Operator Overloading Lab (IntArray)/intarray.h
UTF-8
907
3.078125
3
[]
no_license
/* Lab 3 - Operator Overloading (IntArray) Author: Chris Hopp - 010809627 Version: 04.13.2018 */ #ifndef _INTARRAY_H #define _INTARRAY_H #include <iostream> #include <iomanip> #include <fstream> #include <stdlib.h> using namespace std; class IntArray { private: string name; int upper; int lower; int offset; int intSize; int *intArray; public: IntArray(); IntArray(int elements); IntArray(int low, int high); IntArray(const IntArray& array1); ~IntArray(); int low() const; int high() const; int size() const; void setName(string name1); string getName(); IntArray& operator=(const IntArray& array1); bool operator==(IntArray array1); bool operator!=(IntArray array1); int& operator[](int index); IntArray operator+(IntArray&); void operator+=(IntArray); friend ostream& operator <<(ostream& os, const IntArray& array1); }; #endif
true
eda2a318049f5f2356a404b4cc0356ff711c1db5
C++
etrizzo/PersonalEngineGames
/Thesis/Thesis/Code/Game/StoryData.hpp
UTF-8
2,189
2.609375
3
[]
no_license
#pragma once #include "Game/GameCommon.hpp" #include "Game/StoryRequirementSet.hpp" #include "Game/CharacterRequirementSet.hpp" #include "Game/EffectSet.hpp" #include "Game/StoryDataDefinition.hpp" class Character; class StoryState; class Action; class StoryData{ public: StoryData(){}; StoryData(StoryDataDefinition* definition, int actionIndex = -1); StoryData(std::string name); StoryData( eNodeType type); StoryData(StoryData* clone); ~StoryData(); std::string GetName() const; std::string ToString() const; float UpdateAndGetChance(StoryState* incomingEdge); //state utilities //updates node's story state w/ outbound edges with the effects set void AddData(StoryData* data); //character utilities bool AreAllCharactersSet() const; void ClearCharacters(); void SetCharacter(int charSlot, Character* charToSet); unsigned int GetNumCharacters() const; bool DoesCharacterMeetSlotRequirementsAtEdge(Character* character, unsigned int charSlot, StoryEdge* atEdge); CharacterRequirementSet* GetRequirementsForCharacter(Character* character); void SetCharacters(std::vector<Character*> characters); //returns whether or not the state described is compatible with this nodes incoming requirements bool IsCompatibleWithIncomingEdge(StoryState* edgeState); Character* GetCharacterFromDataString(std::string data); std::string ReadCharacterNameFromDataString(std::string data); void SetPosition(Vector2 pos); Vector2 GetPosition() const; bool operator==( const StoryData& compare ) const; bool operator!=( const StoryData& compare ) const; //actual members std::string m_id; std::string m_name; Action* m_action; StoryDataDefinition* m_definition = nullptr; //Strings m_actions; //detail nodes 4 now //Strings m_actionsWithCharacters; //detail nodes 4 now //std::vector<CharacterRequirementSet*> m_characterReqs; //StoryRequirements m_storyReqs; //EffectSet* m_effectSet; //test bits //float m_value; //generation info mutable std::string m_actionWithCharacters; //mutable to update in GetString eNodeType m_type; unsigned int m_numCharacters; std::vector<Character*> m_characters; Vector2 m_graphPosition = Vector2::HALF; };
true
02dad4b3c27174379ae9316864da7c9666a8e341
C++
PaniQue7/AlgorithmStudy
/0512/1005_MWK.cc
UTF-8
1,182
2.734375
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; vector<int> times; vector<vector<int> > depend; vector<int> dp; void dfs(int node) { if(depend[node].empty()) { dp[node] = times[node]; } else { for(int i = 0; i < depend[node].size(); i++) { if(dp[depend[node][i]] == -1) { dfs(depend[node][i]); } int m = times[node] + dp[depend[node][i]]; if(dp[node] < m) dp[node] = m; } } } int main(void) { int games; cin >> games; while(games--) { int n, k; cin >> n >> k; times.clear(); depend.clear(); dp.clear(); times.resize(n + 1); depend.resize(n + 1); dp.resize(n + 1, -1); for(int i = 1; i <= n; i++) { cin >> times[i]; } for(int i = 1; i <= k; i++) { int from, to; cin >> from >> to; depend[to].push_back(from); } int target; cin >> target; dfs(target); cout << dp[target] << "\n"; } }
true
43eae219b47dcc368e3ceac3e88374c4f0482339
C++
shyaZhou/Design-Patterns
/06CommandPattern/02/CeilingFanMediumCommand.h
UTF-8
784
2.8125
3
[]
no_license
#ifndef _CEILINGFANMediumCOMMAND_H_ #define _CEILINGFANMediumCOMMAND_H_ #include "Command.h" #include "CeilingFan.h" class CeilingFanMediumCommand : public Command { public: CeilingFanMediumCommand(CeilingFan *ceilingFan) : Command("CeilingFanMeidumCommand"), _ceilingFan(ceilingFan) {} void execute() override { _prevSpeed = _ceilingFan->getSpeed(); _ceilingFan->medium(); } void undo() override { if(_prevSpeed == CeilingFan::HIGH) _ceilingFan->high(); else if(_prevSpeed == CeilingFan::MEDIUM) _ceilingFan->medium(); else if(_prevSpeed == CeilingFan::LOW) _ceilingFan->low(); else if(_prevSpeed == CeilingFan::OFF) _ceilingFan->off(); } private: CeilingFan *_ceilingFan; int _prevSpeed; }; #endif
true
635f730468ab96353cd4a3d84696896a9b110617
C++
yuriykulikov/Abandoned-xmega_cpp_example
/drivers/Leds.h
UTF-8
1,411
2.578125
3
[]
no_license
/* This file has been prepared for Doxygen automatic documentation generation.*/ /* * Copyright (C) 2012 Yuriy Kulikov * Universitaet Erlangen-Nuernberg * LS Informationstechnik (Kommunikationselektronik) * Support email: Yuriy.Kulikov.87@googlemail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LEDGROUP_H_ #define LEDGROUP_H_ #include "avr_compiler.h" /* Group of leds */ class LedGroup { private: uint8_t amountOfLeds; PORT_t ** ports; uint8_t *bitmasks; public: LedGroup(uint8_t maxAmountOfLeds); void add(PORT_t * port, uint8_t bitmask, uint8_t isActiveLow); void set(uint8_t bitmask); }; /* * Assume that RGB led is a led group of 3 leds, * then colors are bitmasks. */ typedef enum { RED = 0x01, GREEN = 0x02, BLUE= 0x04, ORANGE = 0x03, PINK = 0x05, SKY = 0x06, WHITE = 0x07, NONE = 0x00, } Color_enum; #endif /* LEDGROUP_H_ */
true
c815e30f5c83b07853769b16b5ba8bb409610cee
C++
wonkicho/algoStudy
/Algorithm/Algorithm/2.cpp
UTF-8
318
2.984375
3
[]
no_license
//#include <iostream> //using namespace std; // //int recur(int x) //{ // if (x >= 2) { // x *= recur(x - 1); // return x; // } // else { // return 1; // } //} // //int main() //{ // int num; // cin >> num; // int result = recur(num); // cout << result; // return 0; //}
true
f1f942ec9f86daf4ed91329fc42c96daafa53581
C++
QingQiu0215/RiskGame
/StrategyBox.cpp
UTF-8
488
2.515625
3
[]
no_license
#include <iostream> #include "Strategy.h" #include "StrategyBox.h" using namespace std; StrategyBox::StrategyBox() {}; StrategyBox::StrategyBox(Strategy *initStrategy) { this->strategy = initStrategy; } void StrategyBox::setStrategyBox(Strategy *newStrategy) { this->strategy = newStrategy; } void StrategyBox::execute(vector <Player*> allPlayers, Deck* deckPtr, int armyQty_startup,int playerNum) { return this->strategy->execute(allPlayers, deckPtr, armyQty_startup,playerNum); }
true
754236d0ef1deba2f43c31e521dd39520af97b8a
C++
Einstein10-Carson/Project-Einstein2
/main--.cpp
UTF-8
303
2.796875
3
[]
no_license
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { int n; int m; n = 5; m =5; for( int i=0; i<n; i++) { for(int j=0; j<m; j++) { std::cout<<"a[i][j]"; } } return 0; }
true
15f4e5a8dab93cdefbfe3443a7a0854883b48055
C++
kartikeysingh6/OpenCVProjects
/EqualSumParti.cpp
UTF-8
888
3.515625
4
[]
no_license
//We're given an array and we've to tell if it's possible to equally divide it or not #include <bits/stdc++.h> using namespace std; int static t[101][1001]; //Subsetsum memoized code int subsetSum(int*arr,int n,int sum){ if(sum==0) return 1; if(n==0) return 0; if(t[n][sum]!=-1) return t[n][sum]; if(arr[n-1]>sum) return t[n][sum]=subsetSum(arr,n-1,sum); else return t[n][sum]=subsetSum(arr,n-1,sum-arr[n-1]) || subsetSum(arr,n-1,sum); } int EqualSumPart(int *arr,int n){ //sum of all elements int sum=0; for(int i=0;i<n;i++) sum+=arr[i]; //we can make two equal halves iff it's even if(sum%2!=0) return 0; //if it's even then do subsetsum for sum/2 return subsetSum(arr,n,sum/2); } int main(){ memset(t,-1,sizeof(t)); int arr[]={1,5,11,5}; int n=sizeof(arr)/sizeof(arr[0]); cout<<EqualSumPart(arr,n); }
true
ba1e7ff0f2a76228415f1fd44a3d5b482ed5315d
C++
Siddu96/CPP_11
/19_Tuple/02_tupleSwap.cpp
UTF-8
1,754
4.21875
4
[]
no_license
// C++ code to demonstrate tuple, get() and make_pair() #include<iostream> #include<tuple> // for tuple int main() { // Declaring tuple //std::tuple <data_type1, data_type2, data_type3> tuple_name = std::make_tuple(data1, data2, data3); //std::tuple <char, int, float> geek = std::make_tuple('a', 10, 15.5); std::tuple <char, int, float> geek('a', 10, 15.5); std::tuple <char, int, float> geek1('z', 90, 16.75); // Assigning values to tuple using make_tuple() //geek = make_tuple('a', 10, 15.5); // Printing initial tuple values using get() std::cout << "The initial values of tuple01 are : "; std::cout << std::get<0>(geek) << " " << std::get<1>(geek); std::cout << " " << std::get<2>(geek) << std::endl; std::cout << "The initial values of tuple02 are : "; std::cout << std::get<0>(geek1) << " " << std::get<1>(geek1); std::cout << " " << std::get<2>(geek1) << std::endl; // Swaping the elements of the tuple geek.swap(geek1); std::cout << "After swapping" << std::endl; // Printing modified tuple values std::cout << "The swaped values of tuple01 are : "; std::cout << std::get<0>(geek) << " " << std::get<1>(geek); std::cout << " " << std::get<2>(geek) << std::endl; std::cout << "The swaped values of tuple02 are : "; std::cout << std::get<0>(geek1) << " " << std::get<1>(geek1); std::cout << " " << std::get<2>(geek1) << std::endl; std::cout << "\nThe size of the tuple is: "; // auto : makes compiler intefer types // decltype : makes compiler evaluate expression std::cout << std::tuple_size<decltype(geek)>::value << " size denote the number of elements in tuple" << std::endl; return 0; }
true
b4c631e45990387d2cf48d3df634c31fe05b51db
C++
wei15987/CS335_HashTable
/Wei.Lian_CS335_Project3/separate_chaining.h
UTF-8
3,367
3.046875
3
[]
no_license
/******************************************************************************* Title : separate_chaining.h Author : Wei Lian Created on : April 7, 2018 Description : Implementation to the HashSeparateChaining class with interface Purpose : Usage : Build with : Modifications : *******************************************************************************/ #ifndef SEPARATE_CHAINING_H #define SEPARATE_CHAINING_H #include <vector> #include <list> #include <string> #include <algorithm> #include <functional> using namespace std; #include "is_prime.h" // SeparateChaining Hash table class // // CONSTRUCTION: an approximate initial size or default of 101 // // ******************PUBLIC OPERATIONS********************* // bool insert( x ) --> Insert x // bool remove( x ) --> Remove x // bool contains( x ) --> Return true if x is present // void makeEmpty( ) --> Remove all items template <typename HashedObj> class HashSeparateChaining { public: explicit HashSeparateChaining(int size = 101000) : current_size_{0} { the_lists_.resize( 101000 ); } void check(const HashedObj &x) { auto &which_list=the_lists_[MyHash(x)]; cout<<"the lists are : "<<endl; for(auto &lol:which_list) cout<<lol<<endl; } bool Contains( const HashedObj & x ) const { auto & which_list = the_lists_[ MyHash( x ) ]; return find( begin( which_list ), end( which_list ), x ) != end( which_list ); } void MakeEmpty( ) { for( auto & this_list : the_lists_ ) this_list.clear( ); } bool Insert( const HashedObj & x,const HashedObj & y) { auto & which_list = the_lists_[ MyHash( x ) ]; if( find( begin( which_list ), end( which_list ), y ) != end( which_list) ) return false; which_list.push_back( y ); // Rehash; see Section 5.5 if( ++current_size_ > the_lists_.size( )/2 ) Rehash( ); return true; } bool Insert( HashedObj && x, HashedObj &&y ) { auto & which_list = the_lists_[ MyHash( x ) ]; if( find( begin( which_list ), end( which_list ), y ) != end( which_list ) ) return false; which_list.push_back( std::move( y ) ); // Rehash; see Section 5.5 if( ++current_size_ > the_lists_.size( )/2 ) Rehash( ); return true; } bool Remove( const HashedObj & x ) { auto & which_list = the_lists_[ MyHash( x ) ]; auto itr = find( begin( which_list ), end( which_list ), x ); if( itr == end( which_list ) ) return false; which_list.erase( itr ); --current_size_; return true; } private: vector<list<HashedObj>> the_lists_; int current_size_; void Rehash( ) { vector<list<HashedObj>> old_lists = the_lists_; int old_size_=current_size_; // Create new double-sized, empty table the_lists_.resize( PrimeProject::NextPrime( 2 * the_lists_.size( ) ) ); for(auto &this_list:the_lists_) { this_list.clear(); } current_size_=0; for(auto &this_list:old_lists) { the_lists_.push_back(this_list); } current_size_=old_size_; // Copy table over*/ } size_t MyHash( const HashedObj & x ) const { static hash<HashedObj> hf; return hf( x ) % the_lists_.size( ); } }; #endif
true
cbc41327d68f2cb5ab66ed1e3b82bd85fda8ab9d
C++
slopezv2/CompetitiveProgramming
/subsum.cpp
UTF-8
849
2.984375
3
[]
no_license
#include<sstream> #include<iostream> #include<string> using namespace std; #define D(x) cout<<#x<< " "<<x<<endl; int main(){ string line; string result =""; while(getline(cin, line)){ stringstream ss; ss<< line; int size, target, i = 0; ss>>size>>target; int array [size] ; getline(cin, line); stringstream sc; sc << line; while(i < size){ int value; sc >> value; array[i] = value;; i++; } int sum = 0,x,y;bool stop = false; for(int i = 0; i < size; i++){ sum = 0; for(int j = i; j < size; j++){ sum += array[j]; if(sum == target){ x = i;y = j;stop = true; break; } if(sum > target) break; } if(stop)break; } if(stop){ result += to_string(x+1) + " " + to_string(y +1) + "\n"; }else{ result += "-1\n"; } } cout<<result; }
true
ab71428c54657d1f87851179eeceb446b8fb797f
C++
Jacobsky98/OOP_WFIIS_2019
/LATO19_GR5_WK6/Pojazd.h
UTF-8
371
2.546875
3
[]
no_license
#pragma once #include <iostream> #include <string> #include "PredkoscMaksymalna.h" class Pojazd : public PredkoscMaksymalna{ public: friend std::ostream& operator<<(std::ostream& o, const Pojazd& p); virtual std::string name() const = 0; virtual ~Pojazd() = default; }; std::ostream& operator<<(std::ostream& o, const Pojazd& p){ return o << p.name(); }
true
232d71e1a9a79317c546b78804ee0ae8aba182df
C++
Graphics-Physics-Libraries/Tiny3D
/Win32Project1/model/mtlloader.cpp
UTF-8
1,775
2.796875
3
[]
no_license
#include "mtlloader.h" #include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include "../assets/assetManager.h" #include "../material/materialManager.h" using namespace std; MtlLoader::MtlLoader(const char* mtlPath) { mtlFilePath=mtlPath; mtlCount=0; readMtlInfo(); readMtlFile(); } MtlLoader::~MtlLoader() { objMtls.clear(); } void MtlLoader::readMtlInfo() { ifstream infile(mtlFilePath); string sline; while(getline(infile,sline)) { if(sline[0]=='n'&&sline[1]=='e')//newmtl mtlCount++; } infile.close(); } void MtlLoader::readMtlFile() { ifstream infile(mtlFilePath); string sline; int n=0,t=0,d=0,a=0,s=0; string value,name,texture; float red=0,green=0,blue=0; Material* mtl=NULL; while(getline(infile,sline)) { if(sline!="") { istringstream ins(sline); ins>>value; if(value=="newmtl") { ins>>name; mtl = new Material(name.c_str()); objMtls[name] = MaterialManager::materials->add(mtl); n++; } else if(value=="map_Kd") { ins>>texture; if (mtl) { if (!AssetManager::assetManager->findTextureAtlasOfs(texture.c_str())) AssetManager::assetManager->addTexture2Alt(texture.c_str()); mtl->tex1 = texture; } t++; } else if(value=="Kd") { ins>>red>>green>>blue; if(mtl) { mtl->diffuse.x=red; mtl->diffuse.y=green; mtl->diffuse.z=blue; } d++; } else if (value == "Ka") { ins >> red >> green >> blue; if (mtl) { mtl->ambient.x = red; mtl->ambient.y = green; mtl->ambient.z = blue; } a++; } else if (value == "Ks") { ins >> red >> green >> blue; if (mtl) { mtl->specular.x = red; mtl->specular.y = green; mtl->specular.z = blue; } s++; } } } infile.close(); }
true
a31364a86611a7e3b56061c106946453a3951c4c
C++
Mikalai/punk_project_a
/source/algorithm/incseq.cpp
UTF-8
1,006
3.015625
3
[]
no_license
#include <utility> #include <algorithm> #include <vector> #include <fstream> std::ifstream input("incseq.in"); std::ofstream output("incseq.out"); int g_n; std::vector<std::pair<int, int>> g_numbers; int main() { input >> g_n; g_numbers.resize(g_n); for (int i = 0; i < g_n; ++i) { input >> g_numbers[i].first; } int max_len = 1; for (int i = 0, max_i = g_numbers.size(); i < max_i; ++i) { g_numbers[i].second = 1; for (int j = 0; j < i; ++j) { if (g_numbers[i].first > g_numbers[j].first && g_numbers[i].second <= g_numbers[j].second) { g_numbers[i].second = g_numbers[j].second + 1; max_len = std::max(g_numbers[i].second, max_len); } } } std::vector<int> result; for (int i = g_numbers.size() - 1; i >= 0; --i) { if (g_numbers[i].second == max_len) { result.push_back(g_numbers[i].first); max_len--; } } output << result.size() << std::endl; for (auto v = result.rbegin(); v != result.rend(); ++v) { output << *v << ' '; } output << std::endl; }
true
f8f0514e0f0bebf5f210b6bf8397130c05e3cddf
C++
scylla-zpp-blas/linear-algebra
/tests/blas_level_1/vector_const_op.cc
UTF-8
9,156
3.1875
3
[ "Apache-2.0" ]
permissive
#include <cmath> #include <boost/test/unit_test.hpp> #include "../test_utils.hh" #include "../fixture.hh" #include "../vector_utils.hh" BOOST_FIXTURE_TEST_CASE(vector_dot_float, vector_fixture) { // Given two vector of five values. std::vector<float> values1 = {4.234f, 3214.4243f, 290342.0f, 0.0f, -1.0f}; std::vector<float> values2 = {3.0f, 392.9001f, 0.005f, 5.0f, 29844.05325811f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); auto vector2 = getScyllaVectorOf(test_const::float_vector_2_id, values2); // When performing dot product of these two vectors. float res = scheduler->sdot(*vector1, *vector2); float sum = 0; for (int i = 0; i < values1.size(); i++) { sum += values1[i] * values2[i]; } print_vector(*vector1); print_vector(*vector2); std::cout << std::setprecision(20) << sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the dot product is correctly calculated and equal to sum. BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_dot_float_same_obj, vector_fixture) { // Given one vector of five values. std::vector<float> values1 = {4.234f, 214.4243f, 342.0f, 0.0f, -1.0f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); // When performing dot product of this vector x this vector. float res = scheduler->sdot(*vector1, *vector1); float sum = 0; for (float v : values1) { sum += v * v; } std::cout << std::setprecision(20) << sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the dot product is correctly calculated and equal to sum. BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_sdsdot_float, vector_fixture) { // Given two vector of five values. std::vector<float> values1 = {4.234f, 3214.4243f, 290342.0f, 0.0f, -1.0f}; std::vector<float> values2 = {3.0f, 392.9001f, 0.005f, 5.0f, 29844.05325811f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); auto vector2 = getScyllaVectorOf(test_const::float_vector_2_id, values2); // When performing dot product of double precision plus value // of these two vectors. float res = scheduler->sdsdot(0.5f, *vector1, *vector2); double sum = 0.5f; for (int i = 0; i < values1.size(); i++) { sum += (double)values1[i] * (double)values2[i]; } std::cout << std::setprecision(20) << sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the dot product is correctly calculated and equal to sum + value. BOOST_CHECK(std::abs((float)sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_dsdot_float, vector_fixture) { // Given two vector of five values. std::vector<float> values1 = {4.234f, 3214.4243f, 290342.0f, 0.0f, -1.0f}; std::vector<float> values2 = {3.0f, 392.9001f, 0.005f, 5.0f, 29844.05325811f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); auto vector2 = getScyllaVectorOf(test_const::float_vector_2_id, values2); // When performing dot product with double precision of these two vectors. double res = scheduler->dsdot(*vector1, *vector2); double sum = 0.0f; for (int i = 0; i < values1.size(); i++) { sum += (double)values1[i] * (double)values2[i]; } std::cout << std::setprecision(20) << sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the dot product is correctly calculated and equal to sum. BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_dot_double, vector_fixture) { // Given two vector of five values. std::vector<double> values1 = {4.234, 3214.4243, 290342.0, 0.0, -1.0}; std::vector<double> values2 = {3.0, 392.9001, 0.005, 5.0, 29844.05325811}; auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1); auto vector2 = getScyllaVectorOf(test_const::double_vector_2_id, values2); // When performing dot product of these two vectors. double res = scheduler->ddot(*vector1, *vector2); double sum = 0; for (int i = 0; i < values1.size(); i++) { sum += values1[i] * values2[i]; } std::cout << std::setprecision(20) << sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the dot product is correctly calculated and equal to sum. BOOST_CHECK(std::abs(sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_norm_float, vector_fixture) { // Given vector of some values. std::vector<float> values1 = {0.00494931f, 0.119193f, 0.927604f, 0.354004f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); // When performing vector euclidean norm. float res = scheduler->snrm2(*vector1); float nrm = 0; for (float v : values1) { nrm += v * v; } nrm = std::sqrt(nrm); std::cout << std::setprecision(20) << nrm << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the norm is correctly calculated and equal to nrm. BOOST_CHECK(std::abs(nrm - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_sasum_float, vector_fixture) { // Given vector of some values. std::vector<float> values1 = {0.00494931f, 0.119193f, -0.927604f, 0.354004f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); // When performing sum of absolute values in this vector. float res = scheduler->sasum(*vector1); float abs_sum = 0; for (float v : values1) { abs_sum += std::abs(v); } std::cout << std::setprecision(20) << abs_sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then it is correctly calculated and equal to sum. BOOST_CHECK(std::abs(abs_sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_isamax_float, vector_fixture) { // Given vector of some values. std::vector<float> values1 = {0.00494931f, 0.119193f, -0.927604f, 0.354004f}; auto vector1 = getScyllaVectorOf(test_const::float_vector_1_id, values1); // When performing max fetch on the abs values in this vector. scylla_blas::index_t res = scheduler->isamax(*vector1); scylla_blas::index_t max_index = 0; for (scylla_blas::index_t i = 1; i < values1.size(); i++) { if (std::abs(values1[i]) > std::abs(values1[max_index])) { max_index = i; } } std::cout << std::setprecision(20) << values1[max_index] << "=sum\n"; std::cout << res << "=res index\n"; // Then the found index corresponds to the index of largest absolute value's index. BOOST_CHECK(max_index + 1 == res); } BOOST_FIXTURE_TEST_CASE(vector_norm_double, vector_fixture) { // Given vector of some values. std::vector<double> values1 = {0.00494931, 0.119193, 0.927604, 0.354004}; auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1); // When performing vector euclidean norm. double res = scheduler->dnrm2(*vector1); double nrm = 0; for (double i : values1) { nrm += i * i; } nrm = sqrt(nrm); std::cout << std::setprecision(20) << nrm << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then the norm is correctly calculated and equal to nrm. BOOST_CHECK(std::abs(nrm - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_dasum_double, vector_fixture) { // Given vector of some values. std::vector<double> values1 = {0.00494931, 0.119193, -0.927604, 0.354004}; auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1); // When performing sum of absolute values in this vector. double res = scheduler->dasum(*vector1); double abs_sum = 0; for (double v : values1) { abs_sum += std::abs(v); } std::cout << std::setprecision(20) << abs_sum << "=sum\n"; std::cout << std::setprecision(20) << res << "=res\n"; // Then it is correctly calculated and equal to sum. BOOST_CHECK(std::abs(abs_sum - res) < scylla_blas::epsilon); } BOOST_FIXTURE_TEST_CASE(vector_idamax_double, vector_fixture) { // Given vector of some values. std::vector<double> values1 = {0.00494931, 0.119193, -0.927604, 0.354004}; auto vector1 = getScyllaVectorOf(test_const::double_vector_1_id, values1); // When performing max fetch on the abs values in this vector. scylla_blas::index_t res = scheduler->idamax(*vector1); scylla_blas::index_t max_index = 0; for (scylla_blas::index_t i = 1; i < values1.size(); i++) { if (std::abs(values1[i]) > std::abs(values1[max_index])) { max_index = i; } } std::cout << std::setprecision(20) << values1[max_index] << "=sum\n"; std::cout << max_index << "=max_index\n"; std::cout << res << "=res index\n"; // Then the found index corresponds to the index of largest absolute value's index. BOOST_CHECK(max_index + 1 == res); }
true
854f46bcd65540d23418e969c8ad2c1cb51c2ad8
C++
DimitarYordanov17/Space_Challenges_2021_Ground_Station
/Arduino Sketches/serialRead/serialRead.ino
UTF-8
1,964
3.1875
3
[]
no_license
/* 05.10.2020 * The stepper goes reverse and forward with different speed. * The maximum speed of the current model is around 14 RPM. * - 2 miliseconds delay means -> 2 * 2048 = 4096 ms for 1 rev. * 60/(4096/1000) = 14.64 RPM with 2 ms delay; [measured ~=14.15 rpm forward ~= 14.38 rpm backwards] * - 3 ms delay -> 3*2048 = 6144 ms for 1 rev; * 60/6.144 = 9.76 RPM with 3 ms delay */ #include "StepperMotor.h" #define STEPPER_PIN_1 10 #define STEPPER_PIN_2 9 #define STEPPER_PIN_3 6 #define STEPPER_PIN_4 5 long timeVar = 0; long prevMillis = 0; long millisPrint = 0; StepperMotor StepMotor; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); StepMotor.initStepper(STEPPER_PIN_1, STEPPER_PIN_2,STEPPER_PIN_3, STEPPER_PIN_4); } double az = 0; double el = 0; bool azimuthdone = false; void loop() { // put your main code here, to run repeatedly: if (Serial.available() >0){ // digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) // delay(1000); // wait for a second // digitalWrite(LED_BUILTIN, LOW); String s = Serial.readString(); String s1 = s.substring(0,s.indexOf(",")); String s2 = s.substring(s.indexOf(",")+1); az = s1.toDouble(); //azimuth el = s2.toDouble(); //elevation Serial.print("az: "); Serial.println(az); Serial.print("el: "); Serial.println(el); // The code belows rotates the servo 2 times with the maximum speed(2ms between step) // then it rotates reverse with same speed /* StepMotor.rotateSteps(true, 1024, 4); delay(2000); */ } if(abs(az)>0){ az-=11.0/64*(az>0?1:-1); StepMotor.rotateSteps(az>0,1,4); delay(1); } else if (abs(el)>0) { if (!azimuthdone){ delay(1000); azimuthdone=true; } el-=11.0/64*(el>0?1:-1); StepMotor.rotateSteps(el>0,1,4); delay(1); } }
true
ea4e3d383f71523a0f7beb5d1b04f35c7d34cad3
C++
Haar-you/kyopro-lib
/Mylib/DataStructure/FenwickTree/fenwick_tree_2d.cpp
UTF-8
1,783
3.140625
3
[]
no_license
#pragma once #include <cassert> #include <vector> namespace haar_lib { template <typename AbelianGroup> class fenwick_tree_2d { public: using value_type = typename AbelianGroup::value_type; private: AbelianGroup G_; int w_, h_; std::vector<std::vector<value_type>> data_; private: value_type get_w(int i, int y) const { value_type ret = G_(); while (i > 0) { ret = G_(ret, data_[i][y]); i -= i & (-i); } return ret; } value_type get_w(int l, int r, int y) const { return G_(get_w(r, y), G_.inv(get_w(l, y))); } value_type get(int x1, int x2, int y) const { value_type ret = G_(); while (y > 0) { ret = G_(ret, get_w(x1, x2, y)); y -= y & (-y); } return ret; } public: fenwick_tree_2d() {} fenwick_tree_2d(int width, int height) : w_(width), h_(height), data_(w_ + 1, std::vector<value_type>(h_ + 1, G_())) {} value_type fold(std::pair<int, int> p1, std::pair<int, int> p2) const { const auto [x1, y1] = p1; const auto [x2, y2] = p2; assert(0 <= x1 and x1 <= x2 and x2 <= w_); assert(0 <= y1 and y1 <= y2 and y2 <= h_); return G_(get(x1, x2, y2), G_.inv(get(x1, x2, y1))); } value_type operator[](std::pair<int, int> p) const { const auto [x, y] = p; return fold({x, y}, {x + 1, y + 1}); } void update(std::pair<int, int> p, const value_type &val) { auto [x, y] = p; assert(0 <= x and x < w_); assert(0 <= y and y < h_); x += 1; y += 1; for (int i = x; i <= w_; i += i & (-i)) { for (int j = y; j <= h_; j += j & (-j)) { data_[i][j] = G_(data_[i][j], val); } } } }; } // namespace haar_lib
true
ba14ef069488d5f2018f723519847ff8ab986251
C++
DingZhan/CCF_NOI
/1111 Blash数集(2).cpp
UTF-8
661
2.609375
3
[]
no_license
#include <iostream> #include <queue> #include <vector> #include <algorithm> #include <set> using namespace std; int main() { long long a, n, last; while(cin>>a>>n) { set<long long> nums; set<long long>::iterator iter; nums.insert(a); iter = nums.begin(); while(nums.size()<=2*n) { a = *iter; nums.insert(2*a+1); nums.insert(3*a+1); ++iter; } for(iter=nums.begin(); iter!=nums.end() && n>0; ++iter) { a = *iter; // cout<<a<<endl; --n; } cout<<a<<endl; } return 0; }
true
cf6c1aae97fd662a8153039e5fb58ca99555eb48
C++
vimtaai/elte
/2017-18-1/pa-3/gyak06b/main.cpp
ISO-8859-2
1,676
2.734375
3
[]
no_license
#include <iostream> using namespace std; int main() { const int MAXN = 32; // Be string mondat; // Ki int magasdb, melydb, vegyesdb; // Beolvasas getline(cin, mondat); string szavak[MAXN]; int szoszam = 0; for(int i = 0; i < mondat.length(); ++i) { if (mondat[i] == ' ') { ++szoszam; } else { szavak[szoszam] += mondat[i]; } } //cout << szoszam + 1 << endl; // Megszmols magasdb = 0; for (int i = 0; i <= szoszam; ++i) { // Eldnts bool magase; int j = 0; while (j < szavak[i].length() && szavak[i][j] != 'a' && szavak[i][j] != 'o' && szavak[i][j] != 'u') { ++j; } magase = (j == szavak[i].length()); // Eldnts vge if (magase) { ++magasdb; } } cout << "Magas hangrendu: " << magasdb << endl; // Megszmols melydb = 0; for (int i = 0; i <= szoszam; ++i) { // Eldnts bool melye; int j = 0; while (j < szavak[i].length() && szavak[i][j] != 'e' && szavak[i][j] != 'i') { ++j; } melye = (j == szavak[i].length()); // Eldnts vge if (melye) { ++melydb; } } cout << "Mely hangrendu: " << melydb << endl; cout << "Vegyes hangrendu: " << szoszam + 1 - magasdb - melydb << endl; // for (int i = 0; i <= szoszam; ++i) // { // cout << szavak[i] << endl; // } return 0; }
true
7e728e722000b43450c714d355dd0866bfa5e4ac
C++
Draketuroth/Lilla-Spelprojektet-Grupp-2
/Window.cpp
IBM852
7,461
3.015625
3
[]
no_license
#include "Window.h" #include <iostream> bool WindowInitialize(HWND &windowHandle) { // HINSTANCE is a handle to an instance. This is the base address of the module in memory and handles the instance of the module to be associated with the window. HINSTANCE applicationHandle = GetModuleHandle(NULL); if (applicationHandle == NULL) { // If GetModuleHandle fails, there is no application handle for us to use. The WindowInitialize function returns false and // sends an error message to the console as a string cout << "Window Handle Error: Application handle could not be retrieved due to the following error\n" << "Error Code: " << GetLastError() << endl; return false; } // Load cursor bitmap HBITMAP hSourceBitmap = (HBITMAP)LoadImage(0, L"Format\\Textures\\cursor.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); if (!hSourceBitmap){ return false; } // Create cursor from the loaded bitmap HCURSOR crossHairCursor = CreateCursorFromBitmap(hSourceBitmap, RGB(0, 0, 0), 0, 0); WNDCLASSEX windowClass = { 0 }; // We start by registering the window class to be used to specify both the behavior and appearence of the window windowClass.style = CS_HREDRAW | CS_VREDRAW; // We require this to specify this option if height or width is ever changed by the user windowClass.lpfnWndProc = WindowProcedure; // Pointer to the callback function defined in the "Windows Function Forward Declarations" section windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.hInstance = applicationHandle; // Handle to the instance holding the window procedure windowClass.hIcon = LoadIcon(0, IDI_APPLICATION); // Load the default window icon windowClass.hCursor = crossHairCursor; // Load the default arrow curser windowClass.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)); // HBRUSH can be used to set the background color of the window windowClass.lpszMenuName = NULL; // The window has no menu windowClass.lpszClassName = L"WindowClass"; // Name for the window class if (!RegisterClassEx(&windowClass)) { // If registration of the window class fails, then the window can't be created. The WindowInitialize function returns false and // sends an error message to the console as a string cout << "Window Class Registration Error: Window Class could not be registered due to the following error\n" << "Error Code: " << GetLastError() << endl; return false; } SetCursor(crossHairCursor); RECT wRC = { 0, 0, WIDTH, HEIGHT }; AdjustWindowRect(&wRC, WS_OVERLAPPEDWINDOW, FALSE); windowHandle = CreateWindow( L"WindowClass", // The name of the previously defined window class (Wide string, 16 bit) L"Litet Spel Projekt", // Text to display at the window title bar (Wide string, 16 bit) WS_OVERLAPPEDWINDOW, //The window style is an overlapped window. An overlapped window has a title bar and a border. CW_USEDEFAULT, // The window's x position in pixels from the monitor's upper left corner CW_USEDEFAULT, // The window's y position in pixels from the monitor's upper left corner wRC.right - wRC.left, // Window width in pixels defined in "Global Window Variables" wRC.bottom - wRC.top, // Windiw height in pixels defined in "Global Window Variables" NULL, // Here we would normally set the parent, but we only have one window NULL, // Since the window class isn't using a menu, we dont have a handle to it applicationHandle, // Handle to the application containing the window NULL // Information that we can send to the WM_CREATE message through its lParam member ); if (windowHandle == NULL) { cout << "Window Handle Error: Window Handle was not valid and window couldn't be created due to the following error\n" << "Error Code: " << GetLastError() << endl; return false; } // The window doesn't show by default, so we must call for it and update it by using the following functions SetCapture(windowHandle); ShowWindow(windowHandle, SW_SHOWDEFAULT); UpdateWindow(windowHandle); return true; } void showFPS(HWND windowHandle, float deltaTime) { static int interval; int fpsCounter = 1.0f / deltaTime; stringstream text_FPS; text_FPS << "FPS: " << fpsCounter << endl; interval++; if (interval == 200) { SetWindowTextA(windowHandle, text_FPS.str().c_str()); interval = 0; } } void GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, HBITMAP &hAndMaskBitmap, HBITMAP &hXorMaskBitmap) { HDC hDC = ::GetDC(NULL); HDC hMainDC = ::CreateCompatibleDC(hDC); HDC hAndMaskDC = ::CreateCompatibleDC(hDC); HDC hXorMaskDC = ::CreateCompatibleDC(hDC); //Get the dimensions of the source bitmap BITMAP bm; ::GetObject(hSourceBitmap, sizeof(BITMAP), &bm); hAndMaskBitmap = ::CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); hXorMaskBitmap = ::CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); //Select the bitmaps to DC HBITMAP hOldMainBitmap = (HBITMAP)::SelectObject(hMainDC, hSourceBitmap); HBITMAP hOldAndMaskBitmap = (HBITMAP)::SelectObject(hAndMaskDC, hAndMaskBitmap); HBITMAP hOldXorMaskBitmap = (HBITMAP)::SelectObject(hXorMaskDC, hXorMaskBitmap); //Scan each pixel of the souce bitmap and create the masks COLORREF MainBitPixel; for (int x = 0; x<bm.bmWidth; ++x) { for (int y = 0; y<bm.bmHeight; ++y) { MainBitPixel = ::GetPixel(hMainDC, x, y); if (MainBitPixel == clrTransparent) { ::SetPixel(hAndMaskDC, x, y, RGB(255, 255, 255)); ::SetPixel(hXorMaskDC, x, y, RGB(0, 0, 0)); } else { ::SetPixel(hAndMaskDC, x, y, RGB(0, 0, 0)); ::SetPixel(hXorMaskDC, x, y, MainBitPixel); } } } ::SelectObject(hMainDC, hOldMainBitmap); ::SelectObject(hAndMaskDC, hOldAndMaskBitmap); ::SelectObject(hXorMaskDC, hOldXorMaskBitmap); ::DeleteDC(hXorMaskDC); ::DeleteDC(hAndMaskDC); ::DeleteDC(hMainDC); ::ReleaseDC(NULL, hDC); } HCURSOR CreateCursorFromBitmap(HBITMAP hSourceBitmap, COLORREF clrTransparent, DWORD xHotspot, DWORD yHotspot) { HCURSOR hRetCursor = NULL; do { if (NULL == hSourceBitmap) { break; } //Create the AND and XOR masks for the bitmap HBITMAP hAndMask = NULL; HBITMAP hXorMask = NULL; GetMaskBitmaps(hSourceBitmap, clrTransparent, hAndMask, hXorMask); if (NULL == hAndMask || NULL == hXorMask) { break; } //Create the cursor using the masks and the hotspot values provided ICONINFO iconinfo = { 0 }; iconinfo.fIcon = FALSE; iconinfo.xHotspot = xHotspot; iconinfo.yHotspot = yHotspot; iconinfo.hbmMask = hAndMask; iconinfo.hbmColor = hXorMask; hRetCursor = ::CreateIconIndirect(&iconinfo); } while (0); return hRetCursor; } LRESULT CALLBACK WindowProcedure(HWND windowHandle, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: // This case only happens when the user presses the window's close button PostQuitMessage(0); // We post a WM_QUIT message with the exit code 0 break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) { PostQuitMessage(0); break; } default: // If a message has not been handled, meaning the window is still open, we sent it to our default window procedure for handling return DefWindowProc(windowHandle, message, wParam, lParam); } return 0; }
true
04040ab741f558cebbf567e12d4be0f7a3d78380
C++
superstylin04/Stacer
/stacer-core/Info/disk_info.cpp
UTF-8
690
2.671875
3
[ "MIT" ]
permissive
#include "disk_info.h" #include <QDebug> DiskInfo::DiskInfo() { } QList<Disk> DiskInfo::getDisks() const { return disks; } void DiskInfo::updateDiskInfo() { try { QStringList result = CommandUtil::exec("df -Pl").split(QChar('\n')); QRegExp sep("\\s+"); for (const QString &line : result.filter(QRegExp("^/"))) { Disk disk; QStringList slist = line.split(sep); disk.size = slist.at(1).toLong() << 10; disk.used = slist.at(2).toLong() << 10; disk.free = slist.at(3).toLong() << 10; disks << disk; } } catch (QString &ex) { qCritical() << ex; } }
true
ad5684a5a7bc0b7c5f4bc5aa88792f2ea74c6df8
C++
wgbusch/laboalgo2num2
/src/Diccionario.h
UTF-8
575
2.953125
3
[]
no_license
#ifndef __DICCIONARIO_H__ #define __DICCIONARIO_H__ #include <vector> using namespace std; typedef int Clave; typedef int Valor; class Diccionario { public: Diccionario(); void definir(Clave k, Valor v); bool def(Clave k) const; Valor obtener(Clave k) const; void borrar(Clave k); bool operator==(Diccionario d) const; vector<Clave> claves() const; public: struct Asociacion{ Clave clave; Valor valor; bool operator==(Asociacion a) const; bool operator<(Asociacion a) const; }; vector<Asociacion> _diccionario; }; #endif /*__DICCIONARIO_H__*/
true
58469a3e4d4b4a54df876e99ccb8dc1e4a1e84d5
C++
mdfarhansadiq/UVA-Online-Judge-Solutions
/UVA_10009.cpp
UTF-8
3,045
2.703125
3
[]
no_license
/*** _______________________________ MD. SYMON HASAN SHOHAN UNIVERSITY OF ASIA PACIFIC isymonhs@gmail.com _______________________________ */ #include<bits/stdc++.h> using namespace std; map < string, vector < string> > G; map < string, int> visited; map <string,string> previous; void BFS(string s) { queue <string> Q; Q.push(s); visited[s]=0; while(Q.empty()==false) { string u=Q.front(); Q.pop(); int sz=G[u].size(); for(int i=0; i<sz; i++) { string v=G[u][i]; if(visited[v]==-1) { visited[v]=visited[u]+1; previous[v]=u; Q.push(v); } } } } void solve() { int t; scanf("%d",&t); string s1,s2; while(t--) { G.clear(); int n,q; scanf("%d %d",&n,&q); while(n--) { cin>>s1>>s2; G[s1].push_back(s2); G[s2].push_back(s1); visited[s1]=-1; visited[s2]=-1; } /* //Graph Print map < string, vector < string> >::iterator gt; for(gt=G.begin();gt!=G.end();gt++) { cout<<"From "<<gt->first; for(int i=0;i<gt->second.size();i++) { cout<<" -> "<<gt->second[i]; } cout<<endl; } cout<<endl; //visited print map < string, int>::iterator iv; for(iv=visited.begin();iv!=visited.end();iv++) { cout<<iv->first<<" = "<<iv->second<<endl; } */ map < string, int>::iterator iv; while(q--) { for(iv=visited.begin(); iv!=visited.end(); iv++) { iv->second=-1; } cin>>s1>>s2; BFS(s1); /* //visited print for(iv=visited.begin(); iv!=visited.end(); iv++) { cout<<iv->first<<" = "<<iv->second<<endl; } cout<<endl;*/ /* //previous print map <string,string>::iterator p; for(p=previous.begin();p!=previous.end();p++) { cout<<p->first<< " <- " <<p->second<<endl; } cout<<endl; */ string temp=s2; vector <char> res; while(temp!=s1) { //cout<<temp<<" > "; res.push_back(temp[0]); temp=previous[temp]; } res.push_back(s1[0]); int sr=res.size(); for(int i=sr-1;i>=0;i--) { printf("%c",res[i]); } printf("\n"); res.clear(); previous.clear(); } if(t!=0) printf("\n"); } } int main() { //ios_base::sync_with_stdio(0);cin.tie(0); //freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); solve(); return 0; }
true
75bd5f1f1bea862509fcf196935a8571312cd6b2
C++
gpeal/Arduino
/libraries/TextStream/TextStream.h
UTF-8
1,696
2.875
3
[]
no_license
/* * TextStream.h * * Created on: 2012/08/07 * Author: sin */ #ifndef TEXTSTREAM_H_ #define TEXTSTREAM_H_ #if ARDUINO >= 100 #include <Arduino.h> #else #include <Wiring.h> #endif #include <Stream.h> // stdlib.h is included in Arduino.h const char endl = '\n'; const char cr = '\r'; const char tab = '\t'; template<class T> inline Stream &operator <<(Stream &stream, T arg) { stream.print(arg); return stream; } class TextStream : public Stream { Stream & stream; // char * sbuf; void printHex(const byte b); public: virtual inline size_t write(uint8_t b) { return stream.write(b); } using Print::write; virtual int available() { return stream.available(); } virtual inline int read() { return stream.read(); } virtual inline int peek() { return stream.peek(); } virtual void flush() { stream.flush(); } TextStream(Stream & s) : stream(s) { } ~TextStream() { } using Print::print; void printBytes(const byte * a, const int length, char gap = ' ', byte base = HEX); void printBytes(const char * s, const int length, char gap = 0x00); void printWords(const word * a, const int length, char gap = ' '); int readToken(char buf[], long timeout = 200); boolean readLine(char buf[], const int startidx, const int maxlen, const long wait = 10); inline boolean readLine(char buf[], const int maxlen, const long wait = 10) { return readLine(buf, 0 , maxlen, wait); } boolean concateLine(char buf[], const int maxlen, const long wait = 10); static int scanBytes(char * str, byte * result, const int maxlen, const byte base = HEX); static int ithToken(const char buf[], const int item, int & fromindex); }; #endif /* TEXTSTREAM_H_ */
true
bb09532bf72872ba0411f64a6a9b0b24dba2e398
C++
jab0079/COMP4300-P1
/include/Scoreboard.hh
UTF-8
3,300
2.515625
3
[]
no_license
#ifndef SCOREBOARD_HH #define SCOREBOARD_HH /* * * Scoreboard.hh * * Contributors: Adam Eichelkraut * Jared Brown * Contact: ake0005@tigermail.auburn.edu * jab0079@tigermail.auburn.edu * * Description: * This class defines the interface for the Scoreboard used * in the scoSim Simulator. * * Change Log: * 12/3/14 - Initial Creation * * */ #include <iostream> #include <vector> #include "Utilities.hh" #include "Instruction.hh" #include "FunctionalUnit.hh" class Instruction; struct InstructionStatus { u_int32_t instr_id; SCO_CYCLE curr_status; // current SCO_CYCL int32_t issue, // store cycle# for each stage read_op, exe_complete, write_result; }; struct FunctionalUnitStatus { bool busy, src1_rdy, src2_rdy; u_int32_t instr_id; // instead of opcode? u_int8_t dest, src1, src2; FU_ID fu_src1, fu_src2; }; class Scoreboard { public: //Constructors / Destructor ------------------------------------------- Scoreboard(); Scoreboard(const bool isPipelined); Scoreboard(const Scoreboard& other); virtual ~Scoreboard(); // Methods ------------------------------------------------------------ virtual void print_scoreboard(); virtual void add_instr_status(const u_int32_t& id, const int32_t& cycle); virtual bool check_FU_busy(FU_ID fu_id); virtual bool check_WAW(u_int8_t r_dest); virtual bool check_WAR(FU_ID fu_id, u_int8_t r_dest); virtual bool check_reg_result(u_int8_t r_dest_num, const FU_ID& fu_id); virtual bool check_range(u_int8_t r_num) const; virtual void update_fu_status_flags(const FU_ID& fu_id); virtual void reset_fu_status(const FU_ID& fu_id); virtual void propagate_piped_fu_status(const FU_ID& fu_id, bool stallfirst); // Gets and Sets------------------------------------------------------- virtual void set_instr_status(const u_int32_t& id, const SCO_CYCLE& new_status, const int32_t& cycle); virtual void set_fu_status(const FU_ID& fu_id, const Instruction& instr); virtual void set_reg_result(const u_int8_t& r_dest_num, const FU_ID& fu_id); virtual void set_fu_count(const u_int32_t& new_fu_count); virtual void set_isPipelined(const bool& isPiped); virtual InstructionStatus get_instr_status(const u_int32_t& inst_id) const; virtual FunctionalUnitStatus get_fu_status(const FU_ID& fu_id) const; virtual FU_ID get_reg_result(const u_int8_t& r_dest_num) const; virtual u_int32_t get_fu_count() const; virtual bool get_isPipelined() const; virtual u_int32_t get_piped_fu_id_offset(FU_ID fu_id) const; protected: private: //std::vector<FunctionalUnit*> funct_units; std::vector<InstructionStatus> instr_status; std::vector<FunctionalUnitStatus> fu_status; FU_ID reg_status[REGISTER_COUNT + FLOATING_POINT_REGISTERS]; u_int32_t fu_count; bool isPipelined; }; #endif
true
9aad78fa70eb736065e8ba35723caf9500b6f8af
C++
Kidd-Ye/program-list-06
/Majority/Majority/main.cpp
UTF-8
893
3.5
4
[]
no_license
// // main.cpp // Majority // // Created by kidd on 2018/9/8. // Copyright © 2018年 Kidd. All rights reserved. // #include <iostream> int Majority(int arr[], int length){ int i, temp, count = 1; temp = arr[0]; for (i = 1; i < length; i++) { if (arr[i] == temp) { count++; }else{ if (count > 0) { count--; }else{ temp = arr[i]; count = 1; } } } if (count > 0) { for (i = count = 0; i < length; i++) { if (arr[i] == temp) { count++; } } } if (count > length/2) { return temp; }else{ return -1; } } int main(int argc, const char * argv[]) { int arr[] = {1,8,6,8,8,8}; printf("数组的主元素为: %d\n", Majority(arr,6)); return 0; }
true
308b87289b4f64156fa36bde44136c5935e33720
C++
bitmingw/LintcodeSolution
/420CountAndSay/main.cpp
UTF-8
1,359
3.359375
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Solution { public: /** * @param n the nth * @return the nth sequence */ string countAndSay(int n) { if (n == 0) return ""; if (n == 1) return "1"; string pre = "1"; string cur; int round = 1; while (round < n) { cur = ""; int n = pre.length(); int p = 0; int pre_num = -1; int cur_num; int cnt = 0; while (p < n) { cur_num = stoi(string(1, pre[p])); if (cur_num != pre_num) { if (pre_num == -1) { pre_num = cur_num; cnt = 1; } else { cur += to_string(cnt); cur += to_string(pre_num); pre_num = cur_num; cnt = 1; } } else { cnt += 1; } ++p; } cur += to_string(cnt); cur += to_string(cur_num); pre = cur; ++round; } return cur; } }; int main() { Solution s; cout << s.countAndSay(4) << endl; cout << s.countAndSay(5) << endl; return 0; }
true
2934b5ad80f378ae4c8a0758b1c7f3eb89b7abf0
C++
meirfuces/ansector-tree-B
/FamilyTree.hpp
UTF-8
1,093
3.0625
3
[]
no_license
#ifndef _FamilyTree_ #define _FamilyTree_ #include <iostream> #include <string> using namespace std; class node { public: string name; string sex; string relation; int height; node *father; node *mother; node(string _name) { // Constructor with parameters this->name = _name; this->height=0; this->relation=""; this->father = this->mother = nullptr; } ~node(){ delete this->father; delete this->mother; } // node* findNode(string son,node *node); }; namespace family { class Tree{ public: node *head; //Constractur //Constractor Tree(string _name) { this->head = new node(_name); } Tree& addFather(string son, string father); Tree& addMother(string son, string mather); void display(); string relation(string ancestor); string find(string nameOfFind); bool remove(string ancestor); void deleteSubTree(node *pNode); }; // class Tree }// namespace family #endif
true
4304894f857a600d021e1334516540915723c997
C++
shailendra-singh-dev/ProgrammingChallenges
/Caribbean Online Judge COJ/1386 - Unearthing Treasures.cpp
UTF-8
578
2.90625
3
[]
no_license
#include <cstdio> #include <vector> #define FOR1(i, a, b, c) for(i = a ; i <= b ; i += c) #define FOR2(i, a, b, c) for(i = a ; i < b ; i += c) #define PB(v, n) v.push_back(n) using namespace std; int P, Q, i, j; int main() { scanf("%d %d", &P, &Q); vector<int> factors1, factors2; FOR1(i, 1, P, 1) { if(P % i == 0) PB(factors1, i); } FOR1(i, 1, Q, 1) { if(Q % i == 0) PB(factors2, i); } FOR2(i, 0, factors1.size(), 1) { FOR2(j, 0, factors2.size(), 1) { printf("%d %d\n", factors1[i], factors2[j]); } } return 0; }
true
bc669beeca56e7c809f285ff7b7ab055d5f9a740
C++
marchenkoiv/lab3-1-
/3_2/Prog3_2.cpp
UTF-8
5,364
3.1875
3
[]
no_license
#include "Hex_S_2.h" using namespace Prog3_2; int main() { int b = 1; int k; Hex st, sum; bool n; do { switch (b) { case 1: std::cout << "Enter new hex number: "; try { std::cin >> st; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your new hex number: "; std::cout << st; break; case 2: std::cout << "Enter the second summand: "; try { std::cin >> sum; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the second summand: "; std::cout << sum; st += (sum); std::cout << "Your result: "; std::cout << st; break; case 3: std::cout << "Enter subtrahned: "; try { std::cin >> sum;; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your subtrahned: "; std::cout << sum; st -= (sum); std::cout << "Your result: "; std::cout << st; break; case 4: std::cout << "Enter the shift amount: "; std::cin >> k; while (!std::cin.good()) { if (std::cin.eof()) return 0; std::cout << "You are wrong! You probably entered the letters" << std::endl; std::cin.clear(); std::cin.ignore(32767, '\n'); std::cin >> k; } st << (k); std::cout << "Your result: "; std::cout << st; break; case 5: std::cout << "Enter the shift amount: "; std::cin >> k; while (!std::cin.good()) { if (std::cin.eof()) return 0; std::cout << "You are wrong! You probably entered the letters" << std::endl; std::cin.clear(); std::cin.ignore(32767, '\n'); std::cin >> k; } st >> (k); std::cout << "Your result: "; std::cout << st; break; case 6: std::cout << "Enter the second number: "; try { std::cin >> sum;; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the first number: "; std::cout << st; std::cout << "Your the second number: "; std::cout << sum; n = st == (sum); std::cout << "The numbers are equal: "; if (n == true) puts("True"); else puts("False"); break; case 7: std::cout << "Enter the second number: "; try { std::cin >> sum;; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the first number: "; std::cout << st; std::cout << "Your the second number: "; std::cout << sum; n = (st != (sum)); std::cout << "The numbers are not equal: "; if (n == true) puts("True"); else puts("False"); break; case 8: std::cout << "Enter the second number: "; try { std::cin >> sum;; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the first number: "; std::cout << st; std::cout << "Your the second number: "; std::cout << sum; n = st > (sum); std::cout << "The first one is greater than the second one: "; if (n == true) puts("True"); else puts("False"); break; case 9: std::cout << "Enter the second number: "; try { std::cin >> sum; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the first number: "; std::cout << st; std::cout << "Your the second number: "; std::cout << sum; n = st < (sum); std::cout << "The first one is less than the second one: "; if (n == true) puts("True"); else puts("False"); break; case 10: std::cout << "Your number: "; std::cout << st; if (st.multoftwo() == true) puts("The number is odd"); else puts("The number is even"); break; case 11: std::cout << "Enter the second number: "; try { std::cin >> sum;; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the first number: "; std::cout << st; std::cout << "Your the second number: "; std::cout << sum; n = st >= (sum); std::cout << "The first one is greater than the second one or equal: "; if (n == true) puts("True"); else puts("False"); break; case 12: std::cout << "Enter the second number: "; try { std::cin >> sum; } catch (const std::exception &ex) { std::cout << ex.what() << std::endl; } std::cout << "Your the first number: "; std::cout << st; std::cout << "Your the second number: "; std::cout << sum; n = st <= (sum); std::cout << "The first one is less than the second one or equal: "; if (n == true) puts("True"); else puts("False"); break; default: std::cout << "Invalid number"; break; } std::cout << "0. Exit \n1. Enter new hex number\n2. Add\n3. Subtract\n4. Shift left\n5. Shift right\n6. Equal\n7. Not equal\n8. Greater\n9. Less\n10. Multiple of two\n11. Greater or equal\n12. Less or equal" << std::endl; std::cout << "Enter the next step: "; std::cin >> b; while (!std::cin.good()) { if (std::cin.eof()) return 0; std::cout << "You are wrong! You probably entered the letters" << std::endl; std::cin.clear(); std::cin.ignore(32767, '\n'); std::cin >> b; } } while (b != 0); return 0; }
true
fc1a2aabe6d40333294dff04f045a0f2524d9607
C++
ppatel56/parth-patel-OS-Course-Project
/CIS 3207 Project 4/fs.cpp
UTF-8
27,017
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstring> #include <list> #include <map> #include <cstdio> #include <string> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <stddef.h> #include <readline/readline.h> #include <readline/history.h> #include "disk.h" using namespace std; #define BLOCKS 8192 //amount of data blocks reserved for file metadata #define MAX_ENTRIES 8 // Max number of entries per block #define BLOCK_SIZE 4096 #define MAX_NUM_FILES 256 // Indicate the status of the file entry #define EMPTY 0 #define BUSY 1 //The number of file descriptors that can exist 64, 0-63 inclusive #define FIRST_FD 0 #define LAST_FD 63 #define MAX_FDS 64 //The number of files that can be on the disk is 256, 0-255 inclusive #define FIRST_FILE_INDEX 0 #define LAST_FILE_INDEX 255 #define FILE_TYPE 0 #define DIR_TYPE 1 //cpp string, append to the string, call string temp, block_write(0,(cstring cast) temp) // The short data type is used in order conserve memory // Entry in the FAT typedef struct{ short status; //status of the block, EMPTY or BUSY short nextBlock; //next block of the file entry } fileEntry; // FAT structure - 8192 number of fileEntry in the FAT typedef struct{ fileEntry file[BLOCKS]; } FAT; // Entry in directory table structure typedef struct { char fileName[15]; // 15 bytes (14 filename + terminator) unsigned short beginningIndex; // index of the file unsigned short type; // determines if the entry is a file (0) or directory (1) unsigned short fileSize; // size of the file unsigned short fileDes; // file descriptor } Entry; // Directory Entry Table. Each can hold up to 8 entries typedef struct DIRECTORY_TABLE{ Entry entry[MAX_ENTRIES]; } directory; // Data block typedef struct DATA_BLOCK{ char sect[BLOCK_SIZE]; } datablock; // DATA - all data blocks typedef struct DATA_BLOCKS{ datablock blocks[BLOCKS]; } DATA; //function prototypes int make_fs(char* disk_name); int mount_fs(char* disk_name); int unmount_fs(char* disk_name); int fs_open(char* name); int fs_close(int fildes); int fs_create(char *name); int fs_delete(char* name); int fs_mkdir(char* name); int fs_read(int fildes, void* buf, size_t nbyte); int fs_write(int fildes, void* buf, size_t nbyte); int fs_get_filesize(int fildes); int fs_lseek(int fildes, off_t offset); int fs_truncate(int fildes, off_t offset); //Helper functions void updateValue(unsigned short *oldValue, unsigned short newValue); short findAvailableBlock(FAT *fat); short findAvailableEntry(directory *dir); int findFileOffset(directory *dir, int file); int findFileEntry(char *fileName, directory *dir); void writeForFile(char *fileName); void readFromFile(char *fileName); //Shell functions void shellPrompt(char *input); char **shellParser (char *input); char **pathParser(char *input); int builtInCommands(char **input); int changeDirectory(char *directoryName); // Directory stack functions - navigating directory entries void push(int directoryBlock); int peek(); int pop(); void printStack(); int getNumEntries(); //used for the unmount process, it is where the entries are stored //in order to be parsed back by the mount_fs string tempStr; // Directory stack - where the directories will stored in order to change directories int directoryStack[MAX_NUM_FILES]; //since directories are technically file int topOfStack = 0; int fileDescriptor; FAT *fat; DATA *Data; Entry *root; /* TEST FOR BLOCK_READ AND BLOCK_WRITE FUNCTIONS block_write(1, "Test"); char *temp; temp = (char *)malloc(1 * sizeof(char*)); block_read(temp); printf("Here is the block_read: %s", temp); */ /*In the make_fs() function, the diskName is passed in then is checked if the name is valid * then tries to make_disk and open_disk otherwise return -1. * The first entry in the fat is busy since the root directory is essentially in the block. * The root directory is then given the appropriate metadata. * The memcpy is used to get the address of root to a buffer, then buffer is written to block 0. * The memcpy is used once again to get addeesss of fat to a buffer, then buffer is written to block 1. * Both buffers are then freed. */ int make_fs(char *diskName){ if(diskName != NULL){ make_disk(diskName); open_disk(diskName); } else{ return -1; } fat = (FAT*)malloc(sizeof(FAT)); Data = (DATA*)malloc(sizeof(DATA)); root = (Entry*)malloc(sizeof(Entry)); fat->file[0].status = BUSY; fat->file[0].nextBlock = -1; updateValue(&(root->fileSize), 0); updateValue(&(root->beginningIndex), 0); updateValue(&(root->type), DIR_TYPE); //char *bufferForRoot = (char*) calloc(BLOCK_SIZE, sizeof(char)); strncpy(root->fileName, "/",sizeof(root->fileName)); char *bufferForRoot = (char *)root; memcpy(bufferForRoot, root, sizeof(BLOCK_SIZE)); block_write(0, bufferForRoot); int i; char *bufferForFat = (char*)fat; memcpy(bufferForFat, fat, sizeof(FAT)); block_write(1, bufferForFat); free(bufferForRoot); free(bufferForFat); return 0; } /*Currently unsuccessful * Attempt to unmount the file system by storing the metadata to a string then later. * The metadata information in the string is supposed to be split by 1 whitespace ' '. * The entries of the directories were supposed to be split by the '-' character. * Each entry and their respective metadata were supposed to be parsed back into memory once * the mount_fs was called, unfortunately I didn't have time to complete the two functions. * The end result for one entry was supposed to this: -file.txt * Problem may also exist with how the structs are set up */ int unmount_fs(char *diskName){ int i = 0; //if disk name was not found. if(diskName == NULL){ puts("Could not find disk."); return -1; } directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); // This was admittedly not a good way to find each entry file as it will // loop through MAX_ENTRIES-times despite only testing with 1 file. for (i = 0; i < MAX_ENTRIES; i++){ tempStr += '-'; tempStr += dir1->entry->fileName; tempStr += '*'; /*string fdStr = to_string(dir1->entry->fileDes); tempStr += fdStr;*/ tempStr += '*'; string sizeStr = to_string( dir1->entry->fileSize); tempStr += sizeStr; tempStr += '*'; string indexStr = to_string(dir1->entry->beginningIndex); tempStr += indexStr; tempStr += '*'; string typeStr = to_string(dir1->entry->type); tempStr += typeStr; } return 0; } // print out the the string that holds the entries and their metadata void printStr(std::string temp){ cout << temp << endl; } // Update the metadata for the entries void updateValue(unsigned short *oldValue, unsigned short newValue){ *oldValue = newValue; } // Find the available block available in the FAT so that the free block short findAvailableBlock(FAT *fat){ short i; for (i = 1; i < BLOCKS; i++){ if (fat->file[i].status == EMPTY){ return i; } } return -1; } // Find the next available entry in the directory short findAvailableEntry(directory *dir1){ short i; for (i = 0; i < MAX_ENTRIES; i++){ if (dir1->entry[i].beginningIndex == 0){ return i; } } return -1; } /*Finding the file offset by getting the file size and file's index. * By iterating through the FAT using the file's index till it reaches * the next block value of -1. * Then the offset of file's size - (BLOCK_SIZE*count) is returned. */ int findFileOffset(directory *dir1, int file){ int sizeOfFile = dir1->entry[file].fileSize; int startIndex = dir1->entry[file].beginningIndex; int count = 0; while (fat->file[startIndex].nextBlock != -1) { startIndex = fat->file[startIndex].nextBlock; count++; } return sizeOfFile-(BLOCK_SIZE*count); } // To find a file entry, the function iterates through the the directory till MAX_ENTRIES. // Once the name, type, and index of directory entry matches the file name, type file, and non-zero index; // return that index int findFileEntry(char *fileName, directory *dir1){ int index; for (index = 0; index < MAX_ENTRIES; index++){ if ( ((strcmp(dir1->entry[index].fileName, fileName)) == 0) && (dir1->entry[index].type == FILE_TYPE) && (dir1->entry[index].beginningIndex != 0)){ return index; } } return -1; } /*The fs_create function creates a file. * The directory is first initialized, then get metadata from the data block using memcpy. * The metadata's address is copied into directory's address. * Then find the next available block for the FAT and then initialize FAT. * Then put in each respective metadata information into the directory entry (file). * Then memcpy the directory into the data block, then block_write using * the available block from the FAT with the buffer being the directory. */ int fs_create(char *fileName){ string strBuf; directory *dir1 = (directory *)malloc(sizeof(directory)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); short freeBlock = findAvailableBlock(fat); fat->file[freeBlock].status = BUSY; fat->file[freeBlock].nextBlock = -1; short freeEntry = findAvailableEntry(dir1); puts(" File's Metadata:"); strncpy(dir1->entry[freeEntry].fileName, fileName, sizeof(fileName)); printf(" File Name: %s \n", dir1->entry[freeEntry].fileName); updateValue(&dir1->entry[freeEntry].fileSize, 0); printf(" File Size: %d\n", dir1->entry[freeEntry].fileSize); updateValue(&dir1->entry[freeEntry].beginningIndex, freeBlock); printf(" Beginning index: %d\n", dir1->entry[freeEntry].beginningIndex); updateValue(&dir1->entry[freeEntry].type, FILE_TYPE); printf(" File Type: %d\n", dir1->entry[freeEntry].type); updateValue(&dir1->entry[freeEntry].fileDes, -1); //printf(" File Descriptor: %d\n", dir1->entry[freeEntry].fileDes); memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); char *buf = (char *)dir1; block_write((int)freeBlock, buf); printf(" Created file %s\n", fileName); return 0; } /*The fs_mkdir function is essentially the same function as fs_create function with the exception of the types */ int fs_mkdir(char * dirName){ directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); short freeBlock = findAvailableBlock(fat); fat->file[freeBlock].status = BUSY; fat->file[freeBlock].nextBlock = -1; short freeEntry = findAvailableEntry(dir1); updateValue(&dir1->entry[freeEntry].fileSize, 0); printf(" Directory Size: %d\n", dir1->entry[freeEntry].fileSize); updateValue(&dir1->entry[freeEntry].beginningIndex, freeBlock); printf(" Starting Index: %d\n", dir1->entry[freeEntry].beginningIndex); updateValue(&dir1->entry[freeEntry].type, DIR_TYPE); //type is 1 which is directory printf(" Dir Type: %d\n", dir1->entry[freeEntry].type); strncpy(dir1->entry[freeBlock].fileName, dirName, sizeof(dirName)); printf(" Dir Name: %s\n", dir1->entry[freeBlock].fileName); memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); char *buf = (char *)dir1; block_write((int)freeBlock, buf); printf(" Creating directory: %s\n", dirName); return 0; } /*Check if the file name is invalid and return -1 if it is. * Otherwise, set up the directory like usual then iterate through maximum number * of file descriptors till there is one available then if directory entry is doesn't * have a filedes then assign the file descriptor to it and return it. * */ int fs_open(char *fileName){ if(fileName == NULL){ return -1; } directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); int i; for(i = 0; i< MAX_FDS; i++){ if(dir1->entry->fileDes == -1 && strcmp(dir1->entry->fileName, fileName) == 0){ dir1->entry->fileDes = i; memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); return dir1->entry->fileDes; } } return -1; } /*Basically do the opposite of the fs_open function by setting the directory entry's * fileDes to -1 and thus closing the file */ int fs_close(int filedes){ if(filedes < FIRST_FD || filedes >LAST_FD){ return -1; } directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); int i; for(i = 0; i< MAX_FDS; i++){ if(dir1->entry->fileDes != -1){ dir1->entry->fileDes = -1; memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); } } return 0; } //Just set up the directory entry then return the fileDes if it matches the //parameter. int fs_get_fileSize(int filedes){ directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); if(dir1->entry->fileDes== filedes){ printf("fileSize: %d\n", dir1->entry->fileSize); return 0; } return -1; } /*The set up the directory entry per usual then find the file entry using the helper function * The index should be greater than -1, then get dir entry's index and passed it to the FAT. * While FAT has not reached -1, make each block in FAT empty. * Then update the dir entry to 0 in size and index */ int fs_delete(char *fileName){ printf(" Deleting directory %s\n", fileName); directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); int index = findFileEntry(fileName, dir1); if (index == -1){ puts(" File not found"); return -1; } else{ int blockIndex = dir1->entry[index].beginningIndex; while (fat->file[blockIndex].nextBlock != -1){ int temp = fat->file[blockIndex].nextBlock; fat->file[blockIndex].status = EMPTY; fat->file[blockIndex].nextBlock = -1; blockIndex = temp; } fat->file[blockIndex].status = EMPTY; fat->file[blockIndex].nextBlock = -1; updateValue(&dir1->entry[index].fileSize, 0); updateValue(&dir1->entry[index].beginningIndex, 0); } memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); return 0; } /*Set up the directory entry as usual then check if the filedes is invalid. * Get the dir entry's index then iterate through the FAT till it reaches -1 and make * the next block the index each iteration. * Then get the length of buffer that was passed in. * While the buffer length is greater than 0, get the offset of the file and block number * Copy the buffer into the data blocks using strncpy. * Then find the free block and use it to do block_write into the disk the string * Then initialize the FAT */ int fs_write(int filedes, void* buf, size_t nbyte){ directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); if (filedes == -1){ printf(" ERROR: File not found. \n"); return -1; } else{ int startingBlock = dir1->entry[filedes].beginningIndex; while (fat->file[startingBlock].nextBlock != -1){ startingBlock = fat->file[startingBlock].nextBlock; } int bufferLength = strlen((char*)buf); while (bufferLength > 0){ printf(" Starting to write at block: %d\n", startingBlock); printf(" Buffer Length: %d\n", bufferLength); int fileOffset = findFileOffset(dir1, filedes); printf(" Offset: %d\n", fileOffset); int blockNumber; if(bufferLength < (BLOCK_SIZE - fileOffset)){ blockNumber = bufferLength; } else{ blockNumber = BLOCK_SIZE - fileOffset; } printf(" Block Number: %d\n", blockNumber); strncpy(Data->blocks[startingBlock].sect + fileOffset, (char *)buf + (strlen((char*)buf) - bufferLength), blockNumber); updateValue(&dir1->entry[filedes].fileSize, blockNumber + dir1->entry[filedes].fileSize); char *strBuf = (char *)malloc(sizeof(nbyte+1)); strcpy(strBuf, (char *)buf); printf(" Filesize: %d\n", dir1->entry[filedes].fileSize); bufferLength = bufferLength - blockNumber; int freeBlock = findAvailableBlock(fat); block_write(freeBlock, strBuf); if ((fileOffset + blockNumber) == BLOCK_SIZE){ fat->file[startingBlock].nextBlock = freeBlock; fat->file[freeBlock].status = BUSY; fat->file[freeBlock].nextBlock = -1; startingBlock = freeBlock; } } } memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); return 0; } //Helper function to write to the file void writeForFile(char *fileName){ directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); int filedes = findFileEntry(fileName, dir1); char buf[1024] = ""; printf("\nWrite to a file: "); scanf("%s", buf); size_t len = strlen(buf); fs_write(filedes, buf, len); } /*Set up the directory entry as usual and check the filedes. * The temp buffer is with BLOCK_SIZE + 1 because of offset * The FAT, using the entry's index will iterate till -1, and will memset the tempBuf to '\0' * Then strcat the '\0' to the buffer, then find the offset and do the same thing with memset with * data block section * Perform the block read with the starting block and the temp buffer. */ int fs_read(int filedes,void *buf,size_t nbytes){ //printf(" Reading file %s\n", fileName); directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); //int file = findFileEntry(dir1, fileName); if (filedes == -1){ printf(" ERROR: File not found \n"); } else { char tempBuf[BLOCK_SIZE + 1]; //char buf[dir1->entry[filedes].fileSize + 1]; //memset(buf, '\0', sizeof(buf)); char buf[nbytes]; int startBlock = dir1->entry[filedes].beginningIndex; while(fat->file[startBlock].nextBlock != -1){ memset(tempBuf, '\0', sizeof(tempBuf)); memcpy(tempBuf, Data->blocks[startBlock].sect, BLOCK_SIZE); strcat(buf, tempBuf); startBlock = fat->file[startBlock].nextBlock; } int offset = findFileOffset(dir1, filedes); memset(tempBuf, '\0', sizeof(tempBuf)); memcpy(tempBuf, Data->blocks[startBlock].sect, offset); strcat(buf, tempBuf); block_read(startBlock, tempBuf); printf("%s\n", buf); } memcpy(&(Data->blocks[peek()]), dir1, sizeof(*dir1)); return 0; } //Helper function to help read from file void readFromFile(char *fileName){ directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); int filedes = findFileEntry(fileName, dir1); char buf[1024] = ""; size_t len = strlen(buf); fs_read(filedes, (void *)buf, len); } // WRITE DATA TO FILE //return top of the directory stack int peek(){ return directoryStack[topOfStack]; } int pop(){ int info; if (topOfStack == 0) { return 0; } else { info = directoryStack[topOfStack]; topOfStack = topOfStack - 1; return info; } } void push(int directoryBlock){ if ( topOfStack == BLOCKS) { printf(" Stack is full! \n"); } else { topOfStack = topOfStack + 1; directoryStack[topOfStack] = directoryBlock; } } //Print the whole directory stack void printStack(){ puts("\nDIRECTORY STACK: \n"); int loop; int numEntries; //getting the size of the array or stack int size = sizeof(directoryStack)/sizeof(int); for(loop = 0; loop < size; loop++){ printf("%d ", directoryStack[loop]); } numEntries = getNumEntries(); printf("\n\nNumber of entries: %d\n\n", numEntries); } //get the number of entries that are currently in the stack int getNumEntries(){ int count = 0; int i = 0; int size = sizeof(directoryStack)/sizeof(int); for(i = 0; i < size; i++){ if(directoryStack[i] > 0){ count++; } } //becuase root directory is in beginning as a zero count+=1; return count; } //Swith between directories in the file system just like a regular linux terminal. //In order to do so in the file system, the directory stack helps changing to a //new directory by pushing an element's beginningIndex from the directory entry table. int changeDirectory(char *directoryName){ //If the user types "cd .." the function will then pop off the current directory from the //directory stack and then point to the next directory on the stack which is the previous directory if (strcmp(directoryName, "..") == 0){ pop(); return 1; } //initialize space for a directory value with size of the value directory *dir1 = (directory *)malloc(sizeof(*dir1)); memcpy(dir1, &(Data->blocks[peek()]), sizeof(*dir1)); for (int i = 0; i < MAX_ENTRIES; i++){ if ((strcmp(directoryName, dir1->entry[i].fileName) == 0) && (dir1->entry[i].type == DIR_TYPE)){ push(dir1->entry[i].beginningIndex); return 1; } } return 0; } char **shellParser (char *input){ int bufferSize = 1024, index = 0; //for the string token position in tokens [index] char **tokens = (char **)malloc(bufferSize * sizeof(char *)); // allocating space for the tokens and its double pointers because elements in the array are // pointers, the array must be a pointer to a pointer char *token; // represents a token in the array of tokens token = strtok(input, " \t\n"); // This --> " \t\n" represents the whitespaces that are common while(token != NULL) { tokens [index] = token; // Maybe check ifthere needs to be a reallocation ifthe bufferSize somehow is less than index. token = strtok(NULL, " \t\n"); // place null terminated \0 at the end of each token index++; } tokens[index] = NULL; return tokens; } char **pathPaser (char *input){ int bufferSize = 1024, index = 0; //for the string token position in tokens [index] char **tokens = (char **)malloc(bufferSize * sizeof(char *)); // allocating space for the tokens and its double pointers because elements in the array are // pointers, the array must be a pointer to a pointer char *token; // represents a token in the array of tokens token = strtok(input, " /"); // This --> " /" represents the path-separator while(token != NULL) { tokens [index] = token; // Maybe check ifthere needs to be a reallocation ifthe bufferSize somehow is less than index. token = strtok(NULL, " /"); // place null terminated \0 at the end of each token index++; } tokens[index] = NULL; return tokens; } int builtInCommands(char **parsedArgs){ if(parsedArgs[0] == NULL){ // if the user doesn’t input a command that are built-in or external i.e. fileDescriptorfileDescriptor or \n puts("Command doesn’t exit. Try again."); return 0; } if(strcmp (parsedArgs[0], "quit")==0){ puts("Exiting the file system."); exit(0); } else if(strcmp (parsedArgs[0], "cd")==0){ changeDirectory(parsedArgs[1]); return 0; } else if(strcmp(parsedArgs[0], "fs_create")==0){ //createFile(fat, Data, parsedArgs[1]); fs_create(parsedArgs[1]); } else if(strcmp(parsedArgs[0], "fs_write") == 0){ //char **extStr = fileParser(parsedArgs[1]); writeForFile(parsedArgs[1]); } else if(strcmp(parsedArgs[0], "fs_read") == 0){ //char **extStr = fileParser(parsedArgs[1]); readFromFile(parsedArgs[1]); } else if(strcmp(parsedArgs[0], "fs_delete") == 0){ //char **extStr = fileParser(parsedArgs[1]); fs_delete(parsedArgs[1]); } else if(strcmp(parsedArgs[0], "fs_mkdir") == 0){ fs_mkdir(parsedArgs[1]); } else if(strcmp(parsedArgs[0], "unmount_fs") == 0){ unmount_fs(parsedArgs[0]); } else if(strcmp(parsedArgs[0], "printStr") == 0){ printStr(tempStr); } /*else if(strcmp(parsedArgs[0], "mount_fs") == 0){ mount_fs(parsedArgs[1]); }*/ else if(strcmp(parsedArgs[0], "fs_open") == 0){ fileDescriptor = fs_open(parsedArgs[1]); } else if(strcmp(parsedArgs[0],"fs_close") == 0){ fs_close(fileDescriptor); } else if(strcmp(parsedArgs[0], "getSize")){ fs_get_fileSize(fileDescriptor); } // if the function fails, return -1 return -1; } void shellPrompt(char *input){ char cwd[1024]; //current working directory getcwd(cwd, sizeof(cwd)); if(getcwd(cwd, sizeof(cwd)) != NULL){ printf("%s>> ",cwd); fgets(input, 1024, stdin); } } int main(){ char diskName[15] = "TESTDRIVE"; puts("\n------MY FILE SYSTEM------\n"); directoryStack[topOfStack] = 0; make_fs(diskName); char input[1024]; shellPrompt(input); int count = 0; while(1){ char **args = shellParser(input); builtInCommands(args); free(args); shellPrompt(input); } return 0; }
true
ba9e6ca65931a3bda5bcaa0c0cf095a0f8593e4b
C++
pnikic/Hacking-uva
/10684.cpp
UTF-8
470
2.90625
3
[]
no_license
#include <iostream> using namespace std; int main() { int n, a; while (cin >> n, n) { int best = 0, cs = 0; for (int i = 0; i < n; ++i) { cin >> a; cs += a; best = max(best, cs); cs = max(cs, 0); } if (best > 0) cout << "The maximum winning streak is " << best << ".\n"; else cout << "Losing streak.\n"; } }
true
6f225934b1c2c3e89423c28c082d23b99732f04b
C++
skgbanga/Sandbox
/cpp/concurrent_servers/utils.h
UTF-8
1,285
2.5625
3
[]
no_license
#pragma once #include <sys/socket.h> #include <netinet/in.h> #include <fmt/ostream.h> // fmt::print #include <fmt/time.h> // time related formatting #include <sys/time.h> // gettimeofday // Directly from https://github.com/eliben/code-for-blog/blob/master/2017/async-socket-server/utils.h // print the error message 'msg' then the perror status and then exit void perror_die(const char* msg); int create_listening_socket(int portnum, int backlog); void report_connected_peer(const sockaddr_in* sa, socklen_t salen); // This contains the core logic of the state machine // sockfd is the socket file descriptor of the connection that has been accepted by the server void serve_connection(int sockfd); // mark a socket non blocking // crashed if it is not possible void mark_non_blocking(int sockfd); // prints the timestamp (microsecond precision) along with the message template <typename... Args> void timed_print(const char *format, Args&& ...args) { struct timeval tv; if (gettimeofday(&tv, nullptr) < 0) perror_die("error getimeofday"); std::time_t t = tv.tv_sec; // get the seconds since epoch fmt::print_colored(fmt::RED, "{:%Y-%m-%d %H:%M:%S}.{:d}: ", *std::localtime(&t), tv.tv_usec); fmt::print(format, std::forward<Args>(args)...); }
true
ab4e39a36ff5b2a014c2e2287477623e7181cc83
C++
Eae02/jamlib
/Src/Graphics/Sampler.cpp
UTF-8
4,175
2.625
3
[ "Zlib" ]
permissive
#include "Sampler.hpp" #include "OpenGL.hpp" #include <exception> namespace jm { TextureMinFilter MakeTextureMinFilter(Filter filter, std::optional<Filter> mipFilter) { switch (filter) { case Filter::Linear: if (!mipFilter.has_value()) return TextureMinFilter::Linear; if (mipFilter.value() == Filter::Linear) return TextureMinFilter::LinearMipmapLinear; return TextureMinFilter::LinearMipmapNearest; case Filter::Nearest: if (!mipFilter.has_value()) return TextureMinFilter::Nearest; if (mipFilter.value() == Filter::Linear) return TextureMinFilter::NearestMipmapLinear; return TextureMinFilter::NearestMipmapNearest; } std::terminate(); } uint32_t detail::TranslateTextureWrapMode(TextureWrapMode wrapMode) { switch (wrapMode) { case TextureWrapMode::ClampToEdge: return GL_CLAMP_TO_EDGE; case TextureWrapMode::MirroredRepeat: return GL_MIRRORED_REPEAT; case TextureWrapMode::Repeat: return GL_REPEAT; case TextureWrapMode::ClampToBorder: return GL_CLAMP_TO_BORDER; } std::abort(); } uint32_t detail::TranslateTextureMinFilter(TextureMinFilter minFilter) { switch (minFilter) { case TextureMinFilter::Nearest: return GL_NEAREST; case TextureMinFilter::Linear: return GL_LINEAR; case TextureMinFilter::NearestMipmapNearest: return GL_NEAREST_MIPMAP_NEAREST; case TextureMinFilter::LinearMipmapNearest: return GL_LINEAR_MIPMAP_NEAREST; case TextureMinFilter::NearestMipmapLinear: return GL_NEAREST_MIPMAP_LINEAR; case TextureMinFilter::LinearMipmapLinear: return GL_LINEAR_MIPMAP_LINEAR; } std::abort(); } static uint32_t currentSampler[32]; void BindSampler(const Sampler* sampler, uint32_t binding) { const uint32_t id = sampler ? sampler->UniqueID() : 0; if (currentSampler[binding] != id) { currentSampler[binding] = id; glBindSampler(binding, sampler ? sampler->Handle() : 0); } } static Sampler* pixel2DSampler = nullptr; const Sampler& Pixel2DSampler() { if (pixel2DSampler == nullptr) { pixel2DSampler = new Sampler; pixel2DSampler->SetMinFilter(TextureMinFilter::LinearMipmapLinear); pixel2DSampler->SetMagFilter(Filter::Nearest); pixel2DSampler->SetWrapU(TextureWrapMode::ClampToEdge); pixel2DSampler->SetWrapV(TextureWrapMode::ClampToEdge); pixel2DSampler->SetWrapW(TextureWrapMode::ClampToEdge); } return *pixel2DSampler; } void detail::DestroyGlobalSamplers() { delete pixel2DSampler; } static uint32_t nextUniqueID = 1; Sampler::Sampler() : m_uniqueID(nextUniqueID++) { GLuint sampler; glGenSamplers(1, &sampler); m_sampler = sampler; } void Sampler::SetMinFilter(TextureMinFilter minFilter) { glSamplerParameteri(m_sampler.Get(), GL_TEXTURE_MIN_FILTER, detail::TranslateTextureMinFilter(minFilter)); } void Sampler::SetMagFilter(TextureMagFilter magFilter) { glSamplerParameteri(m_sampler.Get(), GL_TEXTURE_MAG_FILTER, magFilter == TextureMagFilter::Linear ? GL_LINEAR : GL_NEAREST); } void Sampler::SetMinLod(float minLod) { glSamplerParameterf(m_sampler.Get(), GL_TEXTURE_MIN_LOD, minLod); } void Sampler::SetMaxLod(float maxLod) { glSamplerParameterf(m_sampler.Get(), GL_TEXTURE_MAX_LOD, maxLod); } void Sampler::SetMaxAnistropy(float maxAnistropy) { if (detail::maxAnistropy != 0) { if (maxAnistropy > detail::maxAnistropy) maxAnistropy = detail::maxAnistropy; glSamplerParameterf(m_sampler.Get(), GL_TEXTURE_MAX_ANISOTROPY, maxAnistropy); } } void Sampler::SetWrapU(TextureWrapMode wrapMode) { glSamplerParameteri(m_sampler.Get(), GL_TEXTURE_WRAP_S, detail::TranslateTextureWrapMode(wrapMode)); } void Sampler::SetWrapV(TextureWrapMode wrapMode) { glSamplerParameteri(m_sampler.Get(), GL_TEXTURE_WRAP_T, detail::TranslateTextureWrapMode(wrapMode)); } void Sampler::SetWrapW(TextureWrapMode wrapMode) { glSamplerParameteri(m_sampler.Get(), GL_TEXTURE_WRAP_R, detail::TranslateTextureWrapMode(wrapMode)); } void Sampler::SetBorderColor(const glm::vec4& color) { glSamplerParameterfv(m_sampler.Get(), GL_TEXTURE_BORDER_COLOR, reinterpret_cast<const float*>(&color)); } }
true
2f49ee40a7fdaf562c440f93c3bf304693943942
C++
ImadT/Resolution-de-l-equation-de-chaleur-en-c-
/materiau.cpp
UTF-8
401
2.59375
3
[]
no_license
#include "materiau.h" namespace ensiie{ Materiau::Materiau(double lambda, double rho, double c):lambda_(lambda), rho_(rho), c_(c){ } Materiau::Materiau(const Materiau& m){ lambda_= m.lambda_; rho_ = m.rho_; c_ = m.c_; } double Materiau::get_lambda(){ return lambda_; } double Materiau::get_rho(){ return rho_; } double Materiau::get_c(){ return c_; } }
true
7dcc37c149c37869b5617bb1d41a2f61d1518179
C++
kofyou/PersonalProject-C
/221801212/src/WordCount.cpp
UTF-8
5,300
3.1875
3
[]
no_license
#include <vector> #include <algorithm> #include <string> #include <fstream> #include <sstream> #include <iostream> using namespace std; string duan = ""; int wordcount = 0; int line = 1; int character = 0; struct Record { string word; int count; }; static bool sortType(const Record& v1, const Record& v2) { return v1.count > v2.count;//降序排序 } int wordTest(char a) { return ((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z')); } void lineCount(const char* filename)//行数统计 { ifstream ifile(filename); if (!ifile.good()) { cout << "输入文件打开失败" << endl; return; } vector<char> para; int i = 0; char wordd; while ((wordd = ifile.get()) != EOF) { para.push_back(wordd); i++; } para.push_back('\0'); para.push_back('\0'); for (i = 0; i < para.size(); i++) { if (para[i] == '\n') { line++; } } } void wordCount(const char* filename)//单词统计 { ifstream ifile(filename); if (!ifile.good()) { cout << "输入文件打开失败" << endl; return; } vector<char> para; int i = 0; int j = 0; char wordd; while ((wordd = ifile.get()) != EOF) { para.push_back(wordd); i++; } para.push_back('\0'); para.push_back('\0'); //for (int f = 0; f < para.size(); f++) //{ // cout << para[f]; //} //cout << endl << i << " " << para.size(); i = 0; while (para[i] != '\0') { while (wordTest(para[i])) { i++; j++; if (!wordTest(para[i])) { if (j >= 4) { wordcount++; for (int h = i - j; h < i; h++) { duan = duan + para[h]; } duan += " "; } j = 0; } } i++; } ifile.close(); } void characterCount(const char* filename)//字符数量统计 { ifstream ifile(filename); if (!ifile.good()) { cout << "输入文件打开失败" << endl; return; } char chara; while ((chara = ifile.get()) != EOF) { character++; } } void wordDis()//运行框测试展示 { vector<Record> _words; istringstream iss(duan); string word; int i; while (iss >> word) { for (i = 0; i < _words.size(); ++i) { if (word == _words[i].word) { ++_words[i].count; break; } } if (i == _words.size()) { Record record; record.word = word; record.count = 1; _words.push_back(record); } } cout << duan << endl; cout << "字符数:" << character << endl; cout << "单词数:" << wordcount << endl; cout << "行数:" << line << endl; sort(_words.begin(), _words.end(), sortType);//排序并输出 for (i = 0; i < _words.size(); ++i) { cout << _words[i].word << ":" << _words[i].count << endl; } } void writeFile(const char* filename) { ofstream ofile(filename); if (!ofile.good()) { cout << "输出文件打开失败" << endl; return; } vector<Record> _words; for (int i = 0; i < duan.size(); ++i) { duan[i] = tolower(duan[i]);//转换为小写 } istringstream iss(duan); string word; int i; while (iss >> word) { for (i = 0; i < _words.size(); ++i) { if (word == _words[i].word) { ++_words[i].count; break; } } if (i == _words.size()) { Record record; record.word = word; record.count = 1; _words.push_back(record); } } ofile << "字符数:" << character << endl; ofile << "单词数:" << wordcount << endl; ofile << "行数:" << line << endl; sort(_words.begin(), _words.end(), sortType);//排序并输出 if (_words.size() <= 10) { for (int i = 0; i < _words.size(); ++i) { ofile << _words[i].word << ": " << _words[i].count << endl; } } else { for (int i = 0; i < 10; ++i) { ofile << _words[i].word << ": " << _words[i].count << endl; } } ofile.close(); } int main(int argc, char** argv) { if (argc != 3) { cout << "程序出错"; return 0; } string in_address1 = argv[1]; const char* in_address2 = in_address1.data();//将string地址改为char数组 string out_address1 = argv[2]; const char* out_address2 = out_address1.data();//将string地址改为char数组 wordCount(in_address2);//字符统计 lineCount(in_address2);//行数统计 characterCount(in_address2);//字符统计 writeFile(out_address2);//写入文件 //wordDis();//测试展示 }
true
b22870767692f8b32aa0214c77e7247bb246feac
C++
GCY/NTCU-CSIE-Project
/BookManager/try/ISBNCheck.cpp
UTF-8
1,661
4.09375
4
[ "MIT" ]
permissive
#include <string> int isbnDigitToInt(const char digit); /** * 檢查 ISBN-10 或 ISBN-13 碼是否有效。 * @return true 表示有效 * @param isbn ISBN 字串,無連字號'-'。 */ bool isIsbnValid(std::string isbn) { if (isbn.length() < 10) { return false; } else if (isbn.length() < 13) { // ISBN-10 int i, a = 0, b = 0; for (i = 0; i < 10; i++) { if (isbnDigitToInt(isbn.at(i)) == -1) { return false; } a += isbnDigitToInt(isbn.at(i)); b += a; } return (b % 11 == 0); } else { // ISBN-13 int i; int odd_digit_sum = 0, even_digit_sum = 0; for (i = 0; i<=12; i += 2) { odd_digit_sum += isbnDigitToInt(isbn.at(i)); if (isbnDigitToInt(isbn.at(i)) == -1) { return false; } } for (i = 1; i<=11; i += 2) { even_digit_sum += isbnDigitToInt(isbn.at(i)); if (isbnDigitToInt(isbn.at(i)) == -1) { return false; } } return ((odd_digit_sum+3*even_digit_sum)%10 == 0); } } /** * 把 ASCII 模式的 ISBN 位數轉換為 int 型態 * @return int 型態的位數,可爲 0..10; -1 表示 illegal. * @param digit ISBN digit,可爲 '0'-'9', 'X', 'x'。 */ int isbnDigitToInt(const char digit) { if (digit == 'x' || digit == 'X'){ return 10; } else if (digit >= '0' || digit <= '9') { return (digit-'0'); } else { // illegal return -1; } }
true
667bdac3986f906dbcd7516f74a49acc34c0eb17
C++
amasson42/GLSScene
/GLScene/includes/GLScene/GLSSkeleton.hpp
UTF-8
2,988
2.6875
3
[]
no_license
// // GLSShader.hpp // GLScene // // Created by Arthur Masson on 12/04/2018. // Copyright © 2018 Arthur Masson. All rights reserved. // #ifndef GLSSkeleton_h #define GLSSkeleton_h #include "GLSStructs.hpp" #include "GLSIAnimatable.hpp" #include "GLSInterpolator.hpp" #include "GLSNode.hpp" namespace GLS { class SkeletonAnimation : public IAnimatable { std::vector<TransformInterpolator> _interpolations; timefloat _currentTime; timefloat _duration; bool _loop; friend class Skeleton; public: SkeletonAnimation(); SkeletonAnimation(const SkeletonAnimation& copy); virtual ~SkeletonAnimation(); SkeletonAnimation& operator=(const SkeletonAnimation& copy); TransformInterpolator& interpolatorAt(int boneIndex); timefloat duration() const; void setDuration(timefloat d); void setMinDuration(timefloat d); void setMaxDuration(timefloat d); bool loop() const; void setLoop(bool l); timefloat currentTime() const; virtual void initAnimation(); virtual void animate(timefloat deltaTime); virtual bool alive() const; }; struct AnimationBlender { std::map<std::string, SkeletonAnimation>::iterator iterator; float blendValue; }; class Skeleton : public IAnimatable { public: static const int maxBones = 64; struct Bone { std::weak_ptr<Node> node; glm::mat4 inverseBind; Transform restPose; Bone(std::shared_ptr<Node> node); }; protected: std::vector<Bone> _bones; std::map<std::string, SkeletonAnimation> _animations; std::vector<std::shared_ptr<AnimationBlender>> _activeAnimations; public: Skeleton(); Skeleton(const Skeleton& copy); virtual ~Skeleton(); Skeleton& operator=(const Skeleton& copy); static std::shared_ptr<Skeleton> loadFromAiSceneAnimations(const aiScene *scene, std::shared_ptr<Node> hostNode); // bones void addBone(std::shared_ptr<Node> node); void addBone(std::shared_ptr<Node> node, glm::mat4 offset); int boneCount() const; int indexOfBoneNamed(std::string name) const; const std::vector<Bone>& bones() const; // animations std::vector<std::string> animationNames() const; SkeletonAnimation *createAnimation(std::string name, timefloat duration, bool loop); std::map<std::string, float> getAnimationBlends() const; timefloat getAnimationTime(std::string name) const; virtual void initAnimation(); virtual std::shared_ptr<AnimationBlender> setAnimationBlend(std::string name, timefloat offsetTime = 0, float blend = 1.0f); virtual void stopAnimations(); virtual void animate(timefloat deltaTime); virtual bool alive() const; }; } #endif /* GLSSkeleton_h */
true
4ad5fe50c5cd317611b56a2326b68d5ac2c943b1
C++
TANG-Kai/pyfx
/src/Union.cpp
UTF-8
518
2.53125
3
[]
no_license
#include "Union.h" using namespace vr; const Box Union::getBBox() const { const Box a = m_VolumeA->getBBox(), b = m_VolumeB->getBBox(); return a.expand(b); } const Vector Union::grad(const Vector &p) const { const float f1 = m_VolumeA->eval(p), f2 = m_VolumeA->eval(p); if(f1 > f2) { return m_VolumeA->grad(p); } else { return m_VolumeB->grad(p); } } const float Union::eval(const Vector &p) const { return std::max( m_VolumeA->eval(p), m_VolumeB->eval(p)); }
true
79eaa224a84bc457e075efb585e2583ffd23f912
C++
PriyanshuPatel02/Competitive-programming-everyday
/Phase - 1(60 questions)/Day-3/13. Non-decreasing Array.cpp
UTF-8
501
3
3
[]
no_license
// Link - https://leetcode.com/problems/non-decreasing-array // Author - Shumbul Arifa class Solution { public: bool checkPossibility(vector<int>& nums) { int dec = 0; bool decrease = 0; for (int i = 1; i < nums.size(); i++) { decrease = 0; if (nums[i - 1] > nums[i]) dec++, decrease = 1; if (decrease && i > 1 && nums[i - 2] > nums[i]) { if (i < nums.size() - 1 && nums[i - 1] <= nums[i + 1]) continue; if (i != nums.size() - 1) dec++; } } return dec < 2; } };
true
e94775d7598ad0e41a798568860cd19bbe249e02
C++
qooldeel/adonis
/sparse/sparsematrix.hh
UTF-8
14,382
2.6875
3
[]
no_license
#ifndef SPARSE_MATRIX_CONTAINER_HH #define SPARSE_MATRIX_CONTAINER_HH #include <iostream> #include <vector> #include "umftypetraits.hh" #include "sparseutilities.hh" #include "../common/globalfunctions.hh" #include "../common/error.hh" #include "../common/typeadapter.hh" #include "../common/adonisassert.hh" #include "../misc/useful.hh" namespace Adonis{ /** * \brief For rectangular sparse matrices, the position pointer has a * different size. * */ template<char C> class WhatCompression; //! specialization template<> class WhatCompression<'r'>{ //!row compressed public: template<class INT> static inline INT dim(INT rows, INT cols){ return rows; } }; template<> class WhatCompression<'R'>{ //!row compressed-- just invoke 'r' version public: template<class INT> static inline INT dim(INT rows, INT cols){ return WhatCompression<'r'>::dim(rows,cols); } }; template<> class WhatCompression<'c'>{ //!column compressed public: template<class INT> static inline INT dim(INT rows, INT cols){ return cols; } }; template<> class WhatCompression<'C'>{ //!row compressed -- just invoke 'c' version public: template<class INT> static inline INT dim(INT rows, INT cols){ return WhatCompression<'c'>::dim(rows,cols); } }; /** * \brief Compressed Sparse Row or Column format. The latter is used by * UMFPACK. * * References: * [1] [Y. SAAD, "Iterative Methods for Sparse Linear Systems", 2nd ed., SIAM, chap. 3.4, pp. 84] */ template<class T, char RC, class INT = int> class CompressedSparseStorage{ public: typedef INT IndexType; typedef T value_type; typedef typename TypeAdapter<T>::BaseType BaseType; typedef std::size_t SizeType; typedef value_type* PointerType; typedef IndexType* IndexPointerType; typedef std::vector<typename UmfpackTypeTraits<BaseType>::Type> VecUmfBaseType; static const char compressionType = RC; //alias static const char Value = RC; //! the char-int value is transformed const char value() const {return Value_;} //!default constructor CompressedSparseStorage():rows_(0),cols_(0),nz_(0), posdim_(0){ index_ = new IndexType[nz_]; //! the last position is the number of nonzeros, anyway, here 0 too //posdim_ = WhatCompression<RC>::dim(rows_,cols_)+1; position_ = new IndexType[posdim_]; a_ = new T[nz_]; for(IndexType i = 0; i < nz_; ++i){ index_[i] = IndexType(); a_[i] = T(); } for(IndexType t = 0; t < posdim_;++t) position_[t] = IndexType(); } //! constructor: pos can just contain the positions or the positions+1 //!In any case, the last entry of<TT> position_ </TT>contains <TT>nz_</TT> template<class IV1, class IV2, class V> CompressedSparseStorage(IndexType m, IndexType n, IndexType nz, const IV1& ix, const IV2& pos, const V& val):rows_(m),cols_(n),nz_(nz), posdim_(WhatCompression<RC>::dim(rows_,cols_)+1){ SizeType dimix = static_cast<SizeType>(std::distance(ix.begin(),ix.end())), dimval = static_cast<SizeType>(std::distance(val.begin(),val.end())); adonis_assert(dimix == dimval && dimix == static_cast<SizeType>(nz)); index_ = new IndexType[nz]; IndexType pdimm1 = WhatCompression<RC>::dim(m,n); position_ = new IndexType[posdim_]; a_ = new T[nz]; for(IndexType i = 0; i < nz; ++i){ index_[i] = ix[i]; a_[i] = val[i]; } for(IndexType t = 0; t < pdimm1; ++t) position_[t] = pos[t]; position_[pdimm1] = nz; } //! Read from dense matrix that is stored row-wise in a linear container template<class VEC> void fill_from_row_wise_dense(INT rows, INT cols, const VEC& Afull){ adonis_assert(static_cast<INT>(rows*cols) == static_cast<INT>(std::distance(Afull.begin(),Afull.end()))); if(RC == 'c' || RC == 'C'){ //column compressed form //typedef T value_type; typedef std::vector<T> VType; typedef std::vector<INT> IxVType; INT nz = 0; VType av; IxVType ix, pos; av.reserve(rows*cols); ix.reserve(rows*cols); pos.reserve(cols+1); nz = 0; bool detected = false; pos.push_back(0); for(INT j = 0; j < cols; ++j){ //! just swap for-loops detected = false; for(INT i = 0; i < rows; ++i){ if(!is_zero(Afull[RowMajor::offset(i,j,cols)])){ ix.push_back(i); av.push_back(Afull[RowMajor::offset(i,j,cols)]); nz++; detected = true; //o.k. found some non-negative entry in column j } } if(!detected){ ADONIS_ERROR(LinearAlgebraError,"Full matrix contains a (nearly) ZERO column.\n This may cause severe problems!"); //ADONIS_INFO(Information,"Full matrix contains a (nearly) ZERO column"); //pos.push_back(pos.back()); //just duplicate last entry of pos } pos.push_back(nz); } //! o.k. now we've filled the vectors. now we assign them to the array delete[] index_; delete[] a_; delete[] position_; index_ = new INT[nz]; a_ = new T[nz]; position_ = new INT[cols+1]; //now assign values for(INT i = 0; i < nz; ++i){ index_[i] = ix[i]; a_[i] = av[i]; } for(INT t = 0; t < cols; ++t) position_[t] = pos[t]; position_[cols] = nz; //! assign rows_= rows; cols_ = cols; nz_ = nz; posdim_ = cols+1; } if(RC == 'r' || RC == 'R'){ //column compressed form //typedef T value_type; typedef std::vector<T> VType; typedef std::vector<INT> IxVType; INT nz = 0; VType av; IxVType ix, pos; av.reserve(rows*cols); ix.reserve(rows*cols); pos.reserve(cols+1); nz = 0; bool detected = false; pos.push_back(0); for(INT i = 0; i < rows; ++i){ //DIFFERENCE to 'c','C' detected = false; for(INT j = 0; j < cols; ++j){ if(!is_zero(Afull[RowMajor::offset(i,j,cols)])){ ix.push_back(j); //DIFFERENCE to 'c','C': store column av.push_back(Afull[RowMajor::offset(i,j,cols)]); nz++; detected = true; //o.k. found some non-negative entry in column j } } if(!detected){ ADONIS_ERROR(LinearAlgebraError,"Full matrix contains a (nearly) ZERO column.\n This may cause severe problems!"); //ADONIS_INFO(Information,"Full matrix contains a (nearly) ZERO column"); //pos.push_back(pos.back()); //just duplicate last entry of pos } pos.push_back(nz); } //! o.k. now we've filled the vectors. now we assign them to the array delete[] index_; delete[] a_; delete[] position_; index_ = new INT[nz]; a_ = new T[nz]; position_ = new INT[rows+1]; //DIFFERENCE to 'c','C' for(INT i = 0; i < nz; ++i){ index_[i] = ix[i]; a_[i] = av[i]; } for(INT t = 0; t < rows; ++t) //DIFFERENCE to 'c','C' position_[t] = pos[t]; position_[rows] = nz; //DIFFERENCE to 'c','C' //! assign rows_= rows; cols_ = cols; nz_ = nz; posdim_ = rows+1; } } //! 2nd constructor -- construct from iterators template<class InputIter1, class InputIter2, class InputIter3> CompressedSparseStorage(IndexType m, IndexType n, IndexType nz, InputIter1 f1, InputIter1 l1, InputIter2 f2, InputIter2 l2,InputIter3 f3, InputIter3 l3):rows_(m),cols_(n),nz_(nz),posdim_(WhatCompression<RC>::dim(m,n)+1){ SizeType dimix = static_cast<SizeType>(std::distance(f1,l1)), dimval = static_cast<SizeType>(std::distance(f3,l3)); adonis_assert(dimix == dimval && dimix == static_cast<SizeType>(nz)); index_ = new IndexType[nz]; IndexType pdimm1 = posdim_-1;// WhatCompression<RC>::dim(m,n); position_ = new IndexType[posdim_]; a_ = new T[nz]; InputIter1 it1 = f1; InputIter3 it3 = f3; for(IndexType i = 0; i < nz; ++i){ index_[i] = *it1; a_[i] = *it3; ++it1; ++it3; } InputIter2 it2 = f2; for(IndexType t = 0; t < pdimm1; ++t){ position_[t] = *it2; ++it2; } position_[pdimm1] = nz; } //! copy constructor CompressedSparseStorage(const CompressedSparseStorage& spmtx){ rows_ = spmtx.rows_; cols_ = spmtx.cols_; nz_ = spmtx.nz_; posdim_ = spmtx.posdim_; index_ = new IndexType[nz_]; position_ = new IndexType[posdim_]; a_ = new T[nz_]; for(IndexType i = 0; i< nz_; ++i){ index_[i] = spmtx.index_[i]; a_[i] = spmtx.a_[i]; } //! o.k. just copy from spmtx for(IndexType t = 0; t < posdim_; ++t) position_[t] = spmtx.position_[t]; } //! copy assignment CompressedSparseStorage& operator=(const CompressedSparseStorage& spmtx){ if(this != &spmtx){ //no self-assignment //adonis_assert(rows_ == spmtx.rows_ && cols_ == spmtx.cols_); //adonis_assert(nz_ == spmtx.nz_); if(nz_ != spmtx.nz_){ //std::cout << "===== OPERATOR=: CREATE NEW ARRAYS..."<< std::endl; delete[] index_; delete[] position_; delete[] a_; index_ = new IndexType[spmtx.nz_]; position_ = new IndexType[spmtx.posdim_]; a_ = new T[spmtx.nz_]; } rows_ = spmtx.rows_; cols_ = spmtx.cols_; nz_ = spmtx.nz_; posdim_ = spmtx.posdim_; for(IndexType i = 0; i< nz_; ++i){ index_[i] = spmtx.index_[i]; a_[i] = spmtx.a_[i]; } //! o.k. just copy from spmtx for(IndexType t = 0; t < posdim_; ++t){ position_[t] = spmtx.position_[t]; } } return *this; } //! destructor ~CompressedSparseStorage(){ delete[] a_; delete[] position_; delete[] index_; } void resize(SizeType m, SizeType n, SizeType nnz){ rows_ = m; cols_ = n; nz_ = nnz; posdim_ = WhatCompression<RC>::dim(rows_,cols_)+1; if((index_ != 0) && (position_ != 0) && (a_ != 0)){ delete[] index_; delete[] position_; delete[] a_; } index_ = new IndexType[nz_]; position_ = new IndexType[posdim_]; a_ = new T[nz_]; // initialize arrays --- better it is to prevent spurious results ;) for(IndexType i = 0; i < nz_; ++i){ index_[i] = 0; a_[i] = T(0); } for(IndexType i = 0; i < posdim_; ++i) position_[i] = 0; } //! CAUTION: no size check, it's up to you to provide properly sized //! input data! template<class IT> void fill_index(IT dataIt){ for(IndexType i = 0; i < nz_; ++i) index_[i] = *(dataIt++); } template<class IT> void fill_position(IT posIt){ for(IndexType i = 0; i < posdim_; ++i) position_[i] = *(posIt++); } template<class VALIT> void fill_values(VALIT valIt){ for(IndexType i = 0; i < nz_; ++i) a_[i] = *(valIt++); } //! return pointer to beginning of arrays for compressed storage PointerType values(){return &a_[0];} IndexPointerType index(){return &index_[0];} IndexPointerType position(){return &position_[0];} const PointerType values() const {return &a_[0];} const IndexPointerType index() const {return &index_[0];} const IndexPointerType position() const{return &position_[0];} //! number of nonzeros in matrix const IndexType nonz() const {return nz_;} const IndexType rows() const {return rows_;} const IndexType cols() const {return cols_;} //! alias const IndexType size1() const {return rows_;} const IndexType size2() const {return cols_;} const value_type& operator[](SizeType i) const { adonis_assert(static_cast<INT>(i) < nz_); return a_[i]; } value_type& operator[](SizeType i){ adonis_assert(static_cast<INT>(i) < nz_); return a_[i]; } const IndexType dimension_of_position_array() const{return posdim_;} void restructure(SizeType m, SizeType n, SizeType nz){ delete[] index_; delete[] position_; delete[] a_; index_ = new IndexType [nz]; IndexType posdim = WhatCompression<RC>::dim(m,n)+1; position_ = new IndexType [posdim]; a_ = new T[nz]; //fill with defaults for proper initialization for(SizeType i = 0; i < nz; ++i){ index_[i] = 0; a_[i] = T(); } SizeType pm1 = posdim-1; for(SizeType p = 0; p < pm1; ++p) position_[p] = 0; position_[pm1] = nz; } // void reserve(SizeType rows, SizeType cols){ // delete[] index_; // delete[] position_; // delete[] a_; // } friend std::ostream& operator<<(std::ostream& os, const CompressedSparseStorage& spmtx){ os << std::endl<< "Sparse matrix: rows: "<< spmtx.rows_ << " cols: "<< spmtx.cols_ << " #(nonzeros): "<< spmtx.nz_ << std::endl; os << "Storage organisation: Compressed Sparse " << ((RC == 'c' || RC == 'C')? "Column " : "Row ") << "Scheme:"<< std::endl; os << std::endl<< "nonzeros:"<<std::endl; for(IndexType i = 0; i < spmtx.nz_; ++i) os << spmtx.a_[i] << " "; os << std::endl; os << "index: "<< std::endl; for(IndexType i = 0; i < spmtx.nz_; ++i) os << spmtx.index_[i] << " "; os << std::endl; os << "position:"<<std::endl; IndexType dm = spmtx.posdim_; //WhatCompression<RC>::dim(spmtx.rows_,spmtx.cols_)+1; for(IndexType t = 0; t < dm; ++t) os << spmtx.position_[t] << " "; os << std::endl; return os; } //! solve system \f$ A\cdot x = b, \f$ where \f$A\f$ is sparse //! DOES THIS ONLY WORK FOR n x n MATRICES ???????? template<class V> V& solve(V& x, const V& b){ #if USE_UMFPACK if(static_cast<INT>(x.size() == 0)) x.resize(cols_); //typedef typename UmfpackTypeTraits<INT>::Type IndexType; typedef typename UmfpackTypeTraits<T>::Type Type; typedef typename Type::BaseType BaseType; int status, sys; BaseType Control [UMFPACK_CONTROL], Info[UMFPACK_INFO]; #else ADONIS_ERROR(NotImplementedError,"Sorry, I was too lazy to come up with a substitute for UMFPACK."); #endif } private: IndexType rows_, cols_, nz_, //number of nonzeros posdim_; //size of position array IndexType* index_; //the index of size nz IndexType* position_; //position marking beginnings of rows/columns in a_ T* a_; enum{Value_ = RC}; //! this is needed for the solution of a system \f$ A\cdot x = b\f$, //! especially when using Umfpack VecUmfBaseType are_, aim_, bre_,bim_, xre_,xim_; }; } //end namespace #endif
true
dcad87175be0b642abf968b43f56983b5b1df1a1
C++
tomermy/iot_workshop
/Project2/EX2/EX2.ino
UTF-8
12,300
2.8125
3
[]
no_license
/* The Secret Knock Detecting Box The knocking box embedded a piezo sensor for knocking detection. The Idea behind it is to improve piezo sensitivity and create a more reliable sensor. The Arduino uses the knocking box as a sensor to record a knocking pattern. The user can set a recording knocking pattern as a locking code by pressing the program mode button. Once the user press the program button, the device will play a ringtone and turn on the yellow LED. The device starts to record the user secret sequence right after the tone and until yellow LED is off. To enter a secret code attempt to the device, the user has to make a trigger knock. Once such a trigger established, the device plays a code attempt ringtone, and all LEDs are on. The device stops to record the attempt once all LEDs are off. If the attempt succeeded, a Starwar ringtone is played and turn on the green LED. Otherwise, a failure ringtone is played and turn on the red LED. * The device uses EEPROM to store the secret code, by that, the code does not change when the device is off. The Circuit: * Input: Button - 6 - turn into program mode. Piezo - A0 - knock sensor. * Output: Speaker - 9 - play ringtones to indicate user. Red Led - 13 Yello Led - 12 Green Led - 11 Video link: https://youtu.be/RMhu9U0CG5A Created By: Gilad_Ram #305433260 Tomer_Maimon #308301498 Alon_Shprung #203349048 */ #include <EEPROM.h> // constants const byte RED_LED_PIN= 13; const byte YELLOW_LED_PIN= 12; const byte GREEN_LED_PIN= 11; const byte PIEZO_SENSOR_PIN= A0; const byte SPEAKER_PIN= 4; const int BUTTON_PIN = 6; // logic constants const int rejectValue = 37; // The max diffrenet value between secret knock and input knock const int averageRejectValue = 25; // The max average error const int knockFadeTime = 150; // Debounce timer between knocks. const byte INTERVAL_NORMALIZATION_BOUND = 200; const int MAX_KNOCKS = 30; const int THRESHOLD = 45; const int KNOCK_SAMPLE_INTERVAL = 2000; // Knock variables byte knockKnockCode[MAX_KNOCKS] = {0, 0, 0, 0, 0}; // Initial with no code... Red Light is ON. int knockReading[MAX_KNOCKS]; boolean inProgramMode = false; int pastSoundValue=0; int currentSoundValue; int toProgramModebuttonState; int diffBetweenSensorValues; // RTTL char *songATeam = "A-Team:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#"; char *songStarWars = "StarWars:d=4,o=5,b=45:32p,32f#,32f#,32f#,8b.,8f#.6,32e6,32d#6,32c#6,8b.6,16f#.6,32e6,32d#6,32c#6,8b.6,16f#.6,32e6,32d#6,32e6"; char *songGadget = "Gadget:d=16,o=5,b=50:32d#,32f,32f#,32g#,a#,f#"; char *songZelda = "shinobi:d=4,o=5,b=140:b,f#6,d6,b,g,f#,e,2f#.,a,1f#"; // Leds initial state int redLedState = LOW; int yellowLedState = LOW; int greenLedState = LOW; void setup() { // set the digital pin as output: pinMode(PIEZO_SENSOR_PIN, INPUT); pinMode(BUTTON_PIN, INPUT); pinMode(RED_LED_PIN, OUTPUT); pinMode(YELLOW_LED_PIN, OUTPUT); pinMode(GREEN_LED_PIN, OUTPUT); // load date from memory loadDataFromMemory(); Serial.begin(9600); } void loop() { currentSoundValue = analogRead(PIEZO_SENSOR_PIN); toProgramModebuttonState = digitalRead(BUTTON_PIN); diffBetweenSensorValues = currentSoundValue - pastSoundValue; if (diffBetweenSensorValues > THRESHOLD){ // A trigger knock accrued play_rtttl(songGadget); unlockAttempt(); } pastSoundValue= currentSoundValue; if( toProgramModebuttonState == HIGH){ // Program a new secret code digitalWrite(YELLOW_LED_PIN, HIGH); play_rtttl(songATeam); programNewCode(); } } void resetListeningArray(){ Serial.println("reset the listening array."); int i = 0; // First lets reset the listening array. for (i=0;i<MAX_KNOCKS;i++){ knockReading[i]=0; } } void printListeningArray(){ Serial.println("printing the listening array."); int i = 0; // First lets reset the listening array. for (i=0;i<MAX_KNOCKS;i++){ Serial.println(knockKnockCode[i]); } } void programNewCode(){ listenToSecretKnock(); saveNewCodeData(); // and we blink the green and red alternately to show that program is complete. Serial.println("New code stored."); printListeningArray(); digitalWrite(YELLOW_LED_PIN, LOW); inProgramMode = false; } void unlockAttempt(){ setAllLeds(HIGH); listenToSecretKnock(); setAllLeds(LOW); if (validateKnock() == true){ // The Knock code is valid!!! digitalWrite(GREEN_LED_PIN, HIGH); Serial.println("Secret knock succeeded."); play_rtttl(songStarWars); digitalWrite(GREEN_LED_PIN, LOW); }else{ // The Knock code is not valid!!! digitalWrite(RED_LED_PIN, HIGH); Serial.println("Secret knock failed."); play_rtttl(songZelda); digitalWrite(RED_LED_PIN, LOW); } } // Set all leds to the given value void setAllLeds(int value){ digitalWrite(RED_LED_PIN, value); digitalWrite(YELLOW_LED_PIN, value); digitalWrite(GREEN_LED_PIN, value); } void listenToSecretKnock(){ Serial.println("listen to secret knock starting..."); int currentNumberOfKnocks=0; // Incrementer for the array. int startTime=millis(); // Reference for when this knock started. int now=millis(); int timePassed = now - startTime; resetListeningArray(); delay(knockFadeTime); // wait for this peak to fade before we listen to the next one. do { //listen for the next knock or wait for it to timeout. currentSoundValue = analogRead(PIEZO_SENSOR_PIN); diffBetweenSensorValues = currentSoundValue - pastSoundValue; if (diffBetweenSensorValues >= THRESHOLD){ // A Knock //record the delay time. Serial.println(diffBetweenSensorValues); Serial.println("knock."); now=millis(); knockReading[currentNumberOfKnocks] = now-startTime; currentNumberOfKnocks ++; //increment the counter startTime=now; // and reset our timer for the next knock delay(knockFadeTime); // again, a little delay to let the knock decay. } pastSoundValue = currentSoundValue; now=millis(); timePassed = now -startTime; } while ((timePassed < KNOCK_SAMPLE_INTERVAL) && (currentNumberOfKnocks < MAX_KNOCKS)); } void saveNewCodeData(){ Serial.println("Storing new code."); int maxInterval = getMaxKnockInterval(); int i = 0; for (i=0;i<MAX_KNOCKS;i++){ // normalize the times knockKnockCode[i]= map(knockReading[i],0, maxInterval, 0, INTERVAL_NORMALIZATION_BOUND); EEPROM.write(i, knockKnockCode[i]); } } void loadDataFromMemory(){ Serial.println("Loading code from memory..."); int i = 0; for (i=0;i<MAX_KNOCKS;i++){ knockKnockCode[i]= EEPROM.read(i); } } int getMaxKnockInterval(){ int maxKnockInterval = 0; int currentInterval = 0; int i=0; for (i=0; i< MAX_KNOCKS; i++){ // normalize the times currentInterval = knockReading[i]; if (knockReading[i] > maxKnockInterval){ maxKnockInterval = knockReading[i]; } } return maxKnockInterval; } /* Compare the reading knock to the secret knock code. The comparison of the knocks is calculated with an error rate. returns true - valid code false - invalid code. */ boolean validateKnock(){ int secretKnockCount = compareLengths(); if(secretKnockCount == -1){ // There is a diffrence in the length of the codes return false; } // Once the length is the same we can check the content. int i; int totaltimeDifferences=0; int timeDiff=0; int maxKnockInterval = getMaxKnockInterval(); for (i=0;i<MAX_KNOCKS;i++){ // normalize the times knockReading[i]= map(knockReading[i],0, maxKnockInterval, 0, INTERVAL_NORMALIZATION_BOUND); timeDiff = abs(knockReading[i]-knockKnockCode[i]); if (timeDiff > rejectValue){ Serial.println(timeDiff); // a value diff is to big return false; } totaltimeDifferences += timeDiff; } int totalErrorAverage = totaltimeDifferences/secretKnockCount; Serial.print("The total error Average is: "); Serial.println(totalErrorAverage); if (totalErrorAverage > averageRejectValue){ return false; } return true; } int compareLengths(){ // simply compares the length of the codes int currentKnockCount = 0; int secretKnockCount = 0; int maxKnockInterval = 0; // We use this later to normalize the times. int i=0; for (i=0;i<MAX_KNOCKS;i++){ if (knockReading[i] > 0){ currentKnockCount++; } if (knockKnockCode[i] > 0){ //todo: precalculate this. secretKnockCount++; } } if (currentKnockCount != secretKnockCount){ Serial.println("The length is not equale"); return -1; }else{ Serial.println("The length is equale"); return secretKnockCount; } } /* * This is the RTTL Part * We used the code from the following link * http://www.instructables.com/id/Aruino-Tone-RTTL-Player/ */ #define OCTAVE_OFFSET 0 // These values can also be found as constants in the Tone library (Tone.h) int notes[] = { 0, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951 }; #define isdigit(n) (n >= '0' && n <= '9') void play_rtttl(char *p) { // Absolutely no error checking in here byte default_dur = 4; byte default_oct = 6; int bpm = 63; int num; long wholenote; long duration; byte note; byte scale; // format: d=N,o=N,b=NNN: // find the start (skip name, etc) while(*p != ':') p++; // ignore name p++; // skip ':' // get default duration if(*p == 'd') { p++; p++; // skip "d=" num = 0; while(isdigit(*p)) { num = (num * 10) + (*p++ - '0'); } if(num > 0) default_dur = num; p++; // skip comma } // get default octave if(*p == 'o') { p++; p++; // skip "o=" num = *p++ - '0'; if(num >= 3 && num <=7) default_oct = num; p++; // skip comma } // get BPM if(*p == 'b') { p++; p++; // skip "b=" num = 0; while(isdigit(*p)) { num = (num * 10) + (*p++ - '0'); } bpm = num; p++; // skip colon } // BPM usually expresses the number of quarter notes per minute wholenote = (60 * 1000L / bpm) * 4; // this is the time for whole note (in milliseconds) // now begin note loop while(*p) { // first, get note duration, if available num = 0; while(isdigit(*p)) { num = (num * 10) + (*p++ - '0'); } if(num) duration = wholenote / num; else duration = wholenote / default_dur; // we will need to check if we are a dotted note after // now get the note note = 0; switch(*p) { case 'c': note = 1; break; case 'd': note = 3; break; case 'e': note = 5; break; case 'f': note = 6; break; case 'g': note = 8; break; case 'a': note = 10; break; case 'b': note = 12; break; case 'p': default: note = 0; } p++; // now, get optional '#' sharp if(*p == '#') { note++; p++; } // now, get optional '.' dotted note if(*p == '.') { duration += duration/2; p++; } // now, get scale if(isdigit(*p)) { scale = *p - '0'; p++; } else { scale = default_oct; } scale += OCTAVE_OFFSET; if(*p == ',') p++; // skip comma for next note (or we may be at the end) // now play the note if(note) { tone(SPEAKER_PIN, notes[(scale - 4) * 12 + note]); delay(duration); noTone(SPEAKER_PIN); } else { delay(duration); } } }
true
a6ac8889d7863015e17514c4ec18c36b9713a153
C++
zuev-stepan/MIPT
/MIPT-2SEM/mst/boruvka.cpp
UTF-8
2,393
2.859375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <ctime> using namespace std; typedef vector<vector<double> > Graph; vector<int> go[100000]; struct edge { int x, y; double l; edge(){} edge(int a, int b, double c) : x(a), y(b), l(c) {} }; bool cmp(edge a, edge b){return a.l < b.l;} void dfs(int x, int k, int* used) { used[x] = k; for (int i = 0; i < go[x].size(); i++) { int y = go[x][i]; if (used[y] == 0) dfs(y, k, used); } } double boruvka(vector<edge> r, int n) { sort(r.begin(), r.end(), cmp); int used[n]; int m = r.size(); int ans[m], nr[n]; for (int i = 0; i < n; i++) go[i].clear(); for (int i = 0; i < m; i++) ans[i] = 0; int sz = 0; int cur = 0; double MST = 0; while (sz < n - 1 && cur < n) { cur++; for (int i = 0; i < n; i++) used[i] = 0; int k = 0; for (int i = 0; i < n; i++) if (used[i] == 0) dfs(i, ++k, used); for (int i = 1; i <= k; i++) nr[i] = -1; for (int i = 0; i < m; i++) if (used[r[i].x] != used[r[i].y]) { int x = used[r[i].x]; int y = used[r[i].y]; if (nr[x] == -1 || r[i].l < r[nr[x]].l) nr[x] = i; if (nr[y] == -1 || r[i].l < r[nr[y]].l) nr[y] = i; } for (int i = 1; i <= k; i++) if (nr[i] != -1 && ans[nr[i]] == 0) { int x = nr[i]; ans[x] = 1; MST += r[x].l; go[r[x].x].push_back(r[x].y); go[r[x].y].push_back(r[x].x); sz++; } } return MST; } Graph readGraph() { int n, m; cin >> n >> m; Graph g(n); for (int i = 0; i < n; i++) { g[i].resize(n); } int x, y; double l; for(int i = 0; i < m; i++) { cin >> x >> y >> l; g[x][y] = g[y][x] = l; } return g; } double getTime() { return clock() / (CLOCKS_PER_SEC / 1000); } int main() { freopen("input.txt", "rt", stdin); freopen("outB.txt", "wt", stdout); Graph g = readGraph(); vector<edge> a; for (int i = 0; i < g.size(); i++) for (int j = i + 1; j < g.size(); j++) if (g[i][j] > 0) a.push_back(edge(i, j, g[i][j])); double t = getTime(); for(int i = 0; i < 10; i++) { boruvka(a, g.size()); } cout << boruvka(a, g.size()) << '\n' << getTime() - t; return 0; }
true
d477daf705da3585c5618faf6c367a631f65a326
C++
KoiKomei/Sokoban
/Sokoban/FileManager.cpp
UTF-8
2,614
2.75
3
[]
no_license
#include "FileManager.h" FileManager::FileManager() { found = false; } FileManager::~FileManager() { } void FileManager::LoadContent(const char *filename, vector<vector<string>> &attributes, vector<vector<string>> &contents) { ifstream openfile(filename); string line, newLine; if (openfile.is_open()) { while (!openfile.eof()) { stringstream str; getline(openfile, line); if (line.find("Load=") != string::npos) { type = LoadType::Attributes; line = line.erase(0, line.find("=") + 1); tempAttributes.clear(); } else { type = LoadType::Contents; tempContents.clear(); } str << line; while (getline(str, newLine, ']')) { newLine.erase(remove(newLine.begin(), newLine.end(), '['), newLine.end()); string erase = " \t\n\r"; newLine.erase(newLine.find_last_not_of(erase)+1); if (type == LoadType::Attributes) { tempAttributes.push_back(newLine); } else { tempContents.push_back(newLine); } cout << newLine << endl; } if (type == LoadType::Contents && tempContents.size() > 0) { attributes.push_back(tempAttributes); contents.push_back(tempContents); } } } else { } } void FileManager::LoadContent(const char *filename, vector<vector<string>> &attributes, vector<vector<string>> &contents, string ID) { ifstream openfile(filename); string line, newLine; if (openfile.is_open()) { while (!openfile.eof()) { stringstream str; getline(openfile, line); if (line.find("EndLoad=") != string::npos && line.find(ID) != string::npos) { found = false; break; } else { if (line.find("Load=") != string::npos && line.find(ID) != string::npos) { found = true; continue; } } if (found) { if (line.find("Load=") != string::npos) { type = LoadType::Attributes; line = line.erase(0, line.find("=") + 1); tempAttributes.clear(); } else { type = LoadType::Contents; tempContents.clear(); } str << line; while (getline(str, newLine, ']')) { newLine.erase(remove(newLine.begin(), newLine.end(), '['), newLine.end()); string erase = " \t\n\r"; newLine.erase(newLine.find_last_not_of(erase) + 1); if (type == LoadType::Attributes) { tempAttributes.push_back(newLine); } else { tempContents.push_back(newLine); } cout << newLine << endl; } if (type == LoadType::Contents && tempContents.size() > 0) { attributes.push_back(tempAttributes); contents.push_back(tempContents); } } } } else { } }
true
d14d29fa75f94e4468516fd0522e5d4a869165cd
C++
secondtonone1/fingerserver
/GameMasterTool/LoginPanel.cpp
GB18030
3,854
2.5625
3
[]
no_license
#include "LoginPanel.h" #include "GameMasterTool.h" using namespace Lynx; IMPLEMENT_CLASS(LoginPanel, wxPanel) BEGIN_EVENT_TABLE(LoginPanel, wxPanel) EVT_BUTTON(myID_LOGIN_BTN, onLoginBtnClicked) EVT_BUTTON(myID_LOGIN_QUIT, onQuitBtnClicked) END_EVENT_TABLE() LoginPanel::LoginPanel(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxPanel(parent, id, pos, size, style) { mAccountCtrl = NULL; mPasswordCtrl = NULL; mLoginBtn = NULL; mQuitBtn = NULL; } LoginPanel::~LoginPanel() { release(); } bool LoginPanel::initial() { wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL); SetSizer(topSizer); wxBoxSizer* boxSizer = new wxBoxSizer(wxVERTICAL); topSizer->Add(boxSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 3); boxSizer->Add(10, 10, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); wxBoxSizer* accountSizer = new wxBoxSizer(wxHORIZONTAL); boxSizer->Add(accountSizer, 0, wxGROW | wxALL, 5); wxStaticText* accountLabel = new wxStaticText(this, wxID_STATIC, wxT("˺:"), wxDefaultPosition, wxDefaultSize, 0); accountSizer->Add(accountLabel, 0, wxALIGN_LEFT | wxALL, 5); mAccountCtrl = new wxTextCtrl(this, myID_LOGIN_ACCOUNT_TEXT, wxT(""), wxDefaultPosition, wxSize(150, 20)); mAccountCtrl->SetMaxLength(20); accountSizer->Add(mAccountCtrl, 0, wxALIGN_RIGHT | wxALL, 5); wxBoxSizer* passwordSizer = new wxBoxSizer(wxHORIZONTAL); boxSizer->Add(passwordSizer, 0, wxGROW | wxALL, 5); wxStaticText* passwordLabel = new wxStaticText(this, wxID_STATIC, wxT(":"), wxDefaultPosition, wxDefaultSize, 0); passwordSizer->Add(passwordLabel, 0, wxALIGN_LEFT | wxALL, 5); mPasswordCtrl = new wxTextCtrl(this, myID_LOGIN_PASSWORD_TEXT, wxT(""), wxDefaultPosition, wxSize(150, 20), wxTE_PASSWORD); mPasswordCtrl->SetMaxLength(20); passwordSizer->Add(mPasswordCtrl, 0, wxALIGN_RIGHT | wxALL, 5); // ťSizer wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); boxSizer->Add(btnSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 3); // ¼ť wxButton* mLoginBtn = new wxButton(this, myID_LOGIN_BTN, wxT("¼"), wxDefaultPosition, wxDefaultSize, 0); btnSizer->Add(mLoginBtn, 0, wxALIGN_CENTER_VERTICAL | wxALL, 3); // ˳ť wxButton* mQuitBtn = new wxButton(this, myID_LOGIN_QUIT, wxT("˳"), wxDefaultPosition, wxDefaultSize, 0); btnSizer->Add(mQuitBtn, 0, wxALIGN_CENTER_VERTICAL | wxALL, 3); mAccountCtrl->SetFocus(); // tab˳ mAccountCtrl->MoveAfterInTabOrder(mQuitBtn); mPasswordCtrl->MoveAfterInTabOrder(mAccountCtrl); mLoginBtn->MoveAfterInTabOrder(mPasswordCtrl); mQuitBtn->MoveAfterInTabOrder(mLoginBtn); // õ¼Ĭϴ mLoginBtn->SetDefault(); topSizer->Fit(this); topSizer->SetSizeHints(this); return true; } void LoginPanel::release() { mAccountCtrl = NULL; mPasswordCtrl = NULL; mLoginBtn = NULL; mQuitBtn = NULL; } void LoginPanel::onLoginBtnClicked(wxCommandEvent& ev) { wxString account = mAccountCtrl->GetValue(); wxString password = mPasswordCtrl->GetValue(); if (account.empty()) { LOG_WARN("Account is empty."); wxMessageBox(wxT("˻Ϊ"), wxT("¼"), wxOK); return; } if (password.empty()) { LOG_WARN("Password is empty."); wxMessageBox(wxT("벻Ϊ"), wxT("¼"), wxOK); return; } LogicSystem::getSingleton().setAccountName(account.c_str()); LogicSystem::getSingleton().setAccountPassword(password.c_str()); MAIN_FRAME().showMainFrameWindow(); } void LoginPanel::onQuitBtnClicked(wxCommandEvent& ev) { MAIN_FRAME().Close(true); }
true
7ada185ea046efcc9c9e2a51e205e051eb9966b1
C++
BilhaqAD07/AlgoritmaPemrograman
/SEMESTER 1/ALPROM 1/.vscode/main.cpp
UTF-8
824
3.21875
3
[]
no_license
#include <iostream> using namespace std; float KONVERSIKEL(float A){ float I; I= A+273; return I; } float KONVERSIFAR(float B){ float J; J= B*1.8+32; return J; } int main(){ system("cls"); float n,f,k,F,K; char konversi; cout << "Masukkan Nilai(Celcius) = "; cin >> n; cout << "Dikonversi ke-(F/K) = "; cin >> konversi; switch (konversi) { case 'k': k=KONVERSIKEL(n); cout << "HASIL = " << k; break; case 'f': f=KONVERSIFAR(n); cout << "HASIL = " << f; break; case 'K': K=KONVERSIKEL(n); cout << "HASIL = " << K; break; case 'F': F=KONVERSIFAR(n); cout << "HASIL = " << F; break; default: cout << "Input Konversi Salah, Silakan coba lagi"; } return 0; }
true
6edd96f7808a842c350b35032fbd07ac910e95ca
C++
gisilves/amsdaq-code
/DAQ/DAQ/SlowControl/testq.cxx
UTF-8
641
2.578125
3
[]
no_license
#include <stdio.h> #include <iostream> #include "QList.h" using namespace std; int main() { QCommand *qcmd=0, *first=0; for (unsigned short i=0; i<5; i++) { if (i==0) { qcmd=new QCommand(0,1,2,3,i); cout << qcmd << endl; first=qcmd; } else { QCommand *dum=new QCommand(i,i,0,i,0); qcmd->SetNext(dum); qcmd=dum; } printf("i=%d\n",i); } qcmd=first; int cnt=0; do { printf("%d: %d %d %d %d %d\n",cnt, qcmd->GetCommand(0),qcmd->GetCommand(1),qcmd->GetCommand(2),qcmd->GetCommand(3),qcmd->GetCommand(4)); qcmd=qcmd->GetNext(); cnt++; } while (qcmd); }
true
dbd4087c8efbbae9e3bb46c7c0501bce19c448cc
C++
kdt3rd/gecko
/libs/base/size.h
UTF-8
6,267
3.453125
3
[ "MIT" ]
permissive
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #pragma once #include "type_util.h" #include <algorithm> #include <cmath> #include <cstdint> #include <cstdlib> #include <iostream> namespace base { //////////////////////////////////////// /// @brief Width and height template <typename T> class size { public: static_assert( has_arithmetic_ops<T>::value, "size should be composed of an arithmetic value type" ); using coord_type = T; constexpr size( void ) = default; constexpr size( const size & ) = default; constexpr size( size && ) noexcept = default; size &operator=( const size & ) = default; size &operator=( size && ) noexcept = default; ~size( void ) = default; /// @brief Constructor with width and height constexpr size( coord_type ww, coord_type hh ) : _w( ww ), _h( hh ) {} /// @brief construct a point with a differently typed point. /// /// Requires explicit construction to avoid blind conversion template <typename U> explicit constexpr size( const size<U> &o ) : _w( static_cast<coord_type>( o.w() ) ) , _h( static_cast<coord_type>( o.h() ) ) {} /// @brief explicit cast operator /// /// This enables conversion to a different size type, but /// requires explicit programmer specification of such. template <typename U> explicit inline operator size<U>() const { return size<U>( *this ); } /// @brief Width constexpr coord_type w( void ) const { return _w; } /// @brief Height constexpr coord_type h( void ) const { return _h; } /// @brief Set the width and height void set( coord_type ww, coord_type hh ) { _w = ww; _h = hh; } /// @brief Set the width void set_width( coord_type ww ) { _w = ww; } /// @brief Set the height void set_height( coord_type hh ) { _h = hh; } /// @brief Shrink width and height void shrink( coord_type dw, coord_type dh ) { _w -= dw; _h -= dh; } /// @brief Grow width and height void grow( coord_type dw, coord_type dh ) { _w += dw; _h += dh; } /// @brief Add two sizes together size operator+( const size &s ) const { return { _w + s._w, _h + s._h }; } /// @brief less than operator inline bool operator<( const size &o ) const { return _w < o._w || ( std::equal_to<coord_type>()( _w, o._w ) && _h < o._h ); } inline bool empty( void ) const { return _w <= coord_type( 0 ) && _h <= coord_type( 0 ); } private: coord_type _w = coord_type( 0 ), _h = coord_type( 0 ); }; //////////////////////////////////////// template <typename T> inline bool operator==( const size<T> &a, const size<T> &b ) { return std::equal_to<T>()( a.w(), b.w() ) && std::equal_to<T>()( a.h(), b.h() ); } template <typename T> inline bool operator!=( const size<T> &a, const size<T> &b ) { return !( a == b ); } /// @brief Round size up following rounding rules template <typename T> inline size<T> abs( const size<T> &s ) { using namespace std; return size<T>( static_cast<T>( abs( s.w() ) ), abs( s.h() ) ); } /// @brief Round size up following rounding rules template <typename T> inline size<T> round( const size<T> &s ) { using namespace std; return size<T>( static_cast<T>( round( s.w() ) ), round( s.h() ) ); } /// @brief Round size up to nearest integer based on half-way template <typename T> inline size<long> lround( const size<T> &s ) { using namespace std; return size<long>( lround( s.w() ), lround( s.h() ) ); } /// @brief Round size up to nearest integer based on half-way template <typename T> inline size<long long> llround( const size<T> &s ) { using namespace std; return size<long long>( llround( s.w() ), llround( s.h() ) ); } /// @brief Round size up to nearest integer template <typename T> inline size<T> ceil( const size<T> &s ) { using namespace std; return size<T>( static_cast<T>( ceil( s.w() ) ), static_cast<T>( ceil( s.h() ) ) ); } /// @brief Round size up to nearest integer template <typename T> inline size<T> floor( const size<T> &s ) { using namespace std; return size<T>( static_cast<T>( floor( s.w() ) ), static_cast<T>( floor( s.h() ) ) ); } /// @brief Round size up to nearest integer template <typename T> inline size<T> max( const size<T> &a, const size<T> &b ) { using namespace std; return size<T>( max( a.w(), b.w() ), max( a.h(), b.h() ) ); } /// @brief Round size up to nearest integer template <typename T> inline size<T> min( const size<T> &a, const size<T> &b ) { using namespace std; return size<T>( min( a.w(), b.w() ), min( a.h(), b.h() ) ); } //////////////////////////////////////// /// @brief Stream out a size object template <typename T> inline std::ostream &operator<<( std::ostream &out, const size<T> &s ) { out << s.w() << 'x' << s.h(); return out; } using fsize = size<float>; using dsize = size<double>; using isize = size<int32_t>; using lsize = size<int64_t>; //////////////////////////////////////// } // namespace base // provide std specialization of the functions above namespace std { template <typename T> inline base::size<T> abs( const base::size<T> &a ) { return base::abs( a ); } template <typename T> inline base::size<T> round( const base::size<T> &a ) { return base::round( a ); } template <typename T> inline base::size<long> lround( const base::size<T> &a ) { return base::lround( a ); } template <typename T> inline base::size<long long> llround( const base::size<T> &a ) { return base::llround( a ); } template <typename T> inline base::size<T> ceil( const base::size<T> &a ) { return base::ceil( a ); } template <typename T> inline base::size<T> floor( const base::size<T> &a ) { return base::floor( a ); } template <typename T> inline base::size<T> max( const base::size<T> &a, const base::size<T> &b ) { return base::max( a, b ); } template <typename T> inline base::size<T> min( const base::size<T> &a, const base::size<T> &b ) { return base::min( a, b ); } } // namespace std
true
d3004d8c0a87bb34871bbdecc461c7421b72a5d8
C++
Chewnonobelix/ArmyBuilder
/Src/Model/modif.cpp
UTF-8
994
2.90625
3
[]
no_license
#include "Header/Model/modif.h" Modif::Modif() { } Modif::Modif(const Modif & mod) { m_nom = mod.m_nom; m_cles = mod.m_cles; m_depuis = mod.m_depuis; m_vers = mod.m_vers; } modif Modif::getCles() { return m_cles; } QString Modif::getDepuis() { return m_depuis; } QString Modif::getVers() { return m_vers; } void Modif::setCles(modif cles) { m_cles = cles; } void Modif::setDepuis(QString depuis) { m_depuis = depuis; } void Modif::setVers(QString vers) { m_vers = vers; } void Modif::setNom(QString nom) { m_nom = nom; } QString Modif::getNom() { return m_nom; } void Modif::operator =(const Modif& mod) { m_nom = mod.m_nom; m_cles = mod.m_cles; m_depuis = mod.m_depuis; m_vers = mod.m_vers; } bool operator == (const Modif& a, const Modif& b) { return (a.m_nom == b.m_nom) && (a.m_cles == b.m_cles) && (a.m_depuis==b.m_depuis) && (a.m_vers==b.m_vers); } uint qHash(Modif mod) { return qHash(mod.getNom()); }
true
db4bce3cda712b758a0fea4601ce7b1b5bdf2780
C++
claimred/practice
/cpp/correct-the-time-string.cpp
UTF-8
2,253
3.390625
3
[]
no_license
//Task codewars id: 57873ab5e55533a2890000c7 /* Task codewars description: A new task for you! You have to create a method, that corrects a given time string. There was a problem in addition, so many of the time strings are broken. Time-Format is european. So from "00:00:00" to "23:59:59". <br> <br> Some examples: "09:10:01" -> "09:10:01"<br> "11:70:10" -> "12:10:10"<br> "19:99:99" -> "20:40:39"<br> "24:01:01" -> "00:01:01"<br> If the input-string is null or empty return exactly this value! (empty string for C++)<br/> If the time-string-format is invalid, return null. (empty string for C++) Have fun coding it and please don't forget to vote and rank this kata! :-) I have created other katas. Have a look if you like coding and challenges.*/ #include <string> #include <algorithm> #include <iostream> #include <sstream> #include <cctype> std::vector<std::string> split( std::string str, char c ) { std::vector<std::string> res; std::string tmp = ""; bool found = false; for (int i = 0; i < str.size(); i++) { if (str[i] == c) { found = true; if (!tmp.empty()) res.push_back(tmp); tmp.clear(); } else tmp.push_back(str[i]); } if (found) res.push_back(tmp); return res; } std::string correct(std::string timeString) { std::vector<std::string> spl = split(timeString, ':'); if (spl.size() != 3) return ""; for (int i = 0; i < timeString.size(); i++) { if (!std::isdigit(timeString[i]) && timeString[i] != ':') return ""; } int hh = std::atoi(spl[0].c_str()), mm = std::atoi(spl[1].c_str()), ss = std::atoi(spl[2].c_str()); int tmp = 0; if (ss > 59) { tmp = ss - 60; ss -= 60; mm++; } if (mm > 59) { tmp = mm - 60; mm -= 60; hh++; } if (hh > 23) { hh = hh % 24; } std::string res; spl[0] = std::to_string(hh); spl[1] = std::to_string(mm); spl[2] = std::to_string(ss); if (hh < 10) res += "0"; res += spl[0]; res += ":"; if (mm < 10) res += "0"; res += spl[1]; res += ":"; if (ss < 10) res += "0"; res += spl[2]; return res; }
true
40808da7778240bc923bd45475380a098048f25a
C++
ZiqiuZhou/Linux_HPC
/chapter6_高级IO/sendfile_server.cpp
GB18030
1,765
2.625
3
[]
no_license
#include <sys/socket.h> #include <iostream> #include <netinet/in.h> #include <arpa/inet.h> #include <cassert> #include <unistd.h> #include <cstdlib> #include <string.h> #include <vector> #include <string> #include <cerrno> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <fcntl.h> #include <sys/sendfile.h> /*writevȣsendfile ûΪĿļbufferҲȡļдbuffer,Чʺܸ*/ int main(int argc, char* argv[]) { if (argc <= 3) { return 1; } const char* ip = argv[1]; int port = atoi(argv[2]); const char* file_name = argv[3]; // ĿļΪ struct sockaddr_in server_address {}; bzero(&server_address, sizeof(server_address)); server_address.sin_family = AF_INET; inet_pton(AF_INET, ip, &server_address.sin_addr); server_address.sin_port = htons(port); int sock = socket(PF_INET, SOCK_STREAM, 0); assert(sock >= 0); int ret = bind(sock, (struct sockaddr*)&server_address, sizeof(server_address)); assert(ret != -1); ret = listen(sock, 5); assert(ret != -1); struct sockaddr_in client {}; socklen_t client_addrLen = sizeof(client); int connfd = accept(sock, (struct sockaddr*)&client, &client_addrLen); if (connfd < 0) { std::cout << "error: " << errno; } else { int filefd = open(file_name, O_RDONLY); assert(filefd > 0); struct stat stat_buf; fstat(filefd, &stat_buf); sendfile(connfd, filefd, nullptr, stat_buf.st_size); // һsocket, ڶǴļ(socket) close(connfd); } close(sock); return 0; }
true
b9031bf50e6e7fef3849cda2e1638786dbc504ff
C++
norbertzagozdzon/jimp2
/lab6/lab6_zad1.cpp
UTF-8
1,744
3.3125
3
[]
no_license
#include<iostream> using std::cout; using namespace std; class Complex { private: double re, im; public: Complex() { } Complex(double re, double im) { this->re = re; this->im = im; } Complex operator +(const Complex &c) { return Complex(this->re+c.re,this->im+c.im); } Complex operator -(const Complex &c) { return Complex(this->re-c.re,this->im-c.im); } Complex operator *(const Complex &c) { return Complex((this->re)*(c.re)-(this->im)*(c.im),(this->re)*(c.im)+(this->im)*(c.re)); } Complex operator /(const Complex &c) { double m = c.re*c.re+c.im*c.im; return Complex(((this->re)*(c.re))/m-((this->im)*(c.im))/m,((this->re)*(c.im))/m+((this->im)*(c.re))/m); } void readComplex() { cout<<re<<" + "<<im<<"i"<<std::endl; } friend std::ostream& operator<<(std::ostream &out, const Complex &c) { out<<c.re<<" + "<<c.im<<"i"; return out; } friend std::istream& operator>>(std::istream &in, Complex &c) { in>>c.re; in>>c.im; return in; } }; int main() { std::ostream os(); Complex c1 = Complex(4,5); Complex c2 = Complex(3,5); Complex c4; cin>>c4; cout<<c4+c1; }
true
7bf5c2e33e764fd6619c10aec85bdc1dfa555fa4
C++
cswwp/myleetcoding
/movezero.cpp
UTF-8
257
3.15625
3
[]
no_license
void moveZeroes(int* nums, int numsSize) { int * p=nums; int * q=nums; for(int index=0;index<numsSize;++index) { if((*p)!=0) *q++=*p; ++p; } while(p-q>0) { *q++=0; } } //8ms
true
e302ac143a094211875f9a2b4c3e26a11f07d266
C++
kurufeenve/CPP_Pool2
/day00/day00/ex01/src/Contact.class.cpp
UTF-8
4,372
3.078125
3
[]
no_license
#include "./../includes/Contact.class.hpp" Contact::Contact(void) : _firstName("NAN"), _lastName("NAN"), _nickName("NAN"), _login("NAN"), _postalAddress("NAN"), _emailAddress("NAN"), _phoneNumber("NAN"), _birthdayDate("NAN"), _favoriteMeal("NAN"), _underwearColor("NAN"), _darkestSecret("NAN") {} Contact::Contact(std::string firstName, std::string lastName, std::string nickName, std::string login, std::string postalAddress, std::string emailAddress, std::string phoneNumber, std::string birthdayDate, std::string favoriteMeal, std::string underwearColor, std::string darkestSecret) : _firstName(firstName), _lastName(lastName), _nickName(nickName), _login(login), _postalAddress(postalAddress), _emailAddress(emailAddress), _phoneNumber(phoneNumber), _birthdayDate(birthdayDate), _favoriteMeal(favoriteMeal), _underwearColor(underwearColor), _darkestSecret(darkestSecret) {} Contact::~Contact(void) {} void Contact::addContact(void) { std::string data; std::cin.clear(); std::cout << "First Name: "; std::getline (std::cin, data); this->setFirstName(data); std::cout << "Last Name: "; std::getline (std::cin, data); this->setLastName(data); std::cout << "Nickname: "; std::getline (std::cin, data); this->setNickName(data); std::cout << "Login: "; std::getline (std::cin, data); this->setLogin(data); std::cout << "Postal Address: "; std::getline (std::cin, data); this->setPostalAddress(data); std::cout << "Email Address: "; std::getline (std::cin, data); this->setEmailAddress(data); std::cout << "Phone Number: "; std::getline (std::cin, data); this->setPhoneNumber(data); std::cout << "Birthday Date: "; std::getline (std::cin, data); this->setBirthdayDate(data); std::cout << "Favorite Meal: "; std::getline (std::cin, data); this->setFavoriteMeal(data); std::cout << "Underwear Color: "; std::getline (std::cin, data); this->setUnderwearColor(data); std::cout << "Darkest Secret: "; std::getline (std::cin, data); this->setDarkestSecret(data); } void Contact::showContact(void) { std::cout << "First Name: " << this->_firstName << "\n" << "Last Name: " << this->_lastName << std::endl << "Nickname: " << this->_nickName << std::endl << "Login: " << this->_login << std::endl << "Postal Address: " << this->_postalAddress << std::endl << "Email Address: " << this->_emailAddress << std::endl << "Phone Number: " << this->_phoneNumber << std::endl << "Birthday Date: " << this->_birthdayDate << std::endl << "Favorite Meal: " << this->_favoriteMeal << std::endl << "Underwear Color: " << this->_underwearColor << std::endl << "Darkest Secret: " << this->_darkestSecret << std::endl; } void Contact::searchContact(void) { if (this->_firstName.length() > 10) { std::cout << this->_firstName.substr(0, 9); std::cout << ".|"; } else { std::cout << std::setw(10) << this->_firstName << "|"; } if (this->_lastName.length() > 10) { std::cout << this->_lastName.substr(0, 9); std::cout << ".|"; } else { std::cout << std::setw(10) << this->_lastName << "|"; } if (this->_nickName.length() > 10) { std::cout << this->_nickName.substr(0, 9); std::cout << ".|"; } else { std::cout << std::setw(10) << this->_nickName << "|"; } } void Contact::setFirstName(std::string str) { this->_firstName = str; return ; } void Contact::setLastName(std::string str) { this->_lastName = str; return ; } void Contact::setNickName(std::string str) { this->_nickName = str; return ; } void Contact::setLogin(std::string str) { this->_login = str; return ; } void Contact::setPostalAddress(std::string str) { this->_postalAddress = str; return ; } void Contact::setEmailAddress(std::string str) { this->_emailAddress = str; return ; } void Contact::setPhoneNumber(std::string str) { this->_phoneNumber = str; return ; } void Contact::setBirthdayDate(std::string str) { this->_birthdayDate = str; return ; } void Contact::setFavoriteMeal(std::string str) { this->_favoriteMeal = str; return ; } void Contact::setUnderwearColor(std::string str) { this->_underwearColor = str; return ; } void Contact::setDarkestSecret(std::string str) { this->_darkestSecret = str; return ; }
true
7806def0892e32ad0abd7e189d04a1bae4a16b25
C++
apdiazv/SantanderXVA
/source/Valorizador.cpp
ISO-8859-3
30,310
2.5625
3
[]
no_license
#include "headerFiles.h" #include "Valorizador.h" bool Valorizador::instanceFlag = false; Valorizador* Valorizador::valor = NULL; clock_t clock_2, clock_3; Valorizador* Valorizador::getInstance() { if (!instanceFlag) { valor = new Valorizador; instanceFlag = true; } return valor; } Valorizador::Valorizador(void) { //cout <<" Constructing Valorizador "<< "\n"; } Valorizador::~Valorizador(void) { instanceFlag = false; storeCurvas.clear(); storeHullWhite.clear(); //cout <<" Destructing Valorizador" << "\n"; } double Valorizador::valorOperacion(Operacion* op) { if (op->tipo == "FWD") { Forward* fwd =static_cast<Forward*>(op->oper); return Valorizador::valorForward(fwd); } return 0.0; } double Valorizador::valorOperacionScenario(Operation op, const vector<double>& st, vector<vector<double> >& m2m, string moneda) { if (op._type == "FWD") { return Valorizador::valorForwardScenario(op, st, m2m, moneda); } else if(op._type == "SWAP") { } return 0.0; } double Valorizador::valorOperacionScenario(Operation op, double st, map<string, double>& sim, vector<double>& m2m, string moneda) { if (op._type == "FWD") { return Valorizador::valorForwardScenario(op, st, sim, m2m, moneda); } else if(op._type == "SWAP") { } return 0.0; } double Valorizador::valorForward(Forward* fwd) { Valorizador::addCurvaToStore(fwd->curvaDescuentoCompra); Valorizador::addCurvaToStore(fwd->curvaDescuentoVenta); double r = interpolations(Valorizador::storeCurvas[fwd->curvaDescuentoCompra].tenors, Valorizador::storeCurvas[fwd->curvaDescuentoCompra].rates, fwd->plazoResidual, 2); // 2 es Clamped Spline double vpCompra = (fwd->montoCompra)* exp(-r * fwd->plazoResidual);// /pow(1+r, fwd->plazoResidual); r = interpolations(Valorizador::storeCurvas[fwd->curvaDescuentoVenta].tenors, Valorizador::storeCurvas[fwd->curvaDescuentoVenta].rates, fwd->plazoResidual, 2); // 2 es Clamped Spline double vpVenta = (fwd->montoVenta)* exp(-r * fwd->plazoResidual);// /pow(1+r, fwd->plazoResidual); return Valorizador::aMonedaBase(vpCompra, fwd->monedaCompra) - Valorizador::aMonedaBase(vpVenta, fwd->monedaVenta); } double Valorizador::valorSwap(pair<Leg, Leg>& swapLegs) { //Preparar las curvas Valorizador::addHullWhiteToStore(swapLegs.first.getDiscountCurve()); Valorizador::addHullWhiteToStore(swapLegs.second.getDiscountCurve()); if(swapLegs.first.getProjectCurve() != swapLegs.first.getDiscountCurve()) { Valorizador::addHullWhiteToStore(swapLegs.first.getProjectCurve()); } if(swapLegs.second.getProjectCurve() != swapLegs.second.getDiscountCurve()) { Valorizador::addHullWhiteToStore(swapLegs.second.getProjectCurve()); } //Inicializar el calendario de la operacin: swapLegs.first.initiateCalendars(); swapLegs.second.initiateCalendars(); swapLegs.first.resetAmount(); swapLegs.second.resetAmount(); string monedaBase = getMonedaBase(); double tasaProjCompra = (double)storeHullWhite[swapLegs.first.getProjectCurve()].getR0(); double tasaDiscCompra = (double)storeHullWhite[swapLegs.first.getDiscountCurve()].getR0(); double lastFixingCompra = swapLegs.first.getValueRate(); double valorCompra = valorLegScenario(swapLegs.first, 0 , tasaDiscCompra, tasaProjCompra, lastFixingCompra); double tasaProjVenta = (double)storeHullWhite[swapLegs.second.getProjectCurve()].getR0(); double tasaDiscVenta= (double)storeHullWhite[swapLegs.second.getDiscountCurve()].getR0(); double lastFixingVenta = swapLegs.second.getValueRate(); double valorVenta = valorLegScenario(swapLegs.second, 0, tasaDiscVenta, tasaProjVenta, lastFixingVenta); double vpCompra = aMonedaBase(valorCompra, swapLegs.first.getCurrency()); double vpVenta = aMonedaBase(valorVenta, swapLegs.second.getCurrency()); double m2m = vpCompra - vpVenta; return m2m; } double Valorizador::valorForwardScenario(Operation op, const vector<double>& st, vector<vector<double> >& m2m, string moneda) { clock_2 = clock(); cout << " HG "<<clock_2 <<","; Valorizador::addHullWhiteToStore(op._discountCurve.first); Valorizador::addHullWhiteToStore(op._discountCurve.second); clock_3 = clock(); cout << " HWEnd "<<diffclock(clock_3, clock_2)<<","; //Traer el escenario para las dos tasas y las fx que sirvan considerando la pasada a moneda base. Significa //hacer una query sobre la tabla de simulacin. //string monedaBase = getMonedaBase(); int auxi = st.size(); int auxj = getMaxSim() + 1;//Corregir vector<double> vTemp; //Aqui metemos tiempo, numero de simulacion y m2m for (int i = 0; i < auxi; i++) { //Esto se trae todas las simulaciones disponibles para el st[i] //Se guardan en el mapa sim. La llave del mapa de este tipo, si es la simulacion 10 del factor USDCLP la llave //es "10-USDCLP" y en el doble viene el valor simulado que corresponde. clock_2 = clock(); //cout << " getSimulationAtT "<<clock_2 <<","; map<string, double> sim; double x = getSimulationAtT(op._discountCurve.first, op._discountCurve.second, st[i], sim); clock_3 = clock();; cout << " getSimulationAtTEnd " <<diffclock(clock_3, clock_2)<<","; for (int j = 0; j < auxj; j++) { if ( ((double)st[i] -(op._expiryTime.first / DT)) > TOL) { vTemp.push_back(st[i]); vTemp.push_back((double)j); vTemp.push_back(0.0); m2m.push_back(vTemp); vTemp.clear(); continue; } //Estos tres bloques traen los valores de FX de la simulacion //Pueden servir pata comvertir a moneda base //USDCLP, EURUSD, USDJPY, GBPUSD, USDMXN, CHFUSD, CLFCLP, string auxStr = integerToString(j) + "-USDCLP"; double usdclp = sim[auxStr]; if (usdclp == 0) {usdclp = 1.0;} auxStr = integerToString(j) + "-EURUSD"; double eurusd = sim[auxStr]; if (eurusd == 0) {eurusd = 1.0;} auxStr = integerToString(j) + "-GBPUSD"; double gbpusd = sim[auxStr]; if (gbpusd == 0) {gbpusd = 1.0;} auxStr = integerToString(j) + "-USDJPY"; double usdjpy = sim[auxStr]; if (usdjpy == 0) {usdjpy = 1.0;} auxStr = integerToString(j) + "-USDMXN"; double usdmxn = sim[auxStr]; if (usdmxn == 0) {usdmxn = 1.0;} auxStr = integerToString(j) + "-CHFUSD"; double chfusd = sim[auxStr]; if (chfusd == 0) {chfusd = 1.0;} auxStr = integerToString(j) + "-USDAUD"; double usdaud = sim[auxStr]; if (usdaud == 0) {usdaud = 1.0;} auxStr = integerToString(j) + "-USDCAD"; double usdcad = sim[auxStr]; if (usdcad == 0) {usdcad = 1.0;} auxStr = integerToString(j) + "-USDBRL"; double usdbrl = sim[auxStr]; if (usdbrl == 0) {usdbrl = 1.0;} auxStr = integerToString(j) + "-CLFCLP"; double clfclp = sim[auxStr]; if (clfclp == 0) {clfclp = 1.0;} //GBPUSD, USDMXN, CHFUSD, CLFCLP, USDAUD, USDCAD //Fin bloques que traen FX //Traemos la tasa corta de la pata comprada y calculamos la tasa al plazo //de la pata comprada. auxStr = integerToString(j) + "-" + op._discountCurve.first; double tasaCortaCompra = sim[auxStr]; double dfPlazoCompra = storeHullWhite[op._discountCurve.first].getDiscountFactor(st[i] * DT, op._expiryTime.first, tasaCortaCompra); //Traemos la tasa corta de la pata vendida y calculamos la tasa al plazo //de la pata vendida. auxStr = integerToString(j) + "-" + op._discountCurve.second; double tasaCortaVenta = sim[auxStr]; double dfPlazoVenta = storeHullWhite[op._discountCurve.second].getDiscountFactor(st[i] * DT, op._expiryTime.second, tasaCortaVenta); double vpCompra = aMoneda(moneda, op._amount.first*dfPlazoCompra, op._currency.first, usdclp, eurusd, usdjpy, clfclp, usdaud, usdcad, usdbrl, gbpusd, chfusd, usdmxn); double vpVenta = aMoneda(moneda, op._amount.second*dfPlazoVenta, op._currency.second, usdclp, eurusd, usdjpy, clfclp, usdaud, usdcad, usdbrl, gbpusd, chfusd, usdmxn); vTemp.push_back((double)st[i]); vTemp.push_back((double)j); vTemp.push_back(vpCompra - vpVenta); m2m.push_back(vTemp); vTemp.clear(); } sim.clear(); clock_2 = clock(); cout << " EndV "<<diffclock(clock_2, clock_3)<<","; } return 0.0; } double Valorizador::valorForwardScenario(Operation op, double st, map<string, double>& sim, vector<double>& m2m, string moneda) { clock_2 = clock(); Valorizador::addHullWhiteToStore(op._discountCurve.first); Valorizador::addHullWhiteToStore(op._discountCurve.second); clock_t clock_1 = clock(); const int auxj = m2m.size(); //cout << "ssim " <<diffclock(clock_1, clock_2)<<","; int vcmto = min(getStoppingTimeFromTime(op._expiryTime.first), getStoppingTimeFromTime(op._expiryTime.first)); if (st > vcmto) { for (int j = 0; j < auxj; j++) { m2m.at(j) = 0.0; } } else { for (int j = 0; j < auxj; j++) { //Estos tres bloques traen los valores de FX de la simulacion //Pueden servir pata comvertir a moneda base //USDCLP, EURUSD, USDJPY, GBPUSD, USDMXN, CHFUSD, CLFCLP, string auxStr = integerToString(j) + "-USDCLP"; double usdclp = sim[auxStr]; if (usdclp == 0) {usdclp = 1.0;} auxStr = integerToString(j) + "-EURUSD"; double eurusd = sim[auxStr]; if (eurusd == 0) {eurusd = 1.0;} auxStr = integerToString(j) + "-GBPUSD"; double gbpusd = sim[auxStr]; if (gbpusd == 0) {gbpusd = 1.0;} auxStr = integerToString(j) + "-USDJPY"; double usdjpy = sim[auxStr]; if (usdjpy == 0) {usdjpy = 1.0;} auxStr = integerToString(j) + "-USDMXN"; double usdmxn = sim[auxStr]; if (usdmxn == 0) {usdmxn = 1.0;} auxStr = integerToString(j) + "-CHFUSD"; double chfusd = sim[auxStr]; if (chfusd == 0) {chfusd = 1.0;} auxStr = integerToString(j) + "-USDAUD"; double usdaud = sim[auxStr]; if (usdaud == 0) {usdaud = 1.0;} auxStr = integerToString(j) + "-USDCAD"; double usdcad = sim[auxStr]; if (usdcad == 0) {usdcad = 1.0;} auxStr = integerToString(j) + "-USDBRL"; double usdbrl = sim[auxStr]; if (usdbrl == 0) {usdbrl = 1.0;} auxStr = integerToString(j) + "-CLFCLP"; double clfclp = sim[auxStr]; if (clfclp == 0) {clfclp = 1.0;} //GBPUSD, USDMXN, CHFUSD, CLFCLP, USDAUD, USDCAD //Fin bloques que traen FX //Traemos la tasa corta de la pata comprada y calculamos la tasa al plazo //de la pata comprada. auxStr = integerToString(j) + "-" + op._discountCurve.first; double tasaCortaCompra = sim[auxStr]; double dfPlazoCompra = storeHullWhite[op._discountCurve.first].getDiscountFactor(st * DT, op._expiryTime.first, tasaCortaCompra); //Traemos la tasa corta de la pata vendida y calculamos la tasa al plazo //de la pata vendida. auxStr = integerToString(j) + "-" + op._discountCurve.second; double tasaCortaVenta = sim[auxStr]; double dfPlazoVenta = storeHullWhite[op._discountCurve.second].getDiscountFactor(st * DT, op._expiryTime.second, tasaCortaVenta); double vpCompra = aMoneda(moneda, op._amount.first*dfPlazoCompra, op._currency.first, usdclp, eurusd, usdjpy, clfclp, usdaud, usdcad, usdbrl, gbpusd, chfusd, usdmxn); double vpVenta = aMoneda(moneda, op._amount.second*dfPlazoVenta, op._currency.second, usdclp, eurusd, usdjpy, clfclp, usdaud, usdcad, usdbrl, gbpusd, chfusd, usdmxn); //vTemp.push_back((double)st); //vTemp.push_back((double)j); //vTemp.push_back(vpCompra - vpVenta); m2m.at(j) = vpCompra - vpVenta; //vTemp.clear(); } } clock_3 = clock(); //cout << "EndLoopMap " <<diffclock(clock_3, clock_1)<<"\n"; //cout << " EndV "<<diffclock(clock_3, clock_2)<<","; return 0.0; } double Valorizador::valorSwapScenario(pair<Leg, Leg>& swapLegs, double st, map<string, double>& sim, vector<double>& m2m, string moneda) { //Preparar las curvas Valorizador::addHullWhiteToStore(swapLegs.first.getDiscountCurve()); Valorizador::addHullWhiteToStore(swapLegs.second.getDiscountCurve()); if(swapLegs.first.getProjectCurve() != swapLegs.first.getDiscountCurve()) { Valorizador::addHullWhiteToStore(swapLegs.first.getProjectCurve()); } if(swapLegs.second.getProjectCurve() != swapLegs.second.getDiscountCurve()) { Valorizador::addHullWhiteToStore(swapLegs.second.getProjectCurve()); } //Inicializar el calendario de la operacin: swapLegs.first.initiateCalendars(); swapLegs.second.initiateCalendars(); //const int auxi = st.size(); const int auxj = m2m.size(); //vector<double> vTemp; //Si l tiempo de parada es mayor que el tiempo de vencimiento de la operacin completa con 0.0 int vcmto = min(swapLegs.first.getCalendarCoupon().back(), swapLegs.second.getCalendarCoupon().back()); if ( st > vcmto) { for (int j = 0; j < auxj; j++) { //vTemp.push_back(st); //vTemp.push_back((double)j); //vTemp.push_back(0.0); //m2m.push_back(vTemp); //vTemp.clear(); m2m.at(j) = 0; continue; } } else { //Reset a calendario vigente swapLegs.first.resetCalendars((int)st); swapLegs.second.resetCalendars((int)st); swapLegs.first.resetAmount(); swapLegs.second.resetAmount(); pair<vector<double>, vector<double>> fixSim; if(swapLegs.first.getFlagFixing() == true) { fixSim.first.reserve(auxj); double x = getSimulationAtT(swapLegs.first.getProjectCurve(), swapLegs.first.getLastFixing(), fixSim.first); } if(swapLegs.second.getFlagFixing() == true) { fixSim.second.reserve(auxj); double x = getSimulationAtT(swapLegs.second.getProjectCurve(), swapLegs.second.getLastFixing(), fixSim.second); } //map<string, double> simFirst; //double x = getSimulationAtT(swapLegs.first.getDiscountCurve(), swapLegs.first.getProjectCurve(), st[i], simFirst); //map<string, double> simSecond; //x = getSimulationAtT(swapLegs.second.getDiscountCurve(), swapLegs.second.getProjectCurve(), st[i], simSecond); for (int j = 0; j < auxj; j++) { //Estos tres bloques traen los valores de FX de la simulacion string auxStr = integerToString(j) + "-USDCLP"; double usdclp = sim[auxStr]; if (usdclp == 0) {usdclp = 1.0;} auxStr = integerToString(j) + "-EURUSD"; double eurusd = sim[auxStr]; if (eurusd == 0) {eurusd = 1.0;} auxStr = integerToString(j) + "-USDJPY"; double usdjpy = sim[auxStr]; if (usdjpy == 0) {usdjpy = 1.0;} auxStr = integerToString(j) + "-CLFCLP"; double clfclp = sim[auxStr]; if (clfclp == 0) {clfclp = 1.0;} //Fin bloques que traen FX //Valorizacin pata compra. auxStr = integerToString(j) + "-" + swapLegs.first.getDiscountCurve(); double tasaDiscCompra = sim[auxStr]; auxStr = integerToString(j) + "-" + swapLegs.first.getProjectCurve(); double tasaProjCompra = sim[auxStr]; //LastFixing double lastFixingCompra = 0.0; if(!fixSim.first.empty()) { lastFixingCompra = fixSim.first[j]; } double valorCompra = valorLegScenario(swapLegs.first,(int) st, tasaDiscCompra, tasaProjCompra, lastFixingCompra); //Valorizacin pata Venta. auxStr = integerToString(j) + "-" + swapLegs.second.getDiscountCurve(); double tasaDiscVenta = sim[auxStr]; auxStr = integerToString(j) + "-" + swapLegs.second.getProjectCurve(); double tasaProjVenta = sim[auxStr]; //LastFixing double lastFixingVenta = 0.0; if(!fixSim.second.empty()) { lastFixingVenta = fixSim.second[j]; } double valorVenta = valorLegScenario(swapLegs.second, (int) st, tasaDiscVenta, tasaProjVenta, lastFixingVenta); double vpCompra = aMoneda(moneda, valorCompra, swapLegs.first.getCurrency(), usdclp, eurusd, usdjpy, clfclp); double vpVenta = aMoneda(moneda, valorVenta, swapLegs.second.getCurrency(), usdclp, eurusd, usdjpy, clfclp);//aMoneda(moneda, op._amount.second*dfPlazoVenta, op._currency.second, usdclp, eurusd, usdjpy); //vTemp.push_back((double)st); //vTemp.push_back((double)j); //vTemp.push_back(vpCompra - vpVenta); //m2m.push_back(vTemp); //vTemp.clear(); m2m.at(j) = vpCompra - vpVenta; } //pair<vector<double>, vector<double>> fixSim; fixSim.first.clear(); fixSim.second.clear(); //simFirst.clear(); //simSecond.clear(); } return 0.0; } double Valorizador::valorSwapScenario(pair<Leg, Leg>& swapLegs, const vector<double>& st, vector<vector<double> >& m2m, string moneda) { //Preparar las curvas Valorizador::addHullWhiteToStore(swapLegs.first.getDiscountCurve()); Valorizador::addHullWhiteToStore(swapLegs.second.getDiscountCurve()); if(swapLegs.first.getProjectCurve() != swapLegs.first.getDiscountCurve()) { Valorizador::addHullWhiteToStore(swapLegs.first.getProjectCurve()); } if(swapLegs.second.getProjectCurve() != swapLegs.second.getDiscountCurve()) { Valorizador::addHullWhiteToStore(swapLegs.second.getProjectCurve()); } //Inicializar el calendario de la operacin: swapLegs.first.initiateCalendars(); swapLegs.second.initiateCalendars(); const int auxi = st.size(); const int auxj = getMaxSim() + 1; vector<double> vTemp; //Si l tiempo de parada es mayor que el tiempo de vencimiento de la operacin completa con 0.0 int vcmto = min(swapLegs.first.getCalendarCoupon().back(), swapLegs.second.getCalendarCoupon().back()); for (int i = 0; i < auxi; i++) { if ( st[i] > vcmto) { for (int j = 0; j < auxj; j++) { vTemp.push_back(st[i]); vTemp.push_back((double)j); vTemp.push_back(0.0); m2m.push_back(vTemp); vTemp.clear(); continue; } } else { //Reset a calendario vigente swapLegs.first.resetCalendars((int) st[i]); swapLegs.second.resetCalendars((int) st[i]); swapLegs.first.resetAmount(); swapLegs.second.resetAmount(); pair<vector<double>, vector<double>> fixSim; if(swapLegs.first.getFlagFixing() == true) { fixSim.first.reserve(auxj); double x = getSimulationAtT(swapLegs.first.getProjectCurve(), swapLegs.first.getLastFixing(), fixSim.first); } if(swapLegs.second.getFlagFixing() == true) { fixSim.second.reserve(auxj); double x = getSimulationAtT(swapLegs.second.getProjectCurve(), swapLegs.second.getLastFixing(), fixSim.second); } map<string, double> simFirst; double x = getSimulationAtT(swapLegs.first.getDiscountCurve(), swapLegs.first.getProjectCurve(), st[i], simFirst); map<string, double> simSecond; x = getSimulationAtT(swapLegs.second.getDiscountCurve(), swapLegs.second.getProjectCurve(), st[i], simSecond); for (int j = 0; j < auxj; j++) { //Estos tres bloques traen los valores de FX de la simulacion string auxStr = integerToString(j) + "-USDCLP"; double usdclp = simFirst[auxStr]; if (usdclp == 0) {usdclp = 1.0;} auxStr = integerToString(j) + "-EURUSD"; double eurusd = simFirst[auxStr]; if (eurusd == 0) {eurusd = 1.0;} auxStr = integerToString(j) + "-USDJPY"; double usdjpy = simFirst[auxStr]; if (usdjpy == 0) {usdjpy = 1.0;} auxStr = integerToString(j) + "-CLFCLP"; double clfclp = simFirst[auxStr]; if (clfclp == 0) {clfclp = 1.0;} //Fin bloques que traen FX //Valorizacin pata compra. auxStr = integerToString(j) + "-" + swapLegs.first.getDiscountCurve(); double tasaDiscCompra = simFirst[auxStr]; auxStr = integerToString(j) + "-" + swapLegs.first.getProjectCurve(); double tasaProjCompra = simFirst[auxStr]; //LastFixing double lastFixingCompra = 0.0; if(!fixSim.first.empty()) { lastFixingCompra = fixSim.first[j]; } double valorCompra = valorLegScenario(swapLegs.first, (int)st[i], tasaDiscCompra, tasaProjCompra, lastFixingCompra); //Valorizacin pata Venta. auxStr = integerToString(j) + "-" + swapLegs.second.getDiscountCurve(); double tasaDiscVenta = simSecond[auxStr]; auxStr = integerToString(j) + "-" + swapLegs.second.getProjectCurve(); double tasaProjVenta = simSecond[auxStr]; //LastFixing double lastFixingVenta = 0.0; if(!fixSim.second.empty()) { lastFixingVenta = fixSim.second[j]; } double valorVenta = valorLegScenario(swapLegs.second, (int)st[i], tasaDiscVenta, tasaProjVenta, lastFixingVenta); double vpCompra = aMoneda(moneda, valorCompra, swapLegs.first.getCurrency(), usdclp, eurusd, usdjpy, clfclp); double vpVenta = aMoneda(moneda, valorVenta, swapLegs.second.getCurrency(), usdclp, eurusd, usdjpy, clfclp);//aMoneda(moneda, op._amount.second*dfPlazoVenta, op._currency.second, usdclp, eurusd, usdjpy); vTemp.push_back((double)st[i]); vTemp.push_back((double)j); vTemp.push_back(vpCompra - vpVenta); m2m.push_back(vTemp); vTemp.clear(); } simFirst.clear(); simSecond.clear(); } } return 0.0; } double Valorizador::valorLegScenario(Leg& leg, int stopTime, double discRate, double projRate, double nextFixing) { double pvLeg = 0.0; if(!leg.getCalendarCoupon().empty()) { //Cupones Vigentes == leg.getCalendarCoupon() size_t numCoupons = leg.getCalendarCoupon().size(); //La primera fecha de cupon es anterior al stopTime, el primer discfactor es cero. vector<double> discFactors(numCoupons, 1.0); for (unsigned int i = 1; i < numCoupons; i++) { discFactors.at(i) = storeHullWhite[leg.getDiscountCurve()].getDiscountFactor(stopTime*DT, (leg.getCalendarCoupon()[i])*DT, discRate); } if(leg.tipoPata == "FIX") { pvLeg = valueLegFixScenario(&leg, discFactors); } else if(leg.tipoPata == "FLOAT") { //nextFixing if(leg.getFlagFixing() == false) { nextFixing = leg.getValueRate(); } else { double firstDisc = storeHullWhite[leg.getProjectCurve()].getDiscountFactor((leg.getLastFixing())*DT, (leg.getCalendarCoupon()[1])*DT, nextFixing); nextFixing =(1/firstDisc - 1)/(double)((leg.getCalendarCoupon()[1]- leg.getLastFixing())*DT);//- log(firstDisc)/(double)((leg.getCalendarCoupon()[1]- leg.getLastFixing())*DT); } //forwardRates si fechas de coupon!= Fechas de Fixing y/o curva de proyeccin diferente. vector<double> forwardRates; if(leg.getFlagProj() == true) { //discFactorsProj.reserve(numCoupons); //discFactorsProj.assign(discFactors.begin(), discFactors.end()); //forwardRates.reserve(numCoupons); forwardRates.assign(numCoupons, 0.0); double x = getForwardRateFromDiscountFactors(stopTime, leg.getCalendarCoupon(), discFactors, forwardRates); } else { size_t numFixing = leg.getCalendarFixing().size(); vector<double> discFactorsProj(numFixing, 1.0); for (unsigned int i = 1; i < numFixing; i++) { discFactorsProj.at(i) = storeHullWhite[leg.getProjectCurve()].getDiscountFactor(stopTime*DT, (leg.getCalendarFixing()[i])*DT, projRate); } //forwardRates.reserve(numFixing); forwardRates.assign(numFixing, 0.0); double x = getForwardRateFromDiscountFactors(stopTime, leg.getCalendarFixing(), discFactorsProj, forwardRates); discFactorsProj.clear(); } vector<double> fixingRates; double y = getFixingRatesForLeg(leg.getCalendarCoupon(),leg.getCalendarFixing(), forwardRates, nextFixing, fixingRates); pvLeg = valueLegFloatScenario(&leg, discFactors,fixingRates); // double valueLegFloatScenario(Leg* leg, vector<double> discFactors, vector<double> discFactorsProj, double firstFix); } else if(leg.tipoPata == "FLOATCAM") { //nextFixing if(leg.getFlagFixing() == false) { nextFixing = leg.getValueRate(); } else { double firstDisc = storeHullWhite[leg.getProjectCurve()].getDiscountFactor((leg.getLastFixing())*DT, stopTime*DT, nextFixing); nextFixing =(1/firstDisc - 1)/(double)((stopTime - leg.getLastFixing())*DT);//- log(firstDisc)/(double)((leg.getCalendarCoupon()[1]- leg.getLastFixing())*DT); } double auxInterest = leg.getAmount()*leg.getInterest(leg.getLastFixing(), stopTime, nextFixing); //forwardRates asume que fechas de coupon == Fechas de Fixing y curva de proyeccin= descuento vector<double> forwardRates; forwardRates.assign(numCoupons, 0.0); // Corregido el 30/10 la primera tasa fwd no consideraba el stopTime double x = getForwardRateFromDiscountFactors(stopTime, leg.getCalendarCoupon(), discFactors, forwardRates); //corregido el 30/09 Se estaban multiplicando los intereses double nextInterest = leg.getAmount()*leg.getInterest(stopTime, leg.getCalendarCoupon()[1], forwardRates[1]); pvLeg = valueLegFloatCamScenario(&leg, discFactors, forwardRates, nextInterest)+auxInterest; // double valueLegFloatScenario(Leg* leg, vector<double> discFactors, vector<double> discFactorsProj, double firstFix); } } return pvLeg; } void Valorizador::addCurvaToStore(string nombreCurva) { std::map<std::string, Curva>::iterator it = storeCurvas.find(nombreCurva); if(it == storeCurvas.end()) { Curva* newCurva = new Curva; double x = getCurvaFromNombre(nombreCurva, newCurva); if (x == 0) { storeCurvas.insert(std::pair<std::string, Curva>(nombreCurva, *newCurva)); } delete newCurva; } } void Valorizador::addHullWhiteToStore(string nombreCurva) { int s = storeHullWhite.count(nombreCurva); if(s == 0) { Curva* newCurva = new Curva; double x = getCurvaFromNombre(nombreCurva, newCurva); if (x == 0) { double gamma = getGamma(nombreCurva); double sigma = getSigma(nombreCurva); HullWhite newHullWhite = HullWhite(newCurva, gamma, sigma); storeHullWhite.insert(pair<string, HullWhite>(nombreCurva, newHullWhite)); //storeHullWhite[nombreCurva] = newHullWhite; //delete newHullWhite; } delete newCurva; } } double Valorizador::aMonedaBase(double monto, string moneda) { if (getMonedaBase() == "CLP") { if (moneda == "CLP") { return monto; } if (moneda == "USD") { return monto * getFX("USDCLP")->valor(); } if (moneda == "EUR") { return monto * getFX("EURUSD")->valor()* getFX("USDCLP")->valor() ;} if (moneda == "JPY") { return monto / getFX("USDJPY")->valor() * getFX("USDCLP")->valor(); } if (moneda == "CLF") { return monto * getFX("CLFCLP")->valor(); } if (moneda == "AUD") { return monto / getFX("USDAUD")->valor() * getFX("USDCLP")->valor(); } if (moneda == "CAD") { return monto / getFX("USDCAD")->valor() * getFX("USDCLP")->valor(); } if (moneda == "BRL") { return monto / getFX("USDBRL")->valor() * getFX("USDCLP")->valor(); } if (moneda == "MXN") { return monto / getFX("USDMXN")->valor() * getFX("USDCLP")->valor(); } if (moneda == "GBP") { return monto * getFX("GBPUSD")->valor() * getFX("USDCLP")->valor(); } if (moneda == "CHF") { return monto * getFX("CHFUSD")->valor() * getFX("USDCLP")->valor(); } } else if (getMonedaBase() == "USD") { if (moneda == "USD") { return monto; } if (moneda == "CLP") { return monto / getFX("USDCLP")->valor(); } if (moneda == "EUR") { return monto * getFX("EURUSD")->valor(); } if (moneda == "JPY") { return monto / getFX("USDJPY")->valor(); } if (moneda == "CLF") { return ( monto * getFX("CLFCLP")->valor())/ getFX("USDCLP")->valor(); } if (moneda == "AUD") { return monto / getFX("USDAUD")->valor(); } if (moneda == "CAD") { return monto / getFX("USDCAD")->valor(); } if (moneda == "BRL") { return monto / getFX("USDBRL")->valor(); } if (moneda == "MXN") { return monto / getFX("USDMXN")->valor(); } if (moneda == "GBP") { return monto * getFX("GBPUSD")->valor(); } if (moneda == "CHF") { return monto * getFX("CHFUSD")->valor(); } } return 1.0; } double Valorizador::aMonedaBase(double monto, string moneda, double usdclp, double eurusd, double usdjpy, double clfclp) { if (getMonedaBase() == "CLP") { if (moneda == "CLP") { return monto; } if (moneda == "USD") { return monto * usdclp; } if (moneda == "EUR") { return monto * eurusd * usdclp; } if (moneda == "JPY") { return monto / usdjpy * usdclp; } if (moneda == "CLF") { return monto * clfclp; } } else if (getMonedaBase() == "USD") { if (moneda == "USD") { return monto; } if (moneda == "CLP") { return monto / usdclp; } if (moneda == "EUR") { return monto * eurusd; } if (moneda == "JPY") { return monto / usdjpy; } if (moneda == "CLF") { return monto * clfclp / usdclp ; } } return 0.0; } double Valorizador::aMoneda(string queMoneda, double monto, string monedaMonto, double usdclp, double eurusd, double usdjpy, double clfclp, double usdaud, double usdcad, double usdbrl, double gbpusd, double chfusd, double usdmxn) { if (queMoneda == "CLP") { if (monedaMonto == "CLP") { return monto; } if (monedaMonto == "USD") { return monto * usdclp; } if (monedaMonto == "EUR") { return monto * eurusd * usdclp; } if (monedaMonto == "JPY") { return monto / usdjpy * usdclp; } if (monedaMonto == "CLF") { return monto * clfclp; } if (monedaMonto == "AUD") { return monto / usdaud * usdclp; } if (monedaMonto == "CAD") { return monto / usdcad * usdclp; } if (monedaMonto == "BRL") { return monto / usdbrl * usdclp; } if (monedaMonto == "MXN") { return monto / usdmxn * usdclp; } if (monedaMonto == "GBP") { return monto * gbpusd * usdclp; } if (monedaMonto == "CHF") { return monto * chfusd * usdclp; } } else if (queMoneda == "USD") { if (monedaMonto == "USD") { return monto; } if (monedaMonto == "CLP") { return monto / usdclp; } if (monedaMonto == "EUR") { return monto * eurusd; } if (monedaMonto == "JPY") { return monto / usdjpy; } if (monedaMonto == "CLF") { return monto * clfclp / usdclp; } if (monedaMonto == "AUD") { return monto / usdaud; } if (monedaMonto == "CAD") { return monto / usdcad;} if (monedaMonto == "BRL") { return monto / usdbrl; } if (monedaMonto == "MXN") { return monto / usdmxn; } if (monedaMonto == "GBP") { return monto * gbpusd; } if (monedaMonto == "CHF") { return monto * chfusd; } } return 0.0; }
true
290db42e6a6645a07373f7be57c096b49110a388
C++
maxzerrrrrr/ECEMON
/src/Deck.cpp
UTF-8
5,736
2.765625
3
[]
no_license
#include "Deck.h" Deck::Deck() { //ctor } Deck::~Deck() { //dtor } Deck::Deck(std::string _nom, int _nbre) :nom_deck(_nom), nbre_cartes_max(_nbre) { } void Deck::setNomDeck(std::string _nom) { nom_deck=_nom; } void Deck::setNbreCartes(int _exemplaire) { nbre_cartes_deck=_exemplaire; } std::string Deck::getNomDeck() { return nom_deck; } int Deck::getNbreCartes() { return nbre_cartes_deck; } void Deck::setVectorDeck(std::vector <Carte> Deck) { CollectionJoueur=Deck; } std::vector<Carte> Deck::getVectorDeck() { return CollectionJoueur; } void Deck::CreationDeck(std::string nom) { std::string dossier="DECK/"; std::string exte= ".txt"; std::string chemin; chemin=dossier+nom+exte; std::ofstream fich(chemin, std::ios::app); std::cout << "Opening deck" << std::endl; if(fich) { fich << "ENERGIE EUROPE 1 5 CARTESBMPTERRAIN/energy1europe.bmp" << std::endl; fich << "ENERGIE EUROPE 2 2 CARTESBMPTERRAIN/energy2europe.bmp"<< std::endl; fich << "ENERGIE EUROPE 3 1 CARTESBMPTERRAIN/energy3europe.bmp"<< std::endl; fich << "TERRAIN EUROPE 1 CARTESBMPTERRAIN/terraineurope_t.bmp"<< std::endl; fich << "PIEGE OEIL.D'ODIN 1 CARTESBMPTERRAIN/trap7_t.bmp"<< std::endl; fich << "PIEGE YGGDRASIL 1 CARTESBMPTERRAIN/trap9_t.bmp"<< std::endl; fich << "MAGIE AGLOOLIK 2 CARTESBMPTERRAIN/magie5_t.bmp"<< std::endl; fich << "MAGIE ASKAFROA 1 CARTESBMPTERRAIN/magie7_t.bmp"<< std::endl; fich << "MAGIE AUDHUMLA 1 CARTESBMPTERRAIN/magie9_t.bmp"<< std::endl; fich << "MONSTRE GARM EUROPE 1 0 1100 1100 2 CARTESBMPTERRAIN/monstre25_t.bmp"<< std::endl; fich << "MONSTRE GARUDA EUROPE 1 0 1400 500 1 CARTESBMPTERRAIN/monstre26_t.bmp"<< std::endl; fich << "MONSTRE AMAZONE EUROPE 4 0 2000 2000 1 CARTESBMPTERRAIN/monstre23_t.bmp"<< std::endl; fich << "MONSTRE GNOME EUROPE 1 0 300 1400 1 CARTESBMPTERRAIN/monstre27_t.bmp"<< std::endl; fich << "MONSTRE GRIFFON EUROPE 4 1 2300 1500 1 CARTESBMPTERRAIN/monstre32_t.bmp"<< std::endl; fich << "MONSTRE AITVARAS EUROPE 1 1 250 300 1 CARTESBMPTERRAIN/monstre15_t.bmp"<< std::endl; fich << "MONSTRE GAMAYUN EUROPE 1 0 1300 1200 1 CARTESBMPTERRAIN/monstre24_t.bmp"<< std::endl; } else { std::cout << "Cannot open deck" << std::endl; } fich.close(); } std::vector <Carte> Deck::RecupDeck( std::string nom) { std::string dossier="DECK/"; std::string exte= ".txt"; std::string chemin; std::vector <Carte> CollectionBase; chemin=dossier+nom+exte; std::ifstream fichier(chemin, std::ios::in); std::cout << "Opening deck 2" << std::endl; if(fichier) { int num=0; std::string type; std::string nom; int energie; int atk; int pt_energie; std::string domaine; int def; bool special; std::string path; int nbre_exemplaires; const char* acces; do { fichier >> type; if(type=="MONSTRE") { fichier >> nom >> domaine >> energie >> special >> atk >> def >> nbre_exemplaires>> path; Monstre maCarte; maCarte.AjouterCarteMonstre(maCarte,nom,domaine,energie,special,atk,def,nbre_exemplaires,path); //AJOUT DE LA CARTE DANS LA COLLECTION CollectionBase.push_back(maCarte); acces=path.c_str(); maCarte.AffichInfo(acces); } else if(type=="MAGIE" || type=="PIEGE") { fichier >> nom >> nbre_exemplaires>>path; if(type=="MAGIE") { Magie maCarte; domaine="_"; maCarte.AjouterCarteMagie(maCarte,type,domaine,nbre_exemplaires,path); CollectionBase.push_back(maCarte); acces=path.c_str(); maCarte.AffichInfo(acces); } if(type=="PIEGE") { Piege maCarte; domaine="_"; maCarte.AjouterCartePiege(maCarte,type,domaine,nbre_exemplaires,path); CollectionBase.push_back(maCarte); acces=path.c_str(); maCarte.AffichInfo(acces); } } else if(type=="ENERGIE") { fichier >> domaine >> pt_energie >> nbre_exemplaires>>path; Energie maCarte; maCarte.AjouterCarteEnergie(maCarte,type,domaine,pt_energie,nbre_exemplaires,path); CollectionBase.push_back(maCarte); acces=path.c_str(); maCarte.AffichInfo(acces); } if(type=="TERRAIN") { fichier >> nom >> nbre_exemplaires>>path; Terrain maCarte; maCarte.AjouterCarteTerrain(maCarte,nom,domaine,nbre_exemplaires,path); CollectionBase.push_back(maCarte); acces=path.c_str(); maCarte.AffichInfo(acces); } std::cout << "\n"; num++; } while(fichier.eof()==false); fichier.close(); // fermeture du flux } else { std::cout << "Cannot open deck 2" << std::endl; } return CollectionBase; } void Deck::AfficherDeck() { std::cout << "Nom du deck : " << nom_deck << std::endl; std::cout << "Nombre de cartes : " << nbre_cartes_deck << std::endl; std::cout << "Nombre de cartes max : " << nbre_cartes_max << std::endl; }
true
3f20143d03a1e0c76a2c0052b364b8c7f805d38e
C++
brettschalin/memes-with-friends
/Memes With Friends/Memes With Friends/main.cpp
UTF-8
3,298
2.59375
3
[ "MIT" ]
permissive
#include <stdio.h> #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_physfs.h> #include <physfs.h> #include "Card.h" #include "GameManager.h" const float FPS = 60; const int SCREEN_W = 1920; const int SCREEN_H = 1080; ALLEGRO_COLOR BACKGROUND_COLOR; // set after allegro is initialized GameManager* gameManager; //initialized after allegro int main(int argc, char **argv) { ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; bool doexit = false; if (!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } BACKGROUND_COLOR = al_map_rgb(241, 241, 212); if (!al_install_keyboard()) { fprintf(stderr, "failed to initialize the keyboard!\n"); return -1; } timer = al_create_timer(1.0 / FPS); if (!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } al_set_new_display_flags(ALLEGRO_WINDOWED); display = al_create_display(SCREEN_W, SCREEN_H); if (!display) { fprintf(stderr, "failed to create display!\n"); al_destroy_timer(timer); return -1; } al_set_target_bitmap(al_get_backbuffer(display)); if (!al_init_primitives_addon()) { fprintf(stderr, "failed to initialize primitives addon!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } if (!al_init_image_addon()) { fprintf(stderr, "failed to initialize image addon!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } PHYSFS_init(NULL); if (!PHYSFS_mount("assets.zip", "/", 1)) { fprintf(stderr, "failed to open assets.zip file!\n"); PHYSFS_deinit(); al_shutdown_primitives_addon(); al_shutdown_image_addon(); al_destroy_display(display); al_destroy_timer(timer); } al_set_physfs_file_interface(); event_queue = al_create_event_queue(); if (!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); PHYSFS_deinit(); al_shutdown_primitives_addon(); al_shutdown_image_addon(); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_clear_to_color(BACKGROUND_COLOR); al_flip_display(); al_start_timer(timer); gameManager = new GameManager(); Card *test_card = new Card(); test_card->set_color(al_map_rgb(255, 0, 0)); test_card->set_pos(50, 50); while (!doexit) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } if (ev.type == ALLEGRO_EVENT_KEY_UP) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: doexit = true; break; } } al_clear_to_color(BACKGROUND_COLOR); test_card->draw(); al_flip_display(); } PHYSFS_deinit(); al_shutdown_primitives_addon(); al_shutdown_image_addon(); al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); delete gameManager; return 0; }
true
4c7f8616dd0c9d79e65108c4e99a9bccebccaf51
C++
omniamahfouz21/atbash-cypher
/main.cpp
UTF-8
1,182
3.609375
4
[]
no_license
#include <iostream> using namespace std ; int main (){ class AtbashTable ; { /// <summary> /// Lookup table to shift characters. /// </summary> char[] _shift = new char[char.MaxValue]; /// <summary> /// Generates the lookup table. /// </summary> public AtbashTable() { // Set these as the same. for (int i = 0; i < char.MaxValue; i++) { _shift[i] = (char)i; } // Reverse order of capital letters. for (char c = 'A'; c <= 'Z'; c++) { _shift[(int)c] = (char)('Z' + 'A' - c); } // Reverse order of lowercase letters. for (char c = 'a'; c <= 'z'; c++) { _shift[(int)c] = (char)('z' + 'a' - c); } } /// <summary> /// Apply the Atbash cipher. /// </summary> public string Transform(string value) { try { // Convert to char array char[] a = value.ToCharArray(); // Shift each letter. for (int i = 0; i < a.Length; i++) { int t = (int)a[i]; a[i] = _shift[t]; } // Return new string. return new string(a); } catch { // Just return original value on failure. return value; } } } }
true
68eb60284521dc87cd0ecffd328c1b50ff861c24
C++
grand87/timus
/Problems/leetcode/prime-number-of-set-bits-in-binary-representation/main.cpp
UTF-8
1,710
3.09375
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { static const int bitsCount[16]; int bitsIn32(int val) { int count = 0; while (val > 0) { count += bitsCount[val & 0b1111]; val >>= 4; } return count; } bool* genPrimes(int n) { bool* res = new bool[n + 1]; res[0] = false; res[1] = false; for (int i = 2; i < n; i++) res[i] = true; for (int i = 2; i * i < n; i++) { for (int j = i; j <= n / i; j++) { res[i * j] = false; } } return res; } public: int countPrimeSetBits(int L, int R) { const bool* primes = genPrimes(40); int res = 0; for (int i = L; i <= R; i++) { int const bits = bitsIn32(i); res += primes[bits]; cout << i << " " << bits << " " << res << endl; } delete[] primes; return res; } }; const int Solution::bitsCount[16] = { 0, // 0000b 1, // 0001b 1, // 0010b 2, // 0011b 1, // 0100b 2, // 0101b 2, // 0110b 3, // 0111b 1, // 1000b 2, // 1001b 2, // 1010b 3, // 1011b 2, // 1100b 3, // 1101b 3, // 1110b 4 // 1111b }; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); #endif int t; cin >> t; for (int i = 0; i < t; i++) { int n, m; cin >> n >> m; Solution s; cout << s.countPrimeSetBits(n, m) << endl; } return 0; }
true
6291290c3c4cc65a0d37f1b799399c8bfdcade38
C++
hieule22/truc
/test/scanner/scanner_all_test.cc
UTF-8
4,661
2.96875
3
[]
no_license
// End-to-end tests for lexical analyzer. // Copyright 2016 Hieu Le. #include "src/scanner.h" #include <iostream> #include <string> #include "gtest/gtest.h" namespace { // MockScanner reads tokens from expected output file. class MockScanner : public Scanner { public: explicit MockScanner(char *filename) : Scanner(filename) { infile_.open(filename); stream_ = &infile_; } ~MockScanner() { infile_.close(); } Token *next_token() { std::string token; (*stream_) >> token; if (token == "PROGRAM") { return new KeywordToken(keyword_attr_type::KW_PROGRAM); } else if (token == "PROCEDURE") { return new KeywordToken(keyword_attr_type::KW_PROCEDURE); } else if (token == "INT") { return new KeywordToken(keyword_attr_type::KW_INT); } else if (token == "BOOL") { return new KeywordToken(keyword_attr_type::KW_BOOL); } else if (token == "BEGIN") { return new KeywordToken(keyword_attr_type::KW_BEGIN); } else if (token == "END") { return new KeywordToken(keyword_attr_type::KW_END); } else if (token == "IF") { return new KeywordToken(keyword_attr_type::KW_IF); } else if (token == "THEN") { return new KeywordToken(keyword_attr_type::KW_THEN); } else if (token == "ELSE") { return new KeywordToken(keyword_attr_type::KW_ELSE); } else if (token == "WHILE") { return new KeywordToken(keyword_attr_type::KW_WHILE); } else if (token == "LOOP") { return new KeywordToken(keyword_attr_type::KW_LOOP); } else if (token == "PRINT") { return new KeywordToken(keyword_attr_type::KW_PRINT); } else if (token == "NOT") { return new KeywordToken(keyword_attr_type::KW_NOT); } else if (token == "SEMICOLON") { return new PuncToken(punc_attr_type::PUNC_SEMI); } else if (token == "COLON") { return new PuncToken(punc_attr_type::PUNC_COLON); } else if (token == "COMMA") { return new PuncToken(punc_attr_type::PUNC_COMMA); } else if (token == "ASSIGNMENT") { return new PuncToken(punc_attr_type::PUNC_ASSIGN); } else if (token == "OPENBRACKET") { return new PuncToken(punc_attr_type::PUNC_OPEN); } else if (token == "CLOSEBRACKET") { return new PuncToken(punc_attr_type::PUNC_CLOSE); } else if (token == "EQUAL") { return new RelopToken(relop_attr_type::RELOP_EQ); } else if (token == "NOTEQUAL") { return new RelopToken(relop_attr_type::RELOP_NE); } else if (token == "GREATERTHAN") { return new RelopToken(relop_attr_type::RELOP_GT); } else if (token == "GREATEROREQUAL") { return new RelopToken(relop_attr_type::RELOP_GE); } else if (token == "LESSTHAN") { return new RelopToken(relop_attr_type::RELOP_LT); } else if (token == "LESSOREQUAL") { return new RelopToken(relop_attr_type::RELOP_LE); } else if (token == "ADD") { return new AddopToken(addop_attr_type::ADDOP_ADD); } else if (token == "SUBTRACT") { return new AddopToken(addop_attr_type::ADDOP_SUB); } else if (token == "OR") { return new AddopToken(addop_attr_type::ADDOP_OR); } else if (token == "MULTIPLY") { return new MulopToken(mulop_attr_type::MULOP_MUL); } else if (token == "DIVIDE") { return new MulopToken(mulop_attr_type::MULOP_DIV); } else if (token == "AND") { return new MulopToken(mulop_attr_type::MULOP_AND); } else if (token == "IDENTIFIER") { std::string attribute; (*stream_) >> attribute; return new IdToken(attribute); } else if (token == "NUMBER") { std::string attribute; (*stream_) >> attribute; return new NumToken(attribute); } else if (token == "ENDOFFILE") { return new EofToken(); } std::cerr << "Unrecognized token: " << token << std::endl; std::exit(EXIT_FAILURE); return nullptr; } private: ifstream infile_; istream *stream_; }; // TODO(hieule): Implement all test cases. TEST(ScannerTest, EndToEnd) { const int N_TESTS = 5; for (int i = 0; i < N_TESTS; ++i) { char filename[100]; std::snprintf(filename, sizeof(filename), "test/scanner/data/test%d.in", i); Scanner scanner(filename); std::snprintf(filename, sizeof(filename), "test/scanner/data/test%d.out", i); MockScanner mock(filename); std::unique_ptr<Token> actual; std::unique_ptr<Token> expected; do { actual.reset(scanner.next_token()); expected.reset(mock.next_token()); EXPECT_EQ(*actual->to_string(), *expected->to_string()); } while (typeid(*expected) != typeid(EofToken)); } } } // namespace
true
6d1813b176bd6befbc5f3a0678e092d77f08a19b
C++
Aleksandr-Kovalev/CourseworkCode
/C++/StoreSimulator/HardwareStore.h
UTF-8
1,596
3.46875
3
[]
no_license
#ifndef HARDWARESTORE_H #define HARDWARESTORE_H #include<queue> #include<vector> #include "Shopper.h" class HardwareStore{ private: double storeRevenue; //total money from store std::vector< std::queue<Shopper> > CheckOutArea; //creats a vector of queues with shoppers placed in the queues public: HardwareStore(){ //defualt constructor for new stores storeRevenue = 0; } //Creates a HardwareStore with the specified number of registers. (i.e. the number of queues). HardwareStore(int numRegisters){ storeRevenue = 0; if(numRegisters <= 0) numRegisters = 1; CheckOutArea.resize(numRegisters); } //Adds a shopper to the line that currently has the least number of people waiting on it. void addShopperToLine(const Shopper& shopper); void processShopper(); //Processes the shopper at the front of the longest line. void checkoutAllShoppers(); //Processes all Shoppers still on line for all of the lines. //setters and getters int numRegisters(){ return CheckOutArea.size(); } int queueSize(int index){ return CheckOutArea[index].size(); } Shopper& getShopper(int index){ //get shopper in the index of the vector return CheckOutArea[index].front(); } void addRevenue(double amount){ //keeps adding the revenue storeRevenue += amount; } //Returns the amount of money the HardwareStore has taken in so far. (At the end of the //program, it will represent the total revenue of the store.) double totalRevenue(){ return storeRevenue; } }; #endif
true
9fd7a3d6967185a1966c0d45ef673bead83d42f9
C++
lantimilan/topcoder
/CODEFORCE/prob418C.cpp
UTF-8
2,132
3.578125
4
[]
no_license
// prob418C.cpp // // the problem can be reduced to 1D // suppose you have an array of numbers a[0..n-1] such that // sum_{i=0}^{n-1} a[i]^2 = k^2 // and similarly an array b[0..m-1] such that sum of square is a square // then you can use this array to build a table with permutation // each entry = a[i] * b[j] // now for each row, the sum is a[i] * b[1], a[i] * b[2], ... // for each col, the sum is a[1] * b[j], a[2] * b[j], ... // // if n == m, you can instead do this, // 1,2,3,...,n // 2,3,...n,1 // ... // n,1,2,...,n-1 // so that you have a permutation of 1..n in every row and every col // // now the hard part is to find n positive integers small enough, // that is, no more than 10^8 // if there is no such limit, then the following recursive idea will work // start with 3 and 4, then we know the sum is 5^2, now look for next number // we can use 12, because 5^2 + 12^2 = 13^2 // next one will be y^2 - x^2 = 13^2 = 169, also y-x=1 since y != x // so y = (169+1)/2 = 85, and x = 84, so next element is 84 // but this will soon exceed 10^8 // the idea is then to use a lot of 1's when n is big enough. // This is tourist's construction // // for large enough n // if n is even, target is (n/2)^2 - (n/2 -1)^2 = n-1 // if n is odd, target is ((n+3)/2)^2 - ((n+1)/2)^2 = n + 2 = n-2 + 4 = n-2+2^2 // basecase is n=1, use 1 // n=2 use 3,4 #include <iostream> #include <vector> using namespace std; vector<int> gen(int k) { vector<int> ret; if (k == 1) ret.push_back(1); else if (k == 2) { ret.push_back(3); ret.push_back(4); } else { if (k & 1) { for (int i = 0; i < k-2; ++i) ret.push_back(1); ret.push_back(2); ret.push_back((k+1)/2); } else { for (int i = 0; i < k-1; ++i) ret.push_back(1); ret.push_back(k/2 - 1); } } return ret; } int main() { int n, m; cin >> n >> m; vector<int> a = gen(n); vector<int> b = gen(m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (j) cout << ' '; cout << a[i] * b[j]; } cout << endl; } }
true
f9be13f8aceba70add6705b9b49afaffd69753c3
C++
RedwanPlague/cses_problems
/Sorting-and-Searching/Restaurant-Customers.cpp
UTF-8
939
2.546875
3
[]
no_license
// https://cses.fi/problemset/task/1619/ #include <iostream> #include <set> #include <algorithm> #include <vector> using namespace std; #define F first #define S second #define all(v) (v).begin(),(v).end() typedef pair<int,int> pii; int main () { ios_base::sync_with_stdio(false); cin.tie(nullptr); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif int n; cin >> n; int lim = 2 * n; vector<pii> times(lim); for (int i=0; i<lim; i+=2) { cin >> times[i].F; times[i].S = i; cin >> times[i+1].F; times[i+1].S = i; } sort(all(times)); int mx = 0; set<int> active; for (auto p: times) { auto it = active.find(p.S); if (it != active.end()) { active.erase(it); } else { active.insert(p.S); } mx = max(mx, (int)active.size()); } cout << mx << endl; return 0; }
true
78aff793e4e87542df2fa8f5a0ecd6a8595c0167
C++
gkocevar1/Artos
/ArtosHWM1500Quattro/HWM1500Quattro_Prod/ValvePhase.cpp
UTF-8
8,362
2.671875
3
[]
no_license
#include "ValvePhase.h" /** Constructor */ ValvePhase::ValvePhase() { ValvePhase::init(); } // ------------------ // Public methods /** Switch valves to desired phase */ void ValvePhase::switchToPhase(Constants::Phase phase) { switch (phase) { case Constants::Phase::FlushingSFRusco: { ValvePhase::switchValves( false, // 1 false, // 2 false, // 3 false, // 4 false, // 5 true, // 6 false, // 7 false, // 8 false, // 9 false, // 10 false, // 11 false, // 12 false, // 13 false // 14 ); break; } case Constants::Phase::FlushingUF1B: case Constants::Phase::FlushingUF2G: { ValvePhase::switchValves( true, // 1 true, // 2 true, // 3 true, // 4 false, // 5 false, // 6 false, // 7 false, // 8 false, // 9 true, // 10 true, // 11 true, // 12 true, // 13 true // 14 ); break; } case Constants::Phase::FlushingGAC: { ValvePhase::switchValves( true, // 1 true, // 2 false, // 3 false, // 4 true, // 5 false, // 6 true, // 7 true, // 8 false, // 9 true, // 10 true, // 11 false, // 12 false, // 13 true // 14 ); break; } case Constants::Phase::Filtration: { ValvePhase::switchValves( true, // 1 true, // 2 false, // 3 false, // 4 true, // 5 false, // 6 false, // 7 false, // 8 true, // 9 true, // 10 true, // 11 false, // 12 false, // 13 true // 14 ); break; } case Constants::Phase::BackwashRusco1: { ValvePhase::switchValves( true, // 1 true, // 2 false, // 3 false, // 4 true, // 5 false, // 6 false, // 7 false, // 8 true, // 9 true, // 10 true, // 11 false, // 12 false, // 13 false // 14 ); break; } case Constants::Phase::BackwashRusco2: { ValvePhase::switchValves( true, // 1 true, // 2 false, // 3 false, // 4 true, // 5 true, // 6 false, // 7 false, // 8 true, // 9 true, // 10 true, // 11 false, // 12 false, // 13 false // 14 ); break; } case Constants::Phase::BackwashUF1: { ValvePhase::switchValves( false, // 1 true, // 2 true, // 3 false, // 4 false, // 5 false, // 6 false, // 7 false, // 8 true, // 9 true, // 10 true, // 11 false, // 12 false, // 13 true // 14 ); break; } case Constants::Phase::BackwashUF2: { ValvePhase::switchValves( true, // 1 false, // 2 false, // 3 true, // 4 false, // 5 false, // 6 false, // 7 false, // 8 true, // 9 true, // 10 true, // 11 false, // 12 false, // 13 true // 14 ); break; } case Constants::Phase::BackwashUF3: { ValvePhase::switchValves( true, // 1 true, // 2 false, // 3 false, // 4 false, // 5 false, // 6 false, // 7 false, // 8 true, // 9 false, // 10 true, // 11 true, // 12 false, // 13 true // 14 ); break; } case Constants::Phase::BackwashUF4: { ValvePhase::switchValves( true, // 1 true, // 2 false, // 3 false, // 4 false, // 5 false, // 6 false, // 7 false, // 8 true, // 9 true, // 10 false, // 11 false, // 12 true, // 13 true // 14 ); break; } case Constants::Phase::Desinfection: { ValvePhase::switchValves( false, // 1 false, // 2 true, // 3 true, // 4 false, // 5 false, // 6 false, // 7 true, // 8 true, // 9 false, // 10 false, // 11 true, // 12 true, // 13 false // 14 ); break; } case Constants::Phase::FlushingUF2B: { ValvePhase::switchValves( true, // 1 true, // 2 true, // 3 true, // 4 false, // 5 false, // 6 false, // 7 false, // 8 true, // 9 true, // 10 true, // 11 true, // 12 true, // 13 true // 14 ); break; } case Constants::Phase::Close: { ValvePhase::switchValves( false, // 1 false, // 2 false, // 3 false, // 4 false, // 5 false, // 6 false, // 7 false, // 8 false, // 9 false, // 10 false, // 11 false, // 12 false, // 13 false // 14 ); break; } } } /** deactive all valves. Set PIN state to LOW @param1: delay after deactivation all valves (in milliseconds) */ void ValvePhase::deactivateValves(unsigned int delayTime) { for (int i = 0; i < 14; i++) { if (_activeValves[i] != -1) { // deactivate valve digitalWrite(_activeValves[i], LOW); _activeValves[i] = -1; } } delay(delayTime); } // ------------------ // private methods /** switch valves to proper position */ void ValvePhase::switchValves(boolean v1, boolean v2, boolean v3, boolean v4, boolean v5, boolean v6, boolean v7, boolean v8, boolean v9, boolean v10, boolean v11, boolean v12, boolean v13, boolean v14) { ValvePhase::activateValve((v1 ? Constants::Valve1P : Constants::Valve1M), 0); ValvePhase::activateValve((v2 ? Constants::Valve2P : Constants::Valve2M), 1); ValvePhase::activateValve((v3 ? Constants::Valve3P : Constants::Valve3M), 2); ValvePhase::activateValve((v4 ? Constants::Valve4P : Constants::Valve4M), 3); ValvePhase::activateValve((v5 ? Constants::Valve5P : Constants::Valve5M), 4); ValvePhase::activateValve((v6 ? Constants::Valve6P : Constants::Valve6M), 5); ValvePhase::activateValve((v7 ? Constants::Valve7P : Constants::Valve7M), 6); ValvePhase::activateValve((v8 ? Constants::Valve8P : Constants::Valve8M), 7); ValvePhase::activateValve((v9 ? Constants::Valve9P : Constants::Valve9M), 8); ValvePhase::activateValve((v10 ? Constants::Valve10P : Constants::Valve10M), 9); ValvePhase::activateValve((v11 ? Constants::Valve11P : Constants::Valve11M), 10); ValvePhase::activateValve((v12 ? Constants::Valve12P : Constants::Valve12M), 11); ValvePhase::activateValve((v13 ? Constants::Valve13P : Constants::Valve13M), 12); ValvePhase::activateValve((v14 ? Constants::Valve14P : Constants::Valve14M), 13); // UV light is turned on when pump is running and valve 9 is open. digitalWrite(Constants::UVLight, ((pumpRunning && v9) ? HIGH : LOW)); } /** activate valve */ void ValvePhase::activateValve(int valveId, int pos) { // save active valve _activeValves[pos] = valveId; // open valve digitalWrite(valveId, HIGH); } /** Init valves */ void ValvePhase::init() { _activeValves[0] = -1; _activeValves[1] = -1; _activeValves[2] = -1; _activeValves[3] = -1; _activeValves[4] = -1; _activeValves[5] = -1; _activeValves[6] = -1; _activeValves[7] = -1; _activeValves[8] = -1; _activeValves[9] = -1; _activeValves[10] = -1; _activeValves[11] = -1; _activeValves[12] = -1; _activeValves[13] = -1; }
true
043b8171de4e749a8cc1147a8d0939943021b62f
C++
chaarvii/Algorithm
/Graph/Dijkstra'sShortestPath.cpp
UTF-8
2,480
3.734375
4
[]
no_license
#include<iostream> #include<list> #include<queue> using namespace std; class Graph { int V; // number of vertices vector < pair<int,int> > *Adj_list; // stores the graph public: Graph(int V); // constructor void add_edge(int u,int v,int wt); // adds an edge to the graph void shortest_path(int s); // computes the sortest path of all indices from a given index }; Graph::Graph(int V) { this->V = V; Adj_list = new vector<pair<int,int>> [V]; } void Graph::add_edge(int u,int v,int wt) { Adj_list[u].push_back(make_pair(v,wt)); Adj_list[v].push_back(make_pair(u,wt)); } void Graph::shortest_path(int s) { priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int> >> pq; // queue for storing index number and weight pair vector <int> dist(V,INT_MAX); // stores shortest distance vector <bool> flag(V,false); // optimization step, keeps a tab of vertices that have been updates pq.push(make_pair(s,0)); dist[s] =0; // distance for starting index is zero flag[s] = true; while(!pq.empty()) // loop over it till priority_queue not empty { int w = pq.top().first; pq.pop(); flag[w] = true; for(auto i=Adj_list[w].begin();i!=Adj_list[w].end();i++) { int v = (*i).first; int wt = (*i).second; if(dist[v]>dist[w] + wt&& flag[v]==false) // if new distance is smaller than current distance then update { dist[v] = dist[w]+wt; pq.push(make_pair(v,dist[v])); } } } printf("Vertex Distance from vertex\n"); // print shortest distance for(int i=0;i<V;i++) printf("%d \t\t %d\n",i,dist[i]); } // driver index int main() { Graph g(9); int u,v,wt; int m; cin >> m; for(int i=0;i<m;i++) { cin >> u >> v >> wt; g.add_edge(u,v,wt); cin.ignore(); } g.shortest_path(0); }
true
571d2db2e71802503e8310139df611ada3d9c4dd
C++
racocvr/dvbcam
/tvs-api/RatingProxy.h
UTF-8
1,581
2.640625
3
[]
no_license
#ifndef _RATINGPROXY_H_ #define _RATINGPROXY_H_ #include <string> #include <pthread.h> #include <map> #include "TVServiceDataType.h" #include "MarshallingHelperProxy.h" #include "IRating.h" class TCRatingProxy : public IRating { public: /** * @brief Sets Dbus connection for communication with TVS. * @param [in] pTVSConnection TVService IPC connection. */ static void InitTVSConnection(TVServiceAPIConnection* pTVSConnection); /** * @brief Returns an interface object. * @param [in] tvsHandle Profile identifier. * @return Pointer to interface implementation. */ static IRating* Instance( TVSHandle tvsHandle ); /** * @brief Destroys all interface instances. */ static void Destroy( void ); int GetRatingInfo( _OUT_ std::vector< TSRatingInfo >& ratingInfo ); int SetRatingData( _IN_ ERatingData ratingData, _IN_ unsigned int value ); int GetRatingData( _IN_ ERatingData ratingData, _OUT_ unsigned int& value ); private: TCRatingProxy( TVSHandle tvsHandle ); TCRatingProxy( const TCRatingProxy& ){}; TCRatingProxy& operator= ( const TCRatingProxy& ) { return *this; }; /** * @brief Adds profile related data to proxy method call. * @param [in] helper Proxy marshalling helper. */ void m_AddInterfaceProfiling( TCMarshallingHelperProxy& helper ); static std::map<TVSHandle, IRating*> m_instances; TVSHandle m_tvsHandle; static TVServiceAPIConnection* m_pTVSConnection; static std::string m_interfaceName; static pthread_rwlock_t m_rwlock; // lock for instance creation in multi-thread applications }; #endif //_RATINGPROXY_H_
true
b57e40686286ff20bea3670ce507003ce89190c3
C++
Chylix/ShaderTool
/triebWerk/src/CTWFData.cpp
UTF-8
456
2.515625
3
[]
no_license
#include <CTWFData.h> void triebWerk::CTWFData::AddConfigurationPair(std::string a_Key, std::string a_Value) { m_ConfigurationTable.insert(std::pair<std::string, std::string>(a_Key, a_Value)); } std::string triebWerk::CTWFData::GetValue(std::string a_Key) { auto foundIterator = this->m_ConfigurationTable.find(a_Key); if (foundIterator == this->m_ConfigurationTable.end()) { return std::string(); } else { return foundIterator->second; } }
true
aee42461b3c11103780f9718496eb776c15c7ce9
C++
mmariaa12/task2
/Particle.cpp
UTF-8
2,667
2.953125
3
[]
no_license
#include "Particle.hpp" #include <cassert> #include <cmath> #ifndef EPS #define EPS 1e-9 #endif #define KGRAVITATIONAL 6.6e-11 #define KCOULOMB 8.9e+9 Particle::Particle(void) : x(), v(), f(), m(0), q(0), t(0) {} Particle::Particle(Vector3d x, Vector3d v, double m, double q, double t) : x(x), v(v), f(Vector3d()), m(m), q(q), t(t) { assert(m >= 0 && q >= 0 && t >= 0); } Particle::Particle(const Particle &p) : x(p.x), v(p.v), f(p.f), m(p.m), q(p.q), t(p.t) {} Particle &Particle::operator=(const Particle &p) { this->x = p.x; this->v = p.v; this->f = p.f; this->m = p.m; this->q = p.q; this->t = p.t; return *this; } Vector3d Particle::force(const Particle &dest, const Particle &src) { double gravitational_magnitude, coulomb_magnitude; double direction_square; Vector3d direction; direction = dest.x - src.x; direction_square = direction.square(); assert(fabs(direction_square) > EPS); gravitational_magnitude = KGRAVITATIONAL * dest.m * src.m / direction_square; coulomb_magnitude = KCOULOMB * dest.q * src.q / direction_square; return (gravitational_magnitude + coulomb_magnitude) * direction.normalize(); } bool Particle::detect_collision(const Particle &p1, const Particle &p2, double l) { return (p1.x - p2.x).square() < l * l; } Particle &Particle::collide_in_place(const Particle &p) { double m, this_v_square; m = this->m + p.m; assert(fabs(m) > EPS); this->x = (this->m * this->x + p.m * p.x) / m; this->q += p.q; this_v_square = this->v.square(); this->v = (this->m * this->v + p.m * p.v) / m; this->t = (this->m * (this->t + this_v_square / 2) + p.m * (p.t + p.v.square() / 2)) / m - this->v.square() / 2; this->m = m; return *this; } Particle &Particle::set_force(const Vector3d &f) { this->f = f; return *this; } Particle &Particle::update_in_place(double dt) { assert(fabs(this->m) > EPS); this->x += dt * this->v; this->v += dt / this->m * this->f; return *this; } std::ostream &operator<<(std::ostream &os, const Particle &p) { return os << "{\n x: " << p.x << ",\n v: " << p.v << ",\n f: " << p.f << ",\n m: " << p.m << ",\n q: " << p.q << ",\n t: " << p.t << "\n}"; } bool operator==(const Particle &p1, const Particle &p2) { return p1.x == p2.x && p1.v == p2.v && fabs(p1.m - p2.m) < EPS && fabs(p1.q - p2.q) < EPS && fabs(p1.t - p2.t) < EPS; } bool operator!=(const Particle &p1, const Particle &p2) { return !(p1 == p2); }
true
77f510621d62e2b11124bdf5197da18d38ce794e
C++
strimuer213p/AtCoder_Beginner_Contest_003_B
/AtCoder_Beginner_Contest_003_B/Source.cpp
UTF-8
785
3.171875
3
[]
no_license
#include<iostream> #include<string> #include<array> int main() { std::array<char, 7> ar{ 'a','t','c','o','d','e','r' }; std::array<std::string,2> str; std::cin >> str[0] >> str[1]; for (int i = 0; i < (int)str[0].size(); i++) { for (int x = 0; x < str.size(); x++) { if (str[x][i] == '@') { bool flag = true; if (str[0][i] == str[1][i]) { continue; } for (int j = 0; j < ar.size(); j++) { if (str[x == 0 ? 1 : 0][i] == ar[j]) { flag = false; } } if (flag) { std::cout << "You will lose" << std::endl; exit(0); } } } if (str[0][i] != str[1][i] && str[0][i] != '@' && str[1][i] != '@') { std::cout << "You will lose" << std::endl; exit(0); } } std::cout << "You can win" << std::endl; return 0; }
true
5161820f74f941e9757d4c856c493c4650c7f3d6
C++
GuessWh0o/SomeRandomCode_different_languages
/C/String.h
UTF-8
1,146
3.171875
3
[]
no_license
#pragma once #include <stddef.h> #include <cstring> #include <iostream> namespace Program { typedef unsigned int ui; class String { private: char* str; ui length; static int number_Elem; public: String() { str = NULL; length = 0; } String(const char* s) { length = strlen(s); str = new char[length + 1]; for (ui i(0); i < length; i++) { str[i] = s[i]; str[length] = '\0'; } } String(const String& s) { length = strlen(s.str); str = new char[length + 1]; for (ui i(0); i < length; i++) { str[i] = s.str[i]; str[length] = '\0'; } } friend std::ostream& operator<<(std::ostream & os, String& s) { os << s.str; return os; } String& operator=(const String& s) { delete[] str; length = strlen(s.str); str = new char[length + 1]; for (ui i(0); i < length; i++) { str[i] = s.str[i]; str[length] = '\0'; } return *this; } operator char*() { char* str = new char[this->length + 1]; for (ui i(0); i < length; i++) { str[i] = this->str[i]; str[length] = '\0'; } return str; } ~String() { delete[] str; } }; }
true
dfb7a21f68baa26c01e0d08f8ddc397ed23d41bd
C++
paulAriri/cPlusPlusFunctions
/compareArrays.cpp
UTF-8
767
3.609375
4
[]
no_license
#include <iostream> using namespace std; //function to compare two arrays and conclude if they have the same exact values for all elements bool compare(int a[],int b[],int size) { int first = a[0]; int second = b[0]; for(int i = 0; i<size; i=i+1) { if (a[i] != b[i] ) { return false; } return true; } } //OR bool compare(int a[],int b[],int size) { int first = a[0]; int second = b[0]; for(int i = 0; i<size; i=i+1) { if (a[i] == b[i] ) { count =count+1; } if(count == size) { return true; } else { return false; } } } int main() { return 0; }
true
d5390c634865d4259d19b5f8195d63d07a9ec34b
C++
pankdm/lang-perf
/cython/cpp_solver.cpp
UTF-8
1,347
3
3
[ "MIT" ]
permissive
#include "cpp_solver.h" const int NOT_PROCESSED = -1; CppSolver::CppSolver(vvi* _graph) : graph(_graph) { } void CppSolver::run_bfs(int start, vi* _scores) { vi& scores = *_scores; auto num_cities = graph->size(); scores.assign(num_cities, NOT_PROCESSED); scores[start] = 0; deque<int> queue; queue.push_back(start); while (!queue.empty()) { int now = queue.front(); queue.pop_front(); int value = scores[now]; for (const auto& next : (*graph)[now]) { if (scores[next] == NOT_PROCESSED) { scores[next] = value + 1; queue.push_back(next); } } } } void CppSolver::compute_hash() { clock_t tbegin = clock(); auto num_cities = graph->size(); vvi distances(num_cities); for (int i = 0; i < num_cities; ++i) { vi scores; run_bfs(i, &scores); distances[i] = std::move(scores); } int total_score = 0; for (int i = 0; i < num_cities; ++i) { int current_score = 0; for (const auto& d : distances[i]) { if (d == NOT_PROCESSED) { continue; } int d2 = d * d; current_score ^= d2; } total_score += current_score; } cout << "graph_hash=" << total_score << endl; clock_t tend = clock(); double elapsed_msecs = double(tend - tbegin) / CLOCKS_PER_SEC * 1000; cout << "time=" << elapsed_msecs << endl; }
true
142240b508be79cda83c62aa4d040f12deac8c1e
C++
44652499/embedded
/mycode/大杂烩/AA3.cpp
UTF-8
925
3.328125
3
[]
no_license
#include <iostream> using namespace std; template<class T1,class T2> class pair1 { public: pair1(T1 _first,T2 _second) { first=_first; second=_second; } T1 first; T2 second; }; template<class T> class A { template<class T1> friend ostream& operator <<(ostream& out,A<T1> a); public: A() { } A(T _data) { data=_data; } T data; }; template<class T> ostream& operator <<(ostream& out,A<T> a) { out<<a.data<<endl; return out; } template<class T> class B { template<class T1> ostream& operator <<(ostream& out,typename B<T1> b); public: B() { } B(T _value) { value=_value; } T value; }; template<class T> ostream& operator <<(ostream& out,typename B<T> b) { out<<b.value<<endl; return out; } void fun() { B<string> b("abcd"); A<B<string> > a(b); pair1<int,A<B<string> > > p(10,a); cout<<p.first<<"\t"<<p.second<<endl; } int main(int argc, char const *argv[]) { fun(); return 0; }
true
90ced8c50ce85960694bb43f9685e2c4f67bfcc4
C++
Kowsihan-sk/Codechef-submissions
/Challenges/CodeChef May 2021 div2 Long/Tic_Tac_Toe.cpp
UTF-8
2,448
2.578125
3
[]
no_license
/** Author : S Kowsihan **/ #include <bits/stdc++.h> using namespace std; #define fast \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); #define ll long long #define endl "\n" #define f(a, b, c) for (ll i = a; i < b; i += c) typedef vector<ll> vl; #define fo(i, a, b, c) for (ll i = a; i < b; i += c) int main() { fast; ll TT; cin >> TT; while (TT--) { vector<string> grid(3); f(0, 3, 1) cin >> grid[i]; ll a_win = 0, b_win = 0, count_x = 0, count_o = 0; ll da1 = 0, da2 = 0, db1 = 0, db2 = 0; set<ll> a, b; f(0, 3, 1) { ll x1 = 0, x2 = 0, y1 = 0, y2 = 0; // row column check + count fo(j, 0, 3, 1) { if (grid[i][j] == 'X') count_x++, x1++; else if (grid[i][j] == 'O') count_o++, y1++; if (grid[j][i] == 'X') x2++; else if (grid[j][i] == 'O') y2++; } a.insert(x1), a.insert(x2), b.insert(y1), b.insert(y2); // for diagonals if (grid[i][i] == 'X') da1++; else if (grid[i][i] == 'O') db1++; if (grid[i][2 - i] == 'X') da2++; else if (grid[i][2 - i] == 'O') db2++; } a.insert(da1), a.insert(da2), b.insert(db1), b.insert(db2); if (a.count(3)) a_win = 1; if (b.count(3)) b_win = 1; ll f = a_win > b_win ? 1 : 0, es = (9 - (count_x + count_o)) % 2; // if empty space // both W if (a_win && b_win) cout << 3 << endl; // 1 W else if ((a_win || b_win) && ((f && (count_x == (count_o + 1))) || ((!f) && (count_x == count_o)))) cout << 1 << endl; // no W else if (!a_win && !b_win && (count_o + count_x != 9) && ((es && (count_x == count_o)) || ((!es) && (count_x == (count_o + 1))))) cout << 2 << endl; // if no empty space else if ((count_x + count_o == 9) && ((count_x == 5) && (count_o == 4)) && (!b_win)) cout << 1 << endl; else cout << 3 << endl; } return 0; }
true
929697d67e56bec69c91212f22808353682e1f11
C++
lorenzomoulin/Programacao-Competitiva
/URI/matematica/jogo_do_maior_numero_1829.cpp
UTF-8
834
2.9375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int n ; cin >> n; int v[n]; int cont1 = 0, cont2 = 0; for (int i = 0; i < n; i++){ int a, b, n; char circ, exc; cin >> a >> circ >> b >> n >> exc; if (b*log(a) > (0.5*log(2*M_PI) + (n + 0.5)*log(n) - n)){ v[i] = 1, cont1++; } else v[i] = 2, cont2++; } if (cont1 == cont2) cout << "A competicao terminou empatada!\n"; else if (cont1 > cont2) cout << "Campeao: Lucas!\n"; else cout << "Campeao: Pedro!\n"; for (int i = 0; i < n; i++){ if (v[i] == 1) cout << "Rodada #" << i + 1 << ": Lucas foi o vencedor\n"; else cout << "Rodada #" << i + 1 << ": Pedro foi o vencedor\n"; } return 0; }
true