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
3f6f10553fbfb70aef460e212391d7f93c467f15
C++
AxelTB/SmartGreenHouse
/Arduino/.Time.h
UTF-8
1,228
2.625
3
[]
no_license
#ifndef TIME_H #define TIME_H #include <inttypes.h> typedef uint32_t time_sec; typedef uint64_t time_millis; /******************************************************************* * ==SmartGreenHouse== * Time Class * Created: 17/02/2013 * Author: Ax * License: CC BY-SA 3.0 * http://creativecommons.org/licenses/by-sa/3.0/ *===================================================================== Static Class for time manipulation Use on board timer to evaluate short period of time and fixes overflow (Every ~41 days) ********************************************************************/ /** * @brief OBSOLETE!!! * Provide function to manipulate time * * */ class Time { public: static void init(); static void init(uint8_t type); //Initialize with RTC /// static time_millis getMillis(); protected: private: //Short time variable (till minutes) uint32_t millisH; //Contains the high byte long lastmillis; //To evaluate overflow //Long time variable unsigned short hour, day, month, year;//If you are still using this code and it's 2190 you may wanna changhe this class softwareTimeCounter{ public: } }; #endif // TIME_H
true
a1a5cf7e66cb88c01d1941444381d190450a45fa
C++
Huxinkui/Client-Server
/DataPackage/Serialize.h
UTF-8
3,936
2.78125
3
[]
no_license
#ifndef _SERIALIZE_H #define _SERIALIZE_H //序列化 // int Serialize(const DataPackage &s, char output[]) // { // int count = 0; // memcpy(output, &s.age, sizeof(s.age)); // count += sizeof(s.age); // memcpy(output + count , &s.name_size, sizeof(s.name_size)); // count += sizeof(s.name_size); // memcpy(output + count , &s.Gender_size, sizeof(s.Gender_size)); // count += sizeof(s.Gender_size); // memcpy(output + count, s.name.c_str(), s.name.length()); // count += s.name.length(); // memcpy(output + count, s.Gender.c_str(), s.Gender.length()); // count += s.Gender.length(); // return count; // } // //反序列化 // int Deserialize(DataPackage &s, const char *input, int count) // { // int offset = 0; // memcpy(&s.age, input, sizeof(s.age)); // offset += sizeof(s.age); // memcpy(&s.name_size, input + offset , sizeof(s.name_size)); // offset += sizeof(s.name_size); // memcpy(&s.Gender_size, input + offset,sizeof(s.Gender_size)); // offset += sizeof(s.Gender_size); // s.name.append(input + offset, s.name_size); // offset += s.name_size; // s.Gender.append(input + offset, s.Gender_size); // offset += s.Gender_size; // return 0; // } // int LoginSerialize(const Login &login, char output[]) { int count = 0; memcpy(output + count, &login.dataLenth, sizeof(login.dataLenth)); count += sizeof(login.dataLenth); memcpy(output + count, &login.cmd, sizeof(login.cmd)); count += sizeof(login.cmd); memcpy(output + count, &login.nameLength, sizeof(login.nameLength)); count += sizeof(login.nameLength); memcpy(output + count, &login.passwordLength, sizeof(login.passwordLength)); count += sizeof(login.passwordLength); memcpy(output + count, login.name.c_str(), login.name.length()); count += login.name.length(); //cout << " name size :" << login.name.length() << endl; memcpy(output + count, login.password.c_str(), login.password.length()); count += login.password.length(); return 0; } int LoginDeserialize(Login &login, const char *input, int count) { int offset = 0; memcpy(&login.dataLenth, input, sizeof(login.dataLenth)); offset += sizeof(login.dataLenth); memcpy(&login.cmd, input + offset, sizeof(login.cmd)); offset += sizeof(login.cmd); memcpy(&login.nameLength, input + offset, sizeof(login.nameLength)); offset += sizeof(login.nameLength); memcpy(&login.passwordLength, input + offset, sizeof(login.passwordLength)); offset += sizeof(login.passwordLength); login.name.append(input + offset, login.nameLength); offset += login.nameLength; login.password.append(input + offset, login.passwordLength); //offset += login.passwordLength; return 0; } template<class INFO> int InfoSerialize(const INFO &info, char output[] ) { int count = 0; memcpy(output + count, &info.dataLenth, sizeof(info.dataLenth)); count += sizeof(info.dataLenth); memcpy(output + count, &info.cmd, sizeof(info.cmd)); count += sizeof(info.cmd); memcpy(output + count, &info.infoLength, sizeof(info.infoLength)); count += sizeof(info.infoLength); memcpy(output + count, info.info.c_str(), info.info.length()); count += info.info.length(); return 0; } template<class INFO> int InfoDeserialize(INFO &info, const char *input, int count) { int offset = 0; memcpy(&info.dataLenth, input, sizeof(info.dataLenth)); offset += sizeof(info.dataLenth); memcpy(&info.cmd, input + offset, sizeof(info.cmd)); offset += sizeof(info.cmd); memcpy(&info.infoLength, input + offset, sizeof(info.infoLength)); offset += sizeof(info.infoLength); info.info.append(input + offset, info.infoLength); return 0; } template<class DL> int DLDeserialize(DL &info, const char *input, int count) { int offset = 0; memcpy(&info.dataLenth, input, sizeof(info.dataLenth)); offset += sizeof(info.dataLenth); memcpy(&info.cmd, input + offset, sizeof(info.cmd)); return 0; } #endif
true
ab7311605c67d7ca0f3689c4d99c9c948d8c3fef
C++
Heiden-repository/Study_Algorithm
/coding/TreeDistance.cpp
UTF-8
1,331
2.75
3
[]
no_license
//#include<cstdio> // //int depthX = 0; //int depthY = 0; //int tree[1000]; //int Node[1000]; // //int returnValue(int idx) { // int num; // num = tree[idx]; // return num; //} // //void find(int x, int y) { // int num = x; // // if (x == 0 || y == 0) { // if (x == 0) num = y; // else num = x; // while (num != 0) { // num = returnValue(num); // Node[depthX++] = num; // } // depthY = 0; // return; // } // else { // while (num != 0) { // num = returnValue(num); // Node[depthX++] = num; // } // num = y; // for (int i = 0; i < depthX; i++) { // //printf("Node[%d] : %d depthX : %d depthY : %d i : %d\n", i,Node[i],depthX, depthY, i); // if (Node[i] == num) { depthX = i + 1; return; } // } // depthY++; // while (num != 0) { // num = returnValue(num); // for (int i = 0; i < depthX; i++) { // //printf("Node[%d] : %d depthX : %d depthY : %d i : %d\n", i,Node[i],depthX, depthY, i); // if (Node[i] == num) { depthX = i + 1; return; } // } // depthY++; // } // } //} // // //int main() { // int n, x, y; // // scanf("%d %d %d", &n, &x, &y); // // for (int i = 0; i < n-1; i++) { // int val, idx; // scanf("%d %d", &val, &idx); // tree[idx] = val; // } // // find(x, y); // //printf("depthX : %d depthY : %d\n", depthX, depthY); // printf("%d\n", depthX + depthY); // // return 0; //}
true
788ba45a5874f48c9c4dd6f9d6790cd5bfddc288
C++
alyssssa8/resume
/4. lintcode/LeetCode409LongestPalindrome/LeetCode409Longest Palindrome.cpp
UTF-8
2,271
3.421875
3
[]
no_license
//https://leetcode.com/problems/longest-palindrome/description/ //Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. // //This is case sensitive, for example "Aa" is not considered a palindrome here. // //Note: // Assume the length of given string will not exceed 1, 010. // // Example : // // Input : // "abccccdd" // // Output : // 7 // // Explanation : // One longest palindrome that can be built is "dccaccd", whose length is 7. #include <iostream> #include <math.h> #include <algorithm> #include<vector> #include<string> #include <queue> #include <stack> #include <list> #include <map> //hash table #include<unordered_map> #include <vector> #include <set> using namespace std; // use this one class Solution { public: int longestPalindrome(const string& s) { vector<int> freqs(128, 0); //int freqs[128] = { 0 }; //could use array. both will loop 128 times for (int i = 0; i < s.size(); i++) { freqs[s[i]]++; } int ans = 0; int odd = 0; for (const int freq : freqs) { // could not use int "i = 0; i < s.size(); i++". for example, ababa, will loop all the letters, will have repeatition. int temp = 0; // could not use set, only will have s, will not have the count. if (freq % 2 == 0) { temp = freq; } else { temp = freq - 1; } ans = ans + temp; // same as: ans += freq % 2 == 0 ? freq : freq - 1; // same as: ans += freq / 2 * 2; // same as: ans += ((freq >> 1) << 1); // same as: ans += freq & (INT_MAX - 1); //ans += freq & (~1); // clear the last bit } if (ans < s.size()) { ans++; } return ans; } }; class Solution2 { public: int longestPalindrome(string s) { map<char, int> myMap; int count = 0; for (int i = 0; i < s.size(); i++) { myMap[s[i]]++; if (myMap[s[i]] == 2) { count += 2; myMap[s[i]] = 0; } } if (count < s.size()) { count++; } return count; } }; int main() { int temp[256] = { 0 }; begin(temp); vector<int>nums({ 3, 1 ,0 }); Solution question; question.longestPalindrome("abccccdd"); //question.longestPalindrome("caba"); Solution question2; question2.longestPalindrome("sdasd"); return 0; }
true
167773e0725a4bc8f3b3a10ec26e7fcd6bb4d5bb
C++
Alicelalala/Code
/Data_Struct/20.最小的10个数.cpp
UTF-8
2,102
3.40625
3
[]
no_license
/************************************************************************* > File Name: 20.最小的10个数.cpp > Author: caohaiyan > Mail: 877022406@qq.com > Created Time: 2018年11月03日 星期六 15时55分59秒 ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_N 100000000 #define swap(a, b) { \ __typeof(a) __temp = a; a = b; b = __temp; \ } //一亿个数中, 找到最小的十个数 //建一个十个元素的大顶堆 //如果新来的元素小于堆顶元素,堆顶元素出堆,新元素入堆 typedef struct Heap { int *data; int size; } Heap; Heap *init (int max) { Heap *h = (Heap *)malloc(sizeof(Heap)); h->data = (int *)malloc(sizeof(int) * max); h->size = 0; return h; } void update (Heap *h, int pos, int n) { int ind = pos; int l = pos * 2 + 1; int r = pos * 2 + 2; if (l < n && h->data[l] > h->data[ind]) { ind = l; } if (l < n && h->data[r] > h->data[ind]) { ind = r; } if (ind != pos) { swap(h->data[ind], h->data[pos]); update(h, ind, n); } } void push (Heap *h, int value) { h->data[h->size] = value; int ind = h->size; int f = (ind - 1) / 2; while (h->data[ind] > h->data[f]) { swap(h->data[ind], h->data[f]); ind = f; f = (ind - 1) / 2; } h->size++; } void pop (Heap *h) { swap(h->data[0], h->data[h->size - 1]); h->size--; update(h, 0, h->size); } int top (Heap *h) { return h->data[0]; } void output (Heap *h) { for (int i = 0; i < h->size; i++) { printf("%d ", h->data[i]); } printf("\n"); } void clear (Heap *h) { free(h->data); free(h); } int main() { srand(time(0)); Heap *h = init(15); for (int i = 0; i < MAX_N; i++) { int a = rand() % MAX_N; if (i >= 10) { if (a < top(h)) { pop(h); push(h, a); } } else { push(h, a); } } output(h); return 0; }
true
4662486904024159fe418927104a661596e84167
C++
korECM/BaekJoonStudying
/알고리즘 기초 1/200 - 자료구조 1/2020.02.06/스택수열/1874_JW.cpp
UTF-8
872
2.90625
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; int main() { int n; cin >> n; int num; int count = 0; string result; vector<int> s; count = 0; for (int i = 0; i < n; i++) { cin >> num; getchar(); if (num > count) { while (num != count) { count++; s.push_back(count); result.append("+\n"); } s.pop_back(); result.append("-\n"); } else if (num < count) { if (s.back() == num) { s.pop_back(); result.append("-\n"); } } else { s.pop_back(); result.append("-\n"); } } if (s.empty()) { cout << result << endl; } else { cout << "NO" << endl; } return 0; }
true
4218611dd71a5836dcf761fa71680d22ddef1d26
C++
Frankie-2000-F/PAT_Advanced-Level
/1027/1027/Main.cpp
UTF-8
392
3.203125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int main(){ int rgb; int color[6]; char digits[13] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C' }; for (int i = 0; i < 6; i = i + 2){ cin >> rgb; color[i] = rgb / 13; color[i + 1] = rgb % 13; } cout << "#" ; for (int i = 0; i < 6; i++){ cout << digits[color[i]]; } }
true
f918e22885567e052b71fdf4d9c3b94898f7d55c
C++
stembotvn/UMake-Arduino
/examples/Auto_Light/Auto_Light.ino
UTF-8
589
2.90625
3
[]
no_license
#include "MakerKit.h" #define Light_pin A0 #define LED_pin 2 int light; int ON = 10; int OFF = 30; MakerKit Umake; void setup() { Serial.begin(115200); } void loop() { light = Umake.getLight(Light_pin); // Lấy giá trị cường độ ánh sáng (tính theo %) if(light < ON){ // Nếu cường độ ánh sáng đọc vào nhỏ hơn ngưỡng bật đèn Umake.setLED(LED_pin, 1); // Bật đèn } if(light > OFF){ // Nếu cường độ ánh sáng đọc vào lớn hơn ngưỡng tắt đèn Umake.setLED(LED_pin, 0); // Tắt đèn } }
true
9b5b7ef1a5bc8cbc18a26c7d9b0a4b8defdc8045
C++
rahatchd/TINAH_example
/Arduino/libraries/TINAH_libraries/custom.cpp
UTF-8
295
2.53125
3
[]
no_license
/* * Custom.cpp - Custom library example. * Created by Rahat Dhande, July 19, 2016. */ #include <custom.h> #include <Arduino.h> Example::Example() { Serial.print("Example Object Constructed.\n\n"); } void Example::set(uint8_t x) { _x = x; } uint8_t Example::get(void) { return _x; }
true
1b94f2847a8b3ac5078c6a5552e1f68745301265
C++
ernestyalumni/HrdwCCppCUDA
/Voltron/Source/DataStructures/Graphs/WeightedGraph.h
UTF-8
9,410
3.421875
3
[ "MIT" ]
permissive
#ifndef DATA_STRUCTURES_GRAPHS_WEIGHTED_GRAPH_H #define DATA_STRUCTURES_GRAPHS_WEIGHTED_GRAPH_H #include <algorithm> // std::fill #include <cstddef> #include <cstring> #include <limits> #include <type_traits> // std::is_floating_point namespace DataStructures { namespace Graphs { //------------------------------------------------------------------------------ /// \url https://ece.uwaterloo.ca/~dwharder/aads/Projects/5/Dijkstra/src/Weighted_graph.h /// \ref 11.01. Graph_theory.pptx, Graph theory and the Graph ADT. //------------------------------------------------------------------------------ template <typename EDGE_VALUE_T> class InefficientWeightedGraph { public: //-------------------------------------------------------------------------- /// \ref Slide 24, 11.02.Graph data structures, "Default Values." /// For vertices not connected, use as default value 0, negative number, /// e.g. -1, or positive infinity +oo. /// Positive infinity +oo is most logical in that it makes sense 2 vertices /// which aren't connected have an infinite distance between them. /// /// As defined in IEEE 754 standard, representation of double-precision /// floating-point infinity 8 bytes: /// 0x7F F0 00 00 00 00 00 00; /// negative infinity stored as 0x FF F0 00 00 00 00 00 00. //-------------------------------------------------------------------------- inline static constexpr double infinity_ { std::numeric_limits<double>::infinity()}; InefficientWeightedGraph(const std::size_t n): n_{n}, adjacency_matrix_{new EDGE_VALUE_T*[n]} { for (std::size_t i {0}; i < n; ++i) { adjacency_matrix_[i] = new EDGE_VALUE_T[n]; } //------------------------------------------------------------------------ /// \url https://stackoverflow.com/questions/1373369/which-is-faster-preferred-memset-or-for-loop-to-zero-out-an-array-of-doubles#:~:text=memset%20can%20be%20faster%20since,simply%20does%20a%20loop%20internally. /// \details memset() is faster since it's written in assembly, std::fill /// is a template function which loops internally, but for type safety and /// readable code, std::fill() is the C++ way of doing things. /// memset() needs you to pass number of bytes, not number of elements, /// because it's an old C funciton. //------------------------------------------------------------------------ EDGE_VALUE_T default_value {get_default_value()}; for (std::size_t i {0}; i < n_; ++i) { std::fill( adjacency_matrix_[i], adjacency_matrix_[i] + n_, default_value); } } // Copy ctor. InefficientWeightedGraph(const InefficientWeightedGraph& other): n_{other.n_}, adjacency_matrix_{new EDGE_VALUE_T*[other.n_]} { create_arrays(); for (std::size_t i {0}; i < n_; ++i) { for (std::size_t j {0}; j < n_; ++j) { adjacency_matrix_[i][j] = other.adjacency_matrix_[i][j]; } } } // Copy assignment. InefficientWeightedGraph& operator=(const InefficientWeightedGraph& other) { delete_arrays(); delete[] adjacency_matrix_; n_ = other.n_; adjacency_matrix_ = new EDGE_VALUE_T*[other.n_]; create_arrays(); for (std::size_t i {0}; i < n_; ++i) { for (std::size_t j {0}; j < n_; ++j) { adjacency_matrix_[i][j] = other.adjacency_matrix_[i][j]; } } return *this; } virtual ~InefficientWeightedGraph() { delete_arrays(); delete[] adjacency_matrix_; } EDGE_VALUE_T get_default_value() { /* if (std::is_floating_point_v<EDGE_VALUE_T> || std::is_integral_V<EDGE_VALUE_T>) { return static_cast<EDGE_VALUE_T>(infinity_); } */ if (std::is_same_v<EDGE_VALUE_T, bool>) { return false; } return static_cast<EDGE_VALUE_T>(infinity_); } private: void create_arrays() { for (std::size_t i {0}; i < n_; ++i) { adjacency_matrix_[i] = new EDGE_VALUE_T[n_]; } } void delete_arrays() { for (std::size_t i {0}; i < n_; ++i) { delete[] adjacency_matrix_[i]; } } std::size_t n_; EDGE_VALUE_T** adjacency_matrix_; }; //------------------------------------------------------------------------------ /// \ref 11.02. Graph_data_structures.pptx, Adjacency Matrix Improvement. //------------------------------------------------------------------------------ template <typename EDGE_VALUE_T> class WeightedGraph { public: //-------------------------------------------------------------------------- /// \ref Slide 24, 11.02.Graph data structures, "Default Values." /// For vertices not connected, use as default value 0, negative number, /// e.g. -1, or positive infinity +oo. /// Positive infinity +oo is most logical in that it makes sense 2 vertices /// which aren't connected have an infinite distance between them. /// /// As defined in IEEE 754 standard, representation of double-precision /// floating-point infinity 8 bytes: /// 0x7F F0 00 00 00 00 00 00; /// negative infinity stored as 0x FF F0 00 00 00 00 00 00. //-------------------------------------------------------------------------- inline static constexpr double infinity_ { std::numeric_limits<double>::infinity()}; WeightedGraph(const std::size_t n): n_{n}, // Allocate an array of n pointers to EDGE_VALUE_T. adjacency_matrix_{new EDGE_VALUE_T*[n]}, // Allocate an array of n^2 EDGE_VALUE_T. adjacency_matrix_values_{new EDGE_VALUE_T[n * n]} { for (std::size_t i {0}; i < n; ++i) { // Allocate the addresses. adjacency_matrix_[i] = &(adjacency_matrix_values_[n * i]); } //------------------------------------------------------------------------ /// \url https://stackoverflow.com/questions/1373369/which-is-faster-preferred-memset-or-for-loop-to-zero-out-an-array-of-doubles#:~:text=memset%20can%20be%20faster%20since,simply%20does%20a%20loop%20internally. /// \details memset() is faster since it's written in assembly, std::fill /// is a template function which loops internally, but for type safety and /// readable code, std::fill() is the C++ way of doing things. /// memset() needs you to pass number of bytes, not number of elements, /// because it's an old C funciton. //------------------------------------------------------------------------ std::fill( adjacency_matrix_values_, adjacency_matrix_values_ + n_ * n_, get_default_value()); } // Copy ctor. WeightedGraph(const WeightedGraph& other): n_{other.n_}, adjacency_matrix_{new EDGE_VALUE_T*[other.n_]}, adjacency_matrix_values_{new EDGE_VALUE_T[n_ * n_]} { for (std::size_t i {0}; i < n_; ++i) { adjacency_matrix_[i] = &(adjacency_matrix_values_[n_ * i]); } std::copy( other.adjacency_matrix_values_, other.adjacency_matrix_values_ + other.n_, adjacency_matrix_values_); } // Copy assignment. WeightedGraph& operator=(const WeightedGraph& other) { delete[] adjacency_matrix_[0]; delete[] adjacency_matrix_; n_ = other.n_; adjacency_matrix_ = new EDGE_VALUE_T*[other.n_]; adjacency_matrix_values_ = new EDGE_VALUE_T[n_ * n_]; std::copy( other.adjacency_matrix_values_, other.adjacency_matrix_values_ + other.n_, adjacency_matrix_values_); return *this; } virtual ~WeightedGraph() { delete[] adjacency_matrix_[0]; delete[] adjacency_matrix_; } std::size_t number_of_vertices() const { return n_; } std::size_t number_of_edges() const { std::size_t count {0}; for (std::size_t i {0}; i < n_ * n_; ++i) { if (adjacency_matrix_values_[i] != get_default_value()) { ++count; } } return count; } static EDGE_VALUE_T get_default_value() { if (std::is_same_v<EDGE_VALUE_T, bool>) { return false; } return static_cast<EDGE_VALUE_T>(infinity_); } void add_edge( const std::size_t from, const std::size_t to, const EDGE_VALUE_T value = std::is_same_v<EDGE_VALUE_T, bool> ? true : EDGE_VALUE_T{}) { *(adjacency_matrix_[from] + to) = value; } void delete_edge(const std::size_t from, const std::size_t to) { *(adjacency_matrix_[from] + to) = get_default_value(); } EDGE_VALUE_T get_weight(const std::size_t from, const std::size_t to) { return *(adjacency_matrix_[from] + to); } bool is_edge(const std::size_t from, const std::size_t to) { return *(adjacency_matrix_[from] + to) != get_default_value(); } private: std::size_t n_; // Allocate an array of V pointers to EDGE_VALUE_T. EDGE_VALUE_T** adjacency_matrix_; // Allocate an array of V^2 EDGE_VALUE_T. EDGE_VALUE_T* adjacency_matrix_values_; }; } // namespace Graphs } // namespace DataStructures #endif // DATA_STRUCTURES_GRAPHS_WEIGHTED_GRAPH_H
true
ff949717462a762b3fc1b69fd17bbbed9574edfe
C++
amina-rahman-ananna/my-code
/uva/10035.cpp
UTF-8
618
2.84375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main () { unsigned long long a; unsigned long long b; int sum =0; int count=0; int carry =0; while (cin >> a>> b) { if (a== 0 && b== 0) break; carry =0; sum=0; count=0; while (a||b){ sum = (carry + (a%10)+ (b%10)); if (sum >=10) count++; carry =sum/10; a/=10; b/=10; } if ( count==0) cout << "No carry operation."<< endl; else if (count ==1 ) cout << "1 carry operation."<< endl; else cout << count <<" carry operations."<< endl; } return 0; }
true
f4fa8f13673265b16ace88eee4b48108087801a3
C++
peddinti/CPractice
/DataStructures/LinkedList.cpp
UTF-8
2,816
3.4375
3
[]
no_license
// // Created by Raghava Viswa Mani Kiran Peddinti on 9/3/16. // #include "LinkedList.h" #include "BinaryTree.h" #include <iostream> using namespace std; template <typename T> LinkedList<T>::LinkedList(T array[], int length) { // creating the head first LinkedListNode<T>* previous = new LinkedListNode<T>(&array[0], nullptr); head = *previous; for (int i = 1; i < length; i++) { previous->next = new LinkedListNode<T>(&array[i], nullptr); if (i==1) { head = *previous; } previous = previous->next; } } template <typename T> LinkedListNode<T>* LinkedList<T>::GetTail() { LinkedListNode<T>* previous = &head; while (previous->next != nullptr) previous = previous->next; return previous; } template <typename T> void LinkedList<T>::Insert(T* val) { LinkedListNode<T>* tail = GetTail(); tail->next = new LinkedListNode<T>(val, nullptr); } template <typename T> bool LinkedList<T>::Search(T* val) const { LinkedListNode<T>* previous; *previous = head; while (previous->next != nullptr && (*previous->value_ptr != *val)) previous = previous->next; if (*previous->value_ptr == *val) { return true; } else { return false; } } template <typename T> bool LinkedList<T>::Delete(const T val) { LinkedListNode<T>* previous = &head; // search for the value_ptr // Checking if the head matches if (*previous->value_ptr == val) { // replace head with next element previous = previous->next; head = *previous; return true; } while (previous->next != nullptr && (*previous->next->value_ptr != val)) previous = previous->next; if (previous->next == nullptr) { // no match return false; } else { // there is match and node is previous-> next LinkedListNode<T>* match_node = previous->next; previous->next = match_node->next; delete match_node; return true; } } template <typename T> LinkedListNode<T>* LinkedList<T>::GetHead() const { return &head; } template <typename T> void LinkedList<T>::set_head(LinkedListNode<T> head_value) { head = head_value; } template <typename T> void LinkedList<T>::Print() { LinkedListNode<T>* node = &head; while(node->next != nullptr) { cout << *(node->value_ptr) << "->"; node = node->next; } cout << *(node->value_ptr); cout << endl; } template <typename T> int LinkedList<T>::Length() const { LinkedListNode<T>* node = &head; int length = 0; while (node != nullptr) { node = node->next; length++; } return length; } template class LinkedList<int>; template class LinkedList<string>; template class LinkedList<BinaryTreeNode<int>>; template class LinkedList<BinaryTreeNode<string>>;
true
0b00dfc18657a52dc73e7614794c3448b4f9dcfe
C++
Techno-coder/UndertaleCPPLibrary
/revision_2/src/src/headers/resource/ResourceManager.h
UTF-8
1,529
2.890625
3
[]
no_license
#ifndef PROJECT_RESOURCEMANAGER_H #define PROJECT_RESOURCEMANAGER_H #include <map> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "ResourceItem.h" namespace ug { class ResourceManager { std::map<std::string, std::unique_ptr<sf::Texture>> texturesHolder; std::map<std::string, std::unique_ptr<sf::Font>> fontsHolder; std::map<std::string, std::unique_ptr<sf::SoundBuffer>> soundBuffersHolder; std::map<std::string, std::string> musicFilePathsHolder; public: /** * Load a resource from the ResourceItem * @param item The resource information */ void loadResource(const ResourceItem& item); /** * Get the file path of a music file * @param id The id of the music file * @return A string containing the file path */ const std::string& getMusicFilepath(std::string id); /** * Get a SFML texture * @param id The id of the texture * @return A SFML texture */ const sf::Texture& getTexture(std::string id); /** * Get a SFML sound buffer * @param id The id of the sound buffer * @return A SFML sound buffer */ const sf::SoundBuffer& getSound(std::string id); /** * Get a SFML font * @param id The id of the font * @return A SFML font */ const sf::Font& getFont(std::string id); }; } #endif //PROJECT_RESOURCEMANAGER_H
true
4905d31fab64a9316e5b93680b92e892c0c829c6
C++
LogicJake/code-for-interview
/leetcode-cn/C++/692.前k个高频单词.cpp
UTF-8
1,146
3.109375
3
[]
no_license
/* * @lc app=leetcode.cn id=692 lang=cpp * * [692] 前K个高频单词 */ // @lc code=start #include <algorithm> #include <queue> #include <string> #include <unordered_map> #include <vector> using namespace std; class Solution { public: using PIS = pair<int, string>; struct cmp { bool operator()(const PIS& p1, const PIS& p2) { if (p1.first == p2.first) return p1.second < p2.second; return p1.first > p2.first; } }; vector<string> topKFrequent(vector<string>& words, int k) { unordered_map<string, int> cnt; for (string word : words) { cnt[word] += 1; } priority_queue<PIS, vector<PIS>, cmp> pq; for (auto& [key, value] : cnt) { pq.push({ value, key }); if (pq.size() > k) { pq.pop(); } } vector<string> ans; while (!pq.empty()) { auto v = pq.top().second; ans.push_back(v); pq.pop(); } reverse(ans.begin(), ans.end()); return ans; } }; // @lc code=end
true
e6d1554e19334af7ef6f72b96ebd3b6d3bebf13b
C++
SCS2017/Leetcode-Solution
/二分查找/378_有序矩阵中第k小的元素.cpp
UTF-8
5,828
3.96875
4
[]
no_license
/* 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。 示例: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, 返回 13。 说明: 你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n^2 。 */ #include <bits/stdc++.h> using namespace std; //使用最大优先队列,遍历整个数组,得到最小的k个数,然后返回top元素即可 class Solution { public: int kthSmallest(vector<vector<int> >& matrix, int k) { priority_queue<int, vector<int> > pq; int m = matrix.size(); for(int i = 0; i < m; ++i){ for(int j = 0; j < m; ++j){ pq.push(matrix[i][j]); if(pq.size() > k) pq.pop(); // if(pq.size() < k) // pq.push(matrix[i][j]); // else{ // if(matrix[i][j] < pq.top()){ // pq.pop(); // pq.push(matrix[i][j]); // } // } } } return pq.top(); } }; /* 二分查找法来做,我们由于是有序矩阵,那么左上角的数字一定是最小的,而右下角的数字一定是最大的,所以这个是我们搜索的范围, 然后我们算出中间数字mid,由于矩阵中不同行之间的元素并不是严格有序的,所以我们要在每一行都查找一下 mid, 遍历完所有的行可以找出中间数是第几小的数,然后k比较,进行二分查找,left 和 right 最终会相等,并且会变成数组中第k小的数字 使用upper_bound函数,这个函数是查找第一个大于目标数的元素,如果目标数在比该行的尾元素大, 则返回该行元素的个数,如果目标数比该行首元素小,则返回0 举个例子来说吧,比如数组为: [1 2 12 100] k = 3 那么刚开始 left = 1, right = 100, mid = 50, 遍历完 cnt = 3,此时 right 更新为 50 此时 left = 1, right = 50, mid = 25, 遍历完之后 cnt = 3, 此时 right 更新为 25 此时 left = 1, right = 25, mid = 13, 遍历完之后 cnt = 3, 此时 right 更新为 13 此时 left = 1, right = 13, mid = 7, 遍历完之后 cnt = 2, 此时 left 更新为8 此时 left = 8, right = 13, mid = 10, 遍历完之后 cnt = 2, 此时 left 更新为 11 此时 left = 11, right = 12, mid = 11, 遍历完之后 cnt = 2, 此时 left 更新为 12 循环结束,left 和 right 均为 12,任意返回一个即可。 整体时间复杂度为 O(nlgn*lgX),其中X为最大值和最小值的差值 */ class Solution1 { public: int kthSmallest(vector<vector<int> >& matrix, int k) { int left = matrix[0][0], right = matrix.back().back(); while(left < right){ int mid = left + (right - left) / 2; int cnt = 0; for(int i = 0; i < matrix.size(); ++i) cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin(); if(cnt < k) left = mid + 1; else right = mid; } return left; } }; /* 进一步优化到 O(nlgX),其中X为最大值和最小值的差值, 注意到每列也是有序的,从数组的左下角i = m-1, j = 0开始查找,如果比目标值小,j就向右移一列, 和当前位置同列的上面所有的数字都小于目标值,那么 cnt += i+1,反之则向上移一位,这样我们也能算出 cnt 的值。 这里从右上角开始也是一样的,每次查找总能减少一列或者一行 */ class Solution2 { public: int kthSmallest(vector<vector<int> >& matrix, int k) { int left = matrix[0][0], right = matrix.back().back(); while(left < right){ int mid = left + (right - left) / 2; int cnt = help(matrix, mid); if(cnt < k) left = mid + 1; else right = mid; } return left; } //统计数组中小于target的个数 int help(vector<vector<int> >& matrix, int target){ int m = matrix.size(); int i = m-1, j = 0, res = 0; while(i >= 0 && j < m){ if(matrix[i][j] <= target){ res += i + 1; ++j; } else --i; } return res; } }; // 第k大的数 二分还是不对 // class Solution3 { // public: // int kthLargest(vector<vector<int> >& matrix, int k) { // int left = matrix[0][0], right = matrix.back().back(); // while(left < right){ // int mid = left + (right - left) / 2; // int cnt = help(matrix, mid); // if(cnt < k) // right = mid; // else // left = mid + 1; // } // return left; // } // //统计数组中大于target的个数 // int help(vector<vector<int> >& matrix, int target){ // int m = matrix.size(); // int i = m-1, j = 0, res = 0; // while(i >= 0 && j < m){ // if(matrix[i][j] >= target){ // res += m - j; // --i; // } // else // ++j; // } // return res; // } // }; int main(){ int n; cin >> n; vector<vector<int> > matrix(n, vector<int>(n)); for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j) cin >> matrix[i][j]; } int k; while(cin >> k){ // 其实第k大的数,不就是第n+1-k小的数 int res1 = Solution2().kthSmallest(matrix, n*n+1-k); // int res2 = Solution3().kthLargest(matrix, k); cout << res1 << endl; } return 0; }
true
180564d3921a2955b60cec54f9d7af52cf93e95f
C++
abcosmi/CG-trab3
/codigo/janela.cpp
UTF-8
1,545
2.921875
3
[]
no_license
#include <iostream> #include <string> #include "janela.h" #include "tinyxml2.h" using namespace tinyxml2; Janela::Janela(){ largura = 0; altura = 0; corR = 0; corG = 0; corB = 0; titulo = ""; } int Janela::getAltura(){ return altura; } int Janela::getLargura(){ return largura; } float Janela::getCorR(){ return corR; } float Janela::getCorG(){ return corG; } float Janela::getCorB(){ return corB; } std::string Janela::getTitulo(){ return titulo; } void Janela::setAltura(int a){ altura = a; } void Janela::setLargura(int l){ largura = l; } void Janela::setCorR(float c){ corR = c; } void Janela::setCorG(float c){ corG = c; } void Janela::setCorB(float c){ corB = c; } void Janela::setTitulo(std::string t){ titulo = t; } void Janela::leitura(std::string caminhoXML){ // Carregando arquivo xml: XMLDocument xmlConfig; xmlConfig.LoadFile(caminhoXML.c_str()); // Criando um elemento raiz (no caso, seria a tag aplicação): XMLNode *aplicacao = xmlConfig.FirstChild(); if (aplicacao == NULL){ std::cout << "Não foi possível ler o arquivo xml2" << std::endl; std::exit(1); } int raio = 0; float cx = 0,cy = 0; // Procurando pelos atribudos da janela: XMLElement* circulo = aplicacao->FirstChildElement("circle"); circulo->QueryIntAttribute("r",&raio); circulo->QueryFloatAttribute("cx",&cx); circulo->QueryFloatAttribute("cy",&cy); this->setLargura(raio+cx); this->setAltura(raio+cy); this->setCorR(1); this->setCorG(1); this->setCorB(1); }
true
853be3a3e7ae44e0dd4a9b09b99dd9ee5187f199
C++
jasonristeski/CPP
/LinkedList/DoublyLinkedNodeIterator.h
UTF-8
3,471
3.53125
4
[]
no_license
#pragma once #include <iostream> using namespace std; #include "DoubleLinkedNode.h" template<class DataType> class DoublyLinkedNodeIterator { private: enum IteratorStates {BEFORE,DATA,AFTER}; IteratorStates fState; typedef DoubleLinkedNode<DataType> Node; const Node* fLeftmost; const Node* fRightmost; const Node* fCurrent; public: typedef DoublyLinkedNodeIterator<DataType> Iterator; DoublyLinkedNodeIterator(const Node& aList) { // <BEFORE> < DATA > <AFTER> // NIL <-> n1 <-> n2 <-> n3 <-> .... nx <-> NIL ( x= last node) // fLeftmost,fCurrent = n1 // fRightmost = nx fLeftmost = &aList; while(&fLeftmost->getPrevious() != &Node::NIL) { fLeftmost = &fLeftmost->getPrevious(); } fCurrent = fLeftmost; // first element in list fRightmost = &aList; while(&fRightmost->getNext() != &Node::NIL) { fRightmost = &fRightmost->getNext(); } // fState // if Current != NIL fstate = data else AFTER fState = fCurrent != &Node::NIL ? DATA : AFTER; } const DataType& operator*() const { return fCurrent->getValue(); } Iterator& operator++() // prefix inc { switch(fState) { case BEFORE: { // fCurrent = start of list on foward iter. fCurrent = fLeftmost; if(fCurrent == &Node::NIL) { fState = AFTER; } else { fState = DATA; } break; } case DATA: { fCurrent = &fCurrent->getNext(); if(fCurrent == &Node::NIL) { fState = AFTER; } break; } } return *this; } Iterator operator++(int) // postfix inc { Iterator temp = *this; ++(*this); return temp; } Iterator& operator--() //prefix dec { switch(fState) { case DATA: { fCurrent = &fCurrent->getPrevious(); if(fCurrent == &Node::NIL) { fState = BEFORE; } break; } case AFTER: { fCurrent = fRightmost; // fcurrent = end of list on backwards iter. if(fCurrent == &Node::NIL) { fState = BEFORE; } else { fState = DATA; } break; } } return *this; } Iterator operator--(int) // postfix dec { Iterator temp = *this; --(*this); return temp; } bool operator == (const Iterator& aOtherIter) const { return ((fCurrent == aOtherIter.fCurrent) && (fLeftmost == aOtherIter.fLeftmost) && (fRightmost == aOtherIter.fRightmost) && (fState == aOtherIter.fState)); } bool operator != (const Iterator& aOtherIter) const { return !(*this == aOtherIter); } // end conditions for bi-directional iterator // <BEFORE> < DATA > <AFTER> // NIL <-> n1 <-> n2 <-> n3 <-> .... nx <-> NIL ( x= last node) Iterator leftEnd() const { Iterator lResult = *this; lResult.fCurrent = &fLeftmost->getPrevious(); lResult.fState = lResult.fCurrent != &Node::NIL ? DATA : BEFORE; return lResult; } Iterator first() const // foward iter fstate = after { Iterator lResult = *this; lResult.fCurrent = fLeftmost; lResult.fState = lResult.fCurrent != &Node::NIL ? DATA : AFTER; return lResult; } Iterator last() const // Backward iter fstate = before { Iterator lResult = *this; lResult.fCurrent = fRightmost; lResult.fState = lResult.fCurrent != &Node::NIL ? DATA : BEFORE; return lResult; } Iterator rightEnd() const { Iterator lResult = *this; lResult.fCurrent = &fRightmost->getNext(); lResult.fState = fCurrent != &Node::NIL ? DATA : AFTER; return lResult; } };
true
d813dc77ffa6225a28adca0887740134ab5b9f45
C++
youngslab/hooking-api
/hook/include/hook/hook.hpp
UTF-8
2,789
3.046875
3
[ "MIT" ]
permissive
#pragma once #include <dlfcn.h> #include <chrono> #include <cstring> #include <functional> #include <sstream> #include <string> #include <tuple> #define _str(a) #a #define xstr(a) _str(a) // helper interface function-like macro /** * @brief Load the original function */ #define hook_load(x) hook::load<typeof(x) *>(xstr(x)) /** * @brief Formatting a function with its argmuemnts. */ #define hook_format(f, ...) hook::format(xstr(f), ##__VA_ARGS__) /** * @brief Invoke a function with its argument. It just wrap this std function * for its consistent interface */ #define hook_invoke(...) std::invoke(__VA_ARGS__) /** * @brief Invoke a function and return its result with the time how much it * takes. */ #define hook_invoke_d(...) hook::invoke_d(__VA_ARGS__) namespace hook { template <typename Func> inline auto load(std::string const &x) -> Func { auto ptr = dlsym(RTLD_NEXT, x.data()); if (!ptr) { throw std::runtime_error(x + " is not found."); } return reinterpret_cast<Func>(ptr); } namespace detail { template <typename Stream, typename... Args> auto format(Stream &stream, std::string const &func, Args... args) { constexpr auto sep = ", "; stream << func << "("; ((stream << args << sep), ...); if (sizeof...(args) > 0) { stream.seekp(-strlen(sep), std::ios_base::end); } stream << ")"; } } // namespace detail template <typename Func, typename... Args> struct has_result { constexpr static bool value = !std::is_same_v<std::invoke_result_t<Func, Args...>, void>; }; template <typename Func, typename... Args> constexpr static bool has_result_v = has_result<Func, Args...>::value; template <typename... Args> auto format(std::string const &func, Args &&... args) -> std::string { std::stringstream ss; detail::format(ss, func, std::forward<Args>(args)...); return ss.str(); } template <typename Func, typename... Args, typename Enabled = std::enable_if_t<has_result_v<Func, Args...>>> auto invoke_d(Func const &f, Args &&... args) -> std::pair<decltype(f(args...)), std::chrono::nanoseconds> { auto start = std::chrono::high_resolution_clock::now(); auto res = std::invoke(f, std::forward<Args>(args)...); auto dur = std::chrono::high_resolution_clock::now() - start; return {res, std::chrono::duration_cast<std::chrono::nanoseconds>(dur)}; } template <typename Func, typename... Args, typename Enabled = std::enable_if_t<!has_result_v<Func, Args...>>> auto invoke_d(Func const &f, Args &&... args) -> std::chrono::nanoseconds { auto start = std::chrono::high_resolution_clock::now(); std::invoke(f, std::forward<Args>(args)...); auto dur = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::nanoseconds>(dur); } } // namesapce hook
true
b410212a0f3be169674d0579b354cdd38aafd9a6
C++
zhangchuhu/serviceframe
/service/imlib/SearchBuddyRecordOpHelper.cpp
GB18030
1,739
2.59375
3
[]
no_license
#include "./SearchBuddyRecordOpHelper.h" #include "core/sox/logger.h" using namespace server::imlist; using namespace mysqlpp; //¼ void SearchBuddyRecordOpHelper::insertRecord(SearchBuddyRecordDataSet &data) { Query query = m_conn->query(); query << "insert into search_buddy_record(uid, search_uid, time) values(%0, %1, now())"; query.parse(); log(Info, "%s", query.preview(data.uid,data.search_uid).data()); ResNSel res = query.execute(data.uid, data.search_uid); if (!res.success) { log(Error,"insert into search_buddy_record error!"); throw mysqlpp::BadQuery("SQL operation error!"); } } //ɾ¼ void SearchBuddyRecordOpHelper::deleteRecord(const time_t t) { Query query = m_conn->query(); query << "delete from search_buddy_record where UNIX_TIMESTAMP(time) < UNIX_TIMESTAMP()-%0"; query.parse(); log(Info, "%s", query.preview(static_cast<const uint32_t>(t)).data()); ResNSel res = query.execute(static_cast<const uint32_t>(t)); if (!res.success) { log(Error,"delete search_buddy_record error!"); throw mysqlpp::BadQuery("SQL operation error!"); } } //ȡijûijʱӺѵĴ uint32_t SearchBuddyRecordOpHelper::getCount(const uint32_t uid, const time_t t) { Query query = m_conn->query(); query << "select count(*) from search_buddy_record where uid = %0 and UNIX_TIMESTAMP(time) >=UNIX_TIMESTAMP()-%1"; query.parse(); log(Info, "%s", query.preview(uid, static_cast<const uint32_t>(t)).data()); Result res = query.store(uid, static_cast<const uint32_t>(t)); uint32_t result = SEARCH_BUDDY_MAX_COUNT; if (res) { result = (uint32_t)(res.at(0).at(0)); } return result; }
true
fd0a976472bcf4feac91f0d18d7e5c41250c9168
C++
anc95/leetcode
/18. 4Sum/solution.h
UTF-8
1,403
3.15625
3
[]
no_license
#include <vector> #include <string> using namespace std; class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int size = nums.size(); int startPoint, endPoint; vector<vector<int>> result = {}; for (int i = 0; i < size - 3;) { for (int j = i + 1; j < size - 2;) { int newTarget = target - nums[i] - nums[j]; int nowSum; startPoint = j + 1; endPoint = size - 1; while (startPoint < endPoint) { nowSum = nums[startPoint] + nums[endPoint]; if (nowSum < newTarget) { startPoint++; } else if (nowSum > newTarget) { endPoint--; } else { result.push_back({nums[i], nums[j], nums[startPoint], nums[endPoint]}); while(nums[startPoint] == nums[++startPoint] && startPoint < endPoint); while(nums[endPoint] == nums[--endPoint] && startPoint < endPoint); } } while(nums[j] == nums[++j] && j < size - 2); } while(nums[i] == nums[++i] && i < size - 3); } return result; } };
true
a0f94b182224528f2243ee6ead236b3330af4615
C++
janmlam/TDT4102
/oving10/oving10/Shape.h
UTF-8
160
2.578125
3
[]
no_license
#pragma once #include "Image.h" class Shape { private: Color color; public: Shape(Color color); Color getColor(); virtual void draw(Image &img)=0; };
true
b5ae35ade3d0b0e46524b17a452a3e8f90eb0a4d
C++
charles-pku-2013/CodeRes_Cpp
/Cpp11/Thread/call_once_singleton.cpp
UTF-8
899
3.625
4
[]
no_license
#include <iostream> #include <thread> #include <memory> class Foo { public: using pointer = std::shared_ptr<Foo>; static pointer GetInstance() { std::cout << "Foo::GetInstance()" << std::endl; std::call_once(flag_, []{ pInst_.reset(new Foo); }); return pInst_; } ~Foo() { std::cout << "Foo denstruct" << std::endl; } void Greet() const { std::cout << "Hello foo" << std::endl; } private: static pointer pInst_; static std::once_flag flag_; Foo() { std::cout << "Foo construct" << std::endl; } Foo(const Foo&) = delete; Foo& operator=(const Foo&) = delete; }; Foo::pointer Foo::pInst_; std::once_flag Foo::flag_; int main() { for (int i = 0; i < 10; ++i) { auto inst = Foo::GetInstance(); inst->Greet(); } std::cout << "Test terminating..." << std::endl; return 0; }
true
7cabd90662bbab5813c1fd6296b14a14db3bc90b
C++
naordahan/Task8
/Board.h
UTF-8
1,082
3.015625
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <exception> #include <math.h> #include "Spot.h" #include "IllegalCoordinateException.h" #include "IllegalCharException.h" using namespace std; struct RGB { uint8_t red, green, blue; public: RGB() {} RGB(uint8_t red, uint8_t green, uint8_t blue): red(red), green(green), blue(blue) {} }; class Board{ public: Spot **b; uint length; uint size()const{return length;} Board(); Board(uint length); Board(const Board& b2); Spot& operator[](Coordinate p2)const; Board& operator=(char in); Board& operator=(const Board& b2); bool operator==(const Board &b2) const; string draw (int Pixels); friend ostream& operator<< (ostream& os, const Board& b);//output friend istream& operator>> (istream& input, Board& b);//input void Dcircle(RGB* imge,int Xfrom,int Xto,int Yfrom,int Yto,int dimy); //draws a circle void Dex(RGB* imge,int Xfrom,int Xto,int Yfrom,int Yto,int dimy); // draws an aixs ~Board(); };
true
84756f429a72f8ac4745f5138cc4818d5b18f9ee
C++
JulioNV/CDD-PongGame-Linux-Client-Server
/Clases.h
UTF-8
5,255
3.234375
3
[]
no_license
#ifndef CLASES_H_INCLUDED #define CLASES_H_INCLUDED #include "linuxLibGame.h" int golesA=0, golesB=0; //Declaro las variables globales para indicar los goles recibidos por cada jugador class Jugador { private: int x,y,GolesRecibidos=0; //Coordenadas que tendra el jugador; public: Jugador(int _x, int _y); //Constructor void Pintar(); //Esta funcion pintara una barra que representara al jugador. Utilizara 6 posiciones de caracteres void Borrar(); void set_y(int _x); int get_x(); int get_y(); }; Jugador::Jugador(int _x, int _y) { x = _x; y = _y; } int Jugador::get_x() //Obtiene la coordenada X actual del jugador { return x; } int Jugador::get_y() //Obtiene la coordenada Y actual del jugador { return y; } void Jugador::set_y(int _y) //Cambia el valor de la coordenada del jugador { y+=_y; } void Jugador::Pintar() { gotoxy(x, y-2); printf("%c",219); gotoxy(x, y-1); printf("%c",219); //219 en el codigo ASCII es una barrita que representara al jugador gotoxy(x, y); printf("%c",219); gotoxy(x, y+1); printf("%c",219); gotoxy(x, y+2); printf("%c",219); gotoxy(x, y+3); printf("%c",219); } void Jugador::Borrar() { gotoxy(x, y-2); printf(" "); gotoxy(x, y-1); printf(" "); gotoxy(x, y); printf(" "); gotoxy(x, y+1); printf(" "); gotoxy(x, y+2); printf(" "); gotoxy(x, y+3); printf(" "); } class Pelota { public: int x,y; int dx,dy; public: Pelota(int _x, int _y, int _dx, int _dy); void Pintar(); void Borrar(); void Mover(Jugador A, Jugador B); void Gol(int _x, int _y); void ImprimeMarcador(int a, int b); int get_dx(); int get_dy(); void restaxy(); }; int Pelota::get_dx() { return dx; } int Pelota::get_dy() { return dy; } void Pelota::restaxy() { Borrar(); if(dx>0 && dy>0) { x=x-1; y=y-1; } if(dx<0 && dy<0) { x=x+1; y=y+1; } if(dx>0 && dy<0) { x=x-1; y=y+1; } if(dx<0 && dy>0) { x=x+1; y=y-1; } Pintar(); } Pelota::Pelota(int _x, int _y, int _dx, int _dy) { x=_x; y=_y; dx=_dx; dy=_dy; } void Pelota::Pintar() { gotoxy(x,y); printf("%c",254); } void Pelota::Borrar() { gotoxy(x,y); printf(" "); } void Pelota::ImprimeMarcador(int a, int b) { gotoxy(0,0); printf("Jugador 1: %d",b); printf("\t\t\t"); printf("Jugador 2: %d",a); printf("\n"); } void Pelota::Mover(Jugador A, Jugador B) { Borrar(); x+= dx; y+= dy; Pintar(); if(x+dx == 3) //En caso de colisionar con el borde izquierdo { Borrar(); Gol(38,14); //Significa que hubo un gol, por lo que vuelve al principio golesB++; dx=-dx; //Cambiar el sentido de la pelota hacia el que hizo el punto } if(x+dx==81) //En caso de colisionar con el borde izquierdo { Borrar(); Gol(38,14); //Significa que hubo un gol, por lo que vuelve al principio golesA++; dx=-dx; //Cambiar el sentido de la pelota hacia el que hizo el punto } ImprimeMarcador(golesB, golesA); if(y+dy == 3 || y+dy==27) //En caso de colisionar con los bordes en el eje x dy=-dy; //cambiar el sentido de la pelota if(x+dx == A.get_x() && y>=A.get_y()-2 && y<=A.get_y()+3) dx=-dx; if(x+dx == B.get_x() && y>=B.get_y()-2 && y<=B.get_y()+3) dx=-dx; } void Pelota::Gol(int _x, int _y) { x=_x; y=_y; } class Menu { public: void ImprimePortada(int &a); }; void Menu::ImprimePortada(int &a) { char portada[18][71] = { " ", " aaaass ", " aa aas PROYECTO FINAL DE SEMESTRE ", " aaaass aaa aa aa aaaas Integrantes: ", " aa ss ss aas aa aa -Marcelo Araya ", " aa ss ss aa a aa aa aa -Francisco Ibacache ", " aa aaa aa aas aaaasa -Julio Nain ", " ", " ", " aaaas aaaas aaaas ", " aa aa ss aa ss ", " aa aa ss aa ss Esperando Conexion... ", " aa aa ss aa ss ", " aa aa ss aa ss ", " aaass aaaas aaaas ", " ", }; for(int i=0; i <16; i++) { for(int j=0; j<70; j++) { gotoxy(j+5,i+5); printf("%c", portada[i][j]); } } //Acá hay que invocar el socket en algun momento de la vidita :( } #endif // CLASES_H_INCLUDED
true
b8a97393079a4733e6e67b1984c9432e7ce5fcf8
C++
tadejpetric/vegova
/presentation/smart_pointers.cpp
UTF-8
187
2.5625
3
[]
no_license
#include <memory> int main() { std::unique_ptr<int> a = std::make_unique<int>(3); { auto p = std::make_unique<int>(5); } // p pobriše za sabo } // a pobriše za sabo
true
62897f6de3b07af7b2c3a84062c0f3b9fd45baff
C++
KentaroJay/BasicCG
/6/kadai06_sample.cpp
SHIFT_JIS
7,184
3.5625
4
[]
no_license
#include <cstdlib> #include <cmath> #include <vector> #include <GLUT/glut.h> // 2xNg߂̃NX class Vector2d { public: double x, y; Vector2d() { x = y = 0; } Vector2d(double _x, double _y) { x = _x; y = _y; } void set(double _x, double _y) { x = _x; y = _y; } // 1ɐK void normalize() { double len = length(); x /= len; y /= len; } // Ԃ double length() { return sqrt(x * x + y * y); } // s{ void scale(const double s) { x *= s; y *= s; } // Z̒` Vector2d operator+(Vector2d v) { return Vector2d(x + v.x, y + v.y); } // Z̒` Vector2d operator-(Vector2d v) { return Vector2d(x - v.x, y - v.y); } // ς̒` double operator*(Vector2d v) { return x * v.x + y * v.y; } // Z̒` Vector2d &operator=(const Vector2d &v) { x = v.x; y = v.y; return (*this); } // Z̒` Vector2d &operator+=(const Vector2d &v) { x += v.x; y += v.y; return (*this); } // Z̒` Vector2d &operator-=(const Vector2d &v) { x -= v.x; y -= v.y; return (*this); } // lo͂ void print() { printf("Vector2d(%f %f)\n", x, y); } }; // }CiX̕̕txNg悤ɂ邽߂̒` Fb=(-a); ̂悤ɋLqł Vector2d operator-(const Vector2d &v) { return (Vector2d(-v.x, -v.y)); } // xNgƎ̐ς悤ɂ邽߂̒` F c=5*a+2*b; c=b*3; ̂悤ɋLqł Vector2d operator*(const double &k, const Vector2d &v) { return (Vector2d(k * v.x, k * v.y)); } Vector2d operator*(const Vector2d &v, const double &k) { return (Vector2d(v.x * k, v.y * k)); } // xNgŊ鑀悤ɂ邽߂̒` F c=a/2.3; ̂悤ɋLqł Vector2d operator/(const Vector2d &v, const double &k) { return (Vector2d(v.x / k, v.y / k)); } // ================================================================================================ std::vector<Vector2d> g_ControlPoints; // _i[ // mbgxNg̗vf iQlɂ킹āAvf10ƂĂj const int NUM_NOT = 10; // mbgxNg // ̔z̒lύX邱ƂŊ֐ωB̌ʂƂČ`ςB // ̗ł́AԊuŒlω̂ŁAulBXvCȐvƂȂ double g_NotVector[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // ֐ N{i,n}(t)̒lvZ double getBaseN(int i, int n, double t) { if (n == 0) { // n 0 ̎ t ̒lɉ 0 ܂ 1 Ԃ if (t >= g_NotVector[i] && t < g_NotVector[i + 1]) { return 1.0; } return 0; } else { // ɕKvȃvOR[hLq // ċAig̊֐ getBaseN ĂԏKvj // WvZƂɁAmbgdȂiꂪ[ƂȂjƂɂ́A̍𖳎B double temp1, temp2; if ((g_NotVector[i + n] - g_NotVector[i]) != 0) { temp1 = ((t - g_NotVector[i]) / (g_NotVector[i + n] - g_NotVector[i])); } else { temp1 = 0; } if ((g_NotVector[i + n + 1] - g_NotVector[i + 1]) != 0) { temp2 = ((g_NotVector[i + n + 1] - t) / (g_NotVector[i + n + 1] - g_NotVector[i + 1])); } else { temp2 = 0; } return temp1 * getBaseN(i, n - 1, t) + temp2 * getBaseN(i + 1, n - 1, t); } } // \̊֐ŋL void display(void) { glClearColor(1.0, 1.0, 1.0, 1.0); // Fw glClear(GL_COLOR_BUFFER_BIT); // ʏ // _̕` glPointSize(5); glColor3d(0.0, 0.0, 0.0); glBegin(GL_POINTS); for (unsigned int i = 0; i < g_ControlPoints.size(); i++) { glVertex2d(g_ControlPoints[i].x, g_ControlPoints[i].y); } glEnd(); // _Ԑ̕` glColor3d(1.0, 0.0, 0.0); glLineWidth(1); glBegin(GL_LINE_STRIP); for (unsigned int i = 0; i < g_ControlPoints.size(); i++) { glVertex2d(g_ControlPoints[i].x, g_ControlPoints[i].y); } glEnd(); // BXvCȐ`悷vOR[h // qg1: 3BXvC̏ꍇ͐_4“܂ł͉`Ȃ // qg2: p[^t̒l̎蓾͈͂ɒ glColor3d(1.0, 0.0, 0.0); glLineWidth(1); glBegin(GL_LINE_STRIP); for (unsigned int t = 4; t <= g_ControlPoints.size(); t += 1) { double px = 0, py = 0; for (unsigned int i = 0; i <= 3 + g_ControlPoints.size() - 1; i++) { px += getBaseN(i, 3, t) * g_ControlPoints[i].x; py += getBaseN(i, 3, t) * g_ControlPoints[i].y; } glVertex2d(px, py); } glEnd(); glutSwapBuffers(); } void resizeWindow(int w, int h) { h = (h == 0) ? 1 : h; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // EBhE̍Wnݒ // }EXNbN̍Wƕ`Wv悤Ȑe glOrtho(0, w, h, 0, -10, 10); glMatrixMode(GL_MODELVIEW); } // L[{[hCxg void keyboard(unsigned char key, int x, int y) { switch (key) { case 'q': case 'Q': case '\033': exit(0); /* '\033' ESC ASCII R[h */ default: break; } glutPostRedisplay(); } // }EXCxg void mouse(int button, int state, int x, int y) { if (state == GLUT_DOWN) { switch (button) { case GLUT_LEFT_BUTTON: // NbNʒuɐ_lj // mbg𑝂₹΂ł_ljł邪ANUM_NOT̒lŌŒ肳Ă̂ // łljł킯ł͂Ȃ if (g_ControlPoints.size() < NUM_NOT - 4) { g_ControlPoints.push_back(Vector2d(x, y)); } break; case GLUT_MIDDLE_BUTTON: break; case GLUT_RIGHT_BUTTON: // ̐_̍폜 if (!g_ControlPoints.empty()) { g_ControlPoints.pop_back(); } break; default: break; } glutPostRedisplay(); // ĕ` } } // CvO int main(int argc, char *argv[]) { glutInit(&argc, argv); // Cȕ glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); // `惂[h̎w glutInitWindowSize(800, 800); // EBhETCYw glutCreateWindow(argv[0]); // EBhE쐬 glutDisplayFunc(display); // \֐w glutReshapeFunc(resizeWindow); // EBhETCYύXꂽƂ̊֐w glutKeyboardFunc(keyboard); // L[{[hCxg֐w glutMouseFunc(mouse); // }EXCxg֐w glutMainLoop(); // Cxg҂ return 0; }
true
3e9319b7ec71a7c2459ba8f1e4fa75e147130439
C++
Raks110/Fearless-Knights
/shooter_structs.h
UTF-8
4,355
2.71875
3
[ "BSD-2-Clause" ]
permissive
#ifndef SHOOTER_STRUCTS_H #define SHOOTER_STRUCTS_H #include "shooter_utils.h" #include <algorithm> #include <chrono> #include <random> #include <vector> #include <string.h> #include <ncurses.h> #include <iostream> using namespace std; typedef struct coordinates{ int x; int y; }coordinates; namespace dialogues{ typedef struct scoreDict{ const char *name; long long int score; }scoresReg; vector<string> speaks; vector<scoresReg> highScores; int secondsLeft = 7; int i; int currentDialogue; char base[80]; bool operator==(const scoresReg &lhs, const scoresReg &rhs){ return lhs.name == rhs.name && lhs.score == rhs.score; } void initializeSpeaks(){ speaks.push_back("HAHA. How will you escape the Wrath of Khan?"); speaks.push_back("We monsters are always hungry!"); speaks.push_back("Bullets filled with destruction will devour you!"); speaks.push_back("HAHAHAHAHAHAHAHAHAHAHAHAHAHA!!"); speaks.push_back("Mojo Jojo was my disciple! I trained him myself!"); speaks.push_back("I won't waste your time trash talking, but I will certainly take my time and trash you!"); speaks.push_back("LOL. Look at your sweet ass tryna escape me."); speaks.push_back("Ever heard of oblivion? Well, you'll soon be there."); for(int j=0;j<40;j++){ base[2*j] = '/'; base[(2*j) + 1] = '\\'; } } void displaySpeaks(int rowDisplay, bool SHOULD_CHANGE){ if(speaks.size() == 0){ initializeSpeaks(); unsigned seed = chrono::system_clock::now().time_since_epoch().count(); shuffle(speaks.begin(), speaks.end(), default_random_engine(seed)); } if(SHOULD_CHANGE){ const char *temp = speaks[i].c_str(); currentDialogue = i; init_pair(7,COLOR_RED,COLOR_BLACK); attron(A_DIM); mvprintw(rowDisplay,1,base); mvprintw(rowDisplay + 1,1,"<"); mvprintw(rowDisplay + 1,80,">"); mvprintw(rowDisplay + 2,1,"<"); mvprintw(rowDisplay + 2,80,">"); mvprintw(rowDisplay + 3,1,"<"); mvprintw(rowDisplay + 3,80,">"); mvprintw(rowDisplay + 4,1,base); attroff(A_DIM); attron(A_BOLD); mvprintw(rowDisplay+2,(80-strlen(temp))/2,temp); attron(A_BOLD); i++; if(i == speaks.size()){ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(speaks.begin(), speaks.end(), std::default_random_engine(seed)); i = 0; } } else{ const char *temp = speaks[currentDialogue].c_str(); attron(A_DIM); mvprintw(rowDisplay,1,base); mvprintw(rowDisplay + 1,1,"|"); mvprintw(rowDisplay + 1,80,"|"); mvprintw(rowDisplay + 2,1,"|"); mvprintw(rowDisplay + 2,80,"|"); mvprintw(rowDisplay + 3,1,"|"); mvprintw(rowDisplay + 3,80,"|"); mvprintw(rowDisplay + 4,1,base); attroff(A_DIM); attron(A_BOLD); mvprintw(rowDisplay+2,(80-strlen(temp))/2,temp); attron(A_BOLD); } } bool forSortHighScores(scoresReg a, scoresReg b){ return a.score > b.score; } void getHighScore(int rowLine, int score, const char *name){ int a=6; int r,c; getmaxyx(stdscr,r,c); scoresReg temp = {name,score}; highScores.push_back(temp); sort(highScores.begin(),highScores.end(),forSortHighScores); for(a=0;a<highScores.size();a++){ if(highScores[a] == temp){ break; } } if(highScores.size() > 5){ highScores.erase(highScores.begin() + 5); } for(int b=0;b<highScores.size();b++){ if(b==5){ break; } if(b==a){ attron(A_BOLD); mvprintw(rowLine + b,(c-11)/2,"%d",b+1); printw(". "); attron(A_UNDERLINE); printw(highScores[b].name); attroff(A_UNDERLINE); printw(" "); printw("%d",highScores[b].score); attroff(A_BOLD); } else{ attron(A_DIM); mvprintw(rowLine + b,(c-11)/2,"%d",b+1); printw(". "); printw(highScores[b].name); printw(" "); printw("%d",highScores[b].score); attroff(A_DIM); } } } } #endif
true
af623bf355ca0607a2306bc6d163004ca5996a4c
C++
Suckzoo/CS311
/project2/cs311.cpp
UTF-8
4,534
2.6875
3
[]
no_license
/***************************************************************/ /* */ /* MIPS-32 Instruction Level Simulator */ /* */ /* CS311 KAIST */ /* cs311.c */ /* */ /***************************************************************/ #include "util.h" #include "parse.h" #include "run.h" /**************************************************************/ /* */ /* Procedure : load_program */ /* */ /* Purpose : Load program and service routines into mem. */ /* */ /**************************************************************/ void load_program(char *program_filename) { FILE *prog; int ii = 0; char buffer[33]; /* To notifying data & text segment size */ int flag = 0; int text_index = 0; int data_index = 0; /* Open program file. */ prog = fopen(program_filename, "r"); if (prog == NULL) { printf("Error: Can't open program file %s\n", program_filename); exit(-1); } //read 32bits + '\0' = 33 while (fgets(buffer,33,prog) != NULL) { if(flag == 0) { //check text segment size text_size = fromBinary(buffer); NUM_INST = text_size/4; //initial memory allocation of text segment INST_INFO = (instruction*)malloc(sizeof(instruction)*(text_size/4)); init_inst_info(); } else if(flag == 1) { //check data segment size data_size = fromBinary(buffer); } else{ if(ii < text_size) INST_INFO[text_index++] = parsing_instr(buffer, ii); else if(ii < text_size + data_size) parsing_data(buffer, ii-text_size); else{ //Do not enter this case //assert(0); //However, there is a newline in the input file } ii += 4; } flag++; } CURRENT_STATE.PC = MEM_TEXT_START; } /************************************************************/ /* */ /* Procedure : initialize */ /* */ /* Purpose : Load machine language program */ /* and set up initial state of the machine. */ /* */ /************************************************************/ void initialize(char *program_filename) { int i; init_memory(); load_program(program_filename); RUN_BIT = TRUE; } /***************************************************************/ /* */ /* Procedure : main */ /* */ /***************************************************************/ int main(int argc, char *argv[]) { char** tokens; int count = 1; int addr1 = 0; int addr2 = 0; int num_inst = 0; /* Default option: run 100 cycle */ int i = 100; /* Flags for option */ int mem_dump_set = 0; int debug_set = 0; int num_inst_set = 0; /* Error Checking */ if (argc < 2) { printf("Error: usage: %s [-m addr1:addr2] [-d] [-n num_instr] inputBinary\n", argv[0]); exit(1); } initialize(argv[argc-1]); /* Main argument parsing */ while(count != argc-1) { if(strcmp(argv[count], "-m") == 0) { tokens = str_split(argv[++count],':'); addr1 = (int)strtol(*(tokens), NULL, 16); addr2 = (int)strtol(*(tokens+1), NULL, 16); mem_dump_set = 1; } else if(strcmp(argv[count], "-d") == 0) debug_set = 1; else if(strcmp(argv[count], "-n") == 0) { num_inst = (int)strtol(argv[++count], NULL, 10); num_inst_set = 1; } else { printf("Error: usage: %s [-m addr1:addr2] [-d] [-n num_instr] inputBinary\n", argv[0]); exit(1); } count++; } /* Execute */ if(num_inst_set) i = num_inst; if(debug_set) { printf("Simulating for %d cycles...\n\n", i); for(; i > 0; i--) { if(RUN_BIT == FALSE) { printf("Simulator halted\n\n"); break; } cycle(); rdump(); if(mem_dump_set) mdump(addr1, addr2); } } else{ run(i); rdump(); if(mem_dump_set) mdump(addr1, addr2); } return 0; }
true
892ae7cae6b82a9d7205b11e0b9dd479e6c4cf1f
C++
antonioguerrerocarrillo/1DESARROLLO-DE-APLICACIONES-MULTIPLATAFORMA
/1DAM/programacion en c++/ejercicios y practicas/UD2/cuadrado_perfecto.cpp
UTF-8
396
3.515625
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main () { int numero = 0, i = 0; cout << "introduce el numero para saber si el cuadrado es perfecto " << endl; cin >> numero; for (i = 0; i <= numero; i++) { numero = i * i; if ((pow(numero, 2)) == numero) { cout << "es un cuadrado perfecto " << endl; } else cout << " no es un cuadrado perfecto " << endl; } }
true
5404881d5cd144fb5ef22f8a01efb654845c2336
C++
JanKolomaznik/MedV4D
/MedV4D/src/remoteComp/remoteNodesManager.h
UTF-8
2,639
2.578125
3
[]
no_license
/** * @defgroup cellbe Remote computing */ /** * @ingroup cellbe * @author Vaclav Klecanda * @file remoteNodesManager.h */ /** * @addtogroup cellbe * @{ * * Library used to send some parts of pipeline to remote mashines to be executed * and result sent back. This library is not bound to specific architecture. * It was one of primary request to be platform indemendet. **/ #ifndef CELLCLIENT_HPP #define CELLCLIENT_HPP #include <fstream> #include <string> namespace M4D { namespace RemoteComputing { /** * This class represent the gate to remote computing. Parts of computed pipeline can be send to a server to computed remotely. Then the results are sent back. There can be variety of server and architectures. Primarily this is done for Cell Broadbend Engine (CBE). We have some Play Stations 3 where is CBE with 8 SPE stream processors. But it can be ported to some other supercomputing server like Blade, or some normal servers based on desktop processors. * Main idea is in creation entity called job that represents remote computation. Job is send to server, there is build his instance and stored in job container for later rerun. Then aproprite part of pipeline is created and run. The results are sent back to client. The client lives on ther server until explicit termination message is recieved. Job can be rerun with different settings (through RERUN message, entire data is not resent, instead only changes are sent). Each filter has its own ID through that is identified on the server. * Next item is filter settings vector. It is pair of filterID and filter parameters. Based on filter IDs is created pipeline on server side. * The last item is pointer to dataSet. It is pointer to abstract base class that each dataSet is derived from. Through virtual functions this dataSet can serialize and reSerialize and write its parameters. * Each job on client side is created throuh this class by CreateJob function. * This class also contains container of available servers that can be used for remote computing. It can also load it from config file. */ class RemoteNodesManager { public: RemoteNodesManager(); /** * Returns string reference containing address of least loaded available * server able doing specified job. Here can be implemented some load balancing functionality. */ const std::string & FindAvailableServer(void); private: typedef std::map<uint16, std::string> AvailServersMap; AvailServersMap m_servers; // loading from file support void FindNonCommentLine( std::ifstream &f, std::string &line); }; } // CellBE namespace } // M4D namespace #endif /** @} */
true
673b955cbd49fe59ca315a25c1bf8ebc742ce425
C++
SpiNNakerManchester/Visualiser
/spynnaker_external_device_lib/Threadable.h
UTF-8
1,229
2.640625
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2015 The University of Manchester * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <pthread.h> #ifndef _THREADABLE_H_ #define _THREADABLE_H_ class Threadable { public: Threadable() {} virtual ~Threadable() {} bool start(){ return (pthread_create(&_thread, NULL, _run, this) == 0); } void join() { (void) pthread_join(_thread, NULL); } protected: //Implement this method in your subclass with the code you want your // thread to run virtual void run() = 0; private: static void *_run(void * This) { ((Threadable *)This)->run(); return NULL; } pthread_t _thread; }; #endif /* _THREADABLE_H_ */
true
c78c92d305c9b0ebc4cd27dc10c37a910d8e8874
C++
alemoke/RoomHub
/src/config/ConfigurationWebServer.cpp
UTF-8
3,872
2.515625
3
[ "MIT" ]
permissive
#include "config/ConfigurationWebServer.hpp" #if defined(USE_WIFI) #include <WebServer.h> #elif defined(USE_ETHERNET) #include "httpserver/HttpServer.hpp" #endif #include "SPIFFS.h" #include "config/MasterConfig.hpp" ConfigurationWebServer::ConfigurationWebServer(ConfigurationStorage& _storage): storage(_storage) { } void ConfigurationWebServer::startConfigServer() { #if defined(USE_WIFI) startWiFiConfigServer(); #elif defined(USE_ETHERNET) startEthernetConfigServer(); #endif } #if defined(USE_WIFI) void ConfigurationWebServer::startWiFiConfigServer() { WebServer server(80); server.on("/config/reset", HTTP_POST, [&server, this]() { storage.resetConfig(); server.send(201, "text/plain", "Configuration deleted"); }); server.on("/config/name", HTTP_POST, [&server, this]() { String body = server.arg("plain"); storage.storeName(body.c_str()); server.send(201, "text/plain", body.c_str()); }); server.on("/config/mqtt", HTTP_POST, [&server, this]() { String body = server.arg("plain"); storage.storeMqttHostname(body.c_str()); server.send(201, "text/plain", body.c_str()); }); server.on("/config/device", HTTP_POST, [&server, this]() { String body = server.arg("plain"); if (!body.startsWith(SUPPORTED_DEVICE_FORMAT_VERSION)) { server.send(400, "text/plain", "Unsupported device format version"); } storage.storeDeviceConfig(body.c_str()); server.send(201, "text/plain", body.c_str()); }); server.on("/config/ethernet", HTTP_POST, [&server, this]() { String body = server.arg("plain"); storage.storeEthernetConfig(body.c_str()); server.send(201, "text/plain", body.c_str()); }); server.on("/config/finalize", HTTP_POST, [&server, this]() { configurationFinished = true; server.send(201, "text/plain", "Configuration finalized"); }); server.begin(); while(!configurationFinished) { server.handleClient(); } } #elif defined(USE_ETHERNET) void ConfigurationWebServer::startEthernetConfigServer() { Serial.println("Starting Ethernet server..."); EthernetServer server(80); server.begin(); HttpServer httpServer; httpServer.on(HttpMethod::POST, "/config/reset", [&httpServer, this](const String& body) { storage.resetConfig(); httpServer.send(201, "text/plain", "Configuration deleted"); }); httpServer.on(HttpMethod::POST, "/config/name", [&httpServer, this](const String& body) { storage.storeName(body.c_str()); httpServer.send(201, "text/plain", body.c_str()); }); httpServer.on(HttpMethod::POST, "/config/mqtt", [&httpServer, this](const String& body) { storage.storeMqttHostname(body.c_str()); httpServer.send(201, "text/plain", body.c_str()); }); httpServer.on(HttpMethod::POST, "/config/device", [&httpServer, this](const String& body) { if (!body.startsWith(SUPPORTED_DEVICE_FORMAT_VERSION)) { httpServer.send(400, "text/plain", "Unsupported device format version"); } storage.storeDeviceConfig(body.c_str()); httpServer.send(201, "text/plain", body.c_str()); }); httpServer.on(HttpMethod::POST, "/config/ethernet", [&httpServer, this](const String& body) { storage.storeEthernetConfig(body.c_str()); httpServer.send(201, "text/plain", body.c_str()); }); httpServer.on(HttpMethod::POST, "/config/finalize", [&httpServer, this](const String& body) { configurationFinished = true; httpServer.send(201, "text/plain", "Configuration finalized"); }); while (!configurationFinished) { EthernetClient client = server.available(); httpServer.handleClient(client); } } #endif
true
7804df0e8f90decc966897eb7452726339e19f6d
C++
jatrindo/learncpp
/13.9_overloading_the_subscript_operator/quiz/q1/program.cpp
UTF-8
2,759
4.34375
4
[]
no_license
/* * A map is a class that stores elements as a key-value pair. The key must be * unique, and is used to access the associated pair. * * In this quiz, we're going to write an application that lets us assign grades * to students by name, using a simple map class. The student's name will be the * key, and the grade (as a char) will be the value. * * * a) first write a struct names StudentGrade that contains the student's name * (as a std::string) and grade (as a char) * * * b) Add a class named GradeMap that contains a std::vector of StudentGrade * named m_map. * * * c) Write an overloaded operator[] for this class. * * This function should take a std::string parameter, and return a reference to * a char. In the body of the function, first see if the student's name already * exists (You can use std::find_if from <algorithm>). * * If the student exists, return a reference to the grade and you're done. * Otherwise, use the std::vector::push_back() function to add a StudentGrade * for this new student. When you do this, std::vector will add a copy of your * StudentGrade to itself (resizing if needed, invalidating all previously * returned references). * * Finally, we need to return a reference to the grade for the student we just * added to the std::vector. We can access the student we just added using the * std::vector::back() function. * * The following program should run: [Listing M] * */ #include <string> #include <vector> #include <algorithm> // for std::find_if #include <iostream> // Part a) struct StudentGrade { std::string name{}; char grade{}; }; // Part b) class GradeMap { private: std::vector<StudentGrade> m_map{}; public: char& operator[](const std::string& name); }; char& GradeMap::operator[](const std::string& name) { // Check if student with name exists const auto found{std::find_if(m_map.begin(), m_map.end(), [&](const StudentGrade &student) { return (student.name == name); })}; if (found == m_map.end()) { // Does not exist, add the the student to map m_map.push_back(StudentGrade{ name, 'X' }); // Return a reference to the newly added student's grade return m_map.back().grade; } else { // Exists, return a reference to the student's grade return found->grade; } } // Listing M (for part c) int main() { GradeMap grades{}; grades["Joe"] = 'A'; grades["Frank"] = 'B'; std::cout << "Joe has a grade of " << grades["Joe"] << '\n'; std::cout << "Frank has a grade of " << grades["Frank"] << '\n'; return 0; }
true
a75684732094b80e99163df23032d032c2986fb5
C++
immortalx74/SDLUI
/sdlui_demo_controls_creation.cpp
UTF-8
9,278
2.953125
3
[ "MIT" ]
permissive
// Create some windows. SDLUI_Control_Window *wnd1 = SDLUI_CreateWindow(20, 100, 350, 400, "Window1"); SDLUI_Control_Window *wnd2 = SDLUI_CreateWindow(460, 30, 450, 350, "Window2"); SDLUI_Control_Window *wnd3 = SDLUI_CreateWindow(410, 400, 370, 200, "Window3"); SDLUI_Control_Window *wnd4 = SDLUI_CreateWindow(120, 620, 820, 170, "Colors"); // Add some common controls. Simple controls such as these do not need much explaining. SDLUI_Control_Button *btn1 = SDLUI_CreateButton(wnd1, 10, 40, "PushButton"); SDLUI_Control_TextBox *tbx1 = SDLUI_CreateTextBox(wnd1, 160, 40, 150); SDLUI_Control_SliderInt *si1 = SDLUI_CreateSliderInt(wnd1, 10, 90, 0, 100, 20); SDLUI_Control_SliderInt *si2 = SDLUI_CreateSliderInt(wnd1, 140, 90, 0, 100, 60, SDLUI_ORIENTATION_VERTICAL); SDLUI_Control_CheckBox *chk1 = SDLUI_CreateCheckBox(wnd1, 10, 130, "Checkbox", false); // A ScrollArea is a dual purpose control. It can either host an image (in the form of an SDL_Texture), // or a list, where it effectively replicates the functionality of a listbox. // In both cases it draws and handles scrollbars when the content is bigger than the ScrollArea's size. // In the example bellow we create a ScrollArea that will be used as a listbox. // We pass NULL as the last parameter since we don't have an image texture. SDLUI_Control_ScrollArea *sa1 = SDLUI_CreateScrollArea(wnd1, 10, 220, 320, 160, NULL); // A list needs an array of strings. It doesn't matter what kind of container it is (std::vector, C array of strings, etc), // as long as it can feed the list with a char* representing the caption for each element. This will make more sense // when we'll later call the control's usage function inside the application loop. std::vector<std::string> list_items; for (int i = 0; i < 100; ++i) { std::string cur_item = "List Item: "; cur_item += std::to_string(i); list_items.push_back(cur_item); } // We can now create a list and bind it to the ScrollArea above. // If the size of the data container isn't known at compile time we can simply pass zero to the last function parameter. // In this case we pass the size of the list_items vector. SDLUI_Control_List *lst1 = SDLUI_CreateList(wnd1, sa1, list_items.size()); // Some more controls... SDLUI_Control_Button *btn2 = SDLUI_CreateButton(wnd2, 10, 40, "ClickMe"); SDLUI_Control_CheckBox *chk2 = SDLUI_CreateCheckBox(wnd2, 10, 90, "Another checkbox", true); // Here's another ScrollArea. This time it hosts an image. If the image texture isn't availlable at compile time, // we can pass NULL as the last parameter. Here we first create a texture and pass it on to the ScrollArea. SDL_Surface *surf = IMG_Load("test_image.png"); SDL_Texture *tex = SDL_CreateTextureFromSurface(SDLUI_Core.renderer, surf); SDL_FreeSurface(surf); SDLUI_Control_ScrollArea *sa2 = SDLUI_CreateScrollArea(wnd2, 10, 120, 430, 220, tex); // RadioButtons are handled in groups. A special kind of array(SDLUI_ArrayOfControls) is used // to store pointers to RadioButtons which belong in the same group. The SDLUI_CreateRadioButtonGroup() function // is just a helper to create and initialize such an array. SDLUI_ArrayOfControls rb_group1 = SDLUI_CreateRadioButtonGroup(); SDLUI_ArrayOfControls rb_group2 = SDLUI_CreateRadioButtonGroup(); // Create a bunch of RadioButtons, assigning them to their respective group. SDLUI_Control_RadioButton *rb1 = SDLUI_CreateRadioButton(wnd3, rb_group1, 30, 80, "RadioButton1", true); SDLUI_Control_RadioButton *rb2 = SDLUI_CreateRadioButton(wnd3, rb_group1, 30, 110, "RadioButton2", false); SDLUI_Control_RadioButton *rb3 = SDLUI_CreateRadioButton(wnd3, rb_group1, 30, 140, "RadioButton3", false); SDLUI_Control_RadioButton *rb4 = SDLUI_CreateRadioButton(wnd3, rb_group2, 220, 80, "RadioButton4", false); SDLUI_Control_RadioButton *rb5 = SDLUI_CreateRadioButton(wnd3, rb_group2, 220, 110, "RadioButton5", true); SDLUI_Control_RadioButton *rb6 = SDLUI_CreateRadioButton(wnd3, rb_group2, 220, 140, "RadioButton6", false); // More controls... SDLUI_Control_ToggleButton *tb1 = SDLUI_CreateToggleButton(wnd3, 30, 80, "Toggle Button", true); SDLUI_Control_Button *btn3 = SDLUI_CreateButton(wnd3, 30, 110, "Test"); // A TabContainer is a container for child controls, and all it does is manage their visibility. // It can be created with either a horizontal (default) or vertical strip of tabs. // It's a 3-step proccess: Create a TabContainer, add some tabs, and finally add previously created controls to each tab. // Note that positioning of controls is relative to the window and not to the position of the TabContainer inside the window. SDLUI_Control_TabContainer *tbc1 = SDLUI_CreateTabContainer(wnd3, 10, 40, 350, 140); tbc1->add_tab("First"); tbc1->add_tab("Second"); tbc1->add_tab("Third"); tbc1->set_active_tab(0); tbc1->add_child(0, rb1); tbc1->add_child(0, rb2); tbc1->add_child(0, rb3); tbc1->add_child(0, rb4); tbc1->add_child(0, rb5); tbc1->add_child(0, rb6); tbc1->add_child(1, tb1); tbc1->add_child(1, btn3); // Yet more controls... SDLUI_Control_Button *btn_copy = SDLUI_CreateButton(wnd4, 680, 40, "Copy"); SDLUI_Control_Text *txt01 = SDLUI_CreateText(wnd4, 10, 40, "Active window bar"); SDLUI_Control_Text *txt02 = SDLUI_CreateText(wnd4, 10, 70, "Inactive window bar");; SDLUI_Control_Text *txt03 = SDLUI_CreateText(wnd4, 10, 100, "Window bg"); SDLUI_Control_Text *txt04 = SDLUI_CreateText(wnd4, 10, 130, "Highlight"); // Here's an example creating controls in batch and storing their pointers in an SDLUI_ArrayOfControls. SDLUI_ArrayOfControls color_sliders; color_sliders.create(); i32 x = 200, y = 40; const int num_sliders = 12; for (int i = 0; i < num_sliders; ++i) { SDLUI_Control_SliderInt *si = SDLUI_CreateSliderInt(wnd4, x, y, 0, 255, 0); si->w = 128; color_sliders.push(si); x += 150; if((i + 1) % 3 == 0 && i > 0) { x = 200; y += 30; } } // We modify the 'value' field of each slider after creation. Most control fields are safe to modify directly, // but not all of them (currently undocumented). SDLUI_Control_SliderInt *col_slider; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[0]; col_slider->value = SDLUI_Core.theme.col_active_window_bar.r; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[1]; col_slider->value = SDLUI_Core.theme.col_active_window_bar.g; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[2]; col_slider->value = SDLUI_Core.theme.col_active_window_bar.b; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[3]; col_slider->value = SDLUI_Core.theme.col_inactive_window_bar.r; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[4]; col_slider->value = SDLUI_Core.theme.col_inactive_window_bar.g; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[5]; col_slider->value = SDLUI_Core.theme.col_inactive_window_bar.b; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[6]; col_slider->value = SDLUI_Core.theme.col_window_bg.r; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[7]; col_slider->value = SDLUI_Core.theme.col_window_bg.g; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[8]; col_slider->value = SDLUI_Core.theme.col_window_bg.b; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[9]; col_slider->value = SDLUI_Core.theme.col_highlight.r; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[10]; col_slider->value = SDLUI_Core.theme.col_highlight.g; col_slider = (SDLUI_Control_SliderInt*)color_sliders.data[11]; col_slider->value = SDLUI_Core.theme.col_highlight.b; SDLUI_Control_Window *calc = SDLUI_CreateWindow(980, 280, 170, 280, "Calc"); calc->can_be_resized = false; SDLUI_Control_Text *display = SDLUI_CreateText(calc, 150, 50, "0"); SDLUI_Control_Button *calc_btnc = SDLUI_CreateButton(calc, 130, 80, "C"); calc_btnc->w = 30; SDLUI_Control_Button *calc_btn7 = SDLUI_CreateButton(calc, 10, 120, "7"); calc_btn7->w = 30; SDLUI_Control_Button *calc_btn8 = SDLUI_CreateButton(calc, 50, 120, "8"); calc_btn8->w = 30; SDLUI_Control_Button *calc_btn9 = SDLUI_CreateButton(calc, 90, 120, "9"); calc_btn9->w = 30; SDLUI_Control_Button *calc_btndiv = SDLUI_CreateButton(calc, 130, 120, "/"); calc_btndiv->w = 30; SDLUI_Control_Button *calc_btn4 = SDLUI_CreateButton(calc, 10, 160, "4"); calc_btn4->w = 30; SDLUI_Control_Button *calc_btn5 = SDLUI_CreateButton(calc, 50, 160, "5"); calc_btn5->w = 30; SDLUI_Control_Button *calc_btn6 = SDLUI_CreateButton(calc, 90, 160, "6"); calc_btn6->w = 30; SDLUI_Control_Button *calc_btnmul = SDLUI_CreateButton(calc, 130, 160, "x"); calc_btnmul->w = 30; SDLUI_Control_Button *calc_btn1 = SDLUI_CreateButton(calc, 10, 200, "1"); calc_btn1->w = 30; SDLUI_Control_Button *calc_btn2 = SDLUI_CreateButton(calc, 50, 200, "2"); calc_btn2->w = 30; SDLUI_Control_Button *calc_btn3 = SDLUI_CreateButton(calc, 90, 200, "3"); calc_btn3->w = 30; SDLUI_Control_Button *calc_btnsub = SDLUI_CreateButton(calc, 130, 200, "-"); calc_btnsub->w = 30; SDLUI_Control_Button *calc_btn0 = SDLUI_CreateButton(calc, 10, 240, "0"); calc_btn0->w = 30; SDLUI_Control_Button *calc_btndot = SDLUI_CreateButton(calc, 50, 240, "."); calc_btndot->w = 30; SDLUI_Control_Button *calc_btneq = SDLUI_CreateButton(calc, 90, 240, "="); calc_btneq->w = 30; SDLUI_Control_Button *calc_btnadd = SDLUI_CreateButton(calc, 130, 240, "+"); calc_btnadd->w = 30;
true
8f78c766cc644cbc9bb10ca7ed4aab16b5fa50ec
C++
marcosnils/node-bufferdiff
/bufferdiff.cc
UTF-8
1,152
2.640625
3
[]
no_license
#include <v8.h> #include <node.h> #include <node_buffer.h> #include <cstring> using namespace v8; using namespace node; static Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } Handle<Value> EqBuf(const Arguments &args) { HandleScope scope; if (args.Length() != 2) return VException("Two arguments required - buffer1 and buffer2"); if (!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer."); if (!Buffer::HasInstance(args[1])) return VException("Second argument must be Buffer."); Buffer *buf1 = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject()); Buffer *buf2 = ObjectWrap::Unwrap<Buffer>(args[1]->ToObject()); if (Buffer::Length(buf1) != Buffer::Length(buf2)) return scope.Close(False()); return scope.Close( Boolean::New(memcmp(Buffer::Data(buf1), Buffer::Data(buf2), Buffer::Length(buf1))==0) ); } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("eqBuf"), FunctionTemplate::New(EqBuf)->GetFunction()); }
true
35b0180a8f7d28b4860faac9c4e11925329813d0
C++
manikantanallagatla/Miscellaneous-Files-of-CPP
/DP/floydWarshallAlgo.cpp
UTF-8
1,152
2.734375
3
[]
no_license
#include<bits/stdc++.h> #include<math.h> #define ll long long int #define V 4 #define INF INT_MAX using namespace std; void floydWarshell (int graph[][V]){ int dist[V][V]; for(int i = 0;i<V;i++){ for(int j = 0;j<V;j++){ dist[i][j] = graph[i][j]; } } for(int k = 0;k<V;k++){ for(int i = 0;i<V;i++){ for(int j = 0;j<V;j++){ if(dist[i][j]>(dist[i][k]+dist[k][j]) and dist[i][k]!=INF and dist[k][j]!=INF){ dist[i][j]=(dist[i][k]+dist[k][j]); } } } } for(int i = 0;i<V;i++){ for(int j = 0;j<V;j++){ if(dist[i][j] == INF or dist[i][j] == INT_MAX){ cout<<"INF"<<" "; }else{ cout<<dist[i][j]<<" "; } }cout<<endl; } } int main(){ ios_base::sync_with_stdio(false); int graph[V][V] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; // Print the solution floydWarshell(graph); return 0; }
true
7fc75341b9b6e1a76133d917e7092308e0fd40d7
C++
debanga/Data-Structures-and-Algorithms
/searching/median_2sorted_array_logn.cpp
UTF-8
1,517
3.515625
4
[]
no_license
#include <iostream> using namespace std; int find_j(int i, int n1, int n2) { return (n1+n2+1)/2 - i; } float find_median(int arr1[], int arr2[], int n1, int n2) { int left = 0; int right = n1-1; int mid; int j; bool is_odd = false; if ((n1+n2)%2!=0) { is_odd = true; } while(left<right+2) { mid = left + (right-left)/2; j = find_j(mid, n1, n2); int L1 = mid==0 ? INT16_MIN : arr1[mid-1]; int L2 = j==0 ? INT16_MIN : arr2[j-1]; int R1 = mid==n1 ? INT16_MAX : arr1[mid]; int R2 = j==n2 ? INT16_MAX : arr2[j]; //cout << "[" << mid << "," << j << "]" << endl; //cout << "=[" << L1 << "," << L2 << "]" << endl; //cout << "==[" << R1 << "," << R2 << "]" << endl; if (max(L1, L2)<R1 && max(L1, L2)<R2) { if (is_odd) { return max(L1, L2); } else { return (max(L1, L2)+min(R1, R2))/2.0; } } else if (L2>R1) { left = mid+1; } else { right = mid-1; } } return -1; } int main() { /* int arr1[] = {10, 20, 30, 40, 50}; int arr2[] = {5, 15, 25, 35, 45, 55, 65, 75, 85}; int n1 = 5, n2 = 9; cout << find_median(arr1, arr2, n1, n2) << endl; */ int arr1[] = {10, 90}; int arr2[] = {5, 15, 25, 35, 45, 55, 65, 75, 85}; int n1 = 2, n2 = 9; cout << find_median(arr1, arr2, n1, n2) << endl; }
true
91c3a9ca2b0da73bac6593a21159239234610451
C++
parag-shendye/cpp_lessons
/main.cpp
UTF-8
1,313
3.46875
3
[]
no_license
#include <iostream> #include "Employee.h" #include "Database.h" using namespace std; /* --To add an employee --To fire an employee --To promote an employee --To view all employees, past and present --To view all current employees --To view all former employees */ int main() { /* cout << "Testing Employee class" << endl; Records::Employee emp; emp.setFirstName("John"); emp.setLastName("Galt"); emp.setEmployeeNumber(20); emp.setSalary(40000); emp.promote(500); emp.hire(); emp.display(); cout << emp.getSalary() << endl;*/ Records::Database myDB; Records::Employee& emp1 = myDB.addEmployee("Parag", "Shendye"); //emp1.promote(50); Records::Employee& emp2 = myDB.addEmployee("ABC", "XYZ"); //emp2.promote(100); Records::Employee& emp3 = myDB.addEmployee("Rahul", "Pappu"); emp3.fire(); std::cout << "all Employees: " << std::endl; myDB.displayall(); std::cout << std::endl << "current Employees: " << std::endl; myDB.displaycurrent(); //std::string sAge = "0"; //std::cout << "Enter your age: "; //getline(std::cin, sAge); //int nAge = std::stoi(sAge); //if ((nAge >= 1) && (nAge <= 18)) { // std::cout << "Important birthday" << std::endl; //} //else { // std::cout << "not important" << std::endl; //} }
true
a4dfda9e2e466034c6920695924b803865dabfe1
C++
imhkr/Eminence-CP-dec
/number-theory assignment-1/cubefreenumber.cpp
UTF-8
633
2.578125
3
[]
no_license
#include<iostream> #include <bits/stdc++.h> using namespace std; int main(){ // Write your code here int t; int arr[1234567]; memset(arr, 0, sizeof(arr)); for(int i=2;i<=100;i++){ int c = i * i * i; for (int j=c;j<1234567;j=j+c) { arr[j] = -1; } } int count=1; for(int i=1;i<1234567;i++){ if(arr[i]!=-1){ arr[i] = count; count++; } } cin>>t; int i=0; while(i!=t){ int n; cin>>n; if(arr[n]==-1){ printf("Case %d: Not Cube Free\n",i+1); } else{ printf("Case %d: %d\n",i+1,arr[n]); } i++; } return 0; }
true
ead090d92391c95150084675fd071a4fdc3a1910
C++
mgready/ttttr
/asgn3/SavingAccount.h
UTF-8
455
2.671875
3
[]
no_license
#pragma once #include"Account.h" #include"I_printable.h" #include<iostream> class SavingAccount: public Account,public I_printable { private: string name; double balance; double interest_rate = 1; public: SavingAccount(); SavingAccount(string name, double balance, double interest_rate); void setInterest_rate(double interest_rate); double getInterest_rate(); virtual void deposit(SavingAccount sva,double dollar); virtual void print_data(); };
true
06114cc1dcc768ca3354a601ec4469be990c746b
C++
AbdulrahmanMaktabi/NumbersAndStrings
/prime.cpp
UTF-8
351
3.75
4
[]
no_license
#include <iostream> using namespace std; bool IsPrime(int n); int main(){ int num; cout << "Enter The Number: "; cin >> num; cout << (IsPrime(num) ? "True" : "False") << endl; return 0; } bool IsPrime(int n){ if (1 >= n){ return false; } for(int i=2; i<n; i++){ if(n % i == 0) return false; } return true; }
true
9d2e9a02b2b9643f05041ae712ce8a3a275f604d
C++
luchenqun/leet-code
/problems/606-construct-string-from-binary-tree.cpp
UTF-8
1,572
3.65625
4
[]
no_license
/* * [606] Construct String from Binary Tree * * https://leetcode-cn.com/problems/construct-string-from-binary-tree/description/ * https://leetcode.com/problems/construct-string-from-binary-tree/discuss/ * * algorithms * Easy (44.12%) * Total Accepted: 243 * Total Submissions: 549 * Testcase Example: '[1,2,3,4]' * * 你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。 * 空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。 * 示例 1: * 输入: 二叉树: [1,2,3,4] * ⁠ 1 * ⁠ / \ * ⁠ 2 3 * ⁠ / * ⁠ 4 * 输出: "1(2(4))(3)" * 解释: 原本将是“1(2(4)())(3())”, * 在你省略所有不必要的空括号对之后, * 它将是“1(2(4))(3)”。 * 示例 2: * 输入: 二叉树: [1,2,3,null,4] * ⁠ 1 * ⁠ / \ * ⁠ 2 3 * ⁠ \ * ⁠ 4 * 输出: "1(2()(4))(3)" * 解释: 和第一个示例相似, * 除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。 */ #include <iostream> #include <string> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: string tree2str(TreeNode* t) { } }; int main() { Solution s; return 0; }
true
216fafe35056bbf69c3c19207ef9c6d513715298
C++
tek-nishi/game05
/src/co_misc.hpp
UTF-8
940
3.15625
3
[]
no_license
 #pragma once // // 雑多な処理 // #include <sys/stat.h> #include <string> namespace ngs { // 切り上げて一番近い2のべき乗値を求める int int2pow(const int value) { int res = 1; while(res < (1 << 30)) { if(res >= value) break; res *= 2; } return res; } // ファイルの存在判定 bool isFileExists(const std::string& file) { struct stat info; int result = stat(file.c_str(),&info); return (result == 0); // TODO: ディレクトリかどうかも判定 } template <typename T> T rad2ang(const T rad) { return rad * 180.0 / M_PI; } template <typename T> T ang2rad(const T ang) { return ang * M_PI / 180.0; } // キーワード置換 void replaceString(std::string& text, const std::string& src, const std::string& dst) { std::string::size_type pos = 0; while((pos = text.find(src, pos)) != std::string::npos) { text.replace(pos, src.length(), dst); pos += dst.length(); } } }
true
69c782ad38415221ce601053c1f57be9212975a2
C++
vlfom/Landscape-Generator
/MapGenerator/Hill_algorithm.cpp
UTF-8
8,095
2.921875
3
[]
no_license
#include "stdafx.h" #include <windows.h> #include <stdio.h> #include <iostream> #include <cmath> #include <vector> #include "Hill_algorithm.h" #include "Random.h" int convert(char x) { if (x == 'x') return -1; if (x == 'y') return -2; if (x == '+') return -3; if (x == '-') return -4; if (x == '*') return -5; if (x == '/') return -6; if (x == 's') return -7; if (x == 'c') return -8; if (x == 'q') return -9; if (x == '^') return -10; if (x == 'l') return -11; if (x == 'e') return -12; if (x == '(') return -13; return -100; } int prior(char x) { if (x == -13) return 0; if (x == -3 || x == -4) return 1; if (x == -5 || x == -6) return 2; return 3; } std::vector < int > opn(std::string s) { std::vector < int > res, tmp; int i, j, tmp_prior = 0; for (i = 0; i < (int)s.length(); i++) { if (s[i] == 'x' || s[i] == 'y') { res.push_back(convert(s[i])); } else if (s[i] >= '0' && s[i] <= '9') { int num = s[i] - '0'; j = i + 1; while (j < (int)s.length() && s[j] >= '0' && s[j] <= '9') num = num * 10 + s[j] - '0', j++; i = j - 1; res.push_back(num); } else if (s[i] == '(') tmp.push_back(convert(s[i])); else if (s[i] == ')') { while (tmp.back() != convert('(')) res.push_back(tmp.back()), tmp.pop_back(); tmp.pop_back(); tmp_prior = 0; for (j = 0; j < (int)tmp.size(); j++) if (prior(tmp[j]) > tmp_prior) tmp_prior = prior(tmp[j]); } else if (s[i] == 's') { if (s[i + 1] == 'i') { //sin 's' std::string to_calc; int num = 0; for (j = i + 4; j < (int)s.length(); j++) { if (s[j] == ')') num--; else if (s[j] == '(') num++; if (num < 0) break; to_calc.push_back(s[j]); } std::vector < int > got = opn(to_calc); i = j; for (j = 0; j < (int)got.size(); j++) res.push_back(got[j]); res.push_back(convert('s')); } else { //sqrt 'q' std::string to_calc; int num = 0; for (j = i + 5; j < (int)s.length(); j++) { if (s[j] == ')') num--; else if (s[j] == '(') num++; if (num < 0) break; to_calc.push_back(s[j]); } std::vector < int > got = opn(to_calc); i = j; for (j = 0; j < (int)got.size(); j++) res.push_back(got[j]); res.push_back(convert('q')); } } else if (s[i] == 'c') { //cos 'c' std::string to_calc; int num = 0; for (j = i + 4; j < (int)s.length(); j++) { if (s[j] == ')') num--; else if (s[j] == '(') num++; if (num < 0) break; to_calc.push_back(s[j]); } std::vector < int > got = opn(to_calc); i = j; for (j = 0; j < (int)got.size(); j++) res.push_back(got[j]); res.push_back(convert('c')); } else if (s[i] == 'l') { //ln 'l' std::string to_calc; int num = 0; for (j = i + 3; j < (int)s.length(); j++) { if (s[j] == ')') num--; else if (s[j] == '(') num++; if (num < 0) break; to_calc.push_back(s[j]); } std::vector < int > got = opn(to_calc); i = j; for (j = 0; j < (int)got.size(); j++) res.push_back(got[j]); res.push_back(convert('l')); } else if (s[i] == 'e') { //exp 'e' std::string to_calc; int num = 0; for (j = i + 4; j < (int)s.length(); j++) { if (s[j] == ')') num--; else if (s[j] == '(') num++; if (num < 0) break; to_calc.push_back(s[j]); } std::vector < int > got = opn(to_calc); i = j; for (j = 0; j < (int)got.size(); j++) res.push_back(got[j]); res.push_back(convert('e')); } else if (s[i] == '^') { //^ '^' std::string to_calc; int num = 0; for (j = i + 2; j < (int)s.length(); j++) { if (s[j] == ')') num--; else if (s[j] == '(') num++; if (num < 0) break; to_calc.push_back(s[j]); } std::vector < int > got = opn(to_calc); i = j; for (j = 0; j < (int)got.size(); j++) res.push_back(got[j]); res.push_back(convert('^')); } else { if (tmp_prior < prior(convert(s[i]))) tmp.push_back(convert(s[i])), tmp_prior = prior(convert(s[i])); else { while (!tmp.empty() && prior(tmp.back()) >= prior(convert(s[i]))) res.push_back(tmp.back()), tmp.pop_back(); tmp.push_back(convert(s[i])); tmp_prior = prior(convert(s[i])); } } } if (!tmp.empty()) for (i = (int)tmp.size() - 1; i >= 0; i--) res.push_back(tmp[i]); return res; } double calc(std::vector < int > c, int x, int y) { std::vector < double > to_calc; int i, sz = 0; for (i = 0; i < (int)c.size(); i++) { if (c[i] == convert('x')) to_calc.push_back(x), sz++; else if (c[i] == convert('y')) to_calc.push_back(y), sz++; else if (c[i] == convert('+')) { to_calc[sz - 2] = to_calc[sz - 2] + to_calc[sz - 1]; to_calc.pop_back(); sz--; } else if (c[i] == convert('-')) { to_calc[sz - 2] = to_calc[sz - 2] - to_calc[sz - 1]; to_calc.pop_back(); sz--; } else if (c[i] == convert('*')) { to_calc[sz - 2] = to_calc[sz - 2] * to_calc[sz - 1]; to_calc.pop_back(); sz--; } else if (c[i] == convert('/')) { to_calc[sz - 2] = to_calc[sz - 2] / to_calc[sz - 1]; to_calc.pop_back(); sz--; } else if (c[i] == convert('^')) { to_calc[sz - 2] = pow(to_calc[sz - 2], to_calc[sz - 1]); to_calc.pop_back(); sz--; } else if (c[i] == convert('s')) { to_calc[sz - 1] = sin(to_calc[sz - 1]); } else if (c[i] == convert('c')) { to_calc[sz - 1] = cos(to_calc[sz - 1]); } else if (c[i] == convert('q')) { to_calc[sz - 1] = sqrt(to_calc[sz - 1]); } else if (c[i] == convert('l')) { to_calc[sz - 1] = log(to_calc[sz - 1]); } else if (c[i] == convert('e')) { to_calc[sz - 1] = exp(to_calc[sz - 1]); } else if (c[i] >= 0) to_calc.push_back(c[i]), sz++; } return to_calc.back(); } void HILL_ResizeMap(float***& Map, int size){ int i, j, l; Map = new float**[3]; for (l = 0; l < 3; l++) Map[l] = new float*[size + 5]; for (l = 0; l < 3; l++) for (i = 0; i < size + 5; i++) Map[l][i] = new float[size + 5]; for (l = 0; l < 3; l++) for (i = 0; i < size + 5; i++) for (j = 0; j < size + 5; j++) Map[l][i][j] = 0; } void HILL_zoom_Height_Map(int a, float***& Map, float zoom_y) { int i, j; for (i = 0; i < a + 5; i++) for (j = 0; j < a + 5; j++) Map[0][i][j] *= zoom_y; } void HILL_Centralize(int a, float***& Map){ int i, j; for (i = 0; i < a + 5; i++) for (j = 0; j < a + 5; j++) Map[0][i][j] = (Map[0][i][j] - minH) / (maxH - minH); } void HILL_GenerateHolme(int a, float***& Map, int radius){ int i, j; int xpoint, zpoint; xpoint = rand() % (a + 5); zpoint = rand() % (a + 5); for (i = max(1, xpoint - radius); i <= min(xpoint + radius, a + 4); i++) for (j = max(1, zpoint - radius); j <= min(zpoint + radius, a + 4); j++){ int value; value = radius*radius - ((xpoint - i)*(xpoint - i) + (zpoint - j)*(zpoint - j)); if (value>0)Map[0][i][j] += value; if (Map[0][i][j] > maxH)maxH = Map[0][i][j]; } } void HILL_CreateMap(int a, float***& Map, int random_const, int random, int zoom){ int i, j; long long number; minH = 0; maxH = 0; for (i = 0; i < a + 5; i++) for (j = 0; j < a + 5; j++) { Map[0][i][j] = 0; } int answer = 0; number = a*a; number *= 30000; number /= 1000000 - (random + random_const)*(random + random_const); while (number){ number--; HILL_GenerateHolme(a, Map, (int)(abs(Rand_generate(answer)) * 2 * (random - random_const) + random_const)); } HILL_Centralize(a, Map); HILL_zoom_Height_Map(a, Map, 20); } void CreateFunc(int a, float***& Map, std::string s){ int i, j; s.erase(s.begin(), s.begin() + 9); std::vector< int > ss = opn(s); minH = 0; maxH = 0; for (i = 0; i < a + 5; i++) for (j = 0; j < a + 5; j++) Map[0][i][j] = 0; for (i = -a / 2; i < a / 2 + 5; i++) for (j = -a / 2; j < a / 2 + 5; j++) { double xx = calc(ss, i, j); Map[0][i + a / 2][j + a / 2] = (float) calc(ss, i, j); if (Map[0][i + a / 2][j + a / 2] > maxH) maxH = Map[0][i + a / 2][j + a / 2]; if (Map[0][i + a / 2][j + a / 2] < minH) minH = Map[0][i + a / 2][j + a / 2]; } HILL_Centralize(a, Map); HILL_zoom_Height_Map(a, Map, 20); }
true
ec68be650a079b22196c2f6128ee1a3cc60b1524
C++
David-Sam22/Zorkish
/Task9-Spike_GameStateManagement/cmd_manager.cpp
UTF-8
9,990
2.671875
3
[]
no_license
#include "pch.h" #include "cmd_manager.h" #include <string> #include <list> #include <iostream> #include <fstream> #include "inventory.h" #include "location.h" #include "player.h" #include <algorithm> #include <map> #include "child_entity.h" #include "Message.h" using namespace std; cmd_manager::cmd_manager() { loadFile(); } multimap<string, string> cmd_manager::cmd_map; string cmd_manager::userinput; string cmd_manager::usercmd; void cmd_manager::loadFile() { fstream cmd_file("./worlds/command.txt", ios::binary | ios::in | ios::out); string line; string temp = ""; string first; string second; if (cmd_file.is_open()) { while (getline(cmd_file, line)) { for (auto a : line) { if (a == '\r') { second = temp; temp = ""; continue; } else if (a == ':') { first = temp; temp = ""; continue; } temp += a; } cmd_map.insert(make_pair(first, second)); } cmd_file.close(); } } void cmd_manager::printDebug() { location* loc = location::Instance(); cout << "\nLocate Player:\n" << endl; loc->showPlayer(); cout << "--------------------------------\n" << endl; } void cmd_manager::printHelp() { cout << "\nHelp:\n" << endl; multimap<string, string>::iterator it; for (it = cmd_manager::cmd_map.begin(); it != cmd_manager::cmd_map.end(); ++it) { cout << "`" << it->first << "`" << " - " << it->second << endl; } cout << "--------------------------------\n" << endl; } void cmd_manager::printInventory() { inventory* inv = inventory::Instance(); inv->show_inventory(); } void cmd_manager::printAlias() { cout << "\nAlias:\n" << endl; multimap<string, string>::iterator it; multimap<string, string>::iterator temp; string second; string input; bool isMatch = false; for (it = cmd_manager::cmd_map.begin(); it != cmd_manager::cmd_map.end(); ++it) { cout << " - " << it->first << " :: " << it->second << endl; } cout << "please type in the exist command, you wish to map : " ; cin >> input; transform(input.begin(), input.end(), input.begin(), ::tolower); for (it = cmd_manager::cmd_map.begin(); it != cmd_manager::cmd_map.end(); ++it) { if (input == it->first) { temp = it; second = it->second; isMatch = true; } } if (isMatch) { cout << "new command: " ; cin >> input; cmd_manager::cmd_map.insert(make_pair(input, second)); cmd_manager::cmd_map.erase(temp); } else cout << "Exist command not match.\n" << endl; cout << "--------------------------------\n" << endl; } void cmd_manager::printLook() { location* loc = location::Instance(); Player* pl = Player::Instance(); cout << "\nYou see:\n" << endl; loc->printConnection(pl->getLocation()); cout << "--------------------------------\n" << endl; } bool cmd_manager::checkList(string input) { bool isFound = false; multimap<string, string>::iterator it; string my_str = input; location* loc = location::Instance(); transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower); setInput(my_str); my_str += " "; string cmd = ""; string first_block = ""; string second_block = ""; string third_block = ""; string fourth_block = ""; for (auto x : my_str) { if (x == ' ') { if (first_block == "") { if (cmd == "look" || cmd == "open" || cmd == "take" || cmd == "put" || cmd == "go" || cmd == "attack") { first_block = cmd + ' '; } } else if (second_block == "") { if (cmd == "at" || cmd == "in" || cmd == "the" || cmd == "back") { second_block = cmd + ' '; } else if (loc->checkConnection(cmd)) { second_block += "* "; } else if (loc->checkObject(cmd)) { second_block += "^ "; } } else if (third_block == "") { if (cmd == "from" || cmd == "in" || cmd == "the") { third_block = cmd + ' '; } else if (loc->checkConnection(cmd)) { third_block += "* "; } else if (loc->checkObject(cmd)) { third_block += "^ "; } } else if (fourth_block == "") { if (loc->checkObject(cmd)) { fourth_block += "^ "; } } cmd = ""; } else { cmd = cmd + x; } } string user = first_block + second_block + third_block + fourth_block; if (user == "") { user = getInput(); } for (it = cmd_manager::cmd_map.begin(); it != cmd_manager::cmd_map.end(); ++it) { if (it->first == user) { setCommand(it->second); isFound = true; } } // cout << first_block << second_block << third_block << fourth_block << endl; return isFound; } void cmd_manager::process_input() { location* loc = location::Instance(); Player* pl = Player::Instance(); inventory* inv = inventory::Instance(); map<string, game_object*>::iterator it; string my_str = getInput() + " "; string output = getCmd(); string cmd = ""; string inputCon = ""; string inputItem1 = ""; string inputItem2 = ""; for (auto x : my_str) { if (x == ' ') { if (loc->checkConnection(cmd)) { inputCon = cmd; break; } else if (loc->checkObject(cmd)) { if (inputItem1 == "") { inputItem1 = cmd; if (output == "takeItem" || output == "lookItemAt" || output == "lookItemIn") { break; } } else if (inputItem2 == "") { inputItem2 = cmd; } } cmd = ""; } else { cmd = cmd + x; } } if (output == "debug") { printDebug(); } else if (output == "help") { printHelp(); } else if (output == "look") { printLook(); } else if (output == "inventory") { printInventory(); } else if (output == "alias") { printAlias(); } else if (output == "go") { if (loc->checkConnection(inputCon)) { pl->setPrevLocation(pl->getLocation()); pl->setLocation(loc->getDestination(inputCon, pl->getLocation())); } } else if (output == "back") { pl->setLocation(pl->getPrevLocation()); } else if (output == "lookItemIn") { for (it = location::objects.begin(); it != location::objects.end(); ++it) { if (pl->getLocation() == it->second->_cloc || it->second->_cloc == "Player") { if (inputItem1 == it->second->_name) { if (it->second->has_component("children")) { component* tempComp = it->second->getcomponent("children"); child_entity* tempChild = dynamic_cast<child_entity*>(tempComp); tempChild->show_child(); } } } } } else if (output == "lookItemAt") { for (it = location::objects.begin(); it != location::objects.end(); ++it) { if (pl->getLocation() == it->second->_cloc || it->second->_cloc == "Player") { if (it->first == inputItem1) { cout << "\n" << it->second->_name << " :" << it->second->_desc << endl; } } } cout << "--------------------------------\n" << endl; } else if (output == "takeItem") { for (it = location::objects.begin(); it != location::objects.end(); ++it) { if (pl->getLocation() == it->second->_cloc) { if (!it->second->has_component("health")) { if (it->first == inputItem1) { inv->store_item(*it->second); it->second->_cloc = "Player"; } } } } } else if (output == "takeItemFrom") { if (location::objects.find(inputItem2)->second->_cloc == "Player" || location::objects.find(inputItem2)->second->_cloc == pl->getLocation()) { if (!location::objects.find(inputItem2)->second->has_component("childen")) { if (location::objects.find(inputItem1)->second->_cloc == "child") { if (inputItem1 != inputItem2) { component* tempComponent = location::objects.find(inputItem2)->second->getcomponent("children"); child_entity* pDerived = dynamic_cast<child_entity*>(tempComponent); if (location::objects.find(inputItem2)->second->_cloc == "Player") { inv->store_item(*location::objects.find(inputItem1)->second); } else if (location::objects.find(inputItem2)->second->_cloc == pl->getLocation()) { location::objects.find(inputItem1)->second->_cloc = "Player"; inv->store_item(*location::objects.find(inputItem1)->second); } pDerived->childentity.erase(inputItem1); pDerived->show_child(); } } } } } else if (output == "putItem") { for (it = location::objects.begin(); it != location::objects.end(); ++it) { if (it->second->_name == inputItem2) { if (pl->getLocation() == it->second->_cloc || it->second->_cloc == "Player") { if (it->second->has_component("children")) { if (inputItem1 != inputItem2) { component* tempComponent = it->second->getcomponent("children"); child_entity* pDerived = dynamic_cast<child_entity*>(tempComponent); if (location::objects.find(inputItem1)->second->_cloc == "Player") { inv->takeOut_item(*location::objects.find(inputItem1)->second); location::objects.find(inputItem1)->second->_cloc = "child"; } else if (location::objects.find(inputItem1)->second->_cloc == pl->getLocation()) { location::objects.find(inputItem1)->second->_cloc = "child"; } else if (location::objects.find(inputItem1)->second->_cloc == "child") { inv->takeOut_item(*location::objects.find(inputItem1)->second); } pDerived->add_childentity(inputItem1, location::objects.find(inputItem1)->second); pDerived->show_child(); } } } } } } else if (output == "attack") { Message* msg = Message::Instance(); for (it = location::objects.begin(); it != location::objects.end(); ++it) { if (it->first == "monster") { if (it->second->_cloc == pl->getLocation()) { msg->Send(location::objects.find(it->first)->second, "5"); // 5 is damage sent to objs } } } // msg->Send(); // msg_attack* tempMessage = new msg_attack(loc->objects.find("sword")->second, loc->objects.find("monster")->second); // tempMessage->update(); } else { cout << "\n\n----- You need a weapon to attack.\n" << endl; } }
true
56dcb6dc8f576f9889fb9683e836d2032adbb4cc
C++
ginkgo/AMP-LockFreeSkipList
/test/graph_bipartitioning/PPoPP/PPoPPBBGraphBipartitioningStrategy2.h
UTF-8
3,426
2.578125
3
[]
no_license
/* * StrategyBBGraphBipartitioningStrategy.h * * Created on: Mar 14, 2014 * Author: Martin Wimmer * License: Boost Software License 1.0 (BSL1.0) */ #ifndef PPOPPBBGRAPHBIPARTITIONINGSTRATEGY2_H_ #define PPOPPBBGRAPHBIPARTITIONINGSTRATEGY2_H_ #include <pheet/pheet.h> #include <pheet/sched/strategies/UserDefinedPriority/UserDefinedPriority.h> #include <pheet/ds/StrategyTaskStorage/LSMLocality/LSMLocalityTaskStorage.h> namespace pheet { template <class Pheet, class SubProblem> class PPoPPBBGraphBipartitioningStrategy2 : public Pheet::Environment::BaseStrategy { public: typedef PPoPPBBGraphBipartitioningStrategy2<Pheet,SubProblem> Self; typedef typename Pheet::Environment::BaseStrategy BaseStrategy; typedef LSMLocalityTaskStorage<Pheet, Self> TaskStorage; typedef typename TaskStorage::Place TaskStoragePlace; typedef typename Pheet::Place Place; PPoPPBBGraphBipartitioningStrategy2() :place(nullptr) {} PPoPPBBGraphBipartitioningStrategy2(SubProblem* sub_problem) :place(Pheet::get_place()), sub_problem(sub_problem), lower_bound(sub_problem->get_lower_bound()), estimate(sub_problem->get_estimate()), uncertainty(sub_problem->get_estimate() - sub_problem->get_lower_bound()), // treat_local(estimate < sub_problem->get_global_upper_bound()), upper_bound(sub_problem->upper_bound) {} PPoPPBBGraphBipartitioningStrategy2(Self& other) : BaseStrategy(other), place(other.place), sub_problem(other.sub_problem), lower_bound(other.lower_bound), estimate(other.estimate), uncertainty(other.uncertainty), // treat_local(other.treat_local), upper_bound(other.upper_bound) {} PPoPPBBGraphBipartitioningStrategy2(Self&& other) : BaseStrategy(other), place(other.place), sub_problem(other.sub_problem), lower_bound(other.lower_bound), estimate(other.estimate), uncertainty(other.uncertainty), // treat_local(other.treat_local), upper_bound(other.upper_bound) {} ~PPoPPBBGraphBipartitioningStrategy2() {} Self& operator=(Self&& other) { place = other.place; sub_problem = other.sub_problem; lower_bound = other.lower_bound; estimate = other.estimate; uncertainty = other.uncertainty; // treat_local = other.treat_local; upper_bound = other.upper_bound; return *this; } inline bool prioritize(Self& other) { Place* p = Pheet::get_place(); if(this->place == p) { if(other.place == p) return estimate < other.estimate; else return true; } else if(other.place == p) { return false; } return uncertainty > other.uncertainty; } bool dead_task() { return lower_bound == upper_bound->load(std::memory_order_relaxed); } /* * Checks whether spawn can be converted to a function call */ inline bool can_call(TaskStoragePlace* p) { size_t ub = upper_bound->load(std::memory_order_relaxed); if(lower_bound >= ub) return true; size_t diff = ub - lower_bound; size_t open = (diff / (1 + (ub/sub_problem->size))) >> 1; return open < 28 && (p->size()*p->size() >> open) > 0; } static void print_name() { std::cout << "Strategy2"; } private: Place* place; SubProblem* sub_problem; size_t lower_bound; size_t estimate; size_t uncertainty; // bool treat_local; std::atomic<size_t>* upper_bound; }; } #endif /* STRATEGYBBGRAPHBIPARTITIONINGSTRATEGY2_H_ */
true
9a884c6ba409a0b3a61d8bf3dfa87ec3521a1ce0
C++
foreverhy/leetcode
/ExcelSheetColumnTitle.cc
UTF-8
574
3
3
[]
no_license
#include "leet.h" #include <algorithm> #include <cstring> class Solution{ public: string convertToTitle(int n) { string ret(""); while (n) { auto r = n % 26; n /= 26; if (r) { ret = static_cast<char>('A' - 1 + r) + ret; } else { ret = 'Z' + ret; if (n) --n; } } return ret; } }; int main(){ Solution slu; int x; while (cin >> x) { cout << slu.convertToTitle(x) << endl; } return 0; }
true
73c3250c34788168b9bee8dbd5238a55dae8d144
C++
jgsogo/Tuenti-Challenge
/7.The.Perfect.Larry.Matching.Algorithm/Girl.hpp
UTF-8
4,309
2.984375
3
[]
no_license
#pragma once #include <string> #include <memory> #include <vector> #include <map> #include <algorithm> #include <fstream> #include <bitset> #include <set> // Structs to store data about the world struct Girl { enum Q {GAME, FIGURE, SUITS, CATS, SHOP}; std::size_t id; std::string label; std::bitset<5> answers; std::size_t points; std::size_t component; // for graph connected_components computation. std::set<std::shared_ptr<Girl>> friends; //std::vector<std::shared_ptr<Girl>> friends_of_friends; Girl(std::size_t id) : id(id) { points = 0; component = 0; }; void parse_line(std::ifstream& file) { char q[5]; file >> label >> q[0] >> q[1] >> q[2] >> q[3] >> q[4]; for (auto i=0; i<5; ++i) { if (q[i]=='Y') {answers.set(i);} } }; void print(std::ostream& os) { os << "Girl [" << id << "]: " << label << std::endl; os << "\t GAME:" << answers[0]; os << "\t FIGURE:" << answers[1]; os << "\t SUITS:" << answers[2]; os << "\t CATS:" << answers[3]; os << "\t SHOP:" << answers[4] << std::endl; os << "\t friends:"; for (auto it = friends.begin(); it!=friends.end(); ++it) { std::cout << " " << (*it)->label; } std::cout << std::endl; std::cout << "\t >>> component: " << component << std::endl; std::cout << "\t >>> points: " << points << std::endl; }; std::size_t compute_points(const std::map<std::size_t, std::size_t>& components, const std::size_t& total_shoppers); }; typedef std::shared_ptr<Girl> pGirl; std::size_t Girl::compute_points(const std::map<std::size_t, std::size_t>& components, const std::size_t& total_shoppers) { // RULE#1: 7 points if G likes naughty, dirty games points += answers[GAME] ? 7 : 0; // RULE#2: 3 points for every friend of G who likes super hero action figures. for (auto it = friends.begin(); it!= friends.end(); ++it) { points += (*it)->answers[FIGURE] ? 3 : 0; } // RULE#3: 6 points for every friend of a friend of G, not including the friends of G and G herself, who likes men in leisure suits // RULE#4: 4 points if G has any friend H who likes cats, and no friend of H (except perhaps G) likes cats (4 points at most, not 4 for every friend). // - Build friends of friends vector (and cat candidates) std::vector<pGirl> friends_cat; std::set<pGirl> friends_of_friends; for (auto it = friends.begin(); it!=friends.end(); ++it) { if ( (*it)->answers[CATS] ) { friends_cat.push_back(*it); } friends_of_friends.insert((*it)->friends.begin(), (*it)->friends.end()); } // - Remove friends from friends_of_friends std::vector<pGirl> v(friends_of_friends.size()); std::vector<pGirl>::iterator it; it = std::set_difference(friends_of_friends.begin(), friends_of_friends.end(), friends.begin(), friends.end(), v.begin()); v.resize(it-v.begin()); // - Remove herself from friend_of_friends v.erase(std::remove_if(v.begin(), v.end(), [this](const pGirl& girl){ return girl->id == id;}), v.end()); // RULE#3: 6 points for every friend of a friend of G, not including the friends of G and G herself, who likes men in leisure suits for (auto it = v.begin(); it!= v.end(); ++it) { points += (*it)->answers[SUITS] ? 6 : 0; } // RULE#4: 4 points if G has any friend H who likes cats, and no friend of H (except perhaps G) likes cats (4 points at most, not 4 for every friend). for (auto it = friends_cat.begin(); it!=friends_cat.end(); ++it) { auto none = std::none_of((*it)->friends.begin(), (*it)->friends.end(), [this](const pGirl& girl){ return ((girl->id != id) && (girl->answers[CATS])); }); points += none ? 4 : 0; } // RULE#5: 5 points for every girl H who likes to go shopping and has no possible connection with G through a chain of friends (friends, friends of friends, friends of friends of friends, etc.) auto non_connected_shoppers = total_shoppers - components.find(component)->second; points += 5*non_connected_shoppers; return points; };
true
c20256211acf509b4fa8f0867fd91033cd1c2cc5
C++
rexim/beatwave
/src/beatwave/splat.cpp
UTF-8
1,087
2.859375
3
[ "MIT" ]
permissive
#include <cmath> #include <SFML/Graphics.hpp> #include <core/math.hpp> #include <beatwave/splat.hpp> Splat::Splat(size_t dropCount) { for (size_t i = 0; i < dropCount; ++i) { m_drops.emplace_back(sf::Color::White); } } void Splat::render(sf::RenderTarget *renderTarget) const { for (const auto &drop: m_drops) { drop.render(renderTarget); } } void Splat::tick(int32_t deltaTime) { for (auto &drop: m_drops) { drop.tick(deltaTime); } } void Splat::splat(const sf::Vector2f &center, float radius) { const float step = 2.0f * PI / m_drops.size(); std::uniform_real_distribution<float> dist(0.0f, PI / 8.0f); for (size_t i = 0; i < m_drops.size(); ++i) { const float offset = dist(m_rd); const float directionAngle = step * i + offset; const sf::Vector2f direction(std::cos(directionAngle), std::sin(directionAngle)); m_drops[i].drop(center, center + direction * radius, 20.0f); } }
true
841c06d6bb2f4efd8d1430d992140a85586fb504
C++
cwindom/cpp-module
/day04/ex00/MyVictim.hpp
UTF-8
437
2.75
3
[]
no_license
// // Created by Мария Корогодова on 25.01.2021. // #ifndef EX00_MYVICTIM_HPP #define EX00_MYVICTIM_HPP #include <iostream> #include "Victim.hpp" class MyVictim: public Victim { private: MyVictim(); public: MyVictim(std::string const name); virtual ~MyVictim(); MyVictim(MyVictim const &copy); MyVictim &operator= (MyVictim const &op); std::string get_name() const; virtual void getPolymorphed() const; }; #endif //EX00_MYVICTIM_HPP
true
c134e230f7fc77b42bc181aa5a8af95206acc80d
C++
xvrxvr/basicoopparser
/parser1/main.cpp
UTF-8
1,925
3.0625
3
[]
no_license
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include "EvalSystem.h" /* expr: mul_exp { '+'|'-' mul_exp } mul_exp: primary { '*'|'/' primary } primary: <number> | '(' expr ')' */ class Lexer { char* input; int num; int symbol; public: Lexer(char* in) : input(in), num(0), symbol(-1) {} void init(char* in) {input=in; num=0; symbol=-1;} int lex(int& num) { while(*input) { if (isspace(*input)) {++input; continue;} if (isdigit(*input)) { num=strtol(input,&input,0); return 'N'; } return *input++; } return 0; } int peek_sym(int& onum) { onum=num; if (symbol==-1) {symbol=lex(onum); num=onum;} return symbol; } void next() {symbol=-1;} }; /////////////////////////////////////////////////////////////// int expr(Lexer& L); int primary(Lexer& L) { int num; if (L.peek_sym(num)=='N') { L.next(); return num; } if (L.peek_sym(num)=='(') { L.next(); int rv=expr(L); if (L.peek_sym(num)!=')') { printf("Error!\n"); abort(); } L.next(); return rv; } printf("Error!\n"); abort(); } //mul_exp: primary { '*'|'/' primary } int mul_expr(Lexer& L) { int num,rv=primary(L); for(;;) { if (L.peek_sym(num)=='*') {L.next(); rv*=primary(L);} else if (L.peek_sym(num)=='/') {L.next(); rv/=primary(L);} else return rv; } } //expr: mul_exp { '+'|'-' mul_exp } int expr(Lexer& L) { int num,rv=mul_expr(L); for(;;) { if (L.peek_sym(num)=='+') {L.next(); rv+=mul_expr(L);} else if (L.peek_sym(num)=='=') {L.next(); rv-=mul_expr(L);} else return rv; } } char buf[1024]; int main() { EvalSystem<> es; for(;;) { printf("> "); gets(buf); auto ex= es.compile(buf); std::string res=ex.to_string(); std::string ev=ex.eval().to_string(); printf("%s = %s (%s)\n",buf,ev.c_str(), res.c_str()); } return 0; }
true
fb39be985e8caf2e44d61e90e4fe486ef9e986a6
C++
ud-boss/DSA
/DP/DivisorGame.cpp
UTF-8
852
2.796875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int solve(vector<int> &A) { int N = A.size(); vector<int> Dp(N,1); for(int i=1;i<N;i++) { if(A[i] > A[i-1]) Dp[i] = Dp[i-1]+1; else if(A[i] == A[i-1]) Dp[i] = Dp[i-1]; } for(int i=N-1;i>0;i--) { if(A[i-1] > A[i]) Dp[i-1] = max(Dp[i]+1,Dp[i-1]); else if(A[i-1] == A[i]) Dp[i-1] = Dp[i]; } int res = 0; for(int a : Dp) res += a; return res; } int main() { string str = "1,2,3,3,1"; for(char &c : str) { if(c == ',') c = ' '; } vector<int> A; stringstream is(str); int x; while(is>>x) { A.push_back(x); } cout<<solve(A)<<endl; return 0; }
true
7398eadcc9a4738c4e57bc70b0a13a41b9508b18
C++
Plasmarobo/MikrokopterSerialDriver
/dummy.cpp
UTF-8
550
2.53125
3
[]
no_license
#include "serial_channel.hpp" #include "raw_channel.hpp" #include "serial_frame.hpp" #include <iostream> int main(int argc, char *argv[]) { if(argc < 2) { printf("No port specified, exiting\n"); exit(0); } SerialChannel *r = new RawChannel(argv[1], 0); r->Open(); char *d = new char[5]; d[0] = 100; d[1] = 200; d[2] = 7; d[3] = 5; d[4] = 13; SerialFrame *s = new SerialFrame('a', FC_ADDR, 5, d); unsigned int size = 5; for(int i = 1; i < 600; ++i) { s->Send(r); sleep(1); } r->Close(); delete s; delete [] d; delete r; }
true
0aecd6262c348582cc8eb466ce0098c6dd05c9ee
C++
sigalnotovich/project-in-cpp
/World.h
UTF-8
5,194
3.28125
3
[]
no_license
#ifndef MTM4_WORLD_H #define MTM4_WORLD_H #include "Clan.h" #include "Area.h" #include <map> namespace mtm { typedef std::shared_ptr<Area> AreaPtr; enum AreaType { PLAIN, MOUNTAIN, RIVER }; class World { map<string, Clan> clan_map; //areas: //MtmSet<AreaPtr> areas_set; map<string, AreaPtr> areas_map; MtmSet<std::string> clans_names; MtmSet<std::string> areas_names; //MtmSet<std::string> groups_names; map <string, string> groups_clans_names; //map <group,clan> public: /** * Empty constructor */ World(); /** * Disable copy constructor */ World(const World& world) = delete; /** * Disable assignment operator */ World &operator=(const World &) = delete; ~World(); /** * Add a new clan to the world. * @param new_clan The name of the new clan * @throws WorldInvalidArgument If new_clan is empty * @throws WorldClanNameIsTaken If there is or was a clan with the * given name. */ void addClan(const string& new_clan); /** * Add a new area to the world. * @param area_name The name of the area * @param type The type of the area (PLAIN, MOUNTAIN, RIVER) * @throws WorldInvalidArgument If area_name is empty * @throws WorldAreaNameIsTaken If there is already an area with the * given name. */ void addArea(const string& area_name, AreaType type); /** * Add a new group to the world, with given size, clan, and starting * area (the group "arrives" to the area). * The group should have 77 morale when entering the area. * @param group_name The name of the new group * @param clan_name The name of the clan of the group. * @param num_children Number of children in the group. * @param num_adults Number of the adults in the group. * @param area_name The name of the area the group starts in (arrives * to it first) * @throws WorldInvalidArgument If group_name is empty, or at least * one of num_children and num_adults is negative, or both are 0. * @throws WorldGroupNameIsTaken If there is already a group with the * given name in the world. * @throws WorldClanNotFound If there is no clan with the given name * in the world. * @throws WorldAreaNotFound If there is no area with the given name * in the world. */ void addGroup(const string& group_name, const string& clan_name, int num_children, int num_adults, const string& area_name); /** * Make that an area reachable from another area. * (make 'to' reachable from 'from') * @param from The name of the area that the other area will be * reachable from. * @param to The name of the area that should be reachable from the * other area. * @throws WorldAreaNotFound If at least one of the areas isn't in * the world. */ void makeReachable(const string& from, const string& to); /** * Move a group to destination area. * @param group_name The name of the group that should move * @param destination The name of the area the group should move to. * @throws WorldGroupNotFound If there is no group with the given * name in the world. * @throws WorldAreaNotFound If there is no area with the given name * in the world. * @throws WorldGroupAlreadyInArea If the group is already in the * destination area. * @throws WorldAreaNotReachable If the destination area isn't * reachable from the area the group is currently in. */ void moveGroup(const string& group_name, const string& destination); /** * Make to clans friends. * @param clan1 The name of one of the clans to become friends. * @param clan2 The name of the other clan to become friends with. * @throws WorldClanNotFound If at least one of the clans isn't in * the world. */ void makeFriends(const string& clan1, const string& clan2); /** * Unite to clans to a new clan with a new name. * @param clan1 The name of one of the clan that need to unite. * @param clan2 The name of the second clan that need to unite. * @param new_name The name of the new clan. * @throws WorldInvalidArgument If new_name is empty. * @throws WorldClanNameIsTaken If new_name was already used for a * clan that is not clan1 or clan2. * @throws WorldClanNotFound If clan1 or clan2 are not in the world. */ void uniteClans(const string& clan1, const string& clan2, const string& new_name); /** * Print a group to the ostream, using the group output function (<<). * Add to it another line (after the last one of a regular print) of * the form: * Group's current area: [area name] * That print the area which the group is in. * @param os The ostream to print into. * @param group_name The name of the group to print. * @throws WorldGroupNotFound If there is no group in the world with * the given name. */ void printGroup(std::ostream& os, const string& group_name) const; /** * Print a clan to the ostream, using the clan output function. * @param os The ostream to print into. * @param clan_name The name of the clan to print. * @throws WorldClanNotFound If there is no clan with the given name * in the world. */ void printClan(std::ostream& os, const string& clan_name) const; }; } // namespace mtm #endif //MTM4_WORLD_H
true
786da714cb749be047e82b09bc2cf765b409b80e
C++
sheriby/DandAInLeetCode
/Daily_Problem/2012/Middle/201215_Monotone_Increasing_DIgits/method1/solution.cc
UTF-8
906
3.5625
4
[ "MIT" ]
permissive
#include <vector> using std::vector; class Solution { public: // 将数字变成各位的数字数组 int monotoneIncreasingDigits(int N) { vector<int> numbers; while (N) { numbers.push_back(N % 10); N /= 10; } for (int i = 0; i + 1 < numbers.size(); i++) { if (numbers[i] >= numbers[i + 1]) { continue; } else { numbers[i + 1]--; for (int j = 0; j <= i; j++) { numbers[j] = 9; } } } while (true) { if (numbers.back() == 0) { numbers.pop_back(); } break; } int result = 0; for (int i = numbers.size() - 1; i >= 0; i--) { result *= 10; result += numbers[i]; } return result; } };
true
933d83dac35de0d3c0ad55dac9e00334507e2b15
C++
SudakovOleg/ReadManga
/standartview.cpp
UTF-8
4,489
2.65625
3
[]
no_license
#include "standartview.h" #include "ui_standartview.h" #include <QScrollBar> #include <QScreen> #include <QPushButton> #include <QTimer> StandartView::StandartView(QWidget *parent, const QList<QString>& pages, const QString& name) : QDialog (parent), ui(new Ui::StandartView) { //Узнаем размер экрана //--------------------------------- QScreen* screen = QApplication::screens().at(0); QSize screen_size = screen->availableSize(); //--------------------------------- //Настраиваем GUI //--------------------------------- setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); if(pages.count() == 0) close(); //Пишем имя окна this->setWindowTitle(name); //Выставляем максимальнодоступную высоту окна this->setFixedHeight(screen_size.height() - 45); //Отключаем горизантальный скролл ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->horizontalSlider->setRange(ui->scrollArea->verticalScrollBar()->singleStep(), 100); ui->AutoRead->setText("Включить"); connect(ui->AutoRead,SIGNAL(clicked()), SLOT(autoReadOn())); connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), SLOT(setSpeed(int))); connect(ui->commandLinkButton, SIGNAL(clicked()), parent, SLOT(nextBook())); connect(ui->commandLinkButton, SIGNAL(clicked()), SLOT(close())); //connect(ui->pushButton_2, SIGNAL(clicked()), parent, SLOT(prevBook())); //connect(ui->pushButton_2, SIGNAL(clicked()), SLOT(close())); //--------------------------------- //Настраиваем таймер //--------------------------------- timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(step())); //--------------------------------- //Создаем виджет и слой для него //Настраиваем //--------------------------------- widget = new QWidget(this); lay = new QVBoxLayout(widget); lay->setSpacing(1); ui->scrollArea->setWidget(widget); //--------------------------------- //Натягиваем картинки на лейбл и отправляем их на слой //--------------------------------- //Ссылка на предыдущий лейбл QPixmap t_img(pages.at(pages.size()/2)); QPixmap st_img(pages.at((pages.size()/2) + 1)); if(t_img.width() > st_img.width()) { t_img = st_img; } if(t_img.width() > screen_size.width() - 20) { t_img = t_img.scaled(screen_size.width() - 35, t_img.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); } this->setFixedWidth(t_img.width() + 50); for(const auto & page : pages) { //Создаем лейбл для натягивания картинок //И загружаем саму картинку //--------------------------------- lbl = new QLabel(widget); QPixmap img(page); //--------------------------------- //Адаптируем картинки по размеру //--------------------------------- img = img.scaled(t_img.width(), img.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); lbl->setPixmap(img); lay->addWidget(lbl); //--------------------------------- } ui->scrollArea->verticalScrollBar()->setRange(0, 4000); ui->AutoReadSpeed->setRange(0, 10); ui->AutoReadSpeed->setSingleStep(1); //--------------------------------- } StandartView::~StandartView() { delete widget; delete ui; } void StandartView::setSpeed(int value) { ui->scrollArea->verticalScrollBar()->setSingleStep(value); } void StandartView::autoReadOn() { timer->start(20); ui->AutoRead->setText("Отключить"); disconnect(ui->AutoRead,SIGNAL(clicked()), this, SLOT(autoRaedOn())); connect(ui->AutoRead,SIGNAL(clicked()), SLOT(autoReadOff())); } void StandartView::autoReadOff() { timer->stop(); ui->AutoRead->setText("Включить"); disconnect(ui->AutoRead,SIGNAL(clicked()), this, SLOT(autoRaedOff())); connect(ui->AutoRead,SIGNAL(clicked()), SLOT(autoReadOn())); } void StandartView::step() { ui->scrollArea->verticalScrollBar()->setValue( ui->scrollArea->verticalScrollBar()->value() + ui->AutoReadSpeed->value()); timer->start(20); }
true
d99842c0d94b360f09ecdd34c945c5bc6bbba70f
C++
3817061ShashkinEV/Shashkin_All_Labs
/Queue/queue_main.cpp
UTF-8
921
3.84375
4
[]
no_license
#include <iostream> #include "Queue.h" int main() { TQueue<int> queue(10); int tmp; std::cout << "Queue is: "; if (queue.IsEmpty()) std::cout << "empty.\n"; else if (queue.IsFull()) std::cout << "full.\n"; else std::cout << "not empty and not full.\n"; std::cout << "Filling the queue with values from 1 to 10... \n"; for (int i = 0; i < 10; i++) queue.Put(i+1); std::cout << "Queue is: "; if (queue.IsEmpty()) std::cout << "empty.\n"; else if (queue.IsFull()) std::cout << "full.\n"; else std::cout << "not empty and not full.\n"; std::cout << "Getting element from queue...\n"; tmp = queue.Get(); std::cout << "Element from Queue equals: " << tmp << "\n"; std::cout << "Queue is: "; if (queue.IsEmpty()) std::cout << "empty.\n"; else if (queue.IsFull()) std::cout << "full.\n"; else std::cout << "not empty and not full.\n"; return 0; }
true
3f94d32dd36f00d29ee8c2c3d50255fe5f2b2bfa
C++
namyoungu/baekjoon
/백준 17478번 재귀함수가 뭔가요.cpp
UHC
1,246
3.296875
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int n; void firstPrint(int dep) { int cnt = n - dep; for (int i = 0; i < cnt; i++) { cout << "____"; } } void Print(int dep) { if (dep == -1) return; firstPrint(dep); cout << "\"Լ ?\"" << '\n'; if (dep == 0) { firstPrint(dep); cout << "\"Լ ڱ ڽ ȣϴ Լ\"" << '\n'; firstPrint(dep); cout << " 亯Ͽ." << '\n'; return; } firstPrint(dep); cout << "\" . ⿡ ̼ ־." << '\n'; firstPrint(dep); cout << " ο ߰, Ӱ ־." << '\n'; firstPrint(dep); cout << " κ ǾҴٰ ϳ. ׷ , ο ãƿͼ .\"" << '\n'; Print(dep - 1); firstPrint(dep); cout << " 亯Ͽ." << '\n'; } int main() { cin >> n; cout << " ǻͰа л ãư ." << '\n'; Print(n); return 0; }
true
a67f87a8c274773ae4768db7af97615ca3f6d5b3
C++
Mrd278/Codeforces_Java
/GivenlengthAndSumOfDigits.cpp
UTF-8
1,035
2.515625
3
[]
no_license
#include<bits/stdc++.h> #include<string> using namespace std; #define fo(i, n) for(int i = 0; i < n; i++) typedef long long int ll; void solve() { int m,s, max_ = 0; cin>>m>>s; string maximum, minimum; if(s == 0 && m <= 1) cout<<"0 0"<<endl; else if((s == 0 && m > 1) || (s > 9*pow(2,m-1))) cout<<"-1 -1"<<endl; else { fo(i,m) { s = s - max_; max_ = min(9,s); maximum.append(to_string(max_)); } minimum = maximum; reverse(minimum.begin(),minimum.end()); if(minimum[0] == '0') { string temp = minimum; int k = 0; fo(i, minimum.size()) { if(int(minimum[i]) - 48 > 0) { //cout<<int(minimum[i]) - 48<<endl; minimum.replace(0,1,"1"); minimum.replace(i,i+1, to_string(int(minimum[i]) - 48 -1)); k = i; break; } } minimum.append(temp.substr(k+1, temp.size())); } cout<<minimum<<" "<<maximum<<endl; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout<<fixed; cout<<setprecision(10); solve(); return 0; }
true
3a6ee1fbaa22504da0435046a58398794752db68
C++
johnttaylor/colony.core
/src/Cpl/Text/Tokenizer/Basic.cpp
UTF-8
1,853
2.53125
3
[]
no_license
/*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2022 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ #include "Basic.h" #include "Cpl/Text/strip.h" // using namespace Cpl::Text; using namespace Cpl::Text::Tokenizer; /////////////////////////////// Basic::Basic( char* stringToParse ) :m_ptr( 0 ), m_delimiters( whiteSpace() ), m_base( 0 ), m_count( 0 ) { m_base = m_ptr = stringToParse; } Basic::Basic( char* stringToParse, const char* delimiterSet ) :m_ptr( 0 ), m_delimiters( delimiterSet ), m_base( 0 ), m_count( 0 ) { m_base = m_ptr = stringToParse; } /////////////////////////////// const char* Basic::next() noexcept { // Trap error: null pointer for input string if ( !m_base ) { return 0; } char* startptr = (char*) stripChars( m_ptr, m_delimiters ); if ( *startptr != '\0' ) { m_ptr = (char*) stripNotChars( startptr, m_delimiters ); if ( *m_ptr != '\0' ) { *m_ptr++ = '\0'; } m_count++; return startptr; } return 0; } /////////////////////////////// const char* Basic::getToken( unsigned n ) const noexcept { // Trap out-of-bounds index if ( n >= m_count || !m_base ) { return 0; } // Traverse string for the Nth token const char* token = stripChars( m_base, m_delimiters ); unsigned i; for ( i=0; i < n; i++ ) { while ( *token != '\0' ) { token++; } token = stripChars( ++token, m_delimiters ); } return token; }
true
29a84af6e6727490dd6170de9c6db8ccfb7c331d
C++
RongleXie/Play-Leetcode
/2501-3000/2581-Count-Number-of-Possible-Root-Nodes/cpp-2581/main.cpp
UTF-8
2,085
3.265625
3
[]
no_license
/// Source : https://leetcode.com/problems/count-number-of-possible-root-nodes/description/ /// Author : liuyubobobo /// Time : 2023-03-04 #include <iostream> #include <vector> #include <list> #include <set> using namespace std; /// Rerooting /// Time Complexity: O(n) /// Space Complexity: O(n) class Solution { public: int rootCount(vector<vector<int>>& edges, vector<vector<int>>& guesses, int k) { int n = edges.size() + 1; vector<list<int>> tree(n); for(const vector<int>& edge: edges){ int u = edge[0], v = edge[1]; tree[u].push_back(v), tree[v].push_back(u); } set<pair<int, int>> guess_set; for(const vector<int>& guess: guesses){ int u = guess[0], v = guess[1]; guess_set.insert({u, v}); } set<pair<int, int>> correct_guesses; dfs(tree, 0, -1, guess_set, correct_guesses); int res = 0; dfs_reroot(tree, 0, -1, guess_set, correct_guesses, k, res); return res; } private: void dfs_reroot(const vector<list<int>>& tree, int u, int p, const set<pair<int, int>>& guess_set, set<pair<int, int>>& correct_guesses, const int k, int& res){ if(correct_guesses.size() >= k) res ++; for(int v: tree[u]){ if(v == p) continue; correct_guesses.erase({u, v}); if(guess_set.count({v, u})) correct_guesses.insert({v, u}); dfs_reroot(tree, v, u, guess_set, correct_guesses, k, res); correct_guesses.erase({v, u}); if(guess_set.count({u, v})) correct_guesses.insert({u, v}); } } void dfs(const vector<list<int>>& tree, int u, int p, const set<pair<int, int>>& guess_set, set<pair<int, int>>& correct_guesses){ for(int v: tree[u]){ if(v == p) continue; if(guess_set.count({u, v})) correct_guesses.insert({u, v}); dfs(tree, v, u, guess_set, correct_guesses); } } }; int main() { return 0; }
true
a987a5d1dc6fcb2c5dbbaca035235d9eff2850c5
C++
jleppert/sony
/test.cpp
UTF-8
966
2.640625
3
[]
no_license
#include <opencv2/opencv.hpp> #include <opencv2/ccalib/randpattern.hpp> #include <zmq.hpp> #include <iostream> #include <unistd.h> using namespace std; using namespace cv; using namespace randpattern; int main() { cout << "started okay" << endl; zmq::context_t context (1); zmq::socket_t socket (context, ZMQ_REP); socket.bind ("tcp://*:5555"); RandomPatternGenerator generator = RandomPatternGenerator(3840, 2160); generator.generatePattern(); Mat pattern = generator.getPattern(); namedWindow("pattern", WND_PROP_FULLSCREEN); setWindowProperty("pattern", WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN); imshow("pattern", pattern); waitKey(1); while(true) { cout << "waiting for request" << endl; zmq::message_t request; socket.recv (&request); std::cout << "Received Hello" << std::endl; sleep(1); zmq::message_t reply (5); memcpy (reply.data (), "World", 5); socket.send (reply); } return 0; }
true
62cec61d9d3c3529f7e1e598cbc06472487c2f6c
C++
chanhou/openCL_DNN
/openCl/YoUtil.cpp
UTF-8
2,597
2.84375
3
[]
no_license
#include "YoUtil.hpp" #include <iostream> // for I/O #include <fstream> // for file I/O using namespace std; cl::Context *getContext(cl_device_type type, vector<cl::CommandQueue> &cmdQueues, cl_command_queue_properties props, bool verbose) { vector< cl::Platform > platforms; cl::Platform::get(&platforms); for (cl::Platform &platform : platforms) { vector<cl::Device> devices; platform.getDevices(type, &devices); if (devices.size() == 0) continue; cl::Context *context = new cl::Context(devices); // create command queues in the context cmdQueues.clear(); for (auto& device : context->getInfo<CL_CONTEXT_DEVICES>()) { // cmdQueues.push_back(cl::CommandQueue(*context, device, props)); cmdQueues.push_back(cl::CommandQueue(*context, device, CL_QUEUE_PROFILING_ENABLE)); } if (verbose) { cout << "\n\tThere are " << context->getInfo<CL_CONTEXT_NUM_DEVICES>() << " device(s) in the defined context."; cout << "\n\t# of Command queues: " << cmdQueues.size(); } return context; } if (verbose) cerr << "\nCannot find any platform for given device type: " << type; return nullptr; } string readSourceCode(const char *filename) { ifstream inp(filename); if (!inp) { cerr << "\nError opening file: " << filename << endl; return ""; } string kernel((istreambuf_iterator<char>(inp)), istreambuf_iterator<char>()); inp.close(); return kernel; } cl::Program *compile(cl::Context &context, const string &source, const char *options) { cl::Program *prog = new cl::Program(context, source); try { // prog->build("-cl-std=CL1.2 -w -cl-kernel-arg-info"); prog->build(options); } catch (cl::Error &e) { cerr << "\nFile: " << __FILE__ << ", line: " << __LINE__ << e.what(); cerr << "\nError no: " << e.err() << endl; for (auto& device : context.getInfo<CL_CONTEXT_DEVICES>()) { cout << "\n=== " << device.getInfo<CL_DEVICE_NAME>() << " ==="; cout << "\nBuild log: " << prog->getBuildInfo<CL_PROGRAM_BUILD_LOG>(device); cout << "\nBuild options used:" << prog->getBuildInfo<CL_PROGRAM_BUILD_OPTIONS>(device); } return nullptr; } /* // See Table 5.13 of OpenCL 1.2 specification for information that can be queried to program objects cout << "\n\t# devices associated with the program: " << prog->getInfo<CL_PROGRAM_NUM_DEVICES>(); cout << "\n\t# Kernels defined: " << prog->getInfo<CL_PROGRAM_NUM_KERNELS>(); cout << "\n\tProgram kernel names: " << prog->getInfo<CL_PROGRAM_KERNEL_NAMES>(); cout << "\n\tProg sizes: "; for (auto s : prog->getInfo<CL_PROGRAM_BINARY_SIZES>()) cout << s << ";"; */ return prog; }
true
d589cc2c30c81631e872336c22ec3274da882fb2
C++
shaihitdin/CP
/Olymp/WCS/Division_selection/A.cpp
UTF-8
506
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 100; int d[N]; inline int calc (int x) { int res = 0; while (x) { if (x % 10 == 0) ++res; x /= 10; } return res; } int main () { #ifdef BROKEN freopen ("in", "r", stdin); #endif d[0] = 1; for (int i = 1; i < N; ++i) { d[i] = d[i - 1] + calc (i); } int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if (a == 0) cout << d[b] << "\n"; else cout << d[b] - d[a - 1] << "\n"; } return 0; }
true
79b0920fee7e16367586fff3cfde81aacd995a88
C++
OpsRaven/SenecaOOP345-attic
/filesize.cpp
UTF-8
317
2.78125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int64_t filesize(char*f) { ifstream i(f, ios::in | ios::binary | ios::ate); return i? uint64_t(i.tellg()): -1; } int main(int argc, char**argv) { for(int arg = 1; arg < argc; arg++) cout << argv[arg] << " = " << filesize(argv[arg]) << "\n"; }
true
20572b36da3fe17187f4af7e4b852cfebd8a8af3
C++
ghorges/leetcode
/21-2-5/剑指offer28.cc
UTF-8
956
3.375
3
[]
no_license
// 开始想着很麻烦,但是实际上不难,因为这个树本身 // 是对称的,所以只要从根开始,判断左边和右边即可 // 空间复杂度是O(n),因为压栈的原因。 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool rec = true; bool isSymmetric(TreeNode* root) { if (root == NULL) return true; trans(root->left, root->right); return rec; } void trans(TreeNode* l, TreeNode* r) { if (l == NULL && r==NULL) { return; } if (l == NULL || r == NULL) { rec = false; return; } if (l->val != r->val) { rec = false; return; } trans(l->left, r->right); trans(l->right, r->left); } };
true
1ddfc0d7b825cc318bfb9c443aacf138e54b551b
C++
cwilkens/mortimer-maxwell
/DosLife/MortimerMaxwell/GameObject.h
UTF-8
1,299
2.796875
3
[ "MIT" ]
permissive
// generic game object //#include <windows.h> #include "ConsoleImage.h" #ifndef GAMEOBJECT_H #define GAMEOBJECT_H class ObjectList; enum State { ACTIVE, REMOVE }; enum ObjectType { PLAYER, ENEMY, ITEM, POWERUP, PROJECTILE, SCENERY }; class GameObject { public: // overridden by child virtual State Step() {return REMOVE;}; virtual void Draw(int offx, int offy) {}; virtual void Damage(GameObject *cause, int dmg) {}; virtual void Collide(GameObject *other) {}; GameObject(Console &parent, ObjectType ntype, std::string sfile, float nx, float ny) : sprite(parent, sfile) { type = ntype; x = nx; y = ny; health = 1; spritecollide = true; }; // get functions float GetX() {return x;}; float GetY() {return y;}; int GetW() {return w;}; int GetH() {return h;}; bool GetPrecise() {return spritecollide;}; ConsoleImage* GetSprite() {return &sprite;}; ObjectType GetType() {return type;}; float GetFrame() {return frame;}; void SetController(ObjectList* controller) {Controller = controller;}; // specific virtuals virtual int Pressed() {return 1;}; protected: ObjectType type; ObjectList* Controller; ConsoleImage sprite; bool spritecollide; float x, y; float frame; int w, h; int health; int damage; }; #endif /* GAMEOBJECT_H */
true
5e4a896720fd037d85ab1db8291befeb92ff7871
C++
acsearle/mania
/mania/rect.hpp
UTF-8
4,004
3.3125
3
[]
no_license
// // rect.hpp // mania // // Created by Antony Searle on 9/3/19. // Copyright © 2019 Antony Searle. All rights reserved. // #ifndef rect_hpp #define rect_hpp #include "vec.hpp" namespace manic { // There are many defensible choices for rect storage. The most performance // critical use case is guessed to be constructing quad vertices. Storing // top-left and bottom-right vertices means that two vertices are copies, and // the other two corners are component-wise copies. template<typename T> class rect { public: vec<T, 2> a, b; bool invariant() const { return (a.x <= b.x) && (a.y <= b.y); } rect() = default; rect(const rect&) = default; rect(const vec<T, 2>& x, const vec<T, 2>& y) : a(x) , b(y) { } rect(T ax, T ay, T bx, T by) : a(ax, ay) , b(bx, by) { } void canonicalize() { using std::swap; if (a.x > b.x) swap(a.x, b.x); if (a.y > b.y) swap(a.y, b.y); } vec<T, 2> size() const { return b - a; } T width() const { return b.x - a.x; } T height() const { return b.y - a.y; } friend T area(const rect<T>& x) { return product(x.b - x.a); } T area() const { return product(b - a); } bool contains(vec<T, 2> x) const { return (a.x <= x.x) && (a.y <= x.y) && (x.x < b.x) && (x.y < b.y); } vec2 mid() { return (a + b) / 2.0f; } }; struct area_cmp { template<typename A, typename B> bool operator()(A&& a, B&& b) const { return area(std::forward<A>(a)) < area(std::forward<B>(b)); } }; template<typename T> rect<T> operator+(const rect<T>& x) { return x; } template<typename T> rect<T> operator-(const rect<T>& x) { return rect(-x.b, -x.a); } // Minkowski sum template<typename T> rect<T> operator+(const rect<T>& a, const rect<T>& b) { return rect(a.a + b.a, a.b + b.b); } // Minkowski difference is defined so that // // (A - B) + B == A // // but // // A - B != A + (-B) template<typename T> rect<T> operator-(const rect<T>& a, const rect<T>& b) { return rect(a.a - b.a, a.b - b.b); } // shift template<typename T> rect<T> operator+(const rect<T>& a, const vec<T, 2>& b) { return rect{a.a + b, a.b + b}; } template<typename T> rect<T>& operator+=(rect<T>& a, const vec<T, 2>& b) { a.a += b; a.b += b; return a; } template<typename T> rect<T> operator-(const rect<T>& a, const vec<T, 2>& b) { return rect{a.a - b, a.b - b}; } template<typename T> rect<T>& operator-=(rect<T>& a, const vec<T, 2>& b) { a.a -= b; a.b -= b; return a; } // Scaling template<typename T> rect<T> operator*(const rect<T>& a, T b) { return rect<T>(a.a * b, a.b * b); } template<typename T> rect<T> operator*(T a, const rect<T>& b) { return rect<T>(a * b.a, a * b.b); } template<typename T> rect<T> operator/(const rect<T>& a, T b) { return rect<T>(a.a / b, a.b / b); } // Enclosing rect template<typename T> rect<T> hull(const rect<T>& a, const rect<T>& b) { return rect<T>(std::min(a.a.x, b.a.x), std::min(a.a.y, b.a.y), std::max(a.b.x, b.b.x), std::max(a.b.y, b.b.y)); } template<typename T> rect<T> hull(const rect<T>& a, const vec<T, 2>& b) { return rect<T>(std::min(a.a.x, b.x), std::min(a.a.y, b.y), std::max(a.b.x, b.x), std::max(a.b.y, b.y)); } template<typename T> bool overlap(const rect<T>& a, const rect<T>& b) { return (((a.a.x < b.b.x) && (b.a.x < a.b.x)) && ((a.a.x < b.b.x) && (b.a.x < a.b.x))); } template<typename T> rect<T> intersection(const rect<T>& a, const rect<T>& b) { return rect<T>(std::max(a.a.x, b.a.x), std::max(a.a.y, b.a.y), std::min(a.b.x, b.b.x), std::min(a.b.y, b.b.y)); } } // namespace manic #endif /* rect_hpp */
true
468c8c581b98c91eab73384dcc31dd860b65544f
C++
mehran-alipour/OOP345
/OOP345_myNOTE/OOP345_week01_sol/external_linkage/ModuleB.cpp
UTF-8
268
2.671875
3
[]
no_license
// External Linkage // Module_b.cpp #include <iostream> void display(); int share_me = 0; // variable definition int main() { display(); display(); std::cout << "share_me at " << &share_me << '\n'; std::cout << "share_me is " << share_me++ << '\n'; }
true
2881aa63993bac63ee04737969342cb217d83421
C++
Alpinski/1stExcercises
/Excercises/ConstructDestruct/ConstructDestruct/Source.cpp
UTF-8
444
3.140625
3
[]
no_license
#include <iostream> using namespace std; class Player { public: Player(); //e Player(const char * name); //d Player(int a_max_ammo, int a_max_health); //a Player(float x, float y); //b Player(Player& a_player); //c float X, Y; int ammo; int max_ammo; int health; int max_health; char name[64]; }; void main() { Player p1(100, 100); //a Player p2(25.f, 16.f); //b Player p3(p1); //c Player p4("Jerry"); //d Player p5(); //e }
true
9c69899f5c7f7b4d9ba00f63a952598ecce61fbd
C++
bisrat09/Sudoku-Solver
/sudoku.h
UTF-8
2,898
3.40625
3
[]
no_license
/* sudoku.h By Bisrat Belayneh Mar 8,2017 sudoku.h contains the class definitions of the functions implemented in sudoku.cpp */ #pragma once #include<iostream> #include"puzzle.h" #include"string" #include"sudokuFitness.h" class sudoku : public puzzle { //---------------------------------------------------------------------- // operator>> // stream input operator that reads a sequence of 81 integers from user //makes use of helperStreaminput helper method // takes istream and sudoku and returns istream friend istream& operator>>(istream&, sudoku &p); //----------------------------------------------------------------------------- //operator<< //stream output operator that prints the sudoku puzzle as a formatted text // takes ostream object and sudoku object and returns ostream //makes use of a helper method called helperstreamOutput friend ostream& operator<<(ostream&, const sudoku &p); friend class sudokuOffspring; // so that we can use private members of sudokuOffspring.h friend class sudokuFitness; // so that we can use private members of sudokuOffspring.h public: //--------------------------------------------------------------------------------------------------- //constructor // makes a soduku puzzle setting all elements 0 // obtains the fitness of the the sudoku puzzle from fitness.cpp // sets the member variable array isFixed to false sudoku(); //------------------------------------------------------------------------ //destructor //frees the memory used by grid and isFixed arrays after use ~sudoku(); //------------------------------------------------------------------------------------- // helperStreamInput //reads the input stream of integers as characters // marks them as fixed and variable ,converts back to ints and fills up the grid //takes istream input and returns nothing void helperStreamInput(istream&) ; //------------------------------------------------------------------------------------ //helperStreamOutput //prints out a formatted sudoku puzzle with 81 integers //takes nothing and returns a string representation of the sudoku string helperStreamOutput() const; //---------------------------------------------------------------------------------------- // howfit //gets the fitness of this sudoku from howFit function in fitness class //takes nothing and returns integer int howFit(); //------------------------------------------------------------------------------------ // 2 dimensional array pointer member variable to store fixed/varable state bool **isFixed; private : int **grid; // 2 dimensional array pointer member variable to store soduku digits int fitnessScore; // to store the fitess of each sudoku sudokuFitness fitnessObject; // to communicate with sudokuFitness to get fitnesses };
true
c78c8a7c93f636e75baf16d93954c6487018deab
C++
Mesywang/EPSILON_Noted
/EPSILON/core/common/inc/common/basics/shapes.h
UTF-8
11,942
2.890625
3
[ "MIT" ]
permissive
/** * @file shapes.h * @author HKUST Aerial Robotics Group * @brief * @version 0.1 * @date 2019-03-17 * * @copyright Copyright (c) 2019 */ #ifndef _COMMON_INC_COMMON_BASICS_SHAPES_H__ #define _COMMON_INC_COMMON_BASICS_SHAPES_H__ #include <map> #include <opencv2/core/core.hpp> #include "common/basics/basics.h" #include "common/basics/colormap.h" #include "common/math/calculations.h" namespace common { struct Point { decimal_t x = 0.0; decimal_t y = 0.0; decimal_t z = 0.0; /** * @brief Default constructor */ Point(); /** * @brief Construct a new Point object * * @param _x * @param _y */ Point(decimal_t _x, decimal_t _y); /** * @brief Construct a new Point object * * @param _x * @param _y * @param _z */ Point(decimal_t _x, decimal_t _y, decimal_t _z); /** * @brief Print info */ void print() const; }; struct Point2i { int x = 0; int y = 0; /** * @brief Default constructor */ Point2i(); /** * @brief Construct a new Point 2i object * * @param _x * @param _y */ Point2i(int _x, int _y); /** * @brief Print info */ void print() const; }; template <typename T> struct PointWithValue { Point pt; std::vector<T> values; }; struct OrientedBoundingBox2D { decimal_t x; decimal_t y; decimal_t angle; decimal_t width; decimal_t length; /** * @brief Default constructor */ OrientedBoundingBox2D(); /** * @brief Construct a new Oriented Bounding Box 2D object * * @param x_ x of center of obb * @param y_ y of center of obb * @param angle_ angle between x-positive and longitudinal axis of obb * @param width_ width of obb * @param length_ length of obb */ OrientedBoundingBox2D(const decimal_t x_, const decimal_t y_, const decimal_t angle_, const decimal_t width_, const decimal_t length_); }; template <int N> struct AxisAlignedBoundingBoxND { std::array<decimal_t, N> coord; std::array<decimal_t, N> len; /** * @brief Default constructor */ AxisAlignedBoundingBoxND() {} /** * @brief Construct a new AxisAlignedBoundingBoxND object * * @param coord_ Center of AABB * @param len_ Length of AABB */ AxisAlignedBoundingBoxND(const std::array<decimal_t, N> coord_, const std::array<decimal_t, N> len_) : coord(coord_), len(len_) {} }; template <typename T, int N_DIM> struct AxisAlignedCubeNd { std::array<T, N_DIM> upper_bound; std::array<T, N_DIM> lower_bound; AxisAlignedCubeNd() = default; AxisAlignedCubeNd(const std::array<T, N_DIM> ub, const std::array<T, N_DIM> lb) : upper_bound(ub), lower_bound(lb) {} }; struct Circle { Point center; decimal_t radius; /** * @brief Print info */ void print() const; }; struct PolyLine { int dir; std::vector<Point> points; /** * @brief Print info */ void print() const; }; struct Polygon { std::vector<Point> points; /** * @brief Print info */ void print() const; }; class ShapeUtils { public: /** * @brief Check if 2 OBBs intersect * * @param obb_a OBB A * @param obb_b OBB B * @return true Intersect * @return false No intersect */ static bool CheckIfOrientedBoundingBoxIntersect(const OrientedBoundingBox2D& obb_a, const OrientedBoundingBox2D& obb_b); /** * @brief Get the Vertices Of OrientedBoundingBox object * * @param obb Input OBB * @param vertices Output vertice vector * @return ErrorType */ static ErrorType GetVerticesOfOrientedBoundingBox(const OrientedBoundingBox2D& obb, vec_E<Vecf<2>>* vertices); /** * @brief Get the Perpendicular Axes Of Oriented Bounding Box * * @param vertices * @param axes * @return ErrorType */ static ErrorType GetPerpendicularAxesOfOrientedBoundingBox(const vec_E<Vecf<2>>& vertices, vec_E<Vecf<2>>* axes); /** * @brief Get the Projection On Axis object * * @param vertices * @param axis * @param proj * @return ErrorType */ static ErrorType GetProjectionOnAxis(const vec_E<Vecf<2>>& vertices, const Vecf<2>& axis, Vecf<2>* proj); /** * @brief Get the Perpendicular Axis Of Oriented Bounding Box object * * @param vertices * @param index * @param axis * @return ErrorType */ static ErrorType GetPerpendicularAxisOfOrientedBoundingBox(const vec_E<Vecf<2>>& vertices, const int index, Vecf<2>* axis); /** * @brief Get the Overlap Length * * @param a * @param b * @param len * @return ErrorType */ static ErrorType GetOverlapLength(const Vecf<2> a, const Vecf<2> b, decimal_t* len); /** * @brief Get the cv::Point2i Vector Using Common::Point2i Vector * * @param pts_in Input common::Point2i vector * @param pts_out Output cv::Point2i vector * @return ErrorType */ static ErrorType GetCvPoint2iVecUsingCommonPoint2iVec(const std::vector<Point2i>& pts_in, std::vector<cv::Point2i>* pts_out); /** * @brief Get the cv::Point2i Using Common::Point2i * * @param pt_in Input Common::Point2i * @param pt_out Output cv::Point2i * @return ErrorType */ static ErrorType GetCvPoint2iUsingCommonPoint2i(const Point2i& pt_in, cv::Point2i* pt_out); /** * @brief * * @tparam T * @tparam N_DIM * @param cube_a * @param cube_b * @return true * @return false */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeAContainsAxisAlignedCubeB(const common::AxisAlignedCubeNd<T, N_DIM>& cube_a, const common::AxisAlignedCubeNd<T, N_DIM>& cube_b) { for (int i = 0; i < N_DIM; ++i) { if (cube_a.lower_bound[i] > cube_b.lower_bound[i] || cube_a.upper_bound[i] < cube_b.upper_bound[i]) { return false; } } return true; } /** * @brief * * @tparam T * @tparam N_DIM * @param aabb_a * @param aabb_b * @return true * @return false */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeCollide(const common::AxisAlignedCubeNd<T, N_DIM>& aabb_a, const common::AxisAlignedCubeNd<T, N_DIM>& aabb_b) { for (int i = 0; i < N_DIM; ++i) { decimal_t half_len_a = fabs(static_cast<double>(aabb_a.upper_bound[i] - aabb_a.lower_bound[i]) / 2.0); decimal_t half_len_b = fabs(static_cast<double>(aabb_b.upper_bound[i] - aabb_b.lower_bound[i]) / 2.0); decimal_t center_a = static_cast<double>(aabb_a.upper_bound[i] + aabb_a.lower_bound[i]) / 2.0; decimal_t center_b = static_cast<double>(aabb_b.upper_bound[i] + aabb_b.lower_bound[i]) / 2.0; decimal_t len_c = fabs(center_a - center_b); // ~ Seperated if (fabs(half_len_a + half_len_b) <= len_c) { return false; } } return true; } /** * @brief * * @tparam T * @tparam N_DIM * @param aabb_a * @param aabb_b * @param inter_dim_a * @param inter_dim_b * @return true If two AABBs intersect * @return false If two AABBs is seperated or one AABB contains another */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeNdIntersect(const AxisAlignedCubeNd<T, N_DIM>& aabb_a, const AxisAlignedCubeNd<T, N_DIM>& aabb_b, std::array<bool, N_DIM * 2>* inter_dim_a, std::array<bool, N_DIM * 2>* inter_dim_b) { inter_dim_a->fill(false); inter_dim_b->fill(false); // ~ A contains B or B contains A if (CheckIfAxisAlignedCubeAContainsAxisAlignedCubeB(aabb_a, aabb_b) || CheckIfAxisAlignedCubeAContainsAxisAlignedCubeB(aabb_b, aabb_a)) { return false; } // ~ Check if collide if (!CheckIfAxisAlignedCubeCollide(aabb_a, aabb_b)) { return false; } // ~ Calculate on which A's surface collision happened for (int i = 0; i < N_DIM; ++i) { if (CheckIfAxisAlignedCubeNdCollideOnOneDim(aabb_a, aabb_b, i)) { if (aabb_a.upper_bound[i] < aabb_b.upper_bound[i] && aabb_a.upper_bound[i] > aabb_b.lower_bound[i]) { (*inter_dim_a)[2 * i] = true; } if (aabb_a.lower_bound[i] < aabb_b.upper_bound[i] && aabb_a.lower_bound[i] > aabb_b.lower_bound[i]) { (*inter_dim_a)[2 * i + 1] = true; } } } // ~ Calculate on which B's surface collision happened for (int i = 0; i < N_DIM; ++i) { if (CheckIfAxisAlignedCubeNdCollideOnOneDim(aabb_a, aabb_b, i)) { if (aabb_b.upper_bound[i] > aabb_a.lower_bound[i] && aabb_b.upper_bound[i] < aabb_a.upper_bound[i]) { (*inter_dim_b)[2 * i] = true; } if (aabb_b.lower_bound[i] > aabb_a.lower_bound[i] && aabb_b.lower_bound[i] < aabb_a.upper_bound[i]) { (*inter_dim_b)[2 * i + 1] = true; } } } return true; } /** * @brief * @notice This function only check on dim intersection */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeNdIntersectionOnOneDim(const AxisAlignedCubeNd<T, N_DIM>& aabb_a, const AxisAlignedCubeNd<T, N_DIM>& aabb_b, const int& i) { decimal_t half_len_a = fabs(static_cast<double>(aabb_a.upper_bound[i] - aabb_a.lower_bound[i]) / 2.0); decimal_t half_len_b = fabs(static_cast<double>(aabb_b.upper_bound[i] - aabb_b.lower_bound[i]) / 2.0); decimal_t center_a = aabb_a.lower_bound[i] + half_len_a; decimal_t center_b = aabb_b.lower_bound[i] + half_len_b; decimal_t len_c = fabs(center_a - center_b); // ~ Seperated or Contained if (fabs(half_len_a + half_len_b) <= len_c || fabs(half_len_a - half_len_b) >= len_c) { return false; } return true; }; /** * @brief * @notice This function only check on dim collision * * @tparam T * @tparam N_DIM * @param aabb_a * @param aabb_b * @param i * @return true * @return false */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeNdCollideOnOneDim(const AxisAlignedCubeNd<T, N_DIM>& aabb_a, const AxisAlignedCubeNd<T, N_DIM>& aabb_b, const int& i) { decimal_t half_len_a = fabs(static_cast<double>(aabb_a.upper_bound[i] - aabb_a.lower_bound[i]) / 2.0); decimal_t half_len_b = fabs(static_cast<double>(aabb_b.upper_bound[i] - aabb_b.lower_bound[i]) / 2.0); decimal_t center_a = aabb_a.lower_bound[i] + half_len_a; decimal_t center_b = aabb_b.lower_bound[i] + half_len_b; decimal_t len_c = fabs(center_a - center_b); // ~ Seperated or Contained if (fabs(half_len_a + half_len_b) <= len_c) { return false; } return true; }; }; // class ShapeUtils } // namespace common #endif //_COMMON_INC_COMMON_BASICS_SHAPES_H__
true
69ce80d92e424210ca8895555de4f8cb1e5df1cb
C++
rafalh26/Cpp
/FunctionFun1/FunctionFun1/main.cpp
WINDOWS-1250
311
3.0625
3
[]
no_license
#include <iostream> #include <string> using namespace std; void printMyName(); void printSomething(); int main() { printMyName(); printSomething(); return 0; } void printMyName() { string name = "Rafa\n"; cout << name << endl; } void printSomething() { cout<< "Hey! Look Im here"<<endl; }
true
41de4d73f6297225ac32c468ad1e5d33eb272107
C++
HexRabbit/ACMpractice
/uva10106.cpp
UTF-8
1,091
2.625
3
[]
no_license
#include <iostream> #include <cstdio> #include <vector> #include <string> using namespace std; int main(int argc, char const *argv[]) { vector<int> v1; vector<int> v2; vector<int> res; string s1; string s2; while(cin >> s1) { cin >> s2; v1.resize(0); v2.resize(0); res.resize(0); for (int i = 0; i < s1.length(); ++i) { v1.push_back(s1[s1.length()-i-1]-'0'); } for (int i = 0; i < s2.length(); ++i) { v2.push_back(s2[s2.length()-i-1]-'0'); } for (int i = 0; i < v2.size(); ++i) { for (int j = 0; j < v1.size(); ++j) { if (res.size()<i+j+1) res.push_back(0); res.at(i+j)+=v1.at(j)*v2.at(i); } } int carry=0; #ifdef DEBUG for(int i=0;i<res.size();i++) cout << res.at(i) << endl; #endif for (int i = 0; i < res.size(); ++i) { res.at(i)+=carry; carry = res.at(i)/10; res.at(i) %= 10; if (carry && i == res.size()-1) res.push_back(0); } #ifndef DEBUG if (res.at(res.size()-1)==0) { printf("0"); } else { for(int i=res.size()-1;i>=0;i--) { printf("%d", res.at(i)); } } printf("\n"); #endif } return 0; }
true
87df88fbc533025c9ed5a7a52a7d9cbbb24180d7
C++
CyberSet/Coursework_2nd_semestr
/Kurs/Kurs/class_Int.h
WINDOWS-1251
6,785
3.390625
3
[]
no_license
#include "class_block.h" #include "class_sl.h" #include <algorithm> #ifndef CLASS_INT_H #define CLASS_INT_H using namespace std; class Integer{ private: unsigned int size; // unsigned int digit;// () block* begin, *end, *ptr; // - begin , end public: Integer(block* int_begin, unsigned int int_digit) { size = 1; digit = int_digit; begin = int_begin; ptr = begin; while (!int_begin->isLast()) { int_begin = int_begin->getNext(); size++; } end = int_begin; } Integer(sl Int, unsigned int int_digit) { int unit = 0, i = Int.getSize(); digit = int_digit; char* temp = (char*)calloc(digit, digit * sizeof(char)); while (i > 0) { for (unit = 0; unit < digit; unit++) { if (Int.getRaw()[i - digit + unit] - '0' < 0 || Int.getRaw()[i - digit + unit] - '0' > 9) temp[unit] = '0'; else temp[unit] = Int.getRaw()[i - digit + unit]; } unit = atoi(temp); if (i == Int.getSize()) {// block* cur = new block(unit, NULL); ptr = cur; begin = cur; end = cur; } else { block* cur = new block(unit, ptr); ptr = cur; // if (i <= digit) end = cur;// } i -= digit; size++; } } const char* getRaw() { int junk = pow(10, digit - 1); int total = size * digit, i = 0; ptr = end; while (ptr->getUnit() < junk) { junk /= 10; total--; } if (total == 1) total = 2; char* temp = (char*)calloc(total, total * sizeof(char)); ptr = begin; while(total > 0){ if (ptr == end) for (i = 0; i < total; i++) temp[i] = fmod(ptr->getUnit() / pow(10, total - i - 1), 10) + '0'; else for (i = 0; i < digit; i++) temp[total - digit + i] = fmod(ptr->getUnit() / pow(10, digit - i - 1), 10) + '0'; // , total -= digit; if (ptr != end)ptr = ptr->getNext(); else break; } return temp; } void setBegin(block* int_begin) { begin = int_begin; } void setEnd(block* int_end) { end = int_end; } void setSize(unsigned int int_size) { size = int_size; } void incSize() { size++; } unsigned int getSize() { return size; } block* getBegin() { return begin; } block* getEnd() { return end; } unsigned int getDigit() { return digit; } void Sum(Integer* second) { int junk = pow(10, digit); ptr = begin; block* second_ptr = second->getBegin(); for (int i = size; i < second->getSize(); i++) { block* cur = new block(0, end); end = cur; size++; } while (true) { ptr->setUnit(ptr->getUnit() + second_ptr->getUnit()); if (ptr->getUnit() >= junk) { if (ptr->isLast()) { block* cur = new block(0, ptr); end = cur; size++; } ptr->getNext()->setUnit(ptr->getNext()->getUnit() + ptr->getUnit() / junk); ptr->setUnit(fmod(ptr->getUnit(), junk)); } if (second_ptr->isLast()) break; ptr = ptr->getNext(); second_ptr = second_ptr->getNext(); } ptr = begin; while (true) { if (ptr->getUnit() >= junk) { if (ptr->isLast()) { block* cur = new block(0, ptr); end = cur; size++; } ptr->getNext()->setUnit(ptr->getNext()->getUnit() + ptr->getUnit() / junk); ptr->setUnit(fmod(ptr->getUnit(), junk)); } if (ptr->isLast()) break; ptr = ptr->getNext(); } } void Sub(Integer* second) { int junk = pow(10, digit); ptr = begin; block* second_ptr = second->getBegin(); while (true) { if (ptr->getUnit() < second_ptr->getUnit()) { block* temp = ptr->getNext(); while (temp->getUnit() == 0) temp = temp->getNext(); while (temp != ptr) { temp->setUnit(temp->getUnit() - 1); temp->getPrev()->setUnit(temp->getPrev()->getUnit() + junk); temp = temp->getPrev(); } } ptr->setUnit(ptr->getUnit() - second_ptr->getUnit()); if (second_ptr->isLast()) break; ptr = ptr->getNext(); second_ptr = second_ptr->getNext(); } ptr = end; while (!ptr->isHead() && ptr->getUnit() == 0) { ptr = ptr->getPrev(); end = ptr; size--; } } void Mul(Integer* second) { sl temp("0"); Integer res(temp, digit); int junk = pow(10, digit); ptr = begin; block* res_ptr = res.getBegin(); block* second_ptr = second->getBegin(); block* back_ptr = res_ptr; // , while (true) { res_ptr = back_ptr; ptr = begin; while (true) { res_ptr->setUnit(res_ptr->getUnit() + ptr->getUnit() * second_ptr->getUnit()); if (res_ptr->getUnit() >= junk) { if (res_ptr->isLast()) { block* cur = new block(0, res_ptr); res.setEnd(cur); res.incSize(); } res_ptr->getNext()->setUnit(res_ptr->getNext()->getUnit() + res_ptr->getUnit() / junk); res_ptr->setUnit(fmod(res_ptr->getUnit(), junk)); } if (ptr->isLast()) break; ptr = ptr->getNext(); if (res_ptr->isLast()) { block* cur = new block(0, res_ptr); res.setEnd(cur); res.incSize(); } res_ptr = res_ptr->getNext(); } back_ptr = back_ptr->getNext(); if(second_ptr->isLast()) break; second_ptr = second_ptr->getNext(); } size = res.getSize(); digit = res.getDigit(); begin = res.getBegin(); ptr = begin; end = res.getEnd(); } void Div(Integer* second) { sl temp("0"); Integer res(temp, digit); temp = "1"; Integer one(temp, digit); ptr = end; block* second_ptr = second->getEnd(); bool flag = false; while (!flag) { ptr = end; second_ptr = second->getEnd(); Sub(second); res.Sum(&one); if (size < second->getSize()) flag = true; if (size == second->getSize()) { while (!flag) { if (ptr->getUnit() < second_ptr->getUnit()) { flag = true; break; } else { if (ptr->getUnit() > second_ptr->getUnit()) break; } if (ptr->isHead()) break; ptr = ptr->getPrev(); second_ptr = second_ptr->getPrev(); } } } size = res.getSize(); digit = res.getDigit(); begin = res.getBegin(); ptr = begin; end = res.getEnd(); } bool isEqual(Integer* second) { if (size != second->getSize()) return false; block* second_ptr = second->getBegin(); ptr = begin; while (!ptr->isLast()) { if (ptr->getUnit() != second_ptr->getUnit()) { return false; break; } ptr = ptr->getNext(); second_ptr = second_ptr->getNext(); } return true; } }; #endif
true
3f4cbf62258ad2a6a247e66243efd44a2d359eb3
C++
dat1209/php
/lap trinh huong doi tuong/to_mau_2/main.cpp
UTF-8
507
3.0625
3
[]
no_license
#include <graphics.h> using namespace std; void to_mau(int xa, int ya, int xb, int yb, int xc, int yc, int xd, int yd, int color) { int ymax =yc, ymin=ya; int y=ymin; for(y; y<=ymax; y++) { int xm1 = ((xd-xa)/(ymax-ymin))*(y-ymin)+xa; int xm2 = ((xb-xc)/(ymax-ymin))*(y-ymin)+xb; for(xm1; xm1<=xm2; xm1++) { putpixel(xm1,y,color); } } } int main() { initwindow(480,720); to_mau(20,20,90,20,40,70,60,70,60); getch(); }
true
31298591da0ba29b8ded0c45638dd0276efeebd4
C++
ImMahbus/CpAlgo
/Binary_Exponentiation/Binary_exponentiation.cpp
UTF-8
1,578
3.609375
4
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ll; class BinaryExponentiation { public: ll binaryExpRec(ll base, ll exp); //using recursion O(log(n)) (Fast but uses extra space in stack) ll binaryExpIter(ll base, ll exp); // iterative solution O(log(n)) (fastest among all of the above method) ll binaryExpMod(ll base, ll exp, ll m); // same as above function with mod ll binaryExpPrimeMod(ll base, ll exp, ll m); // if m is prime, x^(exp) and x^(exp mod (m-1)) is same using fermat theoram // best way to calculate Mod if m is prime }; ll BinaryExponentiation::binaryExpRec(ll base, ll exp) { if (exp == 0) return 1; ll result = binaryExpRec(base, exp / 2); if (exp % 2 == 1) result = result * result * base; else result = result * result; return result; } ll BinaryExponentiation::binaryExpIter(ll base, ll exp) { ll result = 1; while (exp > 0) { if (exp % 2 == 1) { result = result * base; } base = base * base; exp = exp / 2; } return result; } ll BinaryExponentiation::binaryExpMod(ll base, ll exp, ll m) { base = base % m; ll result = 1; while (exp > 0) { if (exp % 2 == 1) { result = result * base % m; } base = base * base % m; exp = exp / 2; } return result; } ll BinaryExponentiation::binaryExpPrimeMod(ll base, ll exp, ll m) { exp = exp % (m - 1); return binaryExpMod(base, exp, m); }
true
b7b87e15f2f08d42706c82cd174f9cfa0aa2405f
C++
meysam81/flight-console-app
/finalproject/date.cpp
UTF-8
870
3.21875
3
[]
no_license
#include "date.h" using namespace std; date::date() { year = ""; month = ""; day = ""; } string date::set_year() { cout << "Enter Year " << endl; cin >> year; return "\0"; } string date::set_month() { cout << "Enter Month " << endl; cin >> month; return "\0"; } string date::set_day() { cout << "Enter Day " << endl; cin >> day; return "\0"; } void date::get_date() { cout << year << "/" << month << "/" << day << endl; } string date::get_year() { return year; } string date::get_month() { return month; } string date::get_day() { return day; } istream &operator >>(istream &input, date &data) { return input >> data.day >> data.month >> data.year; } ostream &operator <<(ostream &output, const date &data) { return output << data.day << " " << data.month << " " << data.year << endl; }
true
4befdf62adf44ebd58f0c1780b1f5cb1286ce726
C++
HaakenJ/Data-Structures
/sessions/Session6.Rectangle-Template/Rectangle.h
UTF-8
1,488
3.875
4
[]
no_license
// // Created by Kevin Lundeen on 10/15/20. // #pragma once /** * Rectangle class * * @tparam T the datatype of the rectangle dimensions */ template<typename T> class Rectangle { public: Rectangle(); Rectangle(T width, T length); Rectangle(const Rectangle<T> &other); Rectangle<T> &operator=(const Rectangle<T> &rhs); void setWidth(T newWidth); void setLength(T newLength); T getWidth() const; T getLength() const; T getArea() const; private: T width, length; }; template<typename T> Rectangle<T>::Rectangle(const Rectangle<T> &other) { width = other.width; length = other.length; } template<typename T> Rectangle<T> &Rectangle<T>::operator=(const Rectangle<T> &rhs) { if (&rhs != this) { // no destruction necessary width = rhs.width; length = rhs.length; } return *this; } template<typename T> Rectangle<T>::Rectangle() { width = 0; length = 0; } template<typename T> Rectangle<T>::Rectangle(T width, T length) { this->width = width; this->length = length; } template<typename T> T Rectangle<T>::getWidth() const { return width; } template<typename T> T Rectangle<T>::getLength() const { return length; } template<typename T> void Rectangle<T>::setWidth(T newWidth) { width = newWidth; } template<typename T> void Rectangle<T>::setLength(T newLength) { length = newLength; } template<typename T> T Rectangle<T>::getArea() const { return width * length; }
true
7470370eb7a280548b9eea7d875a8fe4bd3b927b
C++
1092772959/My-ACM-code
/模板/图论模板/最小生成树-kruskal.cpp
UTF-8
874
2.625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int maxn=30; const int maxm=100+10; struct Edge{ int u,v,dist; bool operator<(const Edge &rhs)const{return dist<rhs.dist;} }; struct Kruskal{ int n,m; Edge edges[maxm]; int fa[maxn]; int findset(int x){ return fa[x]==-1?x:fa[x]=findset(fa[x]); } void init(int n){ this->n=n; m=0; memset(fa,-1,sizeof(fa)); } void AddEdge(int u,int v,int dist){ edges[m++]=Edge{u,v,dist}; } int kruskal(){ int sum=0,cnt=0; sort(edges,edges+m); for(int i=0;i<m;i++){ int u=edges[i].u, v=edges[i].v; if(findset(u) != findset(v)){ sum +=edges[i].dist; fa[findset(u)] = findset(v); if(++cnt>=n-1) return sum; } } return -1; } }G;
true
4295e7da67f504c95df12bf7e43a74d5941865ac
C++
aiekick/engine
/src/modules/ai/server/IProtocolHandler.h
UTF-8
1,214
2.953125
3
[]
no_license
/** * @file */ #pragma once #include <memory> #include "IProtocolMessage.h" #include "common/Types.h" namespace ai { typedef uint8_t ClientId; /** * @brief Interface for the execution of assigned IProtocolMessage * * @note Register handler implementations at the @c ProtocolHandlerRegistry */ class IProtocolHandler { public: virtual ~IProtocolHandler() { } virtual void execute(const ClientId& clientId, const IProtocolMessage& message) = 0; }; template<class T> class ProtocolHandler : public IProtocolHandler { public: virtual ~ProtocolHandler () { } void execute (const ClientId& clientId, const IProtocolMessage& message) override { const T *msg = ai_assert_cast<const T*>(&message); execute(clientId, msg); } virtual void execute (const ClientId& clientId, const T* message) = 0; }; class NopHandler: public IProtocolHandler { public: void execute(const ClientId& /*clientId*/, const IProtocolMessage& /*message*/) override { } }; typedef std::shared_ptr<IProtocolHandler> ProtocolHandlerPtr; /** * @brief Use this deleter for any handler that should not get freed by @c delete. */ struct ProtocolHandlerNopDeleter { void operator()(IProtocolHandler* /* ptr */) { } }; }
true
809d977d2f855a306cc9d0830ef649aa4fb6fcc2
C++
ArtiomTr/Game
/TPPEngine/Tpp_Rect.h
UTF-8
1,133
3
3
[ "MIT" ]
permissive
#pragma once #include "Tpp_Vector2.h" namespace tp { template <typename T> class Rect { private: T width; T height; Vector2<T> position; Vector2<T> pivot; public: Rect(T width, T height) : width(width), height(height), position(Vector2<T>::zero()), pivot(Vector2<T>(width / (T) 2, height / (T) 2)) { } Rect(T width, T height, Vector2<T> position) : width(width), height(height), position(position), pivot(Vector2<T>(width / (T) 2, height / (T) 2)) { } Rect(T width, T height, Vector2<T> position, Vector2<T> privot) : width(width), height(height), position(position), pivot(pivot) { } virtual Vector2<T> getPosition() { return position; } virtual Vector2<T> getPivot() { return pivot; } virtual void setPosition(Vector2<T> newPosition) { position = newPosition; } virtual void setPivot(Vector2<T> newPivot) { pivot = newPivot; } virtual void setWidth(T newWidth) { width = newWidth; } virtual void setHeight(T newHeight) { height = newHeight; } virtual T getWidth() { return width; } virtual T getHeight() { return height; } }; }
true
0fa7b93886c53b250a1ee4209ed0c0012fad1d66
C++
RomainJaminet/Neural-Network
/Neuron/main.cpp
UTF-8
324
2.515625
3
[]
no_license
#include "neuron.hpp" #include <iostream> using namespace std; int main () { Neuron * n1 = new Neuron(); Neuron * n2 = new Neuron(); vector<Neuron*> c; c.push_back(n1); c.push_back(n2); Neuron * n3 = new Neuron(c); cout << n3->getJson() << endl; Neuron * test = new Neuron(n3->getJson(),c); return 0; }
true
7a3788e482de5e993b102abbf1be8beb8b49f36d
C++
albert-zhao/my_live555
/include/delaytimeval.hh
UTF-8
1,461
2.953125
3
[]
no_license
#ifndef _DELAY_TIMEVAL_HH #define _DELAY_TIMEVAL_HH #include "timevalue.hh" using namespace std; class DelayTimeVal: public TimeVal { public: DelayTimeVal(const struct timeval &t) :TimeVal(t) { cout << "DelayTimeVal(struct timeval &t) init" << endl; } DelayTimeVal(int sec, int usec) :TimeVal(sec, usec) { cout << "DelayTimeVal(int sec, int usec) init\n" << endl; } DelayTimeVal() : TimeVal() { cout << "DelayTimeVal() init finished\n" << endl; } DelayTimeVal(const DelayTimeVal &val): TimeVal(val) { cout << "DelayTimeVal(const DelayTimeVal &val) init\n" << endl; } DelayTimeVal operator-(const DelayTimeVal & val) { //cout << "DelayTimeVal operator-(const DelayTimeVal & val) 0" << endl; TimeVal &a = *this; ////TimeVal result = (*this) - val; error, will recursive call itself TimeVal result = a - val; //cout << "DelayTimeVal operator-(const DelayTimeVal & val)" << endl; return DelayTimeVal(result.getValue()); } /** =, - , == != need to deal **/ // bool operator==(const DelayTimeVal &val) { // TimeVal &tv = *this; // return tv == val; // } // bool operator!=(const DelayTimeVal &val) { // return !(*this == val); // } /* = use default copy assignemt function */ // DelayTimeVal & operator=(const DelayTimeVal &delaytv); }; #endif
true
fc918551c9024e819aaf8f437bc365d7c2f3a384
C++
tmguvenc/tools
/facecropper/src/facefinder.cpp
UTF-8
3,829
2.71875
3
[]
no_license
#include <facefinder.h> #include <common.h> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; FaceFinder::FaceFinder(FaceFinder::Queue *queue) : m_queue(queue), m_classifier(new cv::CascadeClassifier), m_image_index(0) { } FaceFinder::~FaceFinder() { if(m_classifier){ delete m_classifier; m_classifier = nullptr; } } void FaceFinder::run(const std::vector<std::string> &files) { if(!m_classifier->load("/home/turanmurat/opencv/data/haarcascades/haarcascade_frontalface_alt.xml")) { throw FileNotFoundException(); } for(const auto& file : files){ std::cout << "processing " << file << " ... " << std::flush; switch (get_fileType(file)) { case FileType::Video: process_video_file(file); break; case FileType::Image: process_image_file(file); default: break; } std::cout << "done" << std::endl; } m_queue->push(nullptr); std::cout << "processing done!\n"; } void FaceFinder::run(const std::string &camera_url) { if(!m_classifier->load("/home/turanmurat/opencv/data/haarcascades/haarcascade_frontalface_alt.xml")) { throw FileNotFoundException(); } std::cout << "processing " << camera_url << " ... " << std::flush; process_video_file(camera_url); std::cout << "done" << std::endl; m_queue->push(nullptr); std::cout << "processing done!\n"; } std::vector<std::shared_ptr<cv::Mat>> FaceFinder::find_face(const cv::Mat &image) { std::vector<std::shared_ptr<cv::Mat>> face_images; std::vector<cv::Rect> faces; std::vector<int> reject_levels; std::vector<double> levelWeights; cv::Mat gray; cv::cvtColor(image, gray, CV_BGR2GRAY); m_classifier->detectMultiScale(image, faces, reject_levels, levelWeights, 1.2, 5, cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30), cv::Size(), true); for(const auto& face : faces){ auto expanded_face = expandRect(face, 1.8f); auto croppedImage = std::make_shared<cv::Mat>(); cv::getRectSubPix(image, {expanded_face.width, expanded_face.height}, {expanded_face.x + expanded_face.width/2, expanded_face.y + expanded_face.height/2}, *croppedImage); face_images.push_back(croppedImage); } return std::move(face_images); } void FaceFinder::process_video_file(const std::string &file) { cv::VideoCapture capture(file); if(!capture.isOpened()){ std::cerr << "cannot open " << file << std::endl; return; } auto video_file_name = extractVideoFileName(file); cv::Mat frame; uint32_t frame_index = 0; while(true){ capture >> frame; if(frame.empty()) break; if(frame_index++ % 25 == 0){ for(auto& face : find_face(frame)){ m_queue->push(std::make_shared<CroppedImage>(std::forward<std::shared_ptr<cv::Mat>>(face), file, video_file_name, ++m_image_index)); } } cv::waitKey(1); } capture.release(); } void FaceFinder::process_image_file(const std::string &file) { auto frame = cv::imread(file); if(!frame.empty()){ for(auto& face : find_face(frame)){ m_queue->push(std::make_shared<CroppedImage>(std::forward<std::shared_ptr<cv::Mat>>(face), file, "from_photos", ++m_image_index)); } }else{ std::cerr << "cannot read " << file << std::endl; } } FileType FaceFinder::get_fileType(const std::string& fileName) { const auto& ext = fs::extension(fileName); return (ext == ".avi" || ext == ".mp4" || ext == ".mkv") ? FileType::Video : (ext == ".jpg" || ext == ".bmp" || ext == ".png" || ext == ".jpeg") ? FileType::Image : FileType::Other; }
true
33d94e3b6566ea027fdab0a07f3bcc6d170bd209
C++
shruti-nahar14/C-PlusPlus
/for loop hackerrank.cpp
UTF-8
554
3.546875
4
[]
no_license
///////////////////////////////////// /*Input: 2 7 *Output: two three four five six seven *Description:Display the number with spelling from n1 to n2 range *Date: 4-June-2021 *Author: Shruti Nahar*/ ///////////////////////////////////////// #include<iostream> using namespace std; int main() { int a,b; string c[]={"","one","two","three","four","five","six","seven","eight","nine"}; cout<<"Enter the range of numbers: "; cin>>a>>b; for(int i=a;i<=b;i++) cout<<((i<=9)?c[i]:((i%2==0)?"even":"odd"))<<endl; }
true
11080a3157f0e56da82f7bcd5663c1d0aa1c0585
C++
devanfarrell/NifflerTM
/source/Tape.cpp
UTF-8
1,819
3.65625
4
[]
no_license
#include "Tape.hpp" #include <string> #include <iostream> Tape::Tape() { cells = ""; currentCell = 0; } void Tape::initialize(std::string inputString) { cells = inputString; currentCell = 0; } void Tape::update(char writeCharacter, const char moveDirection) { cells[currentCell] = writeCharacter; if (moveDirection == 'r' || moveDirection == 'R') { currentCell++; } else currentCell--; } char Tape::readCharacter() { char ret_char = cells[currentCell]; return ret_char; } bool Tape::isFirstCell() { bool isFirstCell = false; if (currentCell == 0) isFirstCell = true; return isFirstCell; } bool Tape::isLastCell() { bool isLastCell = false; if (currentCell == cells.length() - 1) isLastCell = true; return isLastCell; } void Tape::appendBlank(char blankCharacter) { std::string temp(" "); temp = blankCharacter; cells += temp; } std::string Tape::left(int maxCellsNumber) { long beginningCell = 0; if (0 < currentCell - maxCellsNumber) { beginningCell = currentCell - maxCellsNumber; } std::string leftString = cells.substr(beginningCell, currentCell - beginningCell); if (leftString.length() < currentCell) { leftString.insert(0, "<"); } return leftString; } std::string Tape::right(int maxCellsNumber, char blankCharacter) { long endCell = cells.length(); endCell--; while ((endCell >= currentCell) && (cells[endCell] == blankCharacter)) { --endCell; } long lastCell = 0; if (endCell < currentCell + maxCellsNumber) { lastCell = endCell; } else lastCell = currentCell + maxCellsNumber; std::string rightString = cells.substr(currentCell, lastCell - currentCell + 1); if (rightString.length() < endCell - currentCell + 1) { rightString.append(">"); } return rightString; }
true
0fc63afd2549230bd2770bf64e85a79c3e6b0662
C++
wokulski48/personalBudget
/ExpenseManager.h
UTF-8
610
2.6875
3
[]
no_license
#ifndef EXPENSEMANAGER_H #define EXPENSEMANAGER_H #include "Expense.h" #include "FileWithExpenses.h" #include "AuxiliaryMethods.h" #include "DateOperationMethods.h" using namespace std; class ExpenseManager { vector <Expense> expenses; FileWithExpenses fileWithExpenses; public: ExpenseManager(string nameOfFileWithExpenses, int loggedInUserId) : fileWithExpenses(nameOfFileWithExpenses, loggedInUserId) { expenses = fileWithExpenses.loadExpensesFromFile(); } void clearUserExpenses(); void addExpense(int loggedInUserId); vector <Expense> getExpenses(); }; #endif
true
f24d048cca3b7ff5a82697648587dfce25e31ebb
C++
felixjones/SDL-GL
/include/FileSystem.h
UTF-8
3,329
2.640625
3
[ "MIT" ]
permissive
#ifndef __FILE_SYSTEM_H__ #define __FILE_SYSTEM_H__ #include <stdint.h> #include "ReadFile.h" #include "WriteFile.h" #include "FileList.h" #define DIRECTORY_LEN ( 240 ) class xiFileArchive; class xiArchiveLoader; class xiFileSystem { public: enum deleteType_e { DELETE_WHEN_DROPPED, DELETE_NEVER }; enum extensionHandler_e { EXTENSION_REMOVE, EXTENSION_KEEP }; static xiFileSystem * Get(); void Retain(); void Release(); xiReadFile * CreateAndOpenFile( const char * const fileName ); xiReadFile * CreateMemoryReadFile( void * const memory, const size_t len, const char * const fileName, const deleteType_e deleteType = DELETE_NEVER ); xiReadFile * CreateLimitReadFile( const char * const fileName, xiReadFile * const alreadyOpenedFile, const size_t pos, const size_t areaSize ); xiWriteFile * CreateMemoryWriteFile( void * const memory, const size_t len, const char * const fileName, const deleteType_e deleteType = DELETE_NEVER ); xiWriteFile * CreateAndWriteFile( const char * const fileName, const xiWriteFile::writeMode_e writeMode = xiWriteFile::WRITE_OVER ); bool AddArchiveFile( const char * const fileName, const xiFileList::ignoreParam_e ignoreMask = xiFileList::IGNORE_NONE, xiFileArchive ** const outArchive = nullptr ); bool AddArchiveReadFile( xiReadFile * const readFile, const xiFileList::ignoreParam_e ignoreMask = xiFileList::IGNORE_NONE, xiFileArchive ** const outArchive = nullptr ); bool AddArchive( xiFileArchive * const archive ); bool MoveArchive( const size_t sourceIndex, const int32_t relative ); void AddArchiveLoader( xiArchiveLoader * const loader ); size_t GetArchiveLoaderCount() const; xiArchiveLoader * GetArchiveLoader( const size_t index ) const; size_t GetArchiveCount() const; xiFileArchive * GetArchive( const size_t index ) const; bool RemoveArchiveAtIndex( const size_t index ); bool RemoveArchiveFile( const char * const fileName ); bool RemoveArchive( const xiFileArchive * const archive ); const char * GetWorkingDirectory(); bool ChangeWorkingDirectoryTo( const char * const newDirectory ); void GetAbsolutePath( char * const dest, const char * const source ) const; void GetFileDirectory( char * const dest, const char * const fileName ) const; void GetFileBasename( char * const dest, const char * const fileName, const extensionHandler_e extHandler = EXTENSION_KEEP ) const; void GetFlatFilename( char * const dest, const char * const directory, const char * const root = "/" ) const; xiFileList * CreateFileList(); xiFileList * CreateEmptyFileList( const char * const path, const xiFileList::ignoreParam_e ignoreMask ); bool DoesFileExist( const char * const fileName ) const; protected: xiFileSystem(); virtual ~xiFileSystem(); private: void ArchiveLoader_PushBack( xiArchiveLoader * const loader ); void FileArchives_PushBack( xiFileArchive * const archive ); void FileArchives_EraseAtIndex( const size_t index ); char workingDirectory[DIRECTORY_LEN]; struct archiveLoader_s { xiArchiveLoader ** archiveLoaders; size_t archiveLoadersLen; } archiveLoader; struct archive_s { xiFileArchive ** archives; size_t archivesLen; } fileArchives; static xiFileSystem * singleton; static int32_t references; }; #endif
true
6c6a22486dbad256af0c881a181828b17e0dd6d0
C++
HelenEgorova/SAKOD
/Record.h
WINDOWS-1251
1,003
3.015625
3
[]
no_license
#pragma once #include <string> using namespace std; // class Record { private: // : , , , , string date; int receiveHours; int receiveMinutes; int returnHours; int returnMinutes; int itemIndex; string customerName; public: // Record(string date1, int receiveHours1, int receiveMinutes1, int returnHours1, int returnMinutes1, string name, int item); // get string getDate(); string getReceiveTime(); string getReturnTime(); string getCustomerName(); int getItemIndex(); // , int getCost(); // string toString(); };
true
ad553787b31dcbd66bf66c109282f5d96d365b7a
C++
cyy1991/abcranger
/src/various.hpp
UTF-8
2,690
2.640625
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <memory> #include <iostream> #include <iomanip> #include <queue> #include <deque> #include <chrono> #include "utility.h" static constexpr std::size_t operator"" _z(unsigned long long n) { return n; } static auto sz = 5_z; static_assert(std::is_same<decltype(sz), std::size_t>::value, ""); static std::vector<double> DEFAULT_SAMPLE_FRACTION = std::vector<double>({1}); template <class T_SRC, class T_DEST> std::unique_ptr<T_DEST> unique_cast(std::unique_ptr<T_SRC> &&src) { if (!src) return std::unique_ptr<T_DEST>(); // Throws a std::bad_cast() if this doesn't work out T_DEST *dest_ptr = &dynamic_cast<T_DEST &>(*src.get()); src.release(); std::unique_ptr<T_DEST> ret(dest_ptr); return ret; } using std::chrono::steady_clock; using std::chrono::duration_cast; using std::chrono::seconds; using std::chrono::microseconds; static steady_clock::time_point last_time;; static std::deque<microseconds> intervals; static size_t etamaxwidth; static inline void initbar() { etamaxwidth = 0; intervals = std::deque<microseconds>(); last_time = steady_clock::now(); } static inline void loadbar(size_t x, size_t n, size_t w = 50) { if ((x != n) && (x % (n / 100 + 1) != 0)) return; size_t width = (std::to_string(n)).length(); steady_clock::time_point temp_time = steady_clock::now(); microseconds elapsed_time = duration_cast<microseconds>(temp_time - last_time); if (intervals.size() == 10) { intervals.pop_front(); } intervals.push_back(elapsed_time); float ratio = x / (float)n; int c = ratio * w; size_t total = 0; for(auto& e : intervals) total += e.count(); float mean = static_cast<float>(total)/static_cast<float>(intervals.size()); size_t remaining_time = std::floor(mean * static_cast<float>(n-x)/1e6); std::string eta = ranger::beautifyTime(remaining_time); size_t etalength = eta.length(); if ((intervals.size() == 10) && (etalength > etamaxwidth)) etamaxwidth = etalength; std::string itsec = std::to_string(1e6/mean); std::cout << " ["; for (auto x = 0; x < c; x++) std::cout << "="; for (auto x = c; x < w; x++) std::cout << " "; std::cout << "] (" << std::setw(width) << x << "/" << std::setw(width) << n << ") "; std::cout << " " << std::setw(5) << std::fixed << std::setprecision(1) << 1e6/mean << " it/sec"; if (intervals.size() == 10) std::cout << ", ETA : " << std::setw(etamaxwidth) << eta; std::cout << "\r" << std::flush; last_time = temp_time; }
true
a5aaa0bbc8481ca4d46b2d1edbe00fec1182dced
C++
arturstaszczyk/mosaiker
/MosaikerLib/FileSystemOps/FileChooser.cpp
UTF-8
624
2.640625
3
[]
no_license
#include "FileChooser.h" #include <QDebug> #include <QFileDialog> FileChooser::FileChooser(QObject* parent) : QObject(parent) { } QString FileChooser::chooseFile(OperationType operationType) { switch(operationType) { case OT_OPEN: return QFileDialog::getOpenFileName(); case OT_WRITE: return QFileDialog::getSaveFileName(); } } QString FileChooser::chooseDir() { QString dirName = ""; try { dirName = QFileDialog::getExistingDirectory(); } catch(std::exception& ex) { qDebug() << ex.what(); } return dirName; }
true
77c4c3e7c3fa4ff7bcb8b7a08af8381540ef30a8
C++
dna10101/FiveInARow
/Calculator/ChessBoard.cpp
GB18030
5,158
3.0625
3
[]
no_license
#include "stdafx.h" #include "ChessBoard.h" #define FIVE 100000 #define ALIVE4 50000 #define DIE4A 250 #define DIE4B 300 #define DIE4C 260 #define ALIVE3 300 #define jALIVE3 200 #define DIE3A 50 #define DIE3B 80 #define DIE3C 60 #define DIE3D 55 #define DIE3E 45 #define DIE3F 20 #define ALIVE2 65 #define OTHER 10 ChessBoard::ChessBoard(int N,int five) { this->width = N; this->five = five; this->board = new char*[N](); for (int i = 0; i < N; i++) { this->board[i] = new char[N](); } } ChessBoard::~ChessBoard() { for (int i = 0; i < this->width; i++) { delete[]this->board[i]; } delete[]this->board; } boolean ChessBoard::Judge(int cx, int cy, Player * p) { int left = 0, right = 0; char currentChar = this->board[cx][cy]; int x = cx,y=cy; // while (--x>= 0) { if (this->board[x][y] == currentChar) { left++; } else { break; } } x = cx; while (++x < this->width) { if (this->board[x][y] == currentChar) { right++; } else { break; } } if (right + left + 1 >= this->five) { return 1; } // Խ '\' left = right = 0; x = cx; y = cy; while ((--x)>= 0 && (++y) < this->width) { if (this->board[x][y] == currentChar) { left++; } else { break; } } x = cx; y = cy; while ((++x < this->width) && (--y>=0)) { if (this->board[x][y] == currentChar) { right++; } else { break; } } if (right + left + 1 >= this->five) { return 1; } // | left = right = 0; x = cx; y = cy; while ((--y) >= 0) { if (this->board[x][y] == currentChar) { left++; } else { break; } } y = cy; while ((++y) <= this->width) { if (this->board[x][y] == currentChar) { right++; } else { break; } } if (left + right + 1 >= this->five) { return 1; } //Խ / left = right = 0; x = cx; y = cy; while ((--x)>= 0 && (--y)>=0) { if (this->board[x][y] == currentChar) { left++; } else { break; } } x = cx; y = cy; while ((++x <this->width) && (++y <this->width)) { if (this->board[x][y] == currentChar) { right++; } else { break; } } if (right + left + 1 >= this->five) { return 1; } return 0; } boolean ChessBoard::SetChess(int x, int y, Player *p) { if (x < 0 || y < 0 || x >= this->width || y >=this->width) return false; if (this->board[x][y] == 0) { this->board[x][y] = p->GetName(); this->step++; return true; } return false; } char ChessBoard::GetChess(int x, int y) { if (x<0 || x>this->width || y<0 || y>this->width) return -1; return this->board[x][y]; } void ChessBoard::CLeanChessBoard() { for (int i = 0; i < this->width; i++) { for (int j = 0; j < this->width; j++) this->board[i][j] = 0; } } int ChessBoard::GetScore(int X, int Y, Player * p) { int maxScore; int count; int left = 0, right = 0; int x = X; int y = Y; // while (--x>=0) { if (this->board[x][y] == p->GetName()) { left++; } else { break; } } x = X; while (++x < this->width) { if (this->board[x][y] == p->GetName()) { right++; } else { break; } } x = X; count = left + right + 1; switch (count) { case 4: maxScore = ALIVE4; break; case 3: maxScore = ALIVE3; break; case 2: maxScore = ALIVE2; break; case 1: maxScore = OTHER; break; default: maxScore = FIVE; break; } left = right = 0; // while (--y>=0) { if (this->board[x][y] == p->GetName()) { left++; } else { break; } } y = Y; while (++y <this->width) { if (this->board[x][y] == p->GetName()) { right++; } else { break; } } y = Y; count = left + right + 1; switch (count) { case 4: maxScore += ALIVE4; break; case 3: maxScore += ALIVE3; break; case 2: maxScore += ALIVE2; break; case 1: maxScore += OTHER; break; default: maxScore += FIVE; break; } left = right = 0; //б\* while (--x>=0 && --y>=0) { if (this->board[x][y] == p->GetName()) { left++; } else { break; } } x = X; y = Y; while (++x <this->width && ++y <this->width) { if (this->board[x][y] == p->GetName()) { right++; } else { break; } } x = X; y = Y; count = left + right + 1; switch (count) { case 4: maxScore += ALIVE4; break; case 3: maxScore += ALIVE3; break; case 2: maxScore += ALIVE2; break; case 1: maxScore += OTHER; break; default: maxScore += FIVE; break; } // left = right = 0; //б/* while (++x <this->width && --y>=0) { if (this->board[x][y] == p->GetName()) { left++; } else { break; } } x = X; y = Y; while (--x > 0 && ++y <= this->width) { if (this->board[x][y] == p->GetName()) { right++; } else { break; } } x = X; y = Y; count = left + right + 1; switch (count) { case 4: maxScore += ALIVE4; break; case 3: maxScore += ALIVE3; break; case 2: maxScore += ALIVE2; break; case 1: maxScore += OTHER; break; default: maxScore += FIVE; break; } return maxScore; } int ChessBoard::GetWidth() { return this->width; }
true
e7e3680a11fc5aafdf47a31700e5a9c742cc2e78
C++
coder-e1adbc/CppPrimer
/chapter04/ex19.cpp
UTF-8
234
2.515625
3
[]
no_license
int *ptr; vector<int> vec; int ival; ptr != 0 && *ptr++ // ptr != 0 && *ptr != 0, ++ptr ival++ && ival // ival != 0 && ival != -1 vec[ival++] <= vec[ival] // warning: undefined // vec[ival] <= vec[ival + 1], ++ival
true
15809fb4fe9d4505c0b7e2692d6d84e201287e66
C++
brandtamos/arduino-binary-clock
/sketch_apr01a/sketch_apr01a.ino
UTF-8
4,415
2.796875
3
[]
no_license
/* Binary clock */ //#include <math.h> //M0 pins //these uses the analog input pins because we need //pins 2 and 3 for interupts! const int M0_BIT0_PIN = A0; const int M0_BIT1_PIN = A1; const int M0_BIT2_PIN = A2; const int M0_BIT3_PIN = A3; //M1 pins const int M1_BIT0_PIN = 4; const int M1_BIT1_PIN = 5; const int M1_BIT2_PIN = 6; //H0 pins const int H0_BIT0_PIN = 7; const int H0_BIT1_PIN = 8; const int H0_BIT2_PIN = 9; const int H0_BIT3_PIN = 10; //H1 pins const int H1_BIT0_PIN = 11; const int H1_BIT1_PIN = 12; //Second indicator const int SECOND_INDICATOR_PIN = 13; //interrupt pins (used for setting time) const int SET_MINUTE_INTERRUPT_PIN = 2; const int SET_HOUR_INTERRUPT_PIN = 3; const int DECOUNCE_WAIT_TIME_MS = 200; //value that holds referential total second value long gSecondValue = 0; //making these values global so the interrupt can modify them int gMinuteValue = 0; int gHourValue = 0; void setup() { //set led pins to output pinMode(M0_BIT0_PIN, OUTPUT); pinMode(M0_BIT1_PIN, OUTPUT); pinMode(M0_BIT2_PIN, OUTPUT); pinMode(M0_BIT3_PIN, OUTPUT); pinMode(M1_BIT0_PIN, OUTPUT); pinMode(M1_BIT1_PIN, OUTPUT); pinMode(M1_BIT2_PIN, OUTPUT); pinMode(H0_BIT0_PIN, OUTPUT); pinMode(H0_BIT1_PIN, OUTPUT); pinMode(H0_BIT2_PIN, OUTPUT); pinMode(H0_BIT3_PIN, OUTPUT); pinMode(H1_BIT0_PIN, OUTPUT); pinMode(H1_BIT1_PIN, OUTPUT); //setup interrupt pins pinMode(SET_MINUTE_INTERRUPT_PIN, INPUT_PULLUP); pinMode(SET_HOUR_INTERRUPT_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(SET_MINUTE_INTERRUPT_PIN), incrementMinuteValue, FALLING); attachInterrupt(digitalPinToInterrupt(SET_HOUR_INTERRUPT_PIN), incrementHourValue, FALLING); } void loop() { outputMinutes(); outputHours(); writeSecondIndicator(); tick(); delay(1000); } void outputMinutes(){ int m0Value = getM0Value(); int m1Value = getM1Value(); writeM0Value(m0Value); writeM1Value(m1Value); } void outputHours(){ int h0Value = getH0Value(); int h1Value = getH1Value(); writeH0Value(h0Value); writeH1Value(h1Value); } void writeM0Value(int m0Value){ digitalWrite(M0_BIT0_PIN, bitRead(m0Value, 0)); digitalWrite(M0_BIT1_PIN, bitRead(m0Value, 1)); digitalWrite(M0_BIT2_PIN, bitRead(m0Value, 2)); digitalWrite(M0_BIT3_PIN, bitRead(m0Value, 3)); } void writeM1Value(int m1Value){ digitalWrite(M1_BIT0_PIN, bitRead(m1Value, 0)); digitalWrite(M1_BIT1_PIN, bitRead(m1Value, 1)); digitalWrite(M1_BIT2_PIN, bitRead(m1Value, 2)); } void writeH0Value(int h0Value){ digitalWrite(H0_BIT0_PIN, bitRead(h0Value, 0)); digitalWrite(H0_BIT1_PIN, bitRead(h0Value, 1)); digitalWrite(H0_BIT2_PIN, bitRead(h0Value, 2)); digitalWrite(H0_BIT3_PIN, bitRead(h0Value, 3)); } void writeH1Value(int h1Value){ digitalWrite(H1_BIT0_PIN, bitRead(h1Value, 0)); digitalWrite(H1_BIT1_PIN, bitRead(h1Value, 1)); } void writeSecondIndicator(){ digitalWrite(SECOND_INDICATOR_PIN, bitRead(gSecondValue, 0)); } void tick(){ // there are 86,400 seconds in a day! gSecondValue = (gSecondValue + 1) % 86400; //gMinuteValue = (int)floor(gSecondValue / 60) % 60; //gHourValue = (int)floor(gSecondValue / 3600) % 24; if(gSecondValue % 60 == 0) incrementMinuteValue(); if(gSecondValue % 3600 == 0) incrementHourValue(); } int getM0Value(){ int minutes = gMinuteValue; return minutes % 10; } int getM1Value(){ int minutes = gMinuteValue; minutes = floor(minutes/10); //shift least significant number out return minutes % 10; } int getH0Value(){ int hours = gHourValue; return hours % 10; } int getH1Value(){ int hours = gHourValue; hours = floor(hours/10); return hours % 10; } void incrementMinuteValue(){ //used to debounce button press static unsigned long last_interrupt_time = 0; unsigned long interrupt_time = millis(); if (interrupt_time - last_interrupt_time > DECOUNCE_WAIT_TIME_MS) { //increment minute value and write out to LEDs gMinuteValue = (gMinuteValue + 1) % 60; outputMinutes(); } last_interrupt_time = interrupt_time; } void incrementHourValue(){ //used to debounce button press static unsigned long last_interrupt_time = 0; unsigned long interrupt_time = millis(); if (interrupt_time - last_interrupt_time > DECOUNCE_WAIT_TIME_MS) { //increment hour value and write to LEDs gHourValue = (gHourValue + 1) % 24; outputHours(); } last_interrupt_time = interrupt_time; }
true
90cf0f559f6f712c62404edb6669b39135de99bc
C++
sarthak815/DS_Manipal
/Lab/Lab3(Stacks)/q3.cpp
UTF-8
1,383
3.640625
4
[]
no_license
#include<iostream> #include <stdlib.h> using namespace std; const int N=5; const int Size=10; class nStacks{ private: int s[Size]={0}; int item; int stk; int top[N]; int bottom[N+1]; public: nStacks(){ for(int i=0,j=-1;i<N;i++,j+=Size/N){ top[i]=j; bottom[i]=j; } bottom[N]=Size-1; } void push(int,int); int pop(int); int peek(int); bool isfull(int); bool isEmpty(int); }; bool nStacks::isfull(int stk){ if(top[stk]+1==bottom[stk+1]){ return true; } return false; } bool nStacks::isEmpty(int stk){ if(top[stk]==bottom[stk]){ return true; } return false; } void nStacks::push(int item,int stk){ if(!(isfull(stk))){ s[++top[stk]]=item; } } int nStacks::pop(int stk){ if(!isEmpty(stk)){ return s[top[stk]--]; } return -1; } int nStacks::peek(int stk){ if(!isEmpty(stk)){ return s[top[stk]]; } return -1; } int main(){ nStacks S; S.push(1,0); S.push(2,1); S.push(3,2); S.push(4,3); S.push(5,4); cout<<S.peek(0)<<endl; cout<<S.peek(1)<<endl; cout<<S.peek(2)<<endl; cout<<S.peek(3)<<endl; cout<<S.peek(4)<<endl; }
true
6bbddeb6105cf04d5b666a2662f115f17f7d4e1b
C++
lucasandre22/cpp-mini-projects-and-studies
/ThreadsImpl/Thread.h
MacCentralEurope
1,224
3.0625
3
[]
no_license
#define HAVE_STRUCT_TIMESPEC #include <pthread.h> #include <iostream> #pragma once class Thread { private: pthread_t _threadID; pthread_attr_t _tAttribute; static pthread_mutex_t _mutex; static void* runThread(void* pThread) { Thread* aux = static_cast<Thread*>(pThread); try { aux->run(); } catch (...) { std::cout << "Erro ao executar a thread!"; } return NULL; } virtual void run() {} //metodo que executar public: Thread() {} virtual ~Thread() {} void join() { pthread_join(_threadID,NULL); } //espera thread acabar void yield() { sched_yield(); } //libera processador void start() { int status = pthread_attr_init(&_tAttribute); status = pthread_attr_setscope(&_tAttribute, PTHREAD_SCOPE_SYSTEM); status = pthread_create(&_threadID, &_tAttribute, Thread::runThread, (void*)(this)); status = pthread_attr_destroy(&_tAttribute); } void lock() { if (_mutex == NULL) pthread_mutex_init(&Thread::_mutex, NULL); pthread_mutex_lock(&Thread::_mutex); } void unlock() { if (Thread::_mutex != NULL) pthread_mutex_unlock(&Thread::_mutex); } //criaria uma superclasse derivada dessa e de outra, como chefo por exemplo }; pthread_mutex_t Thread::_mutex = NULL;
true
27c1d93720fd15e47fb686ad68fe9bbd65e468b9
C++
moh-C/microprocessorSmartWatch
/sevenSegment_counter.ino
UTF-8
3,772
2.859375
3
[]
no_license
int a = 9; int b = 10; int c = 13; int d = 12; int e = 11; int f = 6; int g = 8; void setup() { pinMode(a,OUTPUT); pinMode(b,OUTPUT); pinMode(c,OUTPUT); pinMode(d,OUTPUT); pinMode(e,OUTPUT); pinMode(f,OUTPUT); pinMode(g,OUTPUT); } void loop() { zero(a,b,c,d,e,f,g); delay(1000); one(a,b,c,d,e,f,g); delay(1000); two(a,b,c,d,e,f,g); delay(1000); three(a,b,c,d,e,f,g); delay(1000); four(a,b,c,d,e,f,g); delay(1000); five(a,b,c,d,e,f,g); delay(1000); six(a,b,c,d,e,f,g); delay(1000); seven(a,b,c,d,e,f,g); delay(1000); eight(a,b,c,d,e,f,g); delay(1000); nine(a,b,c,d,e,f,g); delay(1000); } void zero(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,HIGH); digitalWrite(e_block,HIGH); digitalWrite(f_block,HIGH); digitalWrite(g_block,LOW); } void one(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,LOW); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,LOW); digitalWrite(e_block,LOW); digitalWrite(f_block,LOW); digitalWrite(g_block,LOW); } void two(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,HIGH); digitalWrite(c_block,LOW); digitalWrite(d_block,HIGH); digitalWrite(e_block,HIGH); digitalWrite(f_block,LOW); digitalWrite(g_block,HIGH); } void three(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,HIGH); digitalWrite(e_block,LOW); digitalWrite(f_block,LOW); digitalWrite(g_block,HIGH); } void four(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,LOW); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,LOW); digitalWrite(e_block,LOW); digitalWrite(f_block,HIGH); digitalWrite(g_block,HIGH); } void five(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,LOW); digitalWrite(c_block,HIGH); digitalWrite(d_block,HIGH); digitalWrite(e_block,LOW); digitalWrite(f_block,HIGH); digitalWrite(g_block,HIGH); } void six(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,LOW); digitalWrite(c_block,HIGH); digitalWrite(d_block,HIGH); digitalWrite(e_block,HIGH); digitalWrite(f_block,HIGH); digitalWrite(g_block,HIGH); } void seven(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,LOW); digitalWrite(e_block,LOW); digitalWrite(f_block,LOW); digitalWrite(g_block,LOW); } void eight(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,HIGH); digitalWrite(e_block,HIGH); digitalWrite(f_block,HIGH); digitalWrite(g_block,HIGH); } void nine(int a_block, int b_block, int c_block, int d_block, int e_block, int f_block, int g_block){ digitalWrite(a_block,HIGH); digitalWrite(b_block,HIGH); digitalWrite(c_block,HIGH); digitalWrite(d_block,HIGH); digitalWrite(e_block,LOW); digitalWrite(f_block,HIGH); digitalWrite(g_block,HIGH); }
true
9fb02ff3179803f29b70cc9f1c9a514b580c9a3e
C++
bchesley97/FroggerV2
/FroggerV2/FroggerV2/Frog.h
UTF-8
404
2.515625
3
[]
no_license
#pragma once #ifndef FROG_H #define FROG_H #include "Vehicle.h" class Frog { private: sf::RectangleShape *shape; const int jump_length = VEHICLE_LENGTH; int lane; public: Frog(); sf::RectangleShape* getShape(); const int getJump(); int getLane(); void Frog::incrementLane(); void Frog::decrementLane(); void moveLeft(); void moveRight(); void moveUp(); void moveDown(); }; #endif
true
4fbc16711bca03c183c7a8a40a56ea74998e40ab
C++
tatt61880/atcoder
/submissions/abc023_c/main.cpp
UTF-8
1,120
2.546875
3
[]
no_license
#include <iostream> #include <string> #include <map> #include <set> #include <stack> #include <queue> #include <vector> #include <algorithm> #include <functional> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> using namespace std; typedef long long LL; typedef unsigned long long ULL; const LL MOD = 1000000007; #define PrintLn(X) cout << X << endl #define Loop(n) for(int loop_ = n; loop_; --loop_) #define Rep(i, n) for(int i = 0; i < (int)(n); ++i) #define For(i, a, b) for(int i = a; i < (int)(b); ++i) typedef struct{ int r; int c; } Point; int main(void) { int R, C, K; cin >> R >> C >> K; int N; int col[100000]={0}; int row[100000]={0}; vector<Point> v; cin >> N; Rep(i, N){ Point p; cin >> p.r >> p.c; p.r--; p.c--; v.push_back(p); row[p.r]++; col[p.c]++; } int cc[100001]={0}; int rc[100001]={0}; Rep(r, R){ rc[row[r]]++; } Rep(c, C){ cc[col[c]]++; } LL ans = 0; Rep(i, K + 1){ ans += (LL)cc[i] * rc[K - i]; } Rep(i, N){ int num = row[v[i].r] + col[v[i].c]; if(num == K) ans--; if(num == K + 1) ans++; } PrintLn(ans); return 0; }
true